xref: /llvm-project/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp (revision a54f4eae0e1d0ef5adccdcf9f6c2b518dc1101aa)
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 
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 (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 Optional<PromotionInfo> mlir::linalg::promoteSubviewAsNewBuffer(
214     OpBuilder &b, Location loc, memref::SubViewOp subView,
215     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 (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     IntegerAttr sizeAttr = getSmallestBoundingIndex(rangeValue.size);
227     Value size = (!sizeAttr) ? rangeValue.size
228                              : b.create<arith::ConstantOp>(loc, sizeAttr);
229     LLVM_DEBUG(llvm::dbgs() << "Extracted tightest: " << size << "\n");
230     fullSizes.push_back(size);
231     partialSizes.push_back(
232         b.createOrFold<memref::DimOp>(loc, subView, en.index()));
233   }
234   SmallVector<int64_t, 4> dynSizes(fullSizes.size(), -1);
235   // If a callback is not specified, then use the default implementation for
236   // allocating the promoted buffer.
237   Optional<Value> fullLocalView = allocationFn(b, subView, fullSizes, layout);
238   if (!fullLocalView)
239     return {};
240   SmallVector<OpFoldResult, 4> zeros(fullSizes.size(), b.getIndexAttr(0));
241   SmallVector<OpFoldResult, 4> ones(fullSizes.size(), b.getIndexAttr(1));
242   auto partialLocalView = b.createOrFold<memref::SubViewOp>(
243       loc, *fullLocalView, zeros, partialSizes, ones);
244   return PromotionInfo{*fullLocalView, partialLocalView};
245 }
246 
247 static Optional<MapVector<int64_t, PromotionInfo>>
248 promoteSubViews(ImplicitLocOpBuilder &b,
249                 LinalgOpInstancePromotionOptions options, DataLayout &layout) {
250   if (options.subViews.empty())
251     return {};
252 
253   MapVector<int64_t, PromotionInfo> promotionInfoMap;
254 
255   for (auto v : options.subViews) {
256     memref::SubViewOp subView =
257         cast<memref::SubViewOp>(v.second.getDefiningOp());
258     Optional<PromotionInfo> promotionInfo = promoteSubviewAsNewBuffer(
259         b, b.getLoc(), subView, options.allocationFn, layout);
260     if (!promotionInfo)
261       return {};
262     promotionInfoMap[v.first] = *promotionInfo;
263 
264     // Only fill the buffer if the full local view is used
265     if (!options.useFullTileBuffers[v.second])
266       continue;
267     Type subviewEltType = subView.getType().getElementType();
268     Value fillVal =
269         llvm::TypeSwitch<Type, Value>(subviewEltType)
270             .Case([&](FloatType t) {
271               return b.create<arith::ConstantOp>(FloatAttr::get(t, 0.0));
272             })
273             .Case([&](IntegerType t) {
274               return b.create<arith::ConstantOp>(IntegerAttr::get(t, 0));
275             })
276             .Case([&](ComplexType t) {
277               Value tmp;
278               if (auto et = t.getElementType().dyn_cast<FloatType>())
279                 tmp = b.create<arith::ConstantOp>(FloatAttr::get(et, 0.0));
280               else if (auto et = t.getElementType().cast<IntegerType>())
281                 tmp = b.create<arith::ConstantOp>(IntegerAttr::get(et, 0));
282               return b.create<complex::CreateOp>(t, tmp, tmp);
283             })
284             .Default([](auto) { return Value(); });
285     if (!fillVal)
286       return {};
287     b.create<linalg::FillOp>(fillVal, promotionInfo->fullLocalView);
288   }
289 
290   // Copy data into the promoted buffers. Use callback if provided.
291   for (auto v : options.subViews) {
292     auto info = promotionInfoMap.find(v.first);
293     if (info == promotionInfoMap.end())
294       continue;
295     if (failed(options.copyInFn(
296             b, cast<memref::SubViewOp>(v.second.getDefiningOp()),
297             info->second.partialLocalView)))
298       return {};
299   }
300   return promotionInfoMap;
301 }
302 
303 static Optional<LinalgOp>
304 promoteSubViews(ImplicitLocOpBuilder &b, LinalgOp op,
305                 LinalgOpInstancePromotionOptions options, DataLayout &layout) {
306   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
307 
308   // 1. Promote the specified views and use them in the new op.
309   auto promotedBuffersAndViews = promoteSubViews(b, options, layout);
310   if (!promotedBuffersAndViews ||
311       promotedBuffersAndViews->size() != options.subViews.size())
312     return {};
313 
314   // 2. Append all other operands as they appear, this enforces that such
315   // operands are not views. This is to support cases such as FillOp taking
316   // extra scalars etc.  Keep a reference to output buffers;
317   SmallVector<Value, 8> opViews;
318   opViews.reserve(op.getNumInputsAndOutputs());
319   SmallVector<std::pair<Value, Value>, 8> writebackViews;
320   writebackViews.reserve(promotedBuffersAndViews->size());
321   for (OpOperand *opOperand : op.getInputAndOutputOperands()) {
322     int64_t operandNumber = opOperand->getOperandNumber();
323     if (options.subViews.count(operandNumber) != 0) {
324       if (options.useFullTileBuffers[opOperand->get()])
325         opViews.push_back(
326             (*promotedBuffersAndViews)[operandNumber].fullLocalView);
327       else
328         opViews.push_back(
329             (*promotedBuffersAndViews)[operandNumber].partialLocalView);
330       if (operandNumber >= op.getNumInputs())
331         writebackViews.emplace_back(std::make_pair(
332             opOperand->get(),
333             (*promotedBuffersAndViews)[operandNumber].partialLocalView));
334     } else {
335       opViews.push_back(opOperand->get());
336     }
337   }
338   op->setOperands(0, opViews.size(), opViews);
339 
340   OpBuilder::InsertionGuard guard(b);
341   b.setInsertionPointAfter(op);
342   // 3. Emit write-back for the promoted output views: copy the partial view.
343   for (auto viewAndPartialLocalView : writebackViews) {
344     if (failed(options.copyOutFn(b, viewAndPartialLocalView.second,
345                                  viewAndPartialLocalView.first)))
346       return {};
347   }
348 
349   // 4. Dealloc all local buffers.
350   for (const auto &pi : *promotedBuffersAndViews)
351     (void)options.deallocationFn(b, pi.second.fullLocalView);
352   return op;
353 }
354 
355 LogicalResult
356 mlir::linalg::promoteSubviewsPrecondition(Operation *op,
357                                           LinalgPromotionOptions options) {
358   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
359   // Transformation applies to buffers only.
360   if (!linalgOp || !linalgOp.hasBufferSemantics())
361     return failure();
362   // Check that at least one of the requested operands is indeed a subview.
363   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
364     auto sv =
365         isa_and_nonnull<memref::SubViewOp>(opOperand->get().getDefiningOp());
366     if (sv) {
367       if (!options.operandsToPromote.hasValue() ||
368           options.operandsToPromote->count(opOperand->getOperandNumber()))
369         return success();
370     }
371   }
372   // TODO: Check all subviews requested are bound by a static constant.
373   // TODO: Check that the total footprint fits within a given size.
374   return failure();
375 }
376 
377 Optional<LinalgOp>
378 mlir::linalg::promoteSubViews(OpBuilder &builder, LinalgOp linalgOp,
379                               LinalgPromotionOptions options) {
380   LinalgOpInstancePromotionOptions linalgOptions(linalgOp, options);
381   auto layout = DataLayout::closest(linalgOp);
382   ImplicitLocOpBuilder b(linalgOp.getLoc(), builder);
383   return ::promoteSubViews(b, linalgOp, linalgOptions, layout);
384 }
385 
386 namespace {
387 struct LinalgPromotionPass : public LinalgPromotionBase<LinalgPromotionPass> {
388   LinalgPromotionPass() = default;
389   LinalgPromotionPass(bool dynamicBuffers, bool useAlloca) {
390     this->dynamicBuffers = dynamicBuffers;
391     this->useAlloca = useAlloca;
392   }
393 
394   void runOnFunction() override {
395     getFunction().walk([&](LinalgOp op) {
396       auto options = LinalgPromotionOptions()
397                          .setDynamicBuffers(dynamicBuffers)
398                          .setUseAlloca(useAlloca);
399       if (failed(promoteSubviewsPrecondition(op, options)))
400         return;
401       LLVM_DEBUG(llvm::dbgs() << "Promote: " << *(op.getOperation()) << "\n");
402       ImplicitLocOpBuilder b(op.getLoc(), op);
403       promoteSubViews(b, op, options);
404     });
405   }
406 };
407 } // namespace
408 
409 // TODO: support more transformation options in the pass.
410 std::unique_ptr<OperationPass<FuncOp>>
411 mlir::createLinalgPromotionPass(bool dynamicBuffers, bool useAlloca) {
412   return std::make_unique<LinalgPromotionPass>(dynamicBuffers, useAlloca);
413 }
414 std::unique_ptr<OperationPass<FuncOp>> mlir::createLinalgPromotionPass() {
415   return std::make_unique<LinalgPromotionPass>();
416 }
417