MLIR  21.0.0git
Fusion.cpp
Go to the documentation of this file.
1 //===- Fusion.cpp - Implementation of linalg Fusion -----------------------===//
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 Fusion pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/AffineMap.h"
23 #include "mlir/IR/Dominance.h"
24 #include "mlir/Support/LLVM.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/ADT/ScopeExit.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 
32 #include <optional>
33 #include <set>
34 
35 #define DEBUG_TYPE "linalg-fusion"
36 
37 using namespace mlir;
38 using namespace mlir::linalg;
39 
40 /// Implements a simple high-level fusion pass on linalg structured operations.
41 ///
42 /// In each block, linalg ops are processed in reverse textual order.
43 /// Given a linalg op `O`, fusion occurs by:
44 /// 1. inspecting the linalg ops that write into the views read by `O`. There
45 /// are 2 cases:
46 /// a) buffer case: use the SSA value of the views and a simple alias
47 /// analysis on subview ops to determine producer-consumer dependences;
48 /// b) tensor case: use SSA use-def chains on extract_slice ops;
49 /// 2. greedily fuse the linalg ops that produce the subview/extract_slice.
50 /// 3. inspect the fused ops and determine whether they have other remaining
51 /// LinalgOp uses. If not, then erase the original producing linalg op.
52 ///
53 /// More advanced use cases, analyses as well as profitability heuristics are
54 /// left for future work.
55 
58  unsigned dimension;
59 };
60 
61 // Given an `op`, returns the first (`shape`, `dimension`) pair that identifies
62 // the loop range at `loopDepth`. The semantics of the loopToOperandRangesMaps
63 // guarantees at least one such dimension is found. If multiple candidates exist
64 // they must agree by construction (i.e. have the same size) and we just return
65 // the first one.
66 static ShapeDimension
67 getShapeDefiningLoopRange(LinalgOp op, unsigned loopDepth,
68  bool fromSubViewOpOnly = false) {
69  // Iterate over the inputs and outputs in order.
70  // Extract the subranges from the linearized ranges.
71  for (OpOperand &opOperand : op->getOpOperands()) {
72  // The method `getRangeFromOperandShape` requires using SubViewOp or
73  // ExtractSliceOps. If the value isn't defined from there continue.
74  // todo: The method should be adapted to get the values from
75  // `ViewInterface`. The interface needs a `getOrCreateRanges` method which
76  // currently returns a `linalg.range`. The fix here is to move this op to
77  // `std` dialect and add the method to `ViewInterface`.
78  if (fromSubViewOpOnly &&
79  !isa_and_nonnull<memref::SubViewOp, tensor::ExtractSliceOp>(
80  opOperand.get().getDefiningOp()))
81  continue;
82 
83  AffineMap map = op.getMatchingIndexingMap(&opOperand);
84  LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange I/O idx: "
85  << opOperand.getOperandNumber() << "\n");
86  LLVM_DEBUG(llvm::dbgs()
87  << "getShapeDefiningLoopRange map: " << map << "\n");
88  for (const auto &en : llvm::enumerate(map.getResults())) {
89  auto dimExpr = dyn_cast<AffineDimExpr>(en.value());
90  if (!dimExpr)
91  continue;
92  if (loopDepth == cast<AffineDimExpr>(en.value()).getPosition()) {
93  LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange loopDepth: "
94  << loopDepth << "\n");
95  LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange shape: "
96  << opOperand.get() << "\n");
97  return ShapeDimension{opOperand.get(),
98  static_cast<unsigned>(en.index())};
99  }
100  }
101  }
102  llvm_unreachable("Expect to be able to extract a shape defining loop range");
103 }
104 
105 static SmallVector<Value> getTiledOperands(LinalgOp producer) {
106  return producer->getOperands();
107 }
108 
109 /// Fuses the producer by cloning the `producer`. The `fusedLoopsAndRanges`
110 /// provides the loop range information for the fused loops. The rest are
111 /// obtained from the producer itself, since they are not tiled + fused.
112 static LinalgOp fuse(OpBuilder &b, LinalgOp producer,
113  const DenseMap<unsigned, Range> &fusedLoopsAndRanges) {
114  SmallVector<OpFoldResult> ivs, tileSizes, sizeBounds;
115  SmallVector<Range> loopRanges;
116  Location loc = producer.getLoc();
117 
118  for (unsigned i = 0, e = producer.getNumLoops(); i < e; ++i) {
119  auto shapeDim = getShapeDefiningLoopRange(producer, i);
120  OpFoldResult dim =
121  createFoldedDimOp(b, loc, shapeDim.shape, shapeDim.dimension);
122  sizeBounds.push_back(dim);
123  auto it = fusedLoopsAndRanges.find(i);
124  if (it != fusedLoopsAndRanges.end()) {
125  ivs.push_back(it->second.offset);
126  tileSizes.push_back(it->second.size);
127  loopRanges.push_back(it->second);
128  LLVM_DEBUG(llvm::dbgs() << "tiled loop#" << i << " with LoopRange "
129  << loopRanges.back() << "\n");
130  } else {
131  tileSizes.push_back(b.getIndexAttr(0));
132  loopRanges.push_back(Range{b.getIndexAttr(0), dim, b.getIndexAttr(1)});
133  LLVM_DEBUG(llvm::dbgs() << "full loop#" << i << " with LoopRange "
134  << loopRanges.back() << "\n");
135  }
136  }
137 
138  SmallVector<Value, 8> clonedShapes;
139  clonedShapes.reserve(producer->getNumOperands());
140 
141  // Compute subranges for all tensor input/output operands.
142  clonedShapes.append(makeTiledShapes(
143  b, loc, producer, getTiledOperands(producer), ivs, tileSizes, sizeBounds,
144  /**omitPartialTileCheck=*/false));
145 
146  // Take result types from the tiled init operands.
147  MutableOperandRange producerDpsInits = producer.getDpsInitsMutable();
148  SmallVector<Type, 4> resultTypes;
149  resultTypes.reserve(producer->getNumResults());
150  int64_t firstInitOperandIdx =
151  producerDpsInits.getAsOperandRange().getBeginOperandIndex();
152  for (int64_t i = 0, e = producer->getNumResults(); i < e; ++i) {
153  resultTypes.push_back(clonedShapes[firstInitOperandIdx + i].getType());
154  }
155 
156  // Clone the producer with new operands and result types.
157  LinalgOp clonedOp = clone(b, producer, resultTypes, clonedShapes);
158 
159  // Shift all IndexOp results by the tile offset.
160  SmallVector<OpFoldResult> allIvs = llvm::to_vector(
161  llvm::map_range(loopRanges, [&](Range range) { return range.offset; }));
162  offsetIndices(b, clonedOp, allIvs);
163 
164  return clonedOp;
165 }
166 
167 /// Get the loop range for a dimension `dim` based on the `shapedOperand`. It is
168 /// expected to be defined by a subview op or an extract_slice op.
170  Value shapedOperand, unsigned dim) {
171  Operation *shapeProducingOp = shapedOperand.getDefiningOp();
172  if (auto subViewOp = dyn_cast<memref::SubViewOp>(shapeProducingOp))
173  return subViewOp.getOrCreateRanges(b, loc)[dim];
174  if (auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(shapeProducingOp))
175  return sliceOp.getOrCreateRanges(b, loc)[dim];
176  llvm_unreachable("SubviewOp or ExtractSliceOp expected");
177 }
178 
179 /// Fuses the producer into the loop immediately enclosing the consumer.
180 /// This is achieved by "recomputing" the producer at the time it
181 /// is needed just before the consumer.
182 static LinalgOp fuse(OpBuilder &b, LinalgOp producerOp, AffineMap producerMap,
183  OpOperand &consumerOpOperand) {
184  LLVM_DEBUG(llvm::dbgs() << "Producer map: " << producerMap << "\n");
185  DenseMap<unsigned, Range> fusedLoopsAndRanges;
186  Value shapedOperand = consumerOpOperand.get();
187  for (const auto &en : llvm::enumerate(producerMap.getResults())) {
188  unsigned posInProducerLoop = cast<AffineDimExpr>(en.value()).getPosition();
189  fusedLoopsAndRanges[posInProducerLoop] = getRangeFromOperandShape(
190  b, consumerOpOperand.getOwner()->getLoc(), shapedOperand, en.index());
191  }
192  return fuse(b, producerOp, fusedLoopsAndRanges);
193 }
194 
195 /// Walk back use-def chain through scf::For yields.
196 /// Sets `producer` and `outputIndex` if it finds a producer LinalgOp
197 
198 // TODO(ravishankarm, ntv): This can be moved into the dependence graphs
199 // dependence tracking since the dependence tracking is similar to what is done
200 // w.r.t to buffers.
201 static void getProducerOfTensor(Value tensor, OpResult &opResult) {
202  if (!isa<RankedTensorType>(tensor.getType()))
203  return;
204 
205  while (true) {
206  LLVM_DEBUG(llvm::dbgs() << "\ngetProducerOfTensor: " << tensor);
207  if (auto linalgOp = tensor.getDefiningOp<LinalgOp>()) {
208  opResult = cast<OpResult>(tensor);
209  return;
210  }
211  if (auto sliceOp = tensor.getDefiningOp<tensor::ExtractSliceOp>()) {
212  tensor = sliceOp.getSource();
213  continue;
214  }
215  if (auto blockArg = dyn_cast<BlockArgument>(tensor)) {
216  if (auto forOp = blockArg.getDefiningOp<scf::ForOp>()) {
217  tensor = forOp.getInitArgs()[blockArg.getArgNumber()];
218  continue;
219  }
220  }
221  return;
222  }
223 }
224 
225 FailureOr<FusionInfo>
227  Value inputTensor = consumerOpOperand.get();
228  OpResult producerOpResult;
229  getProducerOfTensor(inputTensor, producerOpResult);
230  if (!producerOpResult) {
231  LLVM_DEBUG(llvm::dbgs() << "\nUnable to find producer");
232  return failure();
233  }
234  return fuseProducerOfTensor(b, producerOpResult, consumerOpOperand);
235 }
236 
237 FailureOr<FusionInfo>
239  OpOperand &consumerOpOperand) {
240  auto producerOp = dyn_cast<LinalgOp>(producerOpResult.getOwner());
241  if (!producerOp)
242  return failure();
243 
244  LinalgOp consumerOp = dyn_cast<LinalgOp>(consumerOpOperand.getOwner());
245  if (!consumerOp)
246  return failure();
247 
248  Value inputTensor = consumerOpOperand.get();
249 
250  // Must be an extract_slice op to guarantee there are loops we can fuse into.
251  auto sliceOp = inputTensor.getDefiningOp<tensor::ExtractSliceOp>();
252  if (!sliceOp) {
253  LLVM_DEBUG(llvm::dbgs()
254  << "\nNot fusable, not an extract_slice op: " << inputTensor);
255  return failure();
256  }
257 
258  // If producer is already in the same block as consumer, we are done.
259  if (consumerOpOperand.get().getParentBlock() ==
260  producerOpResult.getParentBlock())
261  return failure();
262 
263  // Insert fused `producer` just before `consumer`.
265  b.setInsertionPoint(consumerOp);
266  LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " << *consumerOp << "\n");
267  OpOperand *opOperand =
268  producerOp.getDpsInitOperand(producerOpResult.getResultNumber());
269  LinalgOp fusedProducer =
270  fuse(b, producerOp, producerOp.getMatchingIndexingMap(opOperand),
271  consumerOpOperand);
272 
273  // Replace use.
274  // Canonicalizations are not guaranteed to have happened before constructing
275  // `fusedProducer`. In the tensor case this can result in temporary type
276  // mismatches. Insert a `tensor.cast` op to propagate the transformation
277  // invariant that types are compatible.
278  Value def = fusedProducer->getResult(producerOpResult.getResultNumber());
279  Type consumerType = consumerOpOperand.get().getType();
280  if (consumerType != def.getType())
281  def = b.create<tensor::CastOp>(fusedProducer.getLoc(), consumerType, def);
282  consumerOpOperand.set(def);
283  return FusionInfo{cast<LinalgOp>(producerOpResult.getOwner()), fusedProducer};
284 }
static LinalgOp fuse(OpBuilder &b, LinalgOp producer, const DenseMap< unsigned, Range > &fusedLoopsAndRanges)
Fuses the producer by cloning the producer.
Definition: Fusion.cpp:112
static void getProducerOfTensor(Value tensor, OpResult &opResult)
Walk back use-def chain through scf::For yields.
Definition: Fusion.cpp:201
static SmallVector< Value > getTiledOperands(LinalgOp producer)
Definition: Fusion.cpp:105
static ShapeDimension getShapeDefiningLoopRange(LinalgOp op, unsigned loopDepth, bool fromSubViewOpOnly=false)
Definition: Fusion.cpp:67
static Range getRangeFromOperandShape(OpBuilder &b, Location loc, Value shapedOperand, unsigned dim)
Get the loop range for a dimension dim based on the shapedOperand.
Definition: Fusion.cpp:169
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
ArrayRef< AffineExpr > getResults() const
Definition: AffineMap.cpp:407
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:104
IRValueT get() const
Return the current value being used by this operand.
Definition: UseDefLists.h:160
void set(IRValueT newValue)
Set the current value being used by this operand.
Definition: UseDefLists.h:163
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
This class provides a mutable adaptor for a range of operands.
Definition: ValueRange.h:118
OperandRange getAsOperandRange() const
Explicit conversion to an OperandRange.
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:346
This class helps build Operations.
Definition: Builders.h:205
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:396
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:453
This class represents a single result from folding an operation.
Definition: OpDefinition.h:271
This class represents an operand of an operation.
Definition: Value.h:243
This is a value defined by a result of an operation.
Definition: Value.h:433
Operation * getOwner() const
Returns the operation that owns this result.
Definition: Value.h:442
unsigned getResultNumber() const
Returns the number of this result.
Definition: Value.h:445
unsigned getBeginOperandIndex() const
Return the operand index of the first element of this range.
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:105
Block * getParentBlock()
Return the Block in which this Value is defined.
Definition: Value.cpp:48
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:20
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:344
FailureOr< FusionInfo > fuseProducerOfTensor(OpBuilder &b, OpOperand &consumerOpOperand)
This implements the fusion part of the "tileAndFuse on tensors" transformation and thus requires the ...
Definition: Fusion.cpp:226
SmallVector< Value > makeTiledShapes(OpBuilder &builder, Location loc, LinalgOp linalgOp, ValueRange valuesToTile, ArrayRef< OpFoldResult > ivs, ArrayRef< OpFoldResult > tileSizes, ArrayRef< OpFoldResult > sizeBounds, bool omitPartialTileCheck)
Creates extract_slice/subview ops for all valuesToTile of the given linalgOp with builder,...
Definition: Utils.cpp:857
OpFoldResult createFoldedDimOp(OpBuilder &b, Location loc, Value val, int64_t dim)
Create one memref::DimOp or tensor::DimOp depending on the type of val.
Definition: LinalgOps.cpp:108
void offsetIndices(OpBuilder &b, LinalgOp linalgOp, ArrayRef< OpFoldResult > offests)
Add the specified offsets to any linalg.index ops contained in the given linalgOp.
Definition: Utils.cpp:879
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition: Utils.cpp:305
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
Implements a simple high-level fusion pass on linalg structured operations.
Definition: Fusion.cpp:56
unsigned dimension
Definition: Fusion.cpp:58
Value shape
Definition: Fusion.cpp:57
Represents a range (offset, size, and stride) where each element of the triple may be dynamic or stat...
OpFoldResult offset
A struct containing the Linalg producer before and after fusion.
Definition: Utils.h:230