MLIR  21.0.0git
VectorToSCF.cpp
Go to the documentation of this file.
1 //===- VectorToSCF.cpp - Convert vector to SCF dialect ----------*- 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 file implements lowering of vector transfer operations to SCF.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <numeric>
14 #include <optional>
15 #include <type_traits>
16 
18 
28 #include "mlir/IR/Builders.h"
30 #include "mlir/Pass/Pass.h"
32 #include "mlir/Transforms/Passes.h"
33 
34 namespace mlir {
35 #define GEN_PASS_DEF_CONVERTVECTORTOSCF
36 #include "mlir/Conversion/Passes.h.inc"
37 } // namespace mlir
38 
39 using namespace mlir;
40 using vector::TransferReadOp;
41 using vector::TransferWriteOp;
42 
43 namespace {
44 
45 /// Attribute name used for labeling transfer ops during progressive lowering.
46 static const char kPassLabel[] = "__vector_to_scf_lowering__";
47 
48 /// Return true if this transfer op operates on a source tensor.
49 static bool isTensorOp(VectorTransferOpInterface xferOp) {
50  if (isa<RankedTensorType>(xferOp.getShapedType())) {
51  if (isa<vector::TransferWriteOp>(xferOp)) {
52  // TransferWriteOps on tensors have a result.
53  assert(xferOp->getNumResults() > 0);
54  }
55  return true;
56  }
57  return false;
58 }
59 
60 /// Patterns that inherit from this struct have access to
61 /// VectorTransferToSCFOptions.
62 template <typename OpTy>
63 struct VectorToSCFPattern : public OpRewritePattern<OpTy> {
64  explicit VectorToSCFPattern(MLIRContext *context,
66  : OpRewritePattern<OpTy>(context), options(opt) {}
67 
68  LogicalResult checkLowerTensors(VectorTransferOpInterface xferOp,
69  PatternRewriter &rewriter) const {
70  if (isTensorOp(xferOp) && !options.lowerTensors) {
71  return rewriter.notifyMatchFailure(
72  xferOp, "lowering tensor transfers is disabled");
73  }
74  return success();
75  }
76 
78 };
79 
80 /// Given a vector transfer op, calculate which dimension of the `source`
81 /// memref should be unpacked in the next application of TransferOpConversion.
82 /// A return value of std::nullopt indicates a broadcast.
83 template <typename OpTy>
84 static std::optional<int64_t> unpackedDim(OpTy xferOp) {
85  // TODO: support 0-d corner case.
86  assert(xferOp.getTransferRank() > 0 && "unexpected 0-d transfer");
87  auto map = xferOp.getPermutationMap();
88  if (auto expr = dyn_cast<AffineDimExpr>(map.getResult(0))) {
89  return expr.getPosition();
90  }
91  assert(xferOp.isBroadcastDim(0) &&
92  "Expected AffineDimExpr or AffineConstantExpr");
93  return std::nullopt;
94 }
95 
96 /// Compute the permutation map for the new (N-1)-D vector transfer op. This
97 /// map is identical to the current permutation map, but the first result is
98 /// omitted.
99 template <typename OpTy>
100 static AffineMap unpackedPermutationMap(OpBuilder &b, OpTy xferOp) {
101  // TODO: support 0-d corner case.
102  assert(xferOp.getTransferRank() > 0 && "unexpected 0-d transfer");
103  auto map = xferOp.getPermutationMap();
104  return AffineMap::get(map.getNumDims(), 0, map.getResults().drop_front(),
105  b.getContext());
106 }
107 
108 /// Calculate the indices for the new vector transfer op.
109 ///
110 /// E.g.: transfer_read %A[%a, %b, %c, %d] ... : vector<5x4x3xf32> ...
111 /// --> transfer_read %A[%a, %b + iv, %c, %d] ... vector<4x3f32>
112 /// ^^^^^^
113 /// `iv` is the iteration variable of the (new) surrounding loop.
114 template <typename OpTy>
115 static void getXferIndices(OpBuilder &b, OpTy xferOp, Value iv,
116  SmallVector<Value, 8> &indices) {
117  typename OpTy::Adaptor adaptor(xferOp);
118  // Corresponding memref dim of the vector dim that is unpacked.
119  auto dim = unpackedDim(xferOp);
120  auto prevIndices = adaptor.getIndices();
121  indices.append(prevIndices.begin(), prevIndices.end());
122 
123  Location loc = xferOp.getLoc();
124  bool isBroadcast = !dim.has_value();
125  if (!isBroadcast) {
126  AffineExpr d0, d1;
127  bindDims(xferOp.getContext(), d0, d1);
128  Value offset = adaptor.getIndices()[*dim];
129  indices[*dim] =
130  affine::makeComposedAffineApply(b, loc, d0 + d1, {offset, iv});
131  }
132 }
133 
134 static void maybeYieldValue(OpBuilder &b, Location loc, bool hasRetVal,
135  Value value) {
136  if (hasRetVal) {
137  assert(value && "Expected non-empty value");
138  b.create<scf::YieldOp>(loc, value);
139  } else {
140  b.create<scf::YieldOp>(loc);
141  }
142 }
143 
144 /// Generates a boolean Value that is true if the iv-th bit in xferOp's mask
145 /// is set to true. No such check is generated under following circumstances:
146 /// * xferOp does not have a mask.
147 /// * xferOp's mask is not 1D. (In case of (N>1)-D, a subvector of the mask is
148 /// computed and attached to the new transfer op in the pattern.)
149 /// * The to-be-unpacked dim of xferOp is a broadcast.
150 template <typename OpTy>
151 static Value generateMaskCheck(OpBuilder &b, OpTy xferOp, Value iv) {
152  if (!xferOp.getMask())
153  return Value();
154  if (xferOp.getMaskType().getRank() != 1)
155  return Value();
156  if (xferOp.isBroadcastDim(0))
157  return Value();
158 
159  Location loc = xferOp.getLoc();
160  return b.create<vector::ExtractElementOp>(loc, xferOp.getMask(), iv);
161 }
162 
163 /// Helper function TransferOpConversion and TransferOp1dConversion.
164 /// Generate an in-bounds check if the transfer op may go out-of-bounds on the
165 /// specified dimension `dim` with the loop iteration variable `iv`.
166 /// E.g., when unpacking dimension 0 from:
167 /// ```
168 /// %vec = vector.transfer_read %A[%a, %b] %cst
169 /// : vector<5x4xf32>, memref<?x?xf32>
170 /// ```
171 /// An if check similar to this will be generated inside the loop:
172 /// ```
173 /// %d = memref.dim %A, %c0 : memref<?x?xf32>
174 /// if (%a + iv < %d) {
175 /// (in-bounds case)
176 /// } else {
177 /// (out-of-bounds case)
178 /// }
179 /// ```
180 ///
181 /// If the transfer is 1D and has a mask, this function generates a more complex
182 /// check also accounts for potentially masked out elements.
183 ///
184 /// This function variant returns the value returned by `inBoundsCase` or
185 /// `outOfBoundsCase`. The MLIR type of the return value must be specified in
186 /// `resultTypes`.
187 template <typename OpTy>
188 static Value generateInBoundsCheck(
189  OpBuilder &b, OpTy xferOp, Value iv, std::optional<int64_t> dim,
190  TypeRange resultTypes,
191  function_ref<Value(OpBuilder &, Location)> inBoundsCase,
192  function_ref<Value(OpBuilder &, Location)> outOfBoundsCase = nullptr) {
193  bool hasRetVal = !resultTypes.empty();
194  Value cond; // Condition to be built...
195 
196  // Condition check 1: Access in-bounds?
197  bool isBroadcast = !dim; // No in-bounds check for broadcasts.
198  Location loc = xferOp.getLoc();
199  ImplicitLocOpBuilder lb(xferOp.getLoc(), b);
200  if (!xferOp.isDimInBounds(0) && !isBroadcast) {
201  Value memrefDim =
202  vector::createOrFoldDimOp(b, loc, xferOp.getSource(), *dim);
203  AffineExpr d0, d1;
204  bindDims(xferOp.getContext(), d0, d1);
205  Value base = xferOp.getIndices()[*dim];
206  Value memrefIdx =
207  affine::makeComposedAffineApply(b, loc, d0 + d1, {base, iv});
208  cond = lb.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, memrefDim,
209  memrefIdx);
210  }
211 
212  // Condition check 2: Masked in?
213  if (auto maskCond = generateMaskCheck(b, xferOp, iv)) {
214  if (cond)
215  cond = lb.create<arith::AndIOp>(cond, maskCond);
216  else
217  cond = maskCond;
218  }
219 
220  // If the condition is non-empty, generate an SCF::IfOp.
221  if (cond) {
222  auto check = lb.create<scf::IfOp>(
223  cond,
224  /*thenBuilder=*/
225  [&](OpBuilder &b, Location loc) {
226  maybeYieldValue(b, loc, hasRetVal, inBoundsCase(b, loc));
227  },
228  /*elseBuilder=*/
229  [&](OpBuilder &b, Location loc) {
230  if (outOfBoundsCase) {
231  maybeYieldValue(b, loc, hasRetVal, outOfBoundsCase(b, loc));
232  } else {
233  b.create<scf::YieldOp>(loc);
234  }
235  });
236 
237  return hasRetVal ? check.getResult(0) : Value();
238  }
239 
240  // Condition is empty, no need for an SCF::IfOp.
241  return inBoundsCase(b, loc);
242 }
243 
244 /// In this function variant, `inBoundsCase` and `outOfBoundsCase` do not have
245 /// a return value. Consequently, this function does not have a return value.
246 template <typename OpTy>
247 static void generateInBoundsCheck(
248  OpBuilder &b, OpTy xferOp, Value iv, std::optional<int64_t> dim,
249  function_ref<void(OpBuilder &, Location)> inBoundsCase,
250  function_ref<void(OpBuilder &, Location)> outOfBoundsCase = nullptr) {
251  generateInBoundsCheck(
252  b, xferOp, iv, dim, /*resultTypes=*/TypeRange(),
253  /*inBoundsCase=*/
254  [&](OpBuilder &b, Location loc) {
255  inBoundsCase(b, loc);
256  return Value();
257  },
258  /*outOfBoundsCase=*/
259  [&](OpBuilder &b, Location loc) {
260  if (outOfBoundsCase)
261  outOfBoundsCase(b, loc);
262  return Value();
263  });
264 }
265 
266 /// Given an ArrayAttr, return a copy where the first element is dropped.
267 static ArrayAttr dropFirstElem(OpBuilder &b, ArrayAttr attr) {
268  if (!attr)
269  return attr;
270  return ArrayAttr::get(b.getContext(), attr.getValue().drop_front());
271 }
272 
273 /// Add the pass label to a vector transfer op if its rank is not the target
274 /// rank.
275 template <typename OpTy>
276 static void maybeApplyPassLabel(OpBuilder &b, OpTy newXferOp,
277  unsigned targetRank) {
278  if (newXferOp.getVectorType().getRank() > targetRank)
279  newXferOp->setAttr(kPassLabel, b.getUnitAttr());
280 }
281 
282 namespace lowering_n_d {
283 
284 /// Helper data structure for data and mask buffers.
285 struct BufferAllocs {
286  Value dataBuffer;
287  Value maskBuffer;
288 };
289 
290 // TODO: Parallelism and threadlocal considerations with a ParallelScope trait.
292  Operation *scope =
294  assert(scope && "Expected op to be inside automatic allocation scope");
295  return scope;
296 }
297 
298 /// Allocate temporary buffers for data (vector) and mask (if present).
299 template <typename OpTy>
300 static BufferAllocs allocBuffers(OpBuilder &b, OpTy xferOp) {
301  Location loc = xferOp.getLoc();
302  OpBuilder::InsertionGuard guard(b);
303  Operation *scope = getAutomaticAllocationScope(xferOp);
304  assert(scope->getNumRegions() == 1 &&
305  "AutomaticAllocationScope with >1 regions");
306  b.setInsertionPointToStart(&scope->getRegion(0).front());
307 
308  BufferAllocs result;
309  auto bufferType = MemRefType::get({}, xferOp.getVectorType());
310  result.dataBuffer = b.create<memref::AllocaOp>(loc, bufferType);
311 
312  if (xferOp.getMask()) {
313  auto maskType = MemRefType::get({}, xferOp.getMask().getType());
314  auto maskBuffer = b.create<memref::AllocaOp>(loc, maskType);
315  b.setInsertionPoint(xferOp);
316  b.create<memref::StoreOp>(loc, xferOp.getMask(), maskBuffer);
317  result.maskBuffer = b.create<memref::LoadOp>(loc, maskBuffer, ValueRange());
318  }
319 
320  return result;
321 }
322 
323 /// Given a MemRefType with VectorType element type, unpack one dimension from
324 /// the VectorType into the MemRefType.
325 ///
326 /// E.g.: memref<9xvector<5x6xf32>> --> memref<9x5xvector<6xf32>>
327 static FailureOr<MemRefType> unpackOneDim(MemRefType type) {
328  auto vectorType = dyn_cast<VectorType>(type.getElementType());
329  // Vectors with leading scalable dims are not supported.
330  // It may be possible to support these in future by using dynamic memref dims.
331  if (vectorType.getScalableDims().front())
332  return failure();
333  auto memrefShape = type.getShape();
334  SmallVector<int64_t, 8> newMemrefShape;
335  newMemrefShape.append(memrefShape.begin(), memrefShape.end());
336  newMemrefShape.push_back(vectorType.getDimSize(0));
337  return MemRefType::get(newMemrefShape,
338  VectorType::Builder(vectorType).dropDim(0));
339 }
340 
341 /// Given a transfer op, find the memref from which the mask is loaded. This
342 /// is similar to Strategy<TransferWriteOp>::getBuffer.
343 template <typename OpTy>
344 static Value getMaskBuffer(OpTy xferOp) {
345  assert(xferOp.getMask() && "Expected that transfer op has mask");
346  auto loadOp = xferOp.getMask().template getDefiningOp<memref::LoadOp>();
347  assert(loadOp && "Expected transfer op mask produced by LoadOp");
348  return loadOp.getMemRef();
349 }
350 
351 /// Codegen strategy, depending on the operation.
352 template <typename OpTy>
353 struct Strategy;
354 
355 /// Code strategy for vector TransferReadOp.
356 template <>
357 struct Strategy<TransferReadOp> {
358  /// Find the StoreOp that is used for writing the current TransferReadOp's
359  /// result to the temporary buffer allocation.
360  static memref::StoreOp getStoreOp(TransferReadOp xferOp) {
361  assert(xferOp->hasOneUse() && "Expected exactly one use of TransferReadOp");
362  auto storeOp = dyn_cast<memref::StoreOp>((*xferOp->use_begin()).getOwner());
363  assert(storeOp && "Expected TransferReadOp result used by StoreOp");
364  return storeOp;
365  }
366 
367  /// Find the temporary buffer allocation. All labeled TransferReadOps are
368  /// used like this, where %buf is either the buffer allocation or a type cast
369  /// of the buffer allocation:
370  /// ```
371  /// %vec = vector.transfer_read ... { __vector_to_scf_lowering__ } ...
372  /// memref.store %vec, %buf[...] ...
373  /// ```
374  static Value getBuffer(TransferReadOp xferOp) {
375  return getStoreOp(xferOp).getMemRef();
376  }
377 
378  /// Retrieve the indices of the current StoreOp that stores into the buffer.
379  static void getBufferIndices(TransferReadOp xferOp,
380  SmallVector<Value, 8> &indices) {
381  auto storeOp = getStoreOp(xferOp);
382  auto prevIndices = memref::StoreOpAdaptor(storeOp).getIndices();
383  indices.append(prevIndices.begin(), prevIndices.end());
384  }
385 
386  /// Rewrite the TransferReadOp, assuming that there are no out-of-bounds
387  /// accesses on the to-be-unpacked dimension.
388  ///
389  /// 1. Generate a new (N-1)-d TransferReadOp using the loop iteration
390  /// variable `iv`.
391  /// 2. Store the result into the (already `vector.type_cast`ed) buffer.
392  ///
393  /// E.g.:
394  /// ```
395  /// %vec = vector.transfer_read %A[%a+%i, %b, %c], %cst
396  /// : memref<?x?x?xf32>, vector<4x3xf32>
397  /// memref.store %vec, %buf[%i] : memref<5xvector<4x3xf32>>
398  /// ```
399  /// Is rewritten to:
400  /// ```
401  /// %casted = vector.type_cast %buf
402  /// : memref<5xvector<4x3xf32>> to memref<5x4xvector<3xf32>>
403  /// for %j = 0 to 4 {
404  /// %vec = vector.transfer_read %A[%a+%i, %b+%j, %c], %cst
405  /// : memref<?x?x?xf32>, vector<3xf32>
406  /// memref.store %vec, %casted[%i, %j] : memref<5x4xvector<3xf32>>
407  /// }
408  /// ```
409  ///
410  /// Note: The loop and type cast are generated in TransferOpConversion.
411  /// The original TransferReadOp and store op are deleted in `cleanup`.
412  /// Note: The `mask` operand is set in TransferOpConversion.
413  static TransferReadOp rewriteOp(OpBuilder &b,
415  TransferReadOp xferOp, Value buffer, Value iv,
416  ValueRange /*loopState*/) {
417  SmallVector<Value, 8> storeIndices;
418  getBufferIndices(xferOp, storeIndices);
419  storeIndices.push_back(iv);
420 
421  SmallVector<Value, 8> xferIndices;
422  getXferIndices(b, xferOp, iv, xferIndices);
423 
424  Location loc = xferOp.getLoc();
425  auto bufferType = dyn_cast<ShapedType>(buffer.getType());
426  auto vecType = dyn_cast<VectorType>(bufferType.getElementType());
427  auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
428  auto newXferOp = b.create<vector::TransferReadOp>(
429  loc, vecType, xferOp.getSource(), xferIndices,
430  AffineMapAttr::get(unpackedPermutationMap(b, xferOp)),
431  xferOp.getPadding(), Value(), inBoundsAttr);
432 
433  maybeApplyPassLabel(b, newXferOp, options.targetRank);
434 
435  b.create<memref::StoreOp>(loc, newXferOp.getVector(), buffer, storeIndices);
436  return newXferOp;
437  }
438 
439  /// Handle out-of-bounds accesses on the to-be-unpacked dimension: Write
440  /// padding value to the temporary buffer.
441  static Value handleOutOfBoundsDim(OpBuilder &b, TransferReadOp xferOp,
442  Value buffer, Value iv,
443  ValueRange /*loopState*/) {
444  SmallVector<Value, 8> storeIndices;
445  getBufferIndices(xferOp, storeIndices);
446  storeIndices.push_back(iv);
447 
448  Location loc = xferOp.getLoc();
449  auto bufferType = dyn_cast<ShapedType>(buffer.getType());
450  auto vecType = dyn_cast<VectorType>(bufferType.getElementType());
451  auto vec = b.create<vector::SplatOp>(loc, vecType, xferOp.getPadding());
452  b.create<memref::StoreOp>(loc, vec, buffer, storeIndices);
453 
454  return Value();
455  }
456 
457  /// Cleanup after rewriting the op.
458  static void cleanup(PatternRewriter &rewriter, TransferReadOp xferOp,
459  scf::ForOp /*forOp*/) {
460  rewriter.eraseOp(getStoreOp(xferOp));
461  rewriter.eraseOp(xferOp);
462  }
463 
464  /// Return the initial loop state for the generated scf.for loop.
465  static Value initialLoopState(TransferReadOp xferOp) { return Value(); }
466 };
467 
468 /// Codegen strategy for vector TransferWriteOp.
469 template <>
470 struct Strategy<TransferWriteOp> {
471  /// Find the temporary buffer allocation. All labeled TransferWriteOps are
472  /// used like this, where %buf is either the buffer allocation or a type cast
473  /// of the buffer allocation:
474  /// ```
475  /// %vec = memref.load %buf[...] ...
476  /// vector.transfer_write %vec ... { __vector_to_scf_lowering__ } ...
477  /// ```
478  static Value getBuffer(TransferWriteOp xferOp) {
479  auto loadOp = xferOp.getVector().getDefiningOp<memref::LoadOp>();
480  assert(loadOp && "Expected transfer op vector produced by LoadOp");
481  return loadOp.getMemRef();
482  }
483 
484  /// Retrieve the indices of the current LoadOp that loads from the buffer.
485  static void getBufferIndices(TransferWriteOp xferOp,
486  SmallVector<Value, 8> &indices) {
487  auto loadOp = xferOp.getVector().getDefiningOp<memref::LoadOp>();
488  auto prevIndices = memref::LoadOpAdaptor(loadOp).getIndices();
489  indices.append(prevIndices.begin(), prevIndices.end());
490  }
491 
492  /// Rewrite the TransferWriteOp, assuming that there are no out-of-bounds
493  /// accesses on the to-be-unpacked dimension.
494  ///
495  /// 1. Load an (N-1)-d vector from the (already `vector.type_cast`ed) buffer,
496  /// using the loop iteration variable `iv`.
497  /// 2. Generate a new (N-1)-d TransferWriteOp, writing the loaded vector back
498  /// to memory.
499  ///
500  /// Note: For more details, see comments on Strategy<TransferReadOp>.
501  static TransferWriteOp rewriteOp(OpBuilder &b,
503  TransferWriteOp xferOp, Value buffer,
504  Value iv, ValueRange loopState) {
505  SmallVector<Value, 8> loadIndices;
506  getBufferIndices(xferOp, loadIndices);
507  loadIndices.push_back(iv);
508 
509  SmallVector<Value, 8> xferIndices;
510  getXferIndices(b, xferOp, iv, xferIndices);
511 
512  Location loc = xferOp.getLoc();
513  auto vec = b.create<memref::LoadOp>(loc, buffer, loadIndices);
514  auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
515  auto source = loopState.empty() ? xferOp.getSource() : loopState[0];
516  Type type = isTensorOp(xferOp) ? xferOp.getShapedType() : Type();
517  auto newXferOp = b.create<vector::TransferWriteOp>(
518  loc, type, vec, source, xferIndices,
519  AffineMapAttr::get(unpackedPermutationMap(b, xferOp)), Value(),
520  inBoundsAttr);
521 
522  maybeApplyPassLabel(b, newXferOp, options.targetRank);
523 
524  return newXferOp;
525  }
526 
527  /// Handle out-of-bounds accesses on the to-be-unpacked dimension.
528  static Value handleOutOfBoundsDim(OpBuilder &b, TransferWriteOp xferOp,
529  Value buffer, Value iv,
530  ValueRange loopState) {
531  return isTensorOp(xferOp) ? loopState[0] : Value();
532  }
533 
534  /// Cleanup after rewriting the op.
535  static void cleanup(PatternRewriter &rewriter, TransferWriteOp xferOp,
536  scf::ForOp forOp) {
537  if (isTensorOp(xferOp)) {
538  assert(forOp->getNumResults() == 1 && "Expected one for loop result");
539  rewriter.replaceOp(xferOp, forOp->getResult(0));
540  } else {
541  rewriter.eraseOp(xferOp);
542  }
543  }
544 
545  /// Return the initial loop state for the generated scf.for loop.
546  static Value initialLoopState(TransferWriteOp xferOp) {
547  return isTensorOp(xferOp) ? xferOp.getSource() : Value();
548  }
549 };
550 
551 template <typename OpTy>
552 static LogicalResult checkPrepareXferOp(OpTy xferOp, PatternRewriter &rewriter,
554  if (xferOp->hasAttr(kPassLabel))
555  return rewriter.notifyMatchFailure(
556  xferOp, "kPassLabel is present (vector-to-scf lowering in progress)");
557  if (xferOp.getVectorType().getRank() <= options.targetRank)
558  return rewriter.notifyMatchFailure(
559  xferOp, "xferOp vector rank <= transformation target rank");
560  if (xferOp.getVectorType().getScalableDims().front())
561  return rewriter.notifyMatchFailure(
562  xferOp, "Unpacking of the leading dimension into the memref is not yet "
563  "supported for scalable dims");
564  if (isTensorOp(xferOp) && !options.lowerTensors)
565  return rewriter.notifyMatchFailure(
566  xferOp, "Unpacking for tensors has been disabled.");
567  if (xferOp.getVectorType().getElementType() !=
568  xferOp.getShapedType().getElementType())
569  return rewriter.notifyMatchFailure(
570  xferOp, "Mismatching source and destination element types.");
571 
572  return success();
573 }
574 
575 /// Prepare a TransferReadOp for progressive lowering.
576 ///
577 /// 1. Allocate a temporary buffer.
578 /// 2. Label the TransferReadOp, marking it eligible for progressive lowering.
579 /// 3. Store the result of the TransferReadOp into the temporary buffer.
580 /// 4. Load the result from the temporary buffer and replace all uses of the
581 /// original TransferReadOp with this load.
582 ///
583 /// E.g.:
584 /// ```
585 /// %vec = vector.transfer_read %A[%a, %b, %c], %cst
586 /// : vector<5x4xf32>, memref<?x?x?xf32>
587 /// ```
588 /// is rewritten to:
589 /// ```
590 /// %0 = memref.alloca() : memref<vector<5x4xf32>>
591 /// %1 = vector.transfer_read %A[%a, %b, %c], %cst
592 /// { __vector_to_scf_lowering__ } : vector<5x4xf32>, memref<?x?x?xf32>
593 /// memref.store %1, %0[] : memref<vector<5x4xf32>>
594 /// %vec = memref.load %0[] : memref<vector<5x4xf32>>
595 /// ```
596 ///
597 /// Note: A second temporary buffer may be allocated for the `mask` operand.
598 struct PrepareTransferReadConversion
599  : public VectorToSCFPattern<TransferReadOp> {
600  using VectorToSCFPattern<TransferReadOp>::VectorToSCFPattern;
601 
602  LogicalResult matchAndRewrite(TransferReadOp xferOp,
603  PatternRewriter &rewriter) const override {
604  if (checkPrepareXferOp(xferOp, rewriter, options).failed())
605  return rewriter.notifyMatchFailure(
606  xferOp, "checkPrepareXferOp conditions not met!");
607 
608  auto buffers = allocBuffers(rewriter, xferOp);
609  auto *newXfer = rewriter.clone(*xferOp.getOperation());
610  newXfer->setAttr(kPassLabel, rewriter.getUnitAttr());
611  if (xferOp.getMask()) {
612  dyn_cast<TransferReadOp>(newXfer).getMaskMutable().assign(
613  buffers.maskBuffer);
614  }
615 
616  Location loc = xferOp.getLoc();
617  rewriter.create<memref::StoreOp>(loc, newXfer->getResult(0),
618  buffers.dataBuffer);
619  rewriter.replaceOpWithNewOp<memref::LoadOp>(xferOp, buffers.dataBuffer);
620 
621  return success();
622  }
623 };
624 
625 /// Prepare a TransferWriteOp for progressive lowering.
626 ///
627 /// 1. Allocate a temporary buffer.
628 /// 2. Store the vector into the buffer.
629 /// 3. Load the vector from the buffer again.
630 /// 4. Use the loaded vector as a TransferWriteOp operand and label the op,
631 /// marking it eligible for progressive lowering via TransferOpConversion.
632 ///
633 /// E.g.:
634 /// ```
635 /// vector.transfer_write %vec, %A[%a, %b, %c]
636 /// : vector<5x4xf32>, memref<?x?x?xf32>
637 /// ```
638 /// is rewritten to:
639 /// ```
640 /// %0 = memref.alloca() : memref<vector<5x4xf32>>
641 /// memref.store %vec, %0[] : memref<vector<5x4xf32>>
642 /// %1 = memref.load %0[] : memref<vector<5x4xf32>>
643 /// vector.transfer_write %1, %A[%a, %b, %c] { __vector_to_scf_lowering__ }
644 /// : vector<5x4xf32>, memref<?x?x?xf32>
645 /// ```
646 ///
647 /// Note: A second temporary buffer may be allocated for the `mask` operand.
648 struct PrepareTransferWriteConversion
649  : public VectorToSCFPattern<TransferWriteOp> {
650  using VectorToSCFPattern<TransferWriteOp>::VectorToSCFPattern;
651 
652  LogicalResult matchAndRewrite(TransferWriteOp xferOp,
653  PatternRewriter &rewriter) const override {
654  if (checkPrepareXferOp(xferOp, rewriter, options).failed())
655  return rewriter.notifyMatchFailure(
656  xferOp, "checkPrepareXferOp conditions not met!");
657 
658  Location loc = xferOp.getLoc();
659  auto buffers = allocBuffers(rewriter, xferOp);
660  rewriter.create<memref::StoreOp>(loc, xferOp.getVector(),
661  buffers.dataBuffer);
662  auto loadedVec = rewriter.create<memref::LoadOp>(loc, buffers.dataBuffer);
663  rewriter.modifyOpInPlace(xferOp, [&]() {
664  xferOp.getVectorMutable().assign(loadedVec);
665  xferOp->setAttr(kPassLabel, rewriter.getUnitAttr());
666  });
667 
668  if (xferOp.getMask()) {
669  rewriter.modifyOpInPlace(xferOp, [&]() {
670  xferOp.getMaskMutable().assign(buffers.maskBuffer);
671  });
672  }
673 
674  return success();
675  }
676 };
677 
678 /// Decompose a n-D PrintOp into a loop of elementary/scalar prints. This allows
679 /// printing both 1D scalable vectors and n-D fixed size vectors.
680 ///
681 /// E.g.:
682 /// ```
683 /// vector.print %v : vector<[4]xi32>
684 /// ```
685 /// is rewritten to:
686 /// ```
687 /// %c0 = arith.constant 0 : index
688 /// %c4 = arith.constant 4 : index
689 /// %c1 = arith.constant 1 : index
690 /// %vscale = vector.vscale
691 /// %length = arith.muli %vscale, %c4 : index
692 /// %lastIndex = arith.subi %length, %c1 : index
693 /// vector.print punctuation <open>
694 /// scf.for %i = %c0 to %length step %c1 {
695 /// %el = vector.extractelement %v[%i : index] : vector<[4]xi32>
696 /// vector.print %el : i32 punctuation <no_punctuation>
697 /// %notLastIndex = arith.cmpi ult, %i, %lastIndex : index
698 /// scf.if %notLastIndex {
699 /// vector.print punctuation <comma>
700 /// }
701 /// }
702 /// vector.print punctuation <close>
703 /// vector.print
704 /// ```
705 struct DecomposePrintOpConversion : public VectorToSCFPattern<vector::PrintOp> {
706  using VectorToSCFPattern<vector::PrintOp>::VectorToSCFPattern;
707  LogicalResult matchAndRewrite(vector::PrintOp printOp,
708  PatternRewriter &rewriter) const override {
709  if (!printOp.getSource())
710  return failure();
711 
712  VectorType vectorType = dyn_cast<VectorType>(printOp.getPrintType());
713  if (!vectorType)
714  return failure();
715 
716  // Currently >= 2D scalable vectors are not supported.
717  // These can't be lowered to LLVM (as LLVM does not support scalable vectors
718  // of scalable vectors), and due to limitations of current ops can't be
719  // indexed with SSA values or flattened. This may change after
720  // https://reviews.llvm.org/D155034, though there still needs to be a path
721  // for lowering to LLVM.
722  if (vectorType.getRank() > 1 && vectorType.isScalable())
723  return failure();
724 
725  auto loc = printOp.getLoc();
726  auto value = printOp.getSource();
727 
728  if (auto intTy = dyn_cast<IntegerType>(vectorType.getElementType())) {
729  // Oddly sized integers are (somewhat) buggy on a lot of backends, so to
730  // avoid issues extend them to a more standard size.
731  // https://github.com/llvm/llvm-project/issues/30613
732  auto width = intTy.getWidth();
733  auto legalWidth = llvm::NextPowerOf2(std::max(8u, width) - 1);
734  auto legalIntTy = IntegerType::get(rewriter.getContext(), legalWidth,
735  intTy.getSignedness());
736  // arith can only take signless integers, so we must cast back and forth.
737  auto signlessSourceVectorType =
738  vectorType.cloneWith({}, getIntTypeWithSignlessSemantics(intTy));
739  auto signlessTargetVectorType =
740  vectorType.cloneWith({}, getIntTypeWithSignlessSemantics(legalIntTy));
741  auto targetVectorType = vectorType.cloneWith({}, legalIntTy);
742  value = rewriter.create<vector::BitCastOp>(loc, signlessSourceVectorType,
743  value);
744  if (value.getType() != signlessTargetVectorType) {
745  if (width == 1 || intTy.isUnsigned())
746  value = rewriter.create<arith::ExtUIOp>(loc, signlessTargetVectorType,
747  value);
748  else
749  value = rewriter.create<arith::ExtSIOp>(loc, signlessTargetVectorType,
750  value);
751  }
752  value = rewriter.create<vector::BitCastOp>(loc, targetVectorType, value);
753  vectorType = targetVectorType;
754  }
755 
756  auto scalableDimensions = vectorType.getScalableDims();
757  auto shape = vectorType.getShape();
758  constexpr int64_t singletonShape[] = {1};
759  if (vectorType.getRank() == 0)
760  shape = singletonShape;
761 
762  if (vectorType.getRank() != 1) {
763  // Flatten n-D vectors to 1D. This is done to allow indexing with a
764  // non-constant value (which can currently only be done via
765  // vector.extractelement for 1D vectors).
766  auto flatLength = std::accumulate(shape.begin(), shape.end(), 1,
767  std::multiplies<int64_t>());
768  auto flatVectorType =
769  VectorType::get({flatLength}, vectorType.getElementType());
770  value = rewriter.create<vector::ShapeCastOp>(loc, flatVectorType, value);
771  }
772 
773  vector::PrintOp firstClose;
774  SmallVector<Value, 8> loopIndices;
775  for (unsigned d = 0; d < shape.size(); d++) {
776  // Setup loop bounds and step.
777  Value lowerBound = rewriter.create<arith::ConstantIndexOp>(loc, 0);
778  Value upperBound = rewriter.create<arith::ConstantIndexOp>(loc, shape[d]);
779  Value step = rewriter.create<arith::ConstantIndexOp>(loc, 1);
780  if (!scalableDimensions.empty() && scalableDimensions[d]) {
781  auto vscale = rewriter.create<vector::VectorScaleOp>(
782  loc, rewriter.getIndexType());
783  upperBound = rewriter.create<arith::MulIOp>(loc, upperBound, vscale);
784  }
785  auto lastIndex = rewriter.create<arith::SubIOp>(loc, upperBound, step);
786 
787  // Create a loop to print the elements surrounded by parentheses.
788  rewriter.create<vector::PrintOp>(loc, vector::PrintPunctuation::Open);
789  auto loop =
790  rewriter.create<scf::ForOp>(loc, lowerBound, upperBound, step);
791  auto printClose = rewriter.create<vector::PrintOp>(
792  loc, vector::PrintPunctuation::Close);
793  if (!firstClose)
794  firstClose = printClose;
795 
796  auto loopIdx = loop.getInductionVar();
797  loopIndices.push_back(loopIdx);
798 
799  // Print a comma after all but the last element.
800  rewriter.setInsertionPointToStart(loop.getBody());
801  auto notLastIndex = rewriter.create<arith::CmpIOp>(
802  loc, arith::CmpIPredicate::ult, loopIdx, lastIndex);
803  rewriter.create<scf::IfOp>(loc, notLastIndex,
804  [&](OpBuilder &builder, Location loc) {
805  builder.create<vector::PrintOp>(
806  loc, vector::PrintPunctuation::Comma);
807  builder.create<scf::YieldOp>(loc);
808  });
809 
810  rewriter.setInsertionPointToStart(loop.getBody());
811  }
812 
813  // Compute the flattened index.
814  // Note: For the > rank 1 vectors this assumes non-scalable.
815  Value flatIndex;
816  auto currentStride = 1;
817  for (int d = shape.size() - 1; d >= 0; d--) {
818  auto stride = rewriter.create<arith::ConstantIndexOp>(loc, currentStride);
819  auto index = rewriter.create<arith::MulIOp>(loc, stride, loopIndices[d]);
820  if (flatIndex)
821  flatIndex = rewriter.create<arith::AddIOp>(loc, flatIndex, index);
822  else
823  flatIndex = index;
824  currentStride *= shape[d];
825  }
826 
827  // Print the scalar elements in the inner most loop.
828  auto element =
829  rewriter.create<vector::ExtractElementOp>(loc, value, flatIndex);
830  rewriter.create<vector::PrintOp>(loc, element,
831  vector::PrintPunctuation::NoPunctuation);
832 
833  rewriter.setInsertionPointAfter(firstClose);
834  rewriter.create<vector::PrintOp>(loc, printOp.getPunctuation());
835  rewriter.eraseOp(printOp);
836  return success();
837  }
838 
839  static IntegerType getIntTypeWithSignlessSemantics(IntegerType intTy) {
840  return IntegerType::get(intTy.getContext(), intTy.getWidth(),
841  IntegerType::Signless);
842  };
843 };
844 
845 /// Progressive lowering of vector transfer ops: Unpack one dimension.
846 ///
847 /// 1. Unpack one dimension from the current buffer type and cast the buffer
848 /// to that new type. E.g.:
849 /// ```
850 /// %vec = memref.load %0[%1] : memref<5xvector<4x3xf32>>
851 /// vector.transfer_write %vec ...
852 /// ```
853 /// The following cast is generated:
854 /// ```
855 /// %casted = vector.type_cast %0
856 /// : memref<5xvector<4x3xf32>> to memref<5x4xvector<3xf32>>
857 /// ```
858 /// 2. Generate a for loop and rewrite the transfer op according to the
859 /// corresponding Strategy<OpTy>. If the to-be-unpacked dimension can be
860 /// out-of-bounds, generate an if-check and handle both cases separately.
861 /// 3. Clean up according to the corresponding Strategy<OpTy>.
862 ///
863 /// Note: If the transfer op is a TransferWriteOp and operates on a tensor
864 /// source (as opposed to a memref source), then each iteration of the generated
865 /// scf.for loop yields the new tensor value. E.g.:
866 /// ```
867 /// %result = scf.for i = 0 to 5 {
868 /// %0 = memref.load %buffer[i] : memref<5xvector<4x3xf32>>
869 /// %1 = vector.transfer_write %0, %source[...]
870 /// : vector<4x3xf32>, tensor<5x4x3xf32>
871 /// scf.yield %1 : tensor<5x4x3xf32>
872 /// }
873 /// ```
874 template <typename OpTy>
875 struct TransferOpConversion : public VectorToSCFPattern<OpTy> {
876  using VectorToSCFPattern<OpTy>::VectorToSCFPattern;
877 
878  void initialize() {
879  // This pattern recursively unpacks one dimension at a time. The recursion
880  // bounded as the rank is strictly decreasing.
881  this->setHasBoundedRewriteRecursion();
882  }
883 
884  static void getMaskBufferLoadIndices(OpTy xferOp, Value castedMaskBuffer,
885  SmallVectorImpl<Value> &loadIndices,
886  Value iv) {
887  assert(xferOp.getMask() && "Expected transfer op to have mask");
888 
889  // Add load indices from the previous iteration.
890  // The mask buffer depends on the permutation map, which makes determining
891  // the indices quite complex, so this is why we need to "look back" to the
892  // previous iteration to find the right indices.
893  Value maskBuffer = getMaskBuffer(xferOp);
894  for (Operation *user : maskBuffer.getUsers()) {
895  // If there is no previous load op, then the indices are empty.
896  if (auto loadOp = dyn_cast<memref::LoadOp>(user)) {
897  Operation::operand_range prevIndices = loadOp.getIndices();
898  loadIndices.append(prevIndices.begin(), prevIndices.end());
899  break;
900  }
901  }
902 
903  // In case of broadcast: Use same indices to load from memref
904  // as before.
905  if (!xferOp.isBroadcastDim(0))
906  loadIndices.push_back(iv);
907  }
908 
909  LogicalResult matchAndRewrite(OpTy xferOp,
910  PatternRewriter &rewriter) const override {
911  if (!xferOp->hasAttr(kPassLabel))
912  return rewriter.notifyMatchFailure(
913  xferOp, "kPassLabel is present (progressing lowering in progress)");
914 
915  // Find and cast data buffer. How the buffer can be found depends on OpTy.
916  ImplicitLocOpBuilder locB(xferOp.getLoc(), rewriter);
917  Value dataBuffer = Strategy<OpTy>::getBuffer(xferOp);
918  auto dataBufferType = dyn_cast<MemRefType>(dataBuffer.getType());
919  FailureOr<MemRefType> castedDataType = unpackOneDim(dataBufferType);
920  if (failed(castedDataType))
921  return rewriter.notifyMatchFailure(xferOp,
922  "Failed to unpack one vector dim.");
923 
924  auto castedDataBuffer =
925  locB.create<vector::TypeCastOp>(*castedDataType, dataBuffer);
926 
927  // If the xferOp has a mask: Find and cast mask buffer.
928  Value castedMaskBuffer;
929  if (xferOp.getMask()) {
930  Value maskBuffer = getMaskBuffer(xferOp);
931  if (xferOp.isBroadcastDim(0) || xferOp.getMaskType().getRank() == 1) {
932  // Do not unpack a dimension of the mask, if:
933  // * To-be-unpacked transfer op dimension is a broadcast.
934  // * Mask is 1D, i.e., the mask cannot be further unpacked.
935  // (That means that all remaining dimensions of the transfer op must
936  // be broadcasted.)
937  castedMaskBuffer = maskBuffer;
938  } else {
939  // It's safe to assume the mask buffer can be unpacked if the data
940  // buffer was unpacked.
941  auto maskBufferType = cast<MemRefType>(maskBuffer.getType());
942  MemRefType castedMaskType = *unpackOneDim(maskBufferType);
943  castedMaskBuffer =
944  locB.create<vector::TypeCastOp>(castedMaskType, maskBuffer);
945  }
946  }
947 
948  // Loop bounds and step.
949  auto lb = locB.create<arith::ConstantIndexOp>(0);
950  auto ub = locB.create<arith::ConstantIndexOp>(
951  castedDataType->getDimSize(castedDataType->getRank() - 1));
952  auto step = locB.create<arith::ConstantIndexOp>(1);
953  // TransferWriteOps that operate on tensors return the modified tensor and
954  // require a loop state.
955  auto loopState = Strategy<OpTy>::initialLoopState(xferOp);
956 
957  // Generate for loop.
958  auto result = locB.create<scf::ForOp>(
959  lb, ub, step, loopState ? ValueRange(loopState) : ValueRange(),
960  [&](OpBuilder &b, Location loc, Value iv, ValueRange loopState) {
961  Type stateType = loopState.empty() ? Type() : loopState[0].getType();
962 
963  auto result = generateInBoundsCheck(
964  b, xferOp, iv, unpackedDim(xferOp),
965  stateType ? TypeRange(stateType) : TypeRange(),
966  /*inBoundsCase=*/
967  [&](OpBuilder &b, Location loc) {
968  // Create new transfer op.
969  OpTy newXfer = Strategy<OpTy>::rewriteOp(
970  b, this->options, xferOp, castedDataBuffer, iv, loopState);
971 
972  // If old transfer op has a mask: Set mask on new transfer op.
973  // Special case: If the mask of the old transfer op is 1D and
974  // the unpacked dim is not a broadcast, no mask is needed on
975  // the new transfer op.
976  if (xferOp.getMask() && (xferOp.isBroadcastDim(0) ||
977  xferOp.getMaskType().getRank() > 1)) {
978  OpBuilder::InsertionGuard guard(b);
979  b.setInsertionPoint(newXfer); // Insert load before newXfer.
980 
981  SmallVector<Value, 8> loadIndices;
982  getMaskBufferLoadIndices(xferOp, castedMaskBuffer,
983  loadIndices, iv);
984  auto mask = b.create<memref::LoadOp>(loc, castedMaskBuffer,
985  loadIndices);
986  rewriter.modifyOpInPlace(newXfer, [&]() {
987  newXfer.getMaskMutable().assign(mask);
988  });
989  }
990 
991  return loopState.empty() ? Value() : newXfer->getResult(0);
992  },
993  /*outOfBoundsCase=*/
994  [&](OpBuilder &b, Location /*loc*/) {
995  return Strategy<OpTy>::handleOutOfBoundsDim(
996  b, xferOp, castedDataBuffer, iv, loopState);
997  });
998 
999  maybeYieldValue(b, loc, !loopState.empty(), result);
1000  });
1001 
1002  Strategy<OpTy>::cleanup(rewriter, xferOp, result);
1003  return success();
1004  }
1005 };
1006 
1007 /// Retrieves the dimensions sizes of a mask. Currently supports CreateMaskOp
1008 /// and ConstantMaskOp.
1009 template <typename VscaleConstantBuilder>
1010 static FailureOr<SmallVector<OpFoldResult>>
1011 getMaskDimSizes(Value mask, VscaleConstantBuilder &createVscaleMultiple) {
1012  if (!mask)
1013  return SmallVector<OpFoldResult>{};
1014  if (auto createMaskOp = mask.getDefiningOp<vector::CreateMaskOp>()) {
1015  return llvm::map_to_vector(createMaskOp.getOperands(), [](Value dimSize) {
1016  return OpFoldResult(dimSize);
1017  });
1018  }
1019  if (auto constantMask = mask.getDefiningOp<vector::ConstantMaskOp>()) {
1020  int dimIdx = 0;
1021  VectorType maskType = constantMask.getVectorType();
1022  auto indexType = IndexType::get(mask.getContext());
1023  return llvm::map_to_vector(
1024  constantMask.getMaskDimSizes(), [&](int64_t dimSize) {
1025  // A scalable dim in a constant_mask means vscale x dimSize.
1026  if (maskType.getScalableDims()[dimIdx++])
1027  return OpFoldResult(createVscaleMultiple(dimSize));
1028  return OpFoldResult(IntegerAttr::get(indexType, dimSize));
1029  });
1030  }
1031  return failure();
1032 }
1033 
1034 /// Scalable vector lowering of transfer_write(transpose). This lowering only
1035 /// supports rank 2 (scalable) vectors, but can be used in conjunction with
1036 /// `UnrollTransferWriteConversion` to support n-D cases. The unroll conversion
1037 /// unrolls until the first scalable dimension.
1038 ///
1039 /// Example:
1040 ///
1041 /// BEFORE:
1042 /// ```mlir
1043 /// %transpose = vector.transpose %vec, [1, 0]
1044 /// : vector<4x[4]xf32> to vector<[4]x4xf32>
1045 /// vector.transfer_write %transpose, %dest[%i, %j] {in_bounds = [true, true]}
1046 /// : vector<[4]x4xf32>, memref<?x?xf32>
1047 /// ```
1048 ///
1049 /// AFTER:
1050 /// ```mlir
1051 /// %c1 = arith.constant 1 : index
1052 /// %c4 = arith.constant 4 : index
1053 /// %c0 = arith.constant 0 : index
1054 /// %0 = vector.extract %arg0[0] : vector<[4]xf32> from vector<4x[4]xf32>
1055 /// %1 = vector.extract %arg0[1] : vector<[4]xf32> from vector<4x[4]xf32>
1056 /// %2 = vector.extract %arg0[2] : vector<[4]xf32> from vector<4x[4]xf32>
1057 /// %3 = vector.extract %arg0[3] : vector<[4]xf32> from vector<4x[4]xf32>
1058 /// %vscale = vector.vscale
1059 /// %c4_vscale = arith.muli %vscale, %c4 : index
1060 /// scf.for %idx = %c0 to %c4_vscale step %c1 {
1061 /// %4 = vector.extract %0[%idx] : f32 from vector<[4]xf32>
1062 /// %5 = vector.extract %1[%idx] : f32 from vector<[4]xf32>
1063 /// %6 = vector.extract %2[%idx] : f32 from vector<[4]xf32>
1064 /// %7 = vector.extract %3[%idx] : f32 from vector<[4]xf32>
1065 /// %slice_i = affine.apply #map(%idx)[%i]
1066 /// %slice = vector.from_elements %4, %5, %6, %7 : vector<4xf32>
1067 /// vector.transfer_write %slice, %arg1[%slice_i, %j] {in_bounds = [true]}
1068 /// : vector<4xf32>, memref<?x?xf32>
1069 /// }
1070 /// ```
1071 struct ScalableTransposeTransferWriteConversion
1072  : VectorToSCFPattern<vector::TransferWriteOp> {
1073  using VectorToSCFPattern::VectorToSCFPattern;
1074 
1075  LogicalResult matchAndRewrite(TransferWriteOp writeOp,
1076  PatternRewriter &rewriter) const override {
1077  if (failed(checkLowerTensors(writeOp, rewriter)))
1078  return failure();
1079 
1080  VectorType vectorType = writeOp.getVectorType();
1081 
1082  // Note: By comparing the scalable dims to an ArrayRef of length two this
1083  // implicitly checks the rank (is also two).
1084  ArrayRef<bool> scalableFlags = vectorType.getScalableDims();
1085  if (scalableFlags != ArrayRef<bool>{true, false}) {
1086  return rewriter.notifyMatchFailure(
1087  writeOp, "expected vector of the form vector<[N]xMxty>");
1088  }
1089 
1090  auto permutationMap = writeOp.getPermutationMap();
1091  if (!permutationMap.isIdentity()) {
1092  return rewriter.notifyMatchFailure(
1093  writeOp, "non-identity permutations are unsupported (lower first)");
1094  }
1095 
1096  // Note: This pattern is only lowering the leading dimension (to a loop),
1097  // so we only check if the leading dimension is in bounds. The in-bounds
1098  // attribute for the trailing dimension will be propagated.
1099  if (!writeOp.isDimInBounds(0)) {
1100  return rewriter.notifyMatchFailure(
1101  writeOp, "out-of-bounds dims are unsupported (use masking)");
1102  }
1103 
1104  Value vector = writeOp.getVector();
1105  auto transposeOp = vector.getDefiningOp<vector::TransposeOp>();
1106  if (!transposeOp ||
1107  transposeOp.getPermutation() != ArrayRef<int64_t>{1, 0}) {
1108  return rewriter.notifyMatchFailure(writeOp, "source not transpose");
1109  }
1110 
1111  auto loc = writeOp.getLoc();
1112  auto createVscaleMultiple =
1113  vector::makeVscaleConstantBuilder(rewriter, loc);
1114 
1115  auto maskDims = getMaskDimSizes(writeOp.getMask(), createVscaleMultiple);
1116  if (failed(maskDims)) {
1117  return rewriter.notifyMatchFailure(writeOp,
1118  "failed to resolve mask dims");
1119  }
1120 
1121  int64_t fixedDimSize = vectorType.getDimSize(1);
1122  auto fixedDimOffsets = llvm::seq(fixedDimSize);
1123 
1124  // Extract all slices from the source of the transpose.
1125  auto transposeSource = transposeOp.getVector();
1126  SmallVector<Value> transposeSourceSlices =
1127  llvm::map_to_vector(fixedDimOffsets, [&](int64_t idx) -> Value {
1128  return rewriter.create<vector::ExtractOp>(loc, transposeSource, idx);
1129  });
1130 
1131  // Loop bounds and step.
1132  auto lb = rewriter.create<arith::ConstantIndexOp>(loc, 0);
1133  auto ub =
1134  maskDims->empty()
1135  ? Value(createVscaleMultiple(vectorType.getDimSize(0)))
1136  : vector::getAsValues(rewriter, loc, maskDims->front()).front();
1137  auto step = rewriter.create<arith::ConstantIndexOp>(loc, 1);
1138 
1139  // Generate a new mask for the slice.
1140  VectorType sliceType = VectorType::Builder(vectorType).dropDim(0);
1141  Value sliceMask = nullptr;
1142  if (!maskDims->empty()) {
1143  sliceMask = rewriter.create<vector::CreateMaskOp>(
1144  loc, sliceType.clone(rewriter.getI1Type()),
1145  ArrayRef<OpFoldResult>(*maskDims).drop_front());
1146  }
1147 
1148  Value initDest = isTensorOp(writeOp) ? writeOp.getSource() : Value{};
1149  ValueRange initLoopArgs = initDest ? initDest : ValueRange{};
1150  auto result = rewriter.create<scf::ForOp>(
1151  loc, lb, ub, step, initLoopArgs,
1152  [&](OpBuilder &b, Location loc, Value iv, ValueRange loopIterArgs) {
1153  // Indices for the new transfer op.
1154  SmallVector<Value, 8> xferIndices;
1155  getXferIndices(b, writeOp, iv, xferIndices);
1156 
1157  // Extract a transposed slice from the source vector.
1158  SmallVector<Value> transposeElements =
1159  llvm::map_to_vector(fixedDimOffsets, [&](int64_t idx) -> Value {
1160  return b.create<vector::ExtractOp>(
1161  loc, transposeSourceSlices[idx], iv);
1162  });
1163  auto sliceVec = b.create<vector::FromElementsOp>(loc, sliceType,
1164  transposeElements);
1165 
1166  // Create the transfer_write for the slice.
1167  Value dest =
1168  loopIterArgs.empty() ? writeOp.getSource() : loopIterArgs.front();
1169  auto newWriteOp = b.create<vector::TransferWriteOp>(
1170  loc, sliceVec, dest, xferIndices,
1171  ArrayRef<bool>(writeOp.getInBoundsValues()).drop_front());
1172  if (sliceMask)
1173  newWriteOp.getMaskMutable().assign(sliceMask);
1174 
1175  // Yield from the loop.
1176  b.create<scf::YieldOp>(loc, loopIterArgs.empty()
1177  ? ValueRange{}
1178  : newWriteOp.getResult());
1179  });
1180 
1181  if (isTensorOp(writeOp))
1182  rewriter.replaceOp(writeOp, result);
1183  else
1184  rewriter.eraseOp(writeOp);
1185 
1186  return success();
1187  }
1188 };
1189 
1190 } // namespace lowering_n_d
1191 
1193 
1194 /// If the original transfer op has a mask, compute the mask of the new transfer
1195 /// op (for the current iteration `i`) and assign it.
1196 template <typename OpTy>
1197 static void maybeAssignMask(OpBuilder &b, OpTy xferOp, OpTy newXferOp,
1198  int64_t i) {
1199  if (!xferOp.getMask())
1200  return;
1201 
1202  if (xferOp.isBroadcastDim(0)) {
1203  // To-be-unpacked dimension is a broadcast, which does not have a
1204  // corresponding mask dimension. Mask attribute remains unchanged.
1205  newXferOp.getMaskMutable().assign(xferOp.getMask());
1206  return;
1207  }
1208 
1209  if (xferOp.getMaskType().getRank() > 1) {
1210  // Unpack one dimension of the mask.
1211  OpBuilder::InsertionGuard guard(b);
1212  b.setInsertionPoint(newXferOp); // Insert load before newXfer.
1213 
1214  llvm::SmallVector<int64_t, 1> indices({i});
1215  Location loc = xferOp.getLoc();
1216  auto newMask = b.create<vector::ExtractOp>(loc, xferOp.getMask(), indices);
1217  newXferOp.getMaskMutable().assign(newMask);
1218  }
1219 
1220  // If we end up here: The mask of the old transfer op is 1D and the unpacked
1221  // dim is not a broadcast, so no mask is needed on the new transfer op.
1222  // `generateInBoundsCheck` will have evaluated the mask already.
1223 }
1224 
1225 /// Progressive lowering of vector TransferReadOp with unrolling: Unpack one
1226 /// dimension. This is similar to TransferOpConversion<TransferReadOp>, but no
1227 /// memref buffer is allocated and the SCF loop is fully unrolled.
1228 ///
1229 /// ```
1230 /// E.g.:
1231 /// ```
1232 /// %vec = vector.transfer_read %A[%a, %b, %c], %padding
1233 /// : memref<?x?x?xf32>, vector<5x4xf32>
1234 /// ```
1235 /// is rewritten to IR such as (simplified):
1236 /// ```
1237 /// %v_init = splat %padding : vector<5x4xf32>
1238 /// %tmp0 = vector.transfer_read %A[%a, %b, %c], %padding
1239 /// : memref<?x?x?xf32>, vector<4xf32>
1240 /// %v0 = vector.insert %tmp0, %v_init[0] : vector<4xf32> into vector<5x4xf32>
1241 /// %tmp1 = vector.transfer_read %A[%a, %b + 1, %c], %padding
1242 /// : memref<?x?x?xf32>, vector<4xf32>
1243 /// %v1 = vector.insert %tmp1, %v0[1] : vector<4xf32> into vector<5x4xf32>
1244 /// ...
1245 /// %tmp4 = vector.transfer_read %A[%a, %b + 4, %c], %padding
1246 /// : memref<?x?x?xf32>, vector<4xf32>
1247 /// %vec = vector.insert %tmp1, %v3[4] : vector<4xf32> into vector<5x4xf32>
1248 /// ```
1249 ///
1250 /// Note: As an optimization, if the result of the original TransferReadOp
1251 /// was directly inserted into another vector, no new %v_init vector is created.
1252 /// Instead, the new TransferReadOp results are inserted into that vector.
1253 struct UnrollTransferReadConversion
1254  : public VectorToSCFPattern<TransferReadOp> {
1255  using VectorToSCFPattern<TransferReadOp>::VectorToSCFPattern;
1256 
1257  void initialize() {
1258  // This pattern recursively unpacks one dimension at a time. The recursion
1259  // bounded as the rank is strictly decreasing.
1260  setHasBoundedRewriteRecursion();
1261  }
1262 
1263  /// Get or build the vector into which the newly created TransferReadOp
1264  /// results are inserted.
1265  Value buildResultVector(PatternRewriter &rewriter,
1266  TransferReadOp xferOp) const {
1267  if (auto insertOp = getInsertOp(xferOp))
1268  return insertOp.getDest();
1269  Location loc = xferOp.getLoc();
1270  return rewriter.create<vector::SplatOp>(loc, xferOp.getVectorType(),
1271  xferOp.getPadding());
1272  }
1273 
1274  /// If the result of the TransferReadOp has exactly one user, which is a
1275  /// vector::InsertOp, return that operation.
1276  vector::InsertOp getInsertOp(TransferReadOp xferOp) const {
1277  if (xferOp->hasOneUse()) {
1278  Operation *xferOpUser = *xferOp->getUsers().begin();
1279  if (auto insertOp = dyn_cast<vector::InsertOp>(xferOpUser))
1280  return insertOp;
1281  }
1282 
1283  return vector::InsertOp();
1284  }
1285 
1286  /// If the result of the TransferReadOp has exactly one user, which is a
1287  /// vector::InsertOp, return that operation's indices.
1288  void getInsertionIndices(TransferReadOp xferOp,
1289  SmallVectorImpl<OpFoldResult> &indices) const {
1290  if (auto insertOp = getInsertOp(xferOp)) {
1291  auto pos = insertOp.getMixedPosition();
1292  indices.append(pos.begin(), pos.end());
1293  }
1294  }
1295 
1296  /// Rewrite the op: Unpack one dimension. Can handle masks, out-of-bounds
1297  /// accesses, and broadcasts and transposes in permutation maps.
1298  LogicalResult matchAndRewrite(TransferReadOp xferOp,
1299  PatternRewriter &rewriter) const override {
1300  if (xferOp.getVectorType().getRank() <= options.targetRank)
1301  return rewriter.notifyMatchFailure(
1302  xferOp, "vector rank is less or equal to target rank");
1303  if (failed(checkLowerTensors(xferOp, rewriter)))
1304  return failure();
1305  if (xferOp.getVectorType().getElementType() !=
1306  xferOp.getShapedType().getElementType())
1307  return rewriter.notifyMatchFailure(
1308  xferOp, "not yet supported: element type mismatch");
1309  auto xferVecType = xferOp.getVectorType();
1310  if (xferVecType.getScalableDims()[0]) {
1311  return rewriter.notifyMatchFailure(
1312  xferOp, "scalable dimensions cannot be unrolled at compile time");
1313  }
1314 
1315  auto insertOp = getInsertOp(xferOp);
1316  auto vec = buildResultVector(rewriter, xferOp);
1317  auto vecType = dyn_cast<VectorType>(vec.getType());
1318 
1319  VectorType newXferVecType = VectorType::Builder(xferVecType).dropDim(0);
1320 
1321  int64_t dimSize = xferVecType.getShape()[0];
1322 
1323  // Generate fully unrolled loop of transfer ops.
1324  Location loc = xferOp.getLoc();
1325  for (int64_t i = 0; i < dimSize; ++i) {
1326  Value iv = rewriter.create<arith::ConstantIndexOp>(loc, i);
1327 
1328  vec = generateInBoundsCheck(
1329  rewriter, xferOp, iv, unpackedDim(xferOp), TypeRange(vecType),
1330  /*inBoundsCase=*/
1331  [&](OpBuilder &b, Location loc) {
1332  // Indices for the new transfer op.
1333  SmallVector<Value, 8> xferIndices;
1334  getXferIndices(b, xferOp, iv, xferIndices);
1335 
1336  // Indices for the new vector.insert op.
1337  SmallVector<OpFoldResult, 8> insertionIndices;
1338  getInsertionIndices(xferOp, insertionIndices);
1339  insertionIndices.push_back(rewriter.getIndexAttr(i));
1340 
1341  auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
1342  auto newXferOp = b.create<vector::TransferReadOp>(
1343  loc, newXferVecType, xferOp.getSource(), xferIndices,
1344  AffineMapAttr::get(unpackedPermutationMap(b, xferOp)),
1345  xferOp.getPadding(), Value(), inBoundsAttr);
1346  maybeAssignMask(b, xferOp, newXferOp, i);
1347  return b.create<vector::InsertOp>(loc, newXferOp, vec,
1348  insertionIndices);
1349  },
1350  /*outOfBoundsCase=*/
1351  [&](OpBuilder &b, Location loc) {
1352  // Loop through original (unmodified) vector.
1353  return vec;
1354  });
1355  }
1356 
1357  if (insertOp) {
1358  // Rewrite single user of the old TransferReadOp, which was an InsertOp.
1359  rewriter.replaceOp(insertOp, vec);
1360  rewriter.eraseOp(xferOp);
1361  } else {
1362  rewriter.replaceOp(xferOp, vec);
1363  }
1364 
1365  return success();
1366  }
1367 };
1368 
1369 /// Progressive lowering of vector TransferWriteOp with unrolling: Unpack one
1370 /// dimension. This is similar to TransferOpConversion<TransferWriteOp>, but no
1371 /// memref buffer is allocated and the SCF loop is fully unrolled.
1372 ///
1373 /// ```
1374 /// E.g.:
1375 /// ```
1376 /// vector.transfer_write %vec, %A[%a, %b, %c]
1377 /// : vector<5x4xf32>, memref<?x?x?xf32>
1378 /// ```
1379 /// is rewritten to IR such as (simplified):
1380 /// ```
1381 /// %v0 = vector.extract %vec[0] : vector<4xf32> from vector<5x4xf32>
1382 /// vector.transfer_write %v0, %A[%a, %b, %c] : vector<4xf32>, memref<...>
1383 /// %v1 = vector.extract %vec[1] : vector<4xf32> from vector<5x4xf32>
1384 /// vector.transfer_write %v1, %A[%a, %b + 1, %c] : vector<4xf32>, memref<...>
1385 /// ...
1386 /// %v4 = vector.extract %vec[4] : vector<4xf32> from vector<5x4xf32>
1387 /// vector.transfer_write %v4, %A[%a, %b + 4, %c] : vector<4xf32>, memref<...>
1388 /// ```
1389 ///
1390 /// Note: As an optimization, if the vector of the original TransferWriteOp
1391 /// was directly extracted from another vector via an ExtractOp `a`, extract
1392 /// the vectors for the newly generated TransferWriteOps from `a`'s input. By
1393 /// doing so, `a` may become dead, and the number of ExtractOps generated during
1394 /// recursive application of this pattern will be minimal.
1395 struct UnrollTransferWriteConversion
1396  : public VectorToSCFPattern<TransferWriteOp> {
1397  using VectorToSCFPattern<TransferWriteOp>::VectorToSCFPattern;
1398 
1399  void initialize() {
1400  // This pattern recursively unpacks one dimension at a time. The recursion
1401  // bounded as the rank is strictly decreasing.
1402  setHasBoundedRewriteRecursion();
1403  }
1404 
1405  /// Return the vector from which newly generated ExtracOps will extract.
1406  Value getDataVector(TransferWriteOp xferOp) const {
1407  if (auto extractOp = getExtractOp(xferOp))
1408  return extractOp.getVector();
1409  return xferOp.getVector();
1410  }
1411 
1412  /// If the input of the given TransferWriteOp is an ExtractOp, return it.
1413  vector::ExtractOp getExtractOp(TransferWriteOp xferOp) const {
1414  if (auto *op = xferOp.getVector().getDefiningOp())
1415  return dyn_cast<vector::ExtractOp>(op);
1416  return vector::ExtractOp();
1417  }
1418 
1419  /// If the input of the given TransferWriteOp is an ExtractOp, return its
1420  /// indices.
1421  void getExtractionIndices(TransferWriteOp xferOp,
1422  SmallVectorImpl<OpFoldResult> &indices) const {
1423  if (auto extractOp = getExtractOp(xferOp)) {
1424  auto pos = extractOp.getMixedPosition();
1425  indices.append(pos.begin(), pos.end());
1426  }
1427  }
1428 
1429  /// Rewrite the op: Unpack one dimension. Can handle masks, out-of-bounds
1430  /// accesses, and broadcasts and transposes in permutation maps.
1431  LogicalResult matchAndRewrite(TransferWriteOp xferOp,
1432  PatternRewriter &rewriter) const override {
1433  VectorType inputVectorTy = xferOp.getVectorType();
1434 
1435  if (inputVectorTy.getRank() <= options.targetRank)
1436  return failure();
1437 
1438  if (failed(checkLowerTensors(xferOp, rewriter)))
1439  return failure();
1440  // Transfer ops that modify the element type are not supported atm.
1441  if (inputVectorTy.getElementType() !=
1442  xferOp.getShapedType().getElementType())
1443  return failure();
1444 
1445  auto vec = getDataVector(xferOp);
1446  if (inputVectorTy.getScalableDims()[0]) {
1447  // Cannot unroll a scalable dimension at compile time.
1448  return failure();
1449  }
1450 
1451  int64_t dimSize = inputVectorTy.getShape()[0];
1452  Value source = xferOp.getSource(); // memref or tensor to be written to.
1453  auto sourceType = isTensorOp(xferOp) ? xferOp.getShapedType() : Type();
1454 
1455  // Generate fully unrolled loop of transfer ops.
1456  Location loc = xferOp.getLoc();
1457  for (int64_t i = 0; i < dimSize; ++i) {
1458  Value iv = rewriter.create<arith::ConstantIndexOp>(loc, i);
1459 
1460  auto updatedSource = generateInBoundsCheck(
1461  rewriter, xferOp, iv, unpackedDim(xferOp),
1462  isTensorOp(xferOp) ? TypeRange(sourceType) : TypeRange(),
1463  /*inBoundsCase=*/
1464  [&](OpBuilder &b, Location loc) {
1465  // Indices for the new transfer op.
1466  SmallVector<Value, 8> xferIndices;
1467  getXferIndices(b, xferOp, iv, xferIndices);
1468 
1469  // Indices for the new vector.extract op.
1470  SmallVector<OpFoldResult, 8> extractionIndices;
1471  getExtractionIndices(xferOp, extractionIndices);
1472  extractionIndices.push_back(b.getI64IntegerAttr(i));
1473 
1474  auto extracted =
1475  b.create<vector::ExtractOp>(loc, vec, extractionIndices);
1476  auto inBoundsAttr = dropFirstElem(b, xferOp.getInBoundsAttr());
1477  Value xferVec;
1478  if (inputVectorTy.getRank() == 1) {
1479  // When target-rank=0, unrolling would causes the vector input
1480  // argument into `transfer_write` to become a scalar. We solve
1481  // this by broadcasting the scalar to a 0D vector.
1482  xferVec = b.create<vector::BroadcastOp>(
1483  loc, VectorType::get({}, extracted.getType()), extracted);
1484  } else {
1485  xferVec = extracted;
1486  }
1487  auto newXferOp = b.create<vector::TransferWriteOp>(
1488  loc, sourceType, xferVec, source, xferIndices,
1489  AffineMapAttr::get(unpackedPermutationMap(b, xferOp)), Value(),
1490  inBoundsAttr);
1491 
1492  maybeAssignMask(b, xferOp, newXferOp, i);
1493 
1494  return isTensorOp(xferOp) ? newXferOp->getResult(0) : Value();
1495  },
1496  /*outOfBoundsCase=*/
1497  [&](OpBuilder &b, Location loc) {
1498  return isTensorOp(xferOp) ? source : Value();
1499  });
1500 
1501  if (isTensorOp(xferOp))
1502  source = updatedSource;
1503  }
1504 
1505  if (isTensorOp(xferOp))
1506  rewriter.replaceOp(xferOp, source);
1507  else
1508  rewriter.eraseOp(xferOp);
1509 
1510  return success();
1511  }
1512 };
1513 
1514 } // namespace lowering_n_d_unrolled
1515 
1516 namespace lowering_1_d {
1517 
1518 /// Compute the indices into the memref for the LoadOp/StoreOp generated as
1519 /// part of TransferOp1dConversion. Return the memref dimension on which
1520 /// the transfer is operating. A return value of std::nullopt indicates a
1521 /// broadcast.
1522 template <typename OpTy>
1523 static std::optional<int64_t>
1524 get1dMemrefIndices(OpBuilder &b, OpTy xferOp, Value iv,
1525  SmallVector<Value, 8> &memrefIndices) {
1526  auto indices = xferOp.getIndices();
1527  auto map = xferOp.getPermutationMap();
1528  assert(xferOp.getTransferRank() > 0 && "unexpected 0-d transfer");
1529 
1530  memrefIndices.append(indices.begin(), indices.end());
1531  assert(map.getNumResults() == 1 &&
1532  "Expected 1 permutation map result for 1D transfer");
1533  if (auto expr = dyn_cast<AffineDimExpr>(map.getResult(0))) {
1534  Location loc = xferOp.getLoc();
1535  auto dim = expr.getPosition();
1536  AffineExpr d0, d1;
1537  bindDims(xferOp.getContext(), d0, d1);
1538  Value offset = memrefIndices[dim];
1539  memrefIndices[dim] =
1540  affine::makeComposedAffineApply(b, loc, d0 + d1, {offset, iv});
1541  return dim;
1542  }
1543 
1544  assert(xferOp.isBroadcastDim(0) &&
1545  "Expected AffineDimExpr or AffineConstantExpr");
1546  return std::nullopt;
1547 }
1548 
1549 /// Codegen strategy for TransferOp1dConversion, depending on the
1550 /// operation.
1551 template <typename OpTy>
1552 struct Strategy1d;
1553 
1554 /// Codegen strategy for TransferReadOp.
1555 template <>
1556 struct Strategy1d<TransferReadOp> {
1557  static void generateForLoopBody(OpBuilder &b, Location loc,
1558  TransferReadOp xferOp, Value iv,
1559  ValueRange loopState) {
1560  SmallVector<Value, 8> indices;
1561  auto dim = get1dMemrefIndices(b, xferOp, iv, indices);
1562  auto vec = loopState[0];
1563 
1564  // In case of out-of-bounds access, leave `vec` as is (was initialized with
1565  // padding value).
1566  auto nextVec = generateInBoundsCheck(
1567  b, xferOp, iv, dim, TypeRange(xferOp.getVectorType()),
1568  /*inBoundsCase=*/
1569  [&](OpBuilder &b, Location loc) {
1570  Value val =
1571  b.create<memref::LoadOp>(loc, xferOp.getSource(), indices);
1572  return b.create<vector::InsertElementOp>(loc, val, vec, iv);
1573  },
1574  /*outOfBoundsCase=*/
1575  [&](OpBuilder & /*b*/, Location loc) { return vec; });
1576  b.create<scf::YieldOp>(loc, nextVec);
1577  }
1578 
1579  static Value initialLoopState(OpBuilder &b, TransferReadOp xferOp) {
1580  // Inititalize vector with padding value.
1581  Location loc = xferOp.getLoc();
1582  return b.create<vector::SplatOp>(loc, xferOp.getVectorType(),
1583  xferOp.getPadding());
1584  }
1585 };
1586 
1587 /// Codegen strategy for TransferWriteOp.
1588 template <>
1589 struct Strategy1d<TransferWriteOp> {
1590  static void generateForLoopBody(OpBuilder &b, Location loc,
1591  TransferWriteOp xferOp, Value iv,
1592  ValueRange /*loopState*/) {
1593  SmallVector<Value, 8> indices;
1594  auto dim = get1dMemrefIndices(b, xferOp, iv, indices);
1595 
1596  // Nothing to do in case of out-of-bounds access.
1597  generateInBoundsCheck(
1598  b, xferOp, iv, dim,
1599  /*inBoundsCase=*/[&](OpBuilder &b, Location loc) {
1600  auto val =
1601  b.create<vector::ExtractElementOp>(loc, xferOp.getVector(), iv);
1602  b.create<memref::StoreOp>(loc, val, xferOp.getSource(), indices);
1603  });
1604  b.create<scf::YieldOp>(loc);
1605  }
1606 
1607  static Value initialLoopState(OpBuilder &b, TransferWriteOp xferOp) {
1608  return Value();
1609  }
1610 };
1611 
1612 /// Lower a 1D vector transfer op to SCF using scalar loads/stores. This is
1613 /// necessary in cases where a 1D vector transfer op cannot be lowered into
1614 /// vector load/stores due to non-unit strides or broadcasts:
1615 ///
1616 /// * Transfer dimension is not the last memref dimension
1617 /// * Transfer dimension is a broadcast (i.e., scalar load + broadcast)
1618 /// * Memref has a layout map with non-unit stride on the last dimension
1619 ///
1620 /// This pattern generates IR as follows:
1621 ///
1622 /// 1. Generate a for loop iterating over each vector element.
1623 /// 2. Inside the loop, generate a InsertElementOp or ExtractElementOp,
1624 /// depending on OpTy.
1625 ///
1626 /// TODO: In some cases (no masking, etc.), LLVM::MatrixColumnMajorLoadOp
1627 /// can be generated instead of TransferOp1dConversion. Add such a pattern
1628 /// to ConvertVectorToLLVM.
1629 ///
1630 /// E.g.:
1631 /// ```
1632 /// vector.transfer_write %vec, %A[%a, %b]
1633 /// {permutation_map = affine_map<(d0, d1) -> (d0)>, in_bounds = [true]}
1634 /// : vector<9xf32>, memref<?x?xf32>
1635 /// ```
1636 /// Is rewritten to approximately the following pseudo-IR:
1637 /// ```
1638 /// for i = 0 to 9 {
1639 /// %t = vector.extractelement %vec[i] : vector<9xf32>
1640 /// memref.store %t, %arg0[%a + i, %b] : memref<?x?xf32>
1641 /// }
1642 /// ```
1643 template <typename OpTy>
1644 struct TransferOp1dConversion : public VectorToSCFPattern<OpTy> {
1645  using VectorToSCFPattern<OpTy>::VectorToSCFPattern;
1646 
1647  LogicalResult matchAndRewrite(OpTy xferOp,
1648  PatternRewriter &rewriter) const override {
1649  // TODO: support 0-d corner case.
1650  if (xferOp.getTransferRank() == 0)
1651  return failure();
1652  auto map = xferOp.getPermutationMap();
1653  auto memRefType = dyn_cast<MemRefType>(xferOp.getShapedType());
1654 
1655  if (!memRefType)
1656  return failure();
1657  if (xferOp.getVectorType().getRank() != 1)
1658  return failure();
1659  if (map.isMinorIdentity() && memRefType.isLastDimUnitStride())
1660  return failure(); // Handled by ConvertVectorToLLVM
1661 
1662  // Loop bounds, step, state...
1663  Location loc = xferOp.getLoc();
1664  auto vecType = xferOp.getVectorType();
1665  auto lb = rewriter.create<arith::ConstantIndexOp>(loc, 0);
1666  Value ub =
1667  rewriter.create<arith::ConstantIndexOp>(loc, vecType.getDimSize(0));
1668  if (vecType.isScalable()) {
1669  Value vscale =
1670  rewriter.create<vector::VectorScaleOp>(loc, rewriter.getIndexType());
1671  ub = rewriter.create<arith::MulIOp>(loc, ub, vscale);
1672  }
1673  auto step = rewriter.create<arith::ConstantIndexOp>(loc, 1);
1674  auto loopState = Strategy1d<OpTy>::initialLoopState(rewriter, xferOp);
1675 
1676  // Generate for loop.
1677  rewriter.replaceOpWithNewOp<scf::ForOp>(
1678  xferOp, lb, ub, step, loopState ? ValueRange(loopState) : ValueRange(),
1679  [&](OpBuilder &b, Location loc, Value iv, ValueRange loopState) {
1680  Strategy1d<OpTy>::generateForLoopBody(b, loc, xferOp, iv, loopState);
1681  });
1682 
1683  return success();
1684  }
1685 };
1686 
1687 } // namespace lowering_1_d
1688 } // namespace
1689 
1692  if (options.unroll) {
1693  patterns.add<lowering_n_d_unrolled::UnrollTransferReadConversion,
1694  lowering_n_d_unrolled::UnrollTransferWriteConversion>(
1695  patterns.getContext(), options);
1696  } else {
1697  patterns.add<lowering_n_d::PrepareTransferReadConversion,
1698  lowering_n_d::PrepareTransferWriteConversion,
1699  lowering_n_d::TransferOpConversion<TransferReadOp>,
1700  lowering_n_d::TransferOpConversion<TransferWriteOp>>(
1701  patterns.getContext(), options);
1702  }
1703  if (options.lowerScalable) {
1704  patterns.add<lowering_n_d::ScalableTransposeTransferWriteConversion>(
1705  patterns.getContext(), options);
1706  }
1707  if (options.targetRank == 1) {
1708  patterns.add<lowering_1_d::TransferOp1dConversion<TransferReadOp>,
1709  lowering_1_d::TransferOp1dConversion<TransferWriteOp>>(
1710  patterns.getContext(), options);
1711  }
1712  patterns.add<lowering_n_d::DecomposePrintOpConversion>(patterns.getContext(),
1713  options);
1714 }
1715 
1716 namespace {
1717 
1718 struct ConvertVectorToSCFPass
1719  : public impl::ConvertVectorToSCFBase<ConvertVectorToSCFPass> {
1720  ConvertVectorToSCFPass() = default;
1721  ConvertVectorToSCFPass(const VectorTransferToSCFOptions &options) {
1722  this->fullUnroll = options.unroll;
1723  this->targetRank = options.targetRank;
1724  this->lowerTensors = options.lowerTensors;
1725  this->lowerScalable = options.lowerScalable;
1726  }
1727 
1728  void runOnOperation() override {
1730  options.unroll = fullUnroll;
1731  options.targetRank = targetRank;
1732  options.lowerTensors = lowerTensors;
1733  options.lowerScalable = lowerScalable;
1734 
1735  // Lower permutation maps first.
1736  RewritePatternSet lowerTransferPatterns(&getContext());
1738  lowerTransferPatterns);
1739  (void)applyPatternsGreedily(getOperation(),
1740  std::move(lowerTransferPatterns));
1741 
1744  (void)applyPatternsGreedily(getOperation(), std::move(patterns));
1745  }
1746 };
1747 
1748 } // namespace
1749 
1750 std::unique_ptr<Pass>
1752  return std::make_unique<ConvertVectorToSCFPass>(options);
1753 }
MLIR_CRUNNERUTILS_EXPORT void printClose()
static MLIRContext * getContext(OpFoldResult val)
static llvm::ManagedStatic< PassManagerOptions > options
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static void printOp(llvm::raw_ostream &os, Operation *op, OpPrintingFlags &flags)
Definition: Unit.cpp:19
static void getXferIndices(RewriterBase &rewriter, TransferOpType xferOp, AffineMap offsetMap, ArrayRef< Value > dimValues, SmallVector< Value, 4 > &indices)
For a vector TransferOpType xferOp, an empty indices vector, and an AffineMap representing offsets to...
Definition: VectorToGPU.cpp:57
static Operation * getAutomaticAllocationScope(Operation *op)
Base type for affine expression.
Definition: AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:104
UnitAttr getUnitAttr()
Definition: Builders.cpp:94
IntegerAttr getI64IntegerAttr(int64_t value)
Definition: Builders.cpp:108
MLIRContext * getContext() const
Definition: Builders.h:56
IntegerType getI1Type()
Definition: Builders.cpp:53
IndexType getIndexType()
Definition: Builders.cpp:51
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
OpTy create(Args &&...args)
Create an operation of specific op type at the current insertion point and location.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:346
This class helps build Operations.
Definition: Builders.h:205
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition: Builders.cpp:544
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:429
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:396
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:453
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition: Builders.h:410
A trait of region holding operations that define a new scope for automatic allocations,...
This class implements the operand iterators for the Operation class.
Definition: ValueRange.h:42
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
unsigned getNumRegions()
Returns the number of regions held by this operation.
Definition: Operation.h:674
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition: Operation.h:687
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition: Operation.h:582
Operation * getParentWithTrait()
Returns the closest surrounding parent operation with trait Trait.
Definition: Operation.h:248
user_range getUsers()
Returns a range of all users.
Definition: Operation.h:874
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Definition: PatternMatch.h:803
Block & front()
Definition: Region.h:65
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
Definition: PatternMatch.h:736
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
Definition: PatternMatch.h:648
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:554
This class provides an abstraction over the various different ranges of value types.
Definition: TypeRange.h:36
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:381
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
MLIRContext * getContext() const
Utility to get the associated MLIRContext that this value is defined in.
Definition: Value.h:132
Type getType() const
Return the type of this value.
Definition: Value.h:129
user_range getUsers() const
Definition: Value.h:228
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:20
This is a builder type that keeps local references to arguments.
Definition: BuiltinTypes.h:270
Builder & dropDim(unsigned pos)
Erase a dim from shape @pos.
Definition: BuiltinTypes.h:295
AffineApplyOp makeComposedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands)
Returns a composed AffineApplyOp by composing map and operands with other AffineApplyOps supplying th...
Definition: AffineOps.cpp:1158
FailureOr< Value > getBuffer(RewriterBase &rewriter, Value value, const BufferizationOptions &options)
Lookup the buffer for the given value.
void populateVectorTransferPermutationMapLoweringPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of transfer read/write lowering patterns that simplify the permutation map (e....
Value createOrFoldDimOp(OpBuilder &b, Location loc, Value source, int64_t dim)
Helper function that creates a memref::DimOp or tensor::DimOp depending on the type of source.
Definition: VectorUtils.cpp:41
SmallVector< Value > getAsValues(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > foldResults)
Convert foldResults into Values.
Definition: VectorOps.cpp:338
auto makeVscaleConstantBuilder(PatternRewriter &rewriter, Location loc)
Returns a functor (int64_t -> Value) which returns a constant vscale multiple.
Definition: VectorUtils.h:113
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition: Utils.cpp:305
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition: AffineExpr.h:348
LogicalResult applyPatternsGreedily(Region &region, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
const FrozenRewritePatternSet & patterns
void populateVectorToSCFConversionPatterns(RewritePatternSet &patterns, const VectorTransferToSCFOptions &options=VectorTransferToSCFOptions())
Collect a set of patterns to convert from the Vector dialect to SCF + func.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
std::unique_ptr< Pass > createConvertVectorToSCFPass(const VectorTransferToSCFOptions &options=VectorTransferToSCFOptions())
Create a pass to convert a subset of vector ops to SCF.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
Definition: PatternMatch.h:358
When lowering an N-d vector transfer op to an (N-1)-d vector transfer op, a temporary buffer is creat...
Definition: VectorToSCF.h:52