xref: /llvm-project/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp (revision 136d746ec7f43584f68c11d3ccc4088db4734d29)
1 //===- Promotion.cpp - Implementation of linalg Promotion -----------------===//
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 the linalg dialect Promotion pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
15 #include "mlir/Dialect/Complex/IR/Complex.h"
16 #include "mlir/Dialect/Linalg/IR/Linalg.h"
17 #include "mlir/Dialect/Linalg/Passes.h"
18 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
19 #include "mlir/Dialect/Linalg/Utils/Utils.h"
20 #include "mlir/Dialect/SCF/IR/SCF.h"
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/AffineExprVisitor.h"
23 #include "mlir/IR/AffineMap.h"
24 #include "mlir/IR/ImplicitLocOpBuilder.h"
25 #include "mlir/Support/LLVM.h"
26 #include "mlir/Transforms/FoldUtils.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/TypeSwitch.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 
33 using namespace mlir;
34 using namespace mlir::linalg;
35 using namespace mlir::scf;
36 
37 using llvm::MapVector;
38 
39 #define DEBUG_TYPE "linalg-promotion"
40 
41 /// Alloc a new buffer of `size` * `width` i8; where `width` is given by the
42 /// data `layout` for `elementType`.
43 /// Use AllocOp or AllocaOp depending on `options`.
44 /// Take an optional alignment.
45 static Value allocBuffer(ImplicitLocOpBuilder &b,
46                          const LinalgPromotionOptions &options,
47                          Type elementType, Value allocSize, DataLayout &layout,
48                          Optional<unsigned> alignment = None) {
49   auto width = layout.getTypeSize(elementType);
50 
51   IntegerAttr alignmentAttr;
52   if (alignment.hasValue())
53     alignmentAttr = b.getI64IntegerAttr(alignment.getValue());
54 
55   // Static buffer.
56   if (auto cst = allocSize.getDefiningOp<arith::ConstantIndexOp>()) {
57     auto staticBufferType =
58         MemRefType::get(width * cst.value(), b.getIntegerType(8));
59     if (options.useAlloca) {
60       return b.createOrFold<memref::AllocaOp>(staticBufferType, ValueRange{},
61                                               alignmentAttr);
62     }
63     return b.createOrFold<memref::AllocOp>(staticBufferType, ValueRange{},
64                                            alignmentAttr);
65   }
66 
67   // Fallback dynamic buffer.
68   auto dynamicBufferType = MemRefType::get(-1, b.getIntegerType(8));
69   Value mul = b.createOrFold<arith::MulIOp>(
70       b.create<arith::ConstantIndexOp>(width), allocSize);
71   if (options.useAlloca)
72     return b.create<memref::AllocaOp>(dynamicBufferType, mul, alignmentAttr);
73   return b.create<memref::AllocOp>(dynamicBufferType, mul, alignmentAttr);
74 }
75 
76 /// Default allocation callback function. This allocates a promoted buffer when
77 /// no call back to do so is provided. The default is to allocate a
78 /// memref<..xi8> and return a view to get a memref type of shape
79 /// boundingSubViewSize.
80 static Optional<Value>
81 defaultAllocBufferCallBack(const LinalgPromotionOptions &options,
82                            OpBuilder &builder, memref::SubViewOp subView,
83                            ArrayRef<Value> boundingSubViewSize,
84                            Optional<unsigned> alignment, DataLayout &layout) {
85   ShapedType viewType = subView.getType();
86   ImplicitLocOpBuilder b(subView.getLoc(), builder);
87   auto zero = b.createOrFold<arith::ConstantIndexOp>(0);
88   auto one = b.createOrFold<arith::ConstantIndexOp>(1);
89 
90   Value allocSize = one;
91   for (const auto &size : llvm::enumerate(boundingSubViewSize))
92     allocSize = b.createOrFold<arith::MulIOp>(allocSize, size.value());
93   Value buffer = allocBuffer(b, options, viewType.getElementType(), allocSize,
94                              layout, alignment);
95   SmallVector<int64_t, 4> dynSizes(boundingSubViewSize.size(),
96                                    ShapedType::kDynamicSize);
97   Value view = b.createOrFold<memref::ViewOp>(
98       MemRefType::get(dynSizes, viewType.getElementType()), buffer, zero,
99       boundingSubViewSize);
100   return view;
101 }
102 
103 /// Default implementation of deallocation of the buffer use for promotion. It
104 /// expects to get the same value that the default allocation method returned,
105 /// i.e. result of a ViewOp.
106 static LogicalResult
107 defaultDeallocBufferCallBack(const LinalgPromotionOptions &options,
108                              OpBuilder &b, Value fullLocalView) {
109   if (!options.useAlloca) {
110     auto viewOp = cast<memref::ViewOp>(fullLocalView.getDefiningOp());
111     b.create<memref::DeallocOp>(viewOp.getSource().getLoc(),
112                                 viewOp.getSource());
113   }
114   return success();
115 }
116 
117 namespace {
118 
119 /// Helper struct that captures the information required to apply the
120 /// transformation on each op. This bridges the abstraction gap with the
121 /// user-facing API which exposes positional arguments to control which operands
122 /// are promoted.
123 struct LinalgOpInstancePromotionOptions {
124   LinalgOpInstancePromotionOptions(LinalgOp op,
125                                    const LinalgPromotionOptions &options);
126   /// SubViews to promote.
127   MapVector<int64_t, Value> subViews;
128   /// True if the full view should be used for the promoted buffer.
129   DenseMap<Value, bool> useFullTileBuffers;
130 
131   /// Callback functions for allocation and deallocation of promoted buffers, as
132   /// well as to copy the data into and out of these buffers.
133   AllocBufferCallbackFn allocationFn;
134   DeallocBufferCallbackFn deallocationFn;
135   CopyCallbackFn copyInFn;
136   CopyCallbackFn copyOutFn;
137 
138   /// Allow the use of dynamically-sized buffers.
139   bool dynamicBuffers;
140 
141   /// Alignment of promoted buffer.
142   Optional<unsigned> alignment;
143 };
144 } // namespace
145 
146 LinalgOpInstancePromotionOptions::LinalgOpInstancePromotionOptions(
147     LinalgOp linalgOp, const LinalgPromotionOptions &options)
148     : subViews(), dynamicBuffers(options.dynamicBuffers),
149       alignment(options.alignment) {
150   assert(linalgOp.hasBufferSemantics() && "revisit usage of shaped operand");
151   auto vUseFullTileBuffers =
152       options.useFullTileBuffers.value_or(llvm::SmallBitVector());
153   vUseFullTileBuffers.resize(linalgOp.getNumInputsAndOutputs(),
154                              options.useFullTileBuffersDefault);
155 
156   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
157     int64_t operandNumber = opOperand->getOperandNumber();
158     if (options.operandsToPromote &&
159         !options.operandsToPromote->count(operandNumber))
160       continue;
161     Operation *op = opOperand->get().getDefiningOp();
162     if (auto sv = dyn_cast_or_null<memref::SubViewOp>(op)) {
163       subViews[operandNumber] = sv;
164       useFullTileBuffers[sv] = vUseFullTileBuffers[operandNumber];
165     }
166   }
167 
168   if (options.allocationFn) {
169     allocationFn = *options.allocationFn;
170   } else {
171     allocationFn = [&](OpBuilder &b, memref::SubViewOp subViewOp,
172                        ArrayRef<Value> boundingSubViewSize,
173                        DataLayout &layout) -> Optional<Value> {
174       return defaultAllocBufferCallBack(options, b, subViewOp,
175                                         boundingSubViewSize, alignment, layout);
176     };
177   }
178 
179   if (options.deallocationFn) {
180     deallocationFn = *options.deallocationFn;
181   } else {
182     deallocationFn = [&](OpBuilder &b, Value buffer) {
183       return defaultDeallocBufferCallBack(options, b, buffer);
184     };
185   }
186 
187   // Save the loc because `linalgOp` goes out of scope.
188   Location loc = linalgOp.getLoc();
189   auto defaultCopyCallBack = [loc](OpBuilder &b, Value src,
190                                    Value dst) -> LogicalResult {
191     b.create<memref::CopyOp>(loc, src, dst);
192     return success();
193   };
194   copyInFn = (options.copyInFn ? *(options.copyInFn) : defaultCopyCallBack);
195   copyOutFn = (options.copyOutFn ? *(options.copyOutFn) : defaultCopyCallBack);
196 }
197 
198 // Performs promotion of a `subView` into a local buffer of the size of the
199 // *ranges* of the `subView`. This produces a buffer whose size may be bigger
200 // than the actual size of the `subView` at the boundaries.
201 // This is related to the full/partial tile problem.
202 // Returns a PromotionInfo containing a `buffer`, `fullLocalView` and
203 // `partialLocalView` such that:
204 //   * `buffer` is always the size of the full tile.
205 //   * `fullLocalView` is a dense contiguous view into that buffer.
206 //   * `partialLocalView` is a dense non-contiguous slice of `fullLocalView`
207 //     that corresponds to the size of `subView` and accounting for boundary
208 //     effects.
209 // The point of the full tile buffer is that constant static tile sizes are
210 // folded and result in a buffer type with statically known size and alignment
211 // properties.
212 // To account for general boundary effects, padding must be performed on the
213 // boundary tiles. For now this is done with an unconditional `fill` op followed
214 // by a partial `copy` op.
215 FailureOr<PromotionInfo> mlir::linalg::promoteSubviewAsNewBuffer(
216     OpBuilder &b, Location loc, memref::SubViewOp subView,
217     const AllocBufferCallbackFn &allocationFn, DataLayout &layout) {
218   auto viewType = subView.getType();
219   auto rank = viewType.getRank();
220   SmallVector<Value, 4> fullSizes;
221   SmallVector<OpFoldResult> partialSizes;
222   fullSizes.reserve(rank);
223   partialSizes.reserve(rank);
224   llvm::SmallBitVector droppedDims = subView.getDroppedDims();
225   int64_t resultDimIdx = 0;
226   for (const auto &en : llvm::enumerate(subView.getOrCreateRanges(b, loc))) {
227     if (droppedDims[en.index()])
228       continue;
229     auto rangeValue = en.value();
230     // Try to extract a tight constant.
231     LLVM_DEBUG(llvm::dbgs() << "Extract tightest: " << rangeValue.size << "\n");
232     FailureOr<int64_t> upperBound =
233         getConstantUpperBoundForIndex(rangeValue.size);
234     Value size =
235         failed(upperBound)
236             ? rangeValue.size
237             : b.create<arith::ConstantIndexOp>(loc, upperBound.getValue());
238     LLVM_DEBUG(llvm::dbgs() << "Extracted tightest: " << size << "\n");
239     fullSizes.push_back(size);
240     partialSizes.push_back(
241         b.createOrFold<memref::DimOp>(loc, subView, resultDimIdx++));
242   }
243   SmallVector<int64_t, 4> dynSizes(fullSizes.size(), -1);
244   // If a callback is not specified, then use the default implementation for
245   // allocating the promoted buffer.
246   Optional<Value> fullLocalView = allocationFn(b, subView, fullSizes, layout);
247   if (!fullLocalView)
248     return failure();
249   SmallVector<OpFoldResult, 4> zeros(fullSizes.size(), b.getIndexAttr(0));
250   SmallVector<OpFoldResult, 4> ones(fullSizes.size(), b.getIndexAttr(1));
251   auto partialLocalView = b.createOrFold<memref::SubViewOp>(
252       loc, *fullLocalView, zeros, partialSizes, ones);
253   return PromotionInfo{*fullLocalView, partialLocalView};
254 }
255 
256 static FailureOr<MapVector<int64_t, PromotionInfo>>
257 promoteSubViews(ImplicitLocOpBuilder &b,
258                 LinalgOpInstancePromotionOptions options, DataLayout &layout) {
259   if (options.subViews.empty())
260     return failure();
261 
262   MapVector<int64_t, PromotionInfo> promotionInfoMap;
263 
264   for (auto v : options.subViews) {
265     memref::SubViewOp subView =
266         cast<memref::SubViewOp>(v.second.getDefiningOp());
267     auto promotionInfo = promoteSubviewAsNewBuffer(
268         b, b.getLoc(), subView, options.allocationFn, layout);
269     if (failed(promotionInfo))
270       return failure();
271     promotionInfoMap[v.first] = *promotionInfo;
272 
273     // Only fill the buffer if the full local view is used
274     if (!options.useFullTileBuffers[v.second])
275       continue;
276     Type subviewEltType = subView.getType().getElementType();
277     Value fillVal =
278         llvm::TypeSwitch<Type, Value>(subviewEltType)
279             .Case([&](FloatType t) {
280               return b.create<arith::ConstantOp>(FloatAttr::get(t, 0.0));
281             })
282             .Case([&](IntegerType t) {
283               return b.create<arith::ConstantOp>(IntegerAttr::get(t, 0));
284             })
285             .Case([&](ComplexType t) {
286               Value tmp;
287               if (auto et = t.getElementType().dyn_cast<FloatType>())
288                 tmp = b.create<arith::ConstantOp>(FloatAttr::get(et, 0.0));
289               else if (auto et = t.getElementType().cast<IntegerType>())
290                 tmp = b.create<arith::ConstantOp>(IntegerAttr::get(et, 0));
291               return b.create<complex::CreateOp>(t, tmp, tmp);
292             })
293             .Default([](auto) { return Value(); });
294     if (!fillVal)
295       return failure();
296     b.create<linalg::FillOp>(fillVal, promotionInfo->fullLocalView);
297   }
298 
299   // Copy data into the promoted buffers. Use callback if provided.
300   for (auto v : options.subViews) {
301     auto info = promotionInfoMap.find(v.first);
302     if (info == promotionInfoMap.end())
303       continue;
304     if (failed(options.copyInFn(
305             b, cast<memref::SubViewOp>(v.second.getDefiningOp()),
306             info->second.partialLocalView)))
307       return failure();
308   }
309   return promotionInfoMap;
310 }
311 
312 static FailureOr<LinalgOp>
313 promoteSubViews(ImplicitLocOpBuilder &b, LinalgOp op,
314                 LinalgOpInstancePromotionOptions options, DataLayout &layout) {
315   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
316 
317   // 1. Promote the specified views and use them in the new op.
318   auto promotedBuffersAndViews = promoteSubViews(b, options, layout);
319   if (failed(promotedBuffersAndViews) ||
320       promotedBuffersAndViews->size() != options.subViews.size())
321     return failure();
322 
323   // 2. Append all other operands as they appear, this enforces that such
324   // operands are not views. This is to support cases such as FillOp taking
325   // extra scalars etc.  Keep a reference to output buffers;
326   SmallVector<Value, 8> opViews;
327   opViews.reserve(op.getNumInputsAndOutputs());
328   SmallVector<std::pair<Value, Value>, 8> writebackViews;
329   writebackViews.reserve(promotedBuffersAndViews->size());
330   for (OpOperand *opOperand : op.getInputAndOutputOperands()) {
331     int64_t operandNumber = opOperand->getOperandNumber();
332     if (options.subViews.count(operandNumber) != 0) {
333       if (options.useFullTileBuffers[opOperand->get()])
334         opViews.push_back(
335             (*promotedBuffersAndViews)[operandNumber].fullLocalView);
336       else
337         opViews.push_back(
338             (*promotedBuffersAndViews)[operandNumber].partialLocalView);
339       if (operandNumber >= op.getNumInputs())
340         writebackViews.emplace_back(std::make_pair(
341             opOperand->get(),
342             (*promotedBuffersAndViews)[operandNumber].partialLocalView));
343     } else {
344       opViews.push_back(opOperand->get());
345     }
346   }
347   op->setOperands(0, opViews.size(), opViews);
348 
349   OpBuilder::InsertionGuard guard(b);
350   b.setInsertionPointAfter(op);
351   // 3. Emit write-back for the promoted output views: copy the partial view.
352   for (auto viewAndPartialLocalView : writebackViews) {
353     if (failed(options.copyOutFn(b, viewAndPartialLocalView.second,
354                                  viewAndPartialLocalView.first)))
355       return failure();
356   }
357 
358   // 4. Dealloc all local buffers.
359   for (const auto &pi : *promotedBuffersAndViews)
360     (void)options.deallocationFn(b, pi.second.fullLocalView);
361   return op;
362 }
363 
364 LogicalResult
365 mlir::linalg::promoteSubviewsPrecondition(Operation *op,
366                                           LinalgPromotionOptions options) {
367   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
368   // Transformation applies to buffers only.
369   if (!linalgOp || !linalgOp.hasBufferSemantics())
370     return failure();
371   // Check that at least one of the requested operands is indeed a subview.
372   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
373     auto sv =
374         isa_and_nonnull<memref::SubViewOp>(opOperand->get().getDefiningOp());
375     if (sv) {
376       if (!options.operandsToPromote ||
377           options.operandsToPromote->count(opOperand->getOperandNumber()))
378         return success();
379     }
380   }
381   // TODO: Check all subviews requested are bound by a static constant.
382   // TODO: Check that the total footprint fits within a given size.
383   return failure();
384 }
385 
386 FailureOr<LinalgOp>
387 mlir::linalg::promoteSubViews(OpBuilder &builder, LinalgOp linalgOp,
388                               const LinalgPromotionOptions &options) {
389   LinalgOpInstancePromotionOptions linalgOptions(linalgOp, options);
390   auto layout = DataLayout::closest(linalgOp);
391   ImplicitLocOpBuilder b(linalgOp.getLoc(), builder);
392   auto res = ::promoteSubViews(b, linalgOp, linalgOptions, layout);
393   if (failed(res))
394     return failure();
395   return res;
396 }
397 
398 namespace {
399 struct LinalgPromotionPass : public LinalgPromotionBase<LinalgPromotionPass> {
400   LinalgPromotionPass() = default;
401   LinalgPromotionPass(bool dynamicBuffers, bool useAlloca) {
402     this->dynamicBuffers = dynamicBuffers;
403     this->useAlloca = useAlloca;
404   }
405 
406   void runOnOperation() override {
407     getOperation().walk([&](LinalgOp op) {
408       auto options = LinalgPromotionOptions()
409                          .setDynamicBuffers(dynamicBuffers)
410                          .setUseAlloca(useAlloca);
411       if (failed(promoteSubviewsPrecondition(op, options)))
412         return;
413       LLVM_DEBUG(llvm::dbgs() << "Promote: " << *(op.getOperation()) << "\n");
414       ImplicitLocOpBuilder b(op.getLoc(), op);
415       // TODO: signalPassFailure() ?
416       (void)promoteSubViews(b, op, options);
417     });
418   }
419 };
420 } // namespace
421 
422 // TODO: support more transformation options in the pass.
423 std::unique_ptr<OperationPass<func::FuncOp>>
424 mlir::createLinalgPromotionPass(bool dynamicBuffers, bool useAlloca) {
425   return std::make_unique<LinalgPromotionPass>(dynamicBuffers, useAlloca);
426 }
427 std::unique_ptr<OperationPass<func::FuncOp>> mlir::createLinalgPromotionPass() {
428   return std::make_unique<LinalgPromotionPass>();
429 }
430