xref: /llvm-project/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp (revision 67d0d7ac0acb0665d6a09f61278fbcf51f0114c2)
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 "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
14 #include "mlir/Dialect/Complex/IR/Complex.h"
15 #include "mlir/Dialect/Linalg/IR/Linalg.h"
16 #include "mlir/Dialect/Linalg/Passes.h"
17 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
18 #include "mlir/Dialect/Linalg/Utils/Utils.h"
19 #include "mlir/Dialect/SCF/IR/SCF.h"
20 #include "mlir/IR/AffineExpr.h"
21 #include "mlir/IR/AffineExprVisitor.h"
22 #include "mlir/IR/AffineMap.h"
23 #include "mlir/IR/ImplicitLocOpBuilder.h"
24 #include "mlir/Support/LLVM.h"
25 #include "mlir/Transforms/FoldUtils.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/SmallBitVector.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.has_value())
52     alignmentAttr = b.getI64IntegerAttr(alignment.value());
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.getSource().getLoc(),
111                                 viewOp.getSource());
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   /// Alignment of promoted buffer.
138   Optional<unsigned> alignment;
139 };
140 } // namespace
141 
142 LinalgOpInstancePromotionOptions::LinalgOpInstancePromotionOptions(
143     LinalgOp linalgOp, const LinalgPromotionOptions &options)
144     : subViews(), alignment(options.alignment) {
145   assert(linalgOp.hasBufferSemantics() && "revisit usage of shaped operand");
146   auto vUseFullTileBuffers =
147       options.useFullTileBuffers.value_or(llvm::SmallBitVector());
148   vUseFullTileBuffers.resize(linalgOp.getNumInputsAndOutputs(),
149                              options.useFullTileBuffersDefault);
150 
151   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
152     int64_t operandNumber = opOperand->getOperandNumber();
153     if (options.operandsToPromote &&
154         !options.operandsToPromote->count(operandNumber))
155       continue;
156     Operation *op = opOperand->get().getDefiningOp();
157     if (auto sv = dyn_cast_or_null<memref::SubViewOp>(op)) {
158       subViews[operandNumber] = sv;
159       useFullTileBuffers[sv] = vUseFullTileBuffers[operandNumber];
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<memref::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 FailureOr<PromotionInfo> mlir::linalg::promoteSubviewAsNewBuffer(
211     OpBuilder &b, Location loc, memref::SubViewOp subView,
212     const 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   llvm::SmallBitVector droppedDims = subView.getDroppedDims();
220   int64_t resultDimIdx = 0;
221   for (const auto &en : llvm::enumerate(subView.getOrCreateRanges(b, loc))) {
222     if (droppedDims[en.index()])
223       continue;
224     auto rangeValue = en.value();
225     // Try to extract a tight constant. If the size is known statically, no need
226     // to look for the bound.
227     LLVM_DEBUG(llvm::dbgs() << "Extract tightest: " << rangeValue.size << "\n");
228     Value size;
229     if (auto attr = rangeValue.size.dyn_cast<Attribute>()) {
230       size = materializeOpFoldResult(b, loc, rangeValue.size);
231     } else {
232       Value materializedSize = materializeOpFoldResult(b, loc, rangeValue.size);
233       FailureOr<int64_t> upperBound =
234           getConstantUpperBoundForIndex(materializedSize);
235       size = failed(upperBound)
236                  ? materializedSize
237                  : b.create<arith::ConstantIndexOp>(loc, upperBound.value());
238     }
239     LLVM_DEBUG(llvm::dbgs() << "Extracted tightest: " << size << "\n");
240     fullSizes.push_back(size);
241     partialSizes.push_back(
242         b.createOrFold<memref::DimOp>(loc, subView, resultDimIdx++));
243   }
244   SmallVector<int64_t, 4> dynSizes(fullSizes.size(), -1);
245   // If a callback is not specified, then use the default implementation for
246   // allocating the promoted buffer.
247   Optional<Value> fullLocalView = allocationFn(b, subView, fullSizes, layout);
248   if (!fullLocalView)
249     return failure();
250   SmallVector<OpFoldResult, 4> zeros(fullSizes.size(), b.getIndexAttr(0));
251   SmallVector<OpFoldResult, 4> ones(fullSizes.size(), b.getIndexAttr(1));
252   auto partialLocalView = b.createOrFold<memref::SubViewOp>(
253       loc, *fullLocalView, zeros, partialSizes, ones);
254   return PromotionInfo{*fullLocalView, partialLocalView};
255 }
256 
257 static FailureOr<MapVector<int64_t, PromotionInfo>>
258 promoteSubViews(ImplicitLocOpBuilder &b,
259                 LinalgOpInstancePromotionOptions options, DataLayout &layout) {
260   if (options.subViews.empty())
261     return failure();
262 
263   MapVector<int64_t, PromotionInfo> promotionInfoMap;
264 
265   for (auto v : options.subViews) {
266     memref::SubViewOp subView =
267         cast<memref::SubViewOp>(v.second.getDefiningOp());
268     auto promotionInfo = promoteSubviewAsNewBuffer(
269         b, b.getLoc(), subView, options.allocationFn, layout);
270     if (failed(promotionInfo))
271       return failure();
272     promotionInfoMap[v.first] = *promotionInfo;
273 
274     // Only fill the buffer if the full local view is used
275     if (!options.useFullTileBuffers[v.second])
276       continue;
277     Type subviewEltType = subView.getType().getElementType();
278     Value fillVal =
279         llvm::TypeSwitch<Type, Value>(subviewEltType)
280             .Case([&](FloatType t) {
281               return b.create<arith::ConstantOp>(FloatAttr::get(t, 0.0));
282             })
283             .Case([&](IntegerType t) {
284               return b.create<arith::ConstantOp>(IntegerAttr::get(t, 0));
285             })
286             .Case([&](ComplexType t) {
287               Value tmp;
288               if (auto et = t.getElementType().dyn_cast<FloatType>())
289                 tmp = b.create<arith::ConstantOp>(FloatAttr::get(et, 0.0));
290               else if (auto et = t.getElementType().cast<IntegerType>())
291                 tmp = b.create<arith::ConstantOp>(IntegerAttr::get(et, 0));
292               return b.create<complex::CreateOp>(t, tmp, tmp);
293             })
294             .Default([](auto) { return Value(); });
295     if (!fillVal)
296       return failure();
297     b.create<linalg::FillOp>(fillVal, promotionInfo->fullLocalView);
298   }
299 
300   // Copy data into the promoted buffers. Use callback if provided.
301   for (auto v : options.subViews) {
302     auto info = promotionInfoMap.find(v.first);
303     if (info == promotionInfoMap.end())
304       continue;
305     if (failed(options.copyInFn(
306             b, cast<memref::SubViewOp>(v.second.getDefiningOp()),
307             info->second.partialLocalView)))
308       return failure();
309   }
310   return promotionInfoMap;
311 }
312 
313 static FailureOr<LinalgOp>
314 promoteSubViews(ImplicitLocOpBuilder &b, LinalgOp op,
315                 LinalgOpInstancePromotionOptions options, DataLayout &layout) {
316   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
317 
318   // 1. Promote the specified views and use them in the new op.
319   auto promotedBuffersAndViews = promoteSubViews(b, options, layout);
320   if (failed(promotedBuffersAndViews) ||
321       promotedBuffersAndViews->size() != options.subViews.size())
322     return failure();
323 
324   // 2. Append all other operands as they appear, this enforces that such
325   // operands are not views. This is to support cases such as FillOp taking
326   // extra scalars etc.  Keep a reference to output buffers;
327   SmallVector<Value, 8> opViews;
328   opViews.reserve(op.getNumInputsAndOutputs());
329   SmallVector<std::pair<Value, Value>, 8> writebackViews;
330   writebackViews.reserve(promotedBuffersAndViews->size());
331   for (OpOperand *opOperand : op.getInputAndOutputOperands()) {
332     int64_t operandNumber = opOperand->getOperandNumber();
333     if (options.subViews.count(operandNumber) != 0) {
334       if (options.useFullTileBuffers[opOperand->get()])
335         opViews.push_back(
336             (*promotedBuffersAndViews)[operandNumber].fullLocalView);
337       else
338         opViews.push_back(
339             (*promotedBuffersAndViews)[operandNumber].partialLocalView);
340       if (operandNumber >= op.getNumInputs())
341         writebackViews.emplace_back(std::make_pair(
342             opOperand->get(),
343             (*promotedBuffersAndViews)[operandNumber].partialLocalView));
344     } else {
345       opViews.push_back(opOperand->get());
346     }
347   }
348   op->setOperands(0, opViews.size(), opViews);
349 
350   OpBuilder::InsertionGuard guard(b);
351   b.setInsertionPointAfter(op);
352   // 3. Emit write-back for the promoted output views: copy the partial view.
353   for (auto viewAndPartialLocalView : writebackViews) {
354     if (failed(options.copyOutFn(b, viewAndPartialLocalView.second,
355                                  viewAndPartialLocalView.first)))
356       return failure();
357   }
358 
359   // 4. Dealloc all local buffers.
360   for (const auto &pi : *promotedBuffersAndViews)
361     (void)options.deallocationFn(b, pi.second.fullLocalView);
362   return op;
363 }
364 
365 LogicalResult
366 mlir::linalg::promoteSubviewsPrecondition(Operation *op,
367                                           LinalgPromotionOptions options) {
368   LinalgOp linalgOp = dyn_cast<LinalgOp>(op);
369   // Transformation applies to buffers only.
370   if (!linalgOp || !linalgOp.hasBufferSemantics())
371     return failure();
372   // Check that at least one of the requested operands is indeed a subview.
373   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
374     auto sv =
375         isa_and_nonnull<memref::SubViewOp>(opOperand->get().getDefiningOp());
376     if (sv) {
377       if (!options.operandsToPromote ||
378           options.operandsToPromote->count(opOperand->getOperandNumber()))
379         return success();
380     }
381   }
382   // TODO: Check all subviews requested are bound by a static constant.
383   // TODO: Check that the total footprint fits within a given size.
384   return failure();
385 }
386 
387 FailureOr<LinalgOp>
388 mlir::linalg::promoteSubViews(OpBuilder &builder, LinalgOp linalgOp,
389                               const LinalgPromotionOptions &options) {
390   LinalgOpInstancePromotionOptions linalgOptions(linalgOp, options);
391   auto layout = DataLayout::closest(linalgOp);
392   ImplicitLocOpBuilder b(linalgOp.getLoc(), builder);
393   auto res = ::promoteSubViews(b, linalgOp, linalgOptions, layout);
394   if (failed(res))
395     return failure();
396   return res;
397 }
398