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