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