xref: /llvm-project/mlir/lib/Dialect/Linalg/Transforms/Promotion.cpp (revision 3cb1f35df2a560d5a8ce2047b87cba8e3c904170)
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/Intrinsics.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/Utils/Utils.h"
20 #include "mlir/Dialect/LoopOps/LoopOps.h"
21 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/AffineExprVisitor.h"
24 #include "mlir/IR/AffineMap.h"
25 #include "mlir/Support/LLVM.h"
26 #include "mlir/Support/STLExtras.h"
27 #include "mlir/Transforms/FoldUtils.h"
28 
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/Support/CommandLine.h"
31 
32 using namespace mlir;
33 using namespace mlir::edsc;
34 using namespace mlir::edsc::intrinsics;
35 using namespace mlir::linalg;
36 using namespace mlir::loop;
37 
38 using llvm::SetVector;
39 
40 using folded_affine_min = folded::ValueBuilder<AffineMinOp>;
41 using folded_linalg_range = folded::ValueBuilder<linalg::RangeOp>;
42 using folded_std_dim = folded::ValueBuilder<DimOp>;
43 using folded_std_subview = folded::ValueBuilder<SubViewOp>;
44 using folded_std_view = folded::ValueBuilder<ViewOp>;
45 
46 #define DEBUG_TYPE "linalg-promotion"
47 
48 /// If `size` comes from an AffineMinOp and one of the dimensions of AffineMin
49 /// is a constant then return a new value set to the smallest such constant.
50 /// Otherwise return size.
51 static Value extractSmallestConstantBoundingSize(OpBuilder &b, Location loc,
52                                                  Value size) {
53   auto affineMinOp = dyn_cast_or_null<AffineMinOp>(size.getDefiningOp());
54   if (!affineMinOp)
55     return size;
56   if (!llvm::any_of(affineMinOp.getAffineMap().getResults(), [](AffineExpr e) {
57         return e.dyn_cast<AffineConstantExpr>();
58       }))
59     return size;
60   int64_t minConst = std::numeric_limits<int64_t>::max();
61   for (auto e : affineMinOp.getAffineMap().getResults())
62     if (auto cst = e.dyn_cast<AffineConstantExpr>())
63       minConst = std::min(minConst, cst.getValue());
64   assert(minConst != std::numeric_limits<int64_t>::max());
65   return b.create<ConstantIndexOp>(loc, minConst);
66 }
67 
68 static Value allocBuffer(Type elementType, Value size, bool dynamicBuffers,
69                          OperationFolder *folder) {
70   auto *ctx = size.getContext();
71   auto width = llvm::divideCeil(elementType.getIntOrFloatBitWidth(), 8);
72   if (!dynamicBuffers)
73     if (auto cst = dyn_cast_or_null<ConstantIndexOp>(size.getDefiningOp()))
74       return std_alloc(
75           MemRefType::get(width * cst.getValue(), IntegerType::get(8, ctx)));
76   Value mul =
77       folded_std_muli(folder, folded_std_constant_index(folder, width), size);
78   return std_alloc(MemRefType::get(-1, IntegerType::get(8, ctx)), mul);
79 }
80 
81 // Performs promotion of a `subView` into a local buffer of the size of the
82 // *ranges* of the `subView`. This produces a buffer whose size may be bigger
83 // than the actual size of the `subView` at the boundaries.
84 // This is related to the full/partial tile problem.
85 // Returns a PromotionInfo containing a `buffer`, `fullLocalView` and
86 // `partialLocalView` such that:
87 //   * `buffer` is always the size of the full tile.
88 //   * `fullLocalView` is a dense contiguous view into that buffer.
89 //   * `partialLocalView` is a dense non-contiguous slice of `fullLocalView`
90 //     that corresponds to the size of `subView` and accounting for boundary
91 //     effects.
92 // The point of the full tile buffer is that constant static tile sizes are
93 // folded and result in a buffer type with statically known size and alignment
94 // properties.
95 // To account for general boundary effects, padding must be performed on the
96 // boundary tiles. For now this is done with an unconditional `fill` op followed
97 // by a partial `copy` op.
98 static PromotionInfo promoteFullTileBuffer(OpBuilder &b, Location loc,
99                                            SubViewOp subView,
100                                            bool dynamicBuffers,
101                                            OperationFolder *folder) {
102   auto zero = folded_std_constant_index(folder, 0);
103   auto one = folded_std_constant_index(folder, 1);
104 
105   auto viewType = subView.getType();
106   auto rank = viewType.getRank();
107   Value allocSize = one;
108   SmallVector<Value, 8> fullSizes, partialSizes;
109   fullSizes.reserve(rank);
110   partialSizes.reserve(rank);
111   for (auto en : llvm::enumerate(subView.getRanges())) {
112     auto rank = en.index();
113     auto rangeValue = en.value();
114     // Try to extract a tight constant
115     Value size = extractSmallestConstantBoundingSize(b, loc, rangeValue.size);
116     allocSize = folded_std_muli(folder, allocSize, size).getValue();
117     fullSizes.push_back(size);
118     partialSizes.push_back(folded_std_dim(folder, subView, rank));
119   }
120   SmallVector<int64_t, 4> dynSizes(fullSizes.size(), -1);
121   auto buffer =
122       allocBuffer(viewType.getElementType(), allocSize, dynamicBuffers, folder);
123   auto fullLocalView = folded_std_view(
124       folder, MemRefType::get(dynSizes, viewType.getElementType()), buffer,
125       fullSizes);
126   SmallVector<Value, 4> zeros(fullSizes.size(), zero);
127   SmallVector<Value, 4> ones(fullSizes.size(), one);
128   auto partialLocalView =
129       folded_std_subview(folder, fullLocalView, zeros, partialSizes, ones);
130   return PromotionInfo{buffer, fullLocalView, partialLocalView};
131 }
132 
133 SmallVector<PromotionInfo, 8>
134 mlir::linalg::promoteSubViews(OpBuilder &b, Location loc,
135                               ArrayRef<Value> subViews, bool dynamicBuffers,
136                               OperationFolder *folder) {
137   if (subViews.empty())
138     return {};
139 
140   ScopedContext scope(b, loc);
141   SmallVector<PromotionInfo, 8> res;
142   res.reserve(subViews.size());
143   DenseMap<Value, PromotionInfo> promotionInfoMap;
144   for (auto v : subViews) {
145     SubViewOp subView = cast<SubViewOp>(v.getDefiningOp());
146     auto promotionInfo =
147         promoteFullTileBuffer(b, loc, subView, dynamicBuffers, folder);
148     promotionInfoMap.insert(std::make_pair(subView.getResult(), promotionInfo));
149     res.push_back(promotionInfo);
150   }
151 
152   for (auto v : subViews) {
153     SubViewOp subView = cast<SubViewOp>(v.getDefiningOp());
154     auto info = promotionInfoMap.find(v);
155     if (info == promotionInfoMap.end())
156       continue;
157     Value fillVal;
158     if (auto t = subView.getType().getElementType().dyn_cast<FloatType>())
159       fillVal = folded_std_constant(folder, FloatAttr::get(t, 0.0));
160     else if (auto t =
161                  subView.getType().getElementType().dyn_cast<IntegerType>())
162       fillVal = folded_std_constant_int(folder, 0, t);
163     // TODO(ntv): fill is only necessary if `promotionInfo` has a full local
164     // view that is different from the partial local view and we are on the
165     // boundary.
166     linalg_fill(info->second.fullLocalView, fillVal);
167   }
168 
169   for (auto v : subViews) {
170     auto info = promotionInfoMap.find(v);
171     if (info == promotionInfoMap.end())
172       continue;
173     linalg_copy(cast<SubViewOp>(v.getDefiningOp()),
174                 info->second.partialLocalView);
175   }
176   return res;
177 }
178 
179 LinalgOp mlir::linalg::promoteSubViewOperands(OpBuilder &b, LinalgOp op,
180                                               SetVector<Value> subViews,
181                                               bool dynamicBuffers,
182                                               OperationFolder *folder) {
183   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
184 
185   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
186     // TODO(ntv): add a level of indirection to linalg.generic.
187     if (convOp.padding())
188       llvm_unreachable("Unexpected conv with padding");
189   }
190 
191   // 1. Promote the specified views and use them in the new op.
192   ScopedContext scope(b, op.getLoc());
193   auto promotedBufferAndViews = promoteSubViews(
194       b, op.getLoc(), subViews.getArrayRef(), dynamicBuffers, folder);
195   SmallVector<Value, 8> opViews;
196   opViews.reserve(op.getNumInputsAndOutputs());
197   SmallVector<std::pair<Value, Value>, 8> writebackViews;
198   writebackViews.reserve(subViews.size());
199   unsigned promotedIdx = 0;
200   for (auto view : op.getInputsAndOutputBuffers()) {
201     if (subViews.count(view) != 0) {
202       opViews.push_back(promotedBufferAndViews[promotedIdx].fullLocalView);
203       writebackViews.emplace_back(std::make_pair(
204           view, promotedBufferAndViews[promotedIdx].partialLocalView));
205       promotedIdx++;
206     } else {
207       opViews.push_back(view);
208     }
209   }
210 
211   // 2. Append all other operands as they appear, this enforces that such
212   // operands are not views. This is to support cases such as FillOp taking
213   // extra scalars etc.
214   auto operands = getAssumedNonViewOperands(op);
215   opViews.append(operands.begin(), operands.end());
216   LinalgOp res = op.clone(b, op.getLoc(), opViews);
217 
218   // 3. Emit write-back for the promoted output views: copy the partial view.
219   for (auto viewAndPartialLocalView : writebackViews) {
220     // WARNING: MUST use the old op to determine whether the operand view is an
221     // output.
222     bool isOutput =
223         op.getIndexOfOutputBuffer(viewAndPartialLocalView.first).hasValue();
224     if (isOutput)
225       linalg_copy(viewAndPartialLocalView.second,
226                   viewAndPartialLocalView.first);
227   }
228 
229   // 4. Dealloc local buffers.
230   for (const auto &pi : promotedBufferAndViews)
231     std_dealloc(pi.buffer);
232 
233   return res;
234 }
235 
236 static void promoteSubViews(FuncOp f, bool dynamicBuffers) {
237   SmallVector<LinalgOp, 8> toErase;
238   OperationFolder folder(f.getContext());
239   f.walk([dynamicBuffers, &folder, &toErase](LinalgOp op) {
240     if (!op.hasBufferSemantics())
241       return;
242 
243     // TODO(ntv) some heuristic here to decide what to promote. Atm only float
244     // and integer buffers can be promoted.
245     SetVector<Value> subViews;
246     OpBuilder b(op);
247     for (auto it : op.getInputsAndOutputBuffers())
248       if (auto sv = dyn_cast_or_null<SubViewOp>(it.getDefiningOp()))
249         if (sv.getType().getElementType().isSignlessIntOrFloat())
250           subViews.insert(sv);
251     if (!subViews.empty()) {
252       promoteSubViewOperands(b, op, subViews, dynamicBuffers, &folder);
253       toErase.push_back(op);
254     }
255   });
256   for (auto op : toErase)
257     op.erase();
258 }
259 
260 namespace {
261 struct LinalgPromotionPass : public LinalgPromotionBase<LinalgPromotionPass> {
262   LinalgPromotionPass() = default;
263   LinalgPromotionPass(bool dynamicBuffers) {
264     this->dynamicBuffers = dynamicBuffers;
265   }
266 
267   void runOnFunction() override {
268     promoteSubViews(getFunction(), dynamicBuffers);
269   }
270 };
271 } // namespace
272 
273 std::unique_ptr<OperationPass<FuncOp>>
274 mlir::createLinalgPromotionPass(bool dynamicBuffers) {
275   return std::make_unique<LinalgPromotionPass>(dynamicBuffers);
276 }
277 std::unique_ptr<OperationPass<FuncOp>> mlir::createLinalgPromotionPass() {
278   return std::make_unique<LinalgPromotionPass>();
279 }
280