1 //===- Bufferize.cpp - Bufferization of linalg ops ------------------===// 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 #include "mlir/Transforms/Bufferize.h" 10 #include "PassDetail.h" 11 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 12 #include "mlir/Dialect/Linalg/Passes.h" 13 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 14 #include "mlir/Dialect/Linalg/Utils/Utils.h" 15 #include "mlir/Dialect/Math/IR/Math.h" 16 #include "mlir/Dialect/StandardOps/Transforms/Passes.h" 17 #include "mlir/Dialect/StandardOps/Utils/Utils.h" 18 #include "mlir/Dialect/Vector/VectorOps.h" 19 #include "mlir/IR/BuiltinDialect.h" 20 #include "mlir/IR/Operation.h" 21 #include "mlir/Pass/Pass.h" 22 23 using namespace ::mlir; 24 using namespace ::mlir::linalg; 25 26 static Value cloneMemref(Location loc, Value memref, OpBuilder &b) { 27 auto memrefType = memref.getType().cast<MemRefType>(); 28 auto alloc = b.create<memref::AllocOp>(loc, memrefType, 29 getDynOperands(loc, memref, b)); 30 b.create<linalg::CopyOp>(loc, memref, alloc); 31 return alloc; 32 } 33 34 static LogicalResult 35 allocateBuffersForResults(Location loc, LinalgOp linalgOp, ValueRange outputs, 36 SmallVectorImpl<Value> &resultBuffers, OpBuilder &b) { 37 // Lazily compute loopRanges. 38 SmallVector<Range, 4> loopRanges; 39 40 // Allocate a buffer for every tensor result. 41 assert(linalgOp.getNumOutputs() == linalgOp->getNumResults()); 42 for (auto en : llvm::enumerate(linalgOp->getResultTypes())) { 43 size_t resultIndex = en.index(); 44 Type resultType = en.value(); 45 46 auto tensorType = resultType.dyn_cast<RankedTensorType>(); 47 if (tensorType == nullptr) { 48 linalgOp.emitOpError() 49 << "tensor to buffer conversion expects ranked tensor results"; 50 return failure(); 51 } 52 auto tensorShape = tensorType.getShape(); 53 auto memrefType = MemRefType::get(tensorShape, tensorType.getElementType()); 54 Value resultTensor = outputs[resultIndex]; 55 56 // Clone output buffers whose value is actually used. 57 if (linalgOp.payloadUsesValueFromOutputOperandIndex(resultIndex)) { 58 resultBuffers.push_back(cloneMemref(loc, resultTensor, b)); 59 continue; 60 } 61 62 // Allocate buffers for statically-shaped results. 63 if (memrefType.hasStaticShape()) { 64 resultBuffers.push_back(b.create<memref::AllocOp>(loc, memrefType)); 65 continue; 66 } 67 68 resultBuffers.push_back(b.create<memref::AllocOp>( 69 loc, memrefType, getDynOperands(loc, resultTensor, b))); 70 } 71 return success(); 72 } 73 74 /// Specialization for `linalg::GenericOp` and `linalg::IndexedGenericOp`. 75 /// A pattern to convert Generic Linalg operations which work on tensors to 76 /// use buffers. BufferPlacement pass should be later used to move 77 /// Alloc operations to the correct positions and insert the missing Dealloc 78 /// operations in the correct places. 79 template <typename GenericOpTy> 80 static void 81 finalizeBufferAllocationForGenericOp(ConversionPatternRewriter &rewriter, 82 GenericOpTy genericOp, ValueRange inputs, 83 ValueRange outputs) { 84 // Generate a new linalg operation that works on buffers. 85 auto newGenericOp = rewriter.create<GenericOpTy>( 86 genericOp.getLoc(), 87 /*resultTensorTypes=*/llvm::None, 88 /*inputs=*/inputs, 89 /*outputs=*/outputs, genericOp.indexing_maps(), 90 genericOp.iterator_types(), genericOp.docAttr(), 91 genericOp.library_callAttr(), genericOp.sparseAttr()); 92 93 // Create a new block in the region of the new Generic Op. 94 Block *oldBlock = genericOp.getBody(); 95 Region &newRegion = newGenericOp.region(); 96 Block *newBlock = rewriter.createBlock(&newRegion, newRegion.begin(), 97 oldBlock->getArgumentTypes()); 98 99 // Clone the body of the old block to the new block. 100 BlockAndValueMapping mapping; 101 mapping.map(oldBlock->getArguments(), newBlock->getArguments()); 102 103 OpBuilder::InsertionGuard guard(rewriter); 104 rewriter.setInsertionPointToEnd(newBlock); 105 for (auto &op : oldBlock->getOperations()) { 106 Operation *clonedOp = rewriter.clone(op, mapping); 107 mapping.map(op.getResults(), clonedOp->getResults()); 108 } 109 110 // Replace the results of the old op with the new output buffers. 111 rewriter.replaceOp(genericOp, outputs); 112 } 113 114 /// Specialization for all other `linalg::LinalgOp`. 115 static void finalizeBufferAllocation(ConversionPatternRewriter &rewriter, 116 linalg::LinalgOp linalgOp, 117 ValueRange inputs, ValueRange outputs) { 118 assert(!isa<linalg::GenericOp>(linalgOp.getOperation())); 119 assert(!isa<linalg::IndexedGenericOp>(linalgOp.getOperation())); 120 SmallVector<Value, 8> newOperands = inputs; 121 newOperands.append(outputs.begin(), outputs.end()); 122 auto otherOperands = linalgOp.getAssumedNonShapedOperands(); 123 newOperands.append(otherOperands.begin(), otherOperands.end()); 124 linalgOp.clone(rewriter, linalgOp.getLoc(), 125 /*resultTypes=*/ArrayRef<Type>{}, newOperands); 126 // Replace the results of the old op with the new output buffers. 127 rewriter.replaceOp(linalgOp, outputs); 128 } 129 130 //===----------------------------------------------------------------------===// 131 // Bufferization patterns. 132 //===----------------------------------------------------------------------===// 133 134 namespace { 135 136 /// Conversion pattern that replaces `linalg.init_tensor` with allocation. 137 class BufferizeInitTensorOp : public OpConversionPattern<InitTensorOp> { 138 public: 139 using OpConversionPattern<InitTensorOp>::OpConversionPattern; 140 141 LogicalResult 142 matchAndRewrite(InitTensorOp op, ArrayRef<Value> operands, 143 ConversionPatternRewriter &rewriter) const final { 144 linalg::InitTensorOpAdaptor adaptor(operands, op->getAttrDictionary()); 145 rewriter.replaceOpWithNewOp<memref::AllocOp>( 146 op, getTypeConverter()->convertType(op.getType()).cast<MemRefType>(), 147 adaptor.sizes()); 148 return success(); 149 } 150 }; 151 152 /// Conversion pattern that bufferizes `linalg.fill` operation. 153 class BufferizeFillOp : public OpConversionPattern<FillOp> { 154 public: 155 using OpConversionPattern<FillOp>::OpConversionPattern; 156 157 LogicalResult 158 matchAndRewrite(FillOp op, ArrayRef<Value> operands, 159 ConversionPatternRewriter &rewriter) const final { 160 linalg::FillOpAdaptor adaptor(operands, op->getAttrDictionary()); 161 if (!op.output().getType().isa<TensorType>()) 162 return rewriter.notifyMatchFailure(op, 163 "operand must be of a tensor type"); 164 165 rewriter.create<FillOp>(op.getLoc(), adaptor.output(), adaptor.value()); 166 rewriter.replaceOp(op, adaptor.output()); 167 168 return success(); 169 } 170 }; 171 172 /// Generic conversion pattern that matches any LinalgOp. This avoids template 173 /// instantiating one pattern for each LinalgOp. 174 class BufferizeAnyLinalgOp : public OpInterfaceConversionPattern<LinalgOp> { 175 public: 176 using OpInterfaceConversionPattern<LinalgOp>::OpInterfaceConversionPattern; 177 178 LogicalResult 179 matchAndRewrite(LinalgOp op, ArrayRef<Value> operands, 180 ConversionPatternRewriter &rewriter) const final { 181 // GenericOpAdaptor below expects an `operand_segment_sizes` attribute. 182 if (!op->hasAttr("operand_segment_sizes")) 183 return failure(); 184 185 // We abuse the GenericOpAdaptor here. 186 // TODO: Manually create an Adaptor that captures inputs and outputs for all 187 // linalg::LinalgOp interface ops. 188 linalg::GenericOpAdaptor adaptor(operands, op->getAttrDictionary()); 189 190 Location loc = op.getLoc(); 191 SmallVector<Value, 2> newOutputBuffers; 192 193 if (failed(allocateBuffersForResults(loc, op, adaptor.outputs(), 194 newOutputBuffers, rewriter))) { 195 return op.emitOpError() 196 << "Failed to allocate buffers for tensor results."; 197 } 198 199 // Delegate to the linalg generic pattern. 200 if (auto genericOp = dyn_cast<linalg::GenericOp>(*op)) { 201 finalizeBufferAllocationForGenericOp<GenericOp>( 202 rewriter, genericOp, adaptor.inputs(), newOutputBuffers); 203 return success(); 204 } 205 206 // Delegate to the linalg indexed generic pattern. 207 if (auto genericOp = dyn_cast<linalg::IndexedGenericOp>(*op)) { 208 finalizeBufferAllocationForGenericOp<IndexedGenericOp>( 209 rewriter, genericOp, adaptor.inputs(), newOutputBuffers); 210 return success(); 211 } 212 213 finalizeBufferAllocation(rewriter, op, adaptor.inputs(), newOutputBuffers); 214 return success(); 215 } 216 }; 217 218 /// Convert `subtensor %t [offsets][sizes][strides] -> %st` to an alloc + copy 219 /// pattern. 220 /// ``` 221 /// %a = alloc(sizes) 222 /// %sv = subview %source [offsets][sizes][strides] 223 /// linalg_copy(%sv, %a) 224 /// ``` 225 /// 226 /// This pattern is arguable a std pattern once linalg::CopyOp becomes 227 /// std::CopyOp. 228 class SubTensorOpConverter : public OpConversionPattern<SubTensorOp> { 229 public: 230 using OpConversionPattern<SubTensorOp>::OpConversionPattern; 231 232 LogicalResult 233 matchAndRewrite(SubTensorOp op, ArrayRef<Value> operands, 234 ConversionPatternRewriter &rewriter) const final { 235 SubTensorOpAdaptor adaptor(operands, op->getAttrDictionary()); 236 Value sourceMemref = adaptor.source(); 237 assert(sourceMemref.getType().isa<MemRefType>()); 238 239 MemRefType subviewMemRefType = 240 getTypeConverter()->convertType(op.getType()).cast<MemRefType>(); 241 // op.sizes() capture exactly the dynamic alloc operands matching the 242 // subviewMemRefType thanks to subview/subtensor canonicalization and 243 // verification. 244 Value alloc = rewriter.create<memref::AllocOp>( 245 op.getLoc(), subviewMemRefType, op.sizes()); 246 Value subView = rewriter.create<memref::SubViewOp>( 247 op.getLoc(), sourceMemref, op.getMixedOffsets(), op.getMixedSizes(), 248 op.getMixedStrides()); 249 rewriter.create<linalg::CopyOp>(op.getLoc(), subView, alloc); 250 rewriter.replaceOp(op, alloc); 251 return success(); 252 } 253 }; 254 255 /// Convert `subtensor_insert %source into %dest [offsets][sizes][strides] -> 256 /// %t` to an buffer_cast + subview + copy + tensor_load pattern. 257 /// buffer_cast and tensor_load are inserted automatically by the 258 /// conversion infra: 259 /// ``` 260 /// %sv = subview %dest [offsets][sizes][strides] 261 /// linalg_copy(%source, %sv) 262 /// // replace with %dest 263 /// ``` 264 /// 265 /// This pattern is arguable a std pattern once linalg::CopyOp becomes 266 /// std::CopyOp. 267 class SubTensorInsertOpConverter 268 : public OpConversionPattern<SubTensorInsertOp> { 269 public: 270 using OpConversionPattern<SubTensorInsertOp>::OpConversionPattern; 271 272 LogicalResult 273 matchAndRewrite(SubTensorInsertOp op, ArrayRef<Value> operands, 274 ConversionPatternRewriter &rewriter) const final { 275 SubTensorInsertOpAdaptor adaptor(operands, op->getAttrDictionary()); 276 Value sourceMemRef = adaptor.source(); 277 assert(sourceMemRef.getType().isa<MemRefType>()); 278 279 // For now, be conservative and copy the converted input memref. 280 // In general, the converted input memref here could be aliased or could 281 // point into constant memory, so mutating it would lead to miscompilations. 282 Value destMemRef = cloneMemref(op.getLoc(), adaptor.dest(), rewriter); 283 assert(destMemRef.getType().isa<MemRefType>()); 284 285 // Take a subview to copy the small memref. 286 Value subview = rewriter.create<memref::SubViewOp>( 287 op.getLoc(), destMemRef, op.getMixedOffsets(), op.getMixedSizes(), 288 op.getMixedStrides()); 289 // Copy the small memref. 290 rewriter.create<linalg::CopyOp>(op.getLoc(), sourceMemRef, subview); 291 rewriter.replaceOp(op, destMemRef); 292 return success(); 293 } 294 }; 295 } // namespace 296 297 namespace { 298 /// Converts Linalg operations that work on tensor-type operands or results to 299 /// work on buffers. 300 struct LinalgBufferizePass : public LinalgBufferizeBase<LinalgBufferizePass> { 301 void runOnOperation() override { 302 MLIRContext &context = getContext(); 303 ConversionTarget target(context); 304 BufferizeTypeConverter typeConverter; 305 306 // Mark all Standard operations legal. 307 target.addLegalDialect<AffineDialect, math::MathDialect, 308 memref::MemRefDialect, StandardOpsDialect>(); 309 target.addIllegalOp<InitTensorOp, SubTensorOp, SubTensorInsertOp>(); 310 311 // Mark all Linalg operations illegal as long as they work on tensors. 312 auto isLegalOperation = [&](Operation *op) { 313 return typeConverter.isLegal(op); 314 }; 315 target.addDynamicallyLegalDialect<linalg::LinalgDialect>(isLegalOperation); 316 target.addDynamicallyLegalOp<ConstantOp>(isLegalOperation); 317 318 RewritePatternSet patterns(&context); 319 populateLinalgBufferizePatterns(typeConverter, patterns); 320 if (failed(applyPartialConversion(getOperation(), target, 321 std::move(patterns)))) 322 signalPassFailure(); 323 } 324 }; 325 } // end anonymous namespace 326 327 std::unique_ptr<OperationPass<FuncOp>> mlir::createLinalgBufferizePass() { 328 return std::make_unique<LinalgBufferizePass>(); 329 } 330 331 void mlir::linalg::populateLinalgBufferizePatterns( 332 BufferizeTypeConverter &typeConverter, RewritePatternSet &patterns) { 333 // TODO: Drop this once tensor constants work in standard. 334 // clang-format off 335 patterns.add< 336 BufferizeAnyLinalgOp, 337 BufferizeFillOp, 338 BufferizeInitTensorOp, 339 SubTensorOpConverter, 340 SubTensorInsertOpConverter 341 >(typeConverter, patterns.getContext()); 342 // clang-format on 343 } 344