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