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