1 //===- Bufferize.cpp - Bufferization utilities ----------------------------===// 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 "PassDetail.h" 10 11 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" 12 #include "mlir/Dialect/Bufferization/IR/Bufferization.h" 13 #include "mlir/Dialect/Bufferization/Transforms/Bufferize.h" 14 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h" 15 #include "mlir/Dialect/Bufferization/Transforms/OneShotModuleBufferize.h" 16 #include "mlir/Dialect/Bufferization/Transforms/Passes.h" 17 #include "mlir/Dialect/Func/IR/FuncOps.h" 18 #include "mlir/Dialect/MemRef/IR/MemRef.h" 19 #include "mlir/IR/Operation.h" 20 #include "mlir/Pass/PassManager.h" 21 #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 22 #include "mlir/Transforms/Passes.h" 23 24 using namespace mlir; 25 using namespace mlir::bufferization; 26 27 //===----------------------------------------------------------------------===// 28 // BufferizeTypeConverter 29 //===----------------------------------------------------------------------===// 30 31 static Value materializeToTensor(OpBuilder &builder, TensorType type, 32 ValueRange inputs, Location loc) { 33 assert(inputs.size() == 1); 34 assert(inputs[0].getType().isa<BaseMemRefType>()); 35 return builder.create<bufferization::ToTensorOp>(loc, type, inputs[0]); 36 } 37 38 /// Registers conversions into BufferizeTypeConverter 39 BufferizeTypeConverter::BufferizeTypeConverter() { 40 // Keep all types unchanged. 41 addConversion([](Type type) { return type; }); 42 // Convert RankedTensorType to MemRefType. 43 addConversion([](RankedTensorType type) -> Type { 44 return MemRefType::get(type.getShape(), type.getElementType()); 45 }); 46 // Convert UnrankedTensorType to UnrankedMemRefType. 47 addConversion([](UnrankedTensorType type) -> Type { 48 return UnrankedMemRefType::get(type.getElementType(), 0); 49 }); 50 addArgumentMaterialization(materializeToTensor); 51 addSourceMaterialization(materializeToTensor); 52 addTargetMaterialization([](OpBuilder &builder, BaseMemRefType type, 53 ValueRange inputs, Location loc) -> Value { 54 assert(inputs.size() == 1 && "expected exactly one input"); 55 56 if (auto inputType = inputs[0].getType().dyn_cast<MemRefType>()) { 57 // MemRef to MemRef cast. 58 assert(inputType != type && "expected different types"); 59 // Unranked to ranked and ranked to unranked casts must be explicit. 60 auto rankedDestType = type.dyn_cast<MemRefType>(); 61 if (!rankedDestType) 62 return nullptr; 63 FailureOr<Value> replacement = 64 castOrReallocMemRefValue(builder, inputs[0], rankedDestType); 65 if (failed(replacement)) 66 return nullptr; 67 return *replacement; 68 } 69 70 if (inputs[0].getType().isa<TensorType>()) { 71 // Tensor to MemRef cast. 72 return builder.create<bufferization::ToMemrefOp>(loc, type, inputs[0]); 73 } 74 75 llvm_unreachable("only tensor/memref input types supported"); 76 }); 77 } 78 79 void mlir::bufferization::populateBufferizeMaterializationLegality( 80 ConversionTarget &target) { 81 target.addLegalOp<bufferization::ToTensorOp, bufferization::ToMemrefOp>(); 82 } 83 84 namespace { 85 // In a finalizing bufferize conversion, we know that all tensors have been 86 // converted to memrefs, thus, this op becomes an identity. 87 class BufferizeToTensorOp 88 : public OpConversionPattern<bufferization::ToTensorOp> { 89 public: 90 using OpConversionPattern::OpConversionPattern; 91 LogicalResult 92 matchAndRewrite(bufferization::ToTensorOp op, OpAdaptor adaptor, 93 ConversionPatternRewriter &rewriter) const override { 94 rewriter.replaceOp(op, adaptor.memref()); 95 return success(); 96 } 97 }; 98 } // namespace 99 100 namespace { 101 // In a finalizing bufferize conversion, we know that all tensors have been 102 // converted to memrefs, thus, this op becomes an identity. 103 class BufferizeToMemrefOp 104 : public OpConversionPattern<bufferization::ToMemrefOp> { 105 public: 106 using OpConversionPattern::OpConversionPattern; 107 LogicalResult 108 matchAndRewrite(bufferization::ToMemrefOp op, OpAdaptor adaptor, 109 ConversionPatternRewriter &rewriter) const override { 110 rewriter.replaceOp(op, adaptor.tensor()); 111 return success(); 112 } 113 }; 114 } // namespace 115 116 void mlir::bufferization::populateEliminateBufferizeMaterializationsPatterns( 117 BufferizeTypeConverter &typeConverter, RewritePatternSet &patterns) { 118 patterns.add<BufferizeToTensorOp, BufferizeToMemrefOp>(typeConverter, 119 patterns.getContext()); 120 } 121 122 namespace { 123 struct FinalizingBufferizePass 124 : public FinalizingBufferizeBase<FinalizingBufferizePass> { 125 using FinalizingBufferizeBase< 126 FinalizingBufferizePass>::FinalizingBufferizeBase; 127 128 void runOnOperation() override { 129 auto func = getOperation(); 130 auto *context = &getContext(); 131 132 BufferizeTypeConverter typeConverter; 133 RewritePatternSet patterns(context); 134 ConversionTarget target(*context); 135 136 populateEliminateBufferizeMaterializationsPatterns(typeConverter, patterns); 137 138 // If all result types are legal, and all block arguments are legal (ensured 139 // by func conversion above), then all types in the program are legal. 140 // 141 // We also check that the operand types are legal to avoid creating invalid 142 // IR. For example, this prevents 143 // populateEliminateBufferizeMaterializationsPatterns from updating the 144 // types of the operands to a return op without updating the enclosing 145 // function. 146 target.markUnknownOpDynamicallyLegal( 147 [&](Operation *op) { return typeConverter.isLegal(op); }); 148 149 if (failed(applyFullConversion(func, target, std::move(patterns)))) 150 signalPassFailure(); 151 } 152 }; 153 154 static BufferizationOptions::LayoutMapOption 155 parseLayoutMapOption(const std::string &s) { 156 if (s == "fully-dynamic-layout-map") 157 return BufferizationOptions::LayoutMapOption::FullyDynamicLayoutMap; 158 if (s == "identity-layout-map") 159 return BufferizationOptions::LayoutMapOption::IdentityLayoutMap; 160 if (s == "infer-layout-map") 161 return BufferizationOptions::LayoutMapOption::InferLayoutMap; 162 llvm_unreachable("invalid layout map option"); 163 } 164 165 struct OneShotBufferizePass 166 : public OneShotBufferizeBase<OneShotBufferizePass> { 167 OneShotBufferizePass() : OneShotBufferizeBase<OneShotBufferizePass>() {} 168 169 explicit OneShotBufferizePass(const OneShotBufferizationOptions &options) 170 : options(options) {} 171 172 void getDependentDialects(DialectRegistry ®istry) const override { 173 registry 174 .insert<bufferization::BufferizationDialect, memref::MemRefDialect>(); 175 registerAllocationOpInterfaceExternalModels(registry); 176 } 177 178 void runOnOperation() override { 179 OneShotBufferizationOptions opt; 180 if (!options) { 181 // Make new bufferization options if none were provided when creating the 182 // pass. 183 opt.dropEquivalentFuncResults = dropEquivalentFuncResults; 184 opt.allowReturnAllocs = allowReturnAllocs; 185 opt.allowUnknownOps = allowUnknownOps; 186 opt.alwaysAliasingWithDest = alwaysAliasingWithDest; 187 opt.analysisFuzzerSeed = analysisFuzzerSeed; 188 opt.createDeallocs = createDeallocs; 189 opt.functionBoundaryTypeConversion = 190 parseLayoutMapOption(functionBoundaryTypeConversion); 191 opt.printConflicts = printConflicts; 192 opt.testAnalysisOnly = testAnalysisOnly; 193 opt.bufferizeFunctionBoundaries = bufferizeFunctionBoundaries; 194 opt.unknownTypeConversion = parseLayoutMapOption(unknownTypeConversion); 195 196 OpFilter::Entry::FilterFn filterFn = 197 [&](Operation *op) { 198 // Filter may be specified via options. 199 if (this->dialectFilter.hasValue()) 200 return llvm::is_contained(this->dialectFilter, 201 op->getDialect()->getNamespace()); 202 // No filter specified: All other ops are allowed. 203 return true; 204 }; 205 opt.opFilter.allowOperation(filterFn); 206 } else { 207 opt = *options; 208 } 209 210 ModuleOp moduleOp = getOperation(); 211 if (opt.bufferizeFunctionBoundaries) { 212 if (failed(runOneShotModuleBufferize(moduleOp, opt))) { 213 signalPassFailure(); 214 return; 215 } 216 } else { 217 if (failed(runOneShotBufferize(moduleOp, opt))) { 218 signalPassFailure(); 219 return; 220 } 221 } 222 223 if (opt.testAnalysisOnly) 224 return; 225 226 OpPassManager cleanupPipeline("builtin.module"); 227 cleanupPipeline.addPass(createCanonicalizerPass()); 228 cleanupPipeline.addPass(createCSEPass()); 229 cleanupPipeline.addPass(createLoopInvariantCodeMotionPass()); 230 (void)runPipeline(cleanupPipeline, moduleOp); 231 } 232 233 private: 234 llvm::Optional<OneShotBufferizationOptions> options; 235 }; 236 } // namespace 237 238 namespace { 239 struct BufferizationBufferizePass 240 : public BufferizationBufferizeBase<BufferizationBufferizePass> { 241 void runOnOperation() override { 242 BufferizationOptions options = getPartialBufferizationOptions(); 243 options.opFilter.allowDialect<BufferizationDialect>(); 244 245 if (failed(bufferizeOp(getOperation(), options))) 246 signalPassFailure(); 247 } 248 249 void getDependentDialects(DialectRegistry ®istry) const override { 250 registry 251 .insert<bufferization::BufferizationDialect, memref::MemRefDialect>(); 252 } 253 }; 254 } // namespace 255 256 std::unique_ptr<Pass> mlir::bufferization::createBufferizationBufferizePass() { 257 return std::make_unique<BufferizationBufferizePass>(); 258 } 259 260 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass() { 261 return std::make_unique<OneShotBufferizePass>(); 262 } 263 264 std::unique_ptr<Pass> mlir::bufferization::createOneShotBufferizePass( 265 const OneShotBufferizationOptions &options) { 266 return std::make_unique<OneShotBufferizePass>(options); 267 } 268 269 std::unique_ptr<OperationPass<func::FuncOp>> 270 mlir::bufferization::createFinalizingBufferizePass() { 271 return std::make_unique<FinalizingBufferizePass>(); 272 } 273 274 //===----------------------------------------------------------------------===// 275 // BufferizableOpInterface-based Bufferization 276 //===----------------------------------------------------------------------===// 277 278 static bool isaTensor(Type t) { return t.isa<TensorType>(); } 279 280 /// Return true if the given op has a tensor result or a tensor operand. 281 static bool hasTensorSemantics(Operation *op) { 282 if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) { 283 bool hasTensorArg = any_of(funcOp.getArgumentTypes(), isaTensor); 284 bool hasTensorResult = any_of(funcOp.getResultTypes(), isaTensor); 285 return hasTensorArg || hasTensorResult; 286 } 287 288 bool hasTensorResult = any_of(op->getResultTypes(), isaTensor); 289 bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor); 290 return hasTensorResult || hasTensorOperand; 291 } 292 293 LogicalResult bufferization::bufferizeOp(Operation *op, 294 const AnalysisState &analysisState) { 295 // Catch incorrect API usage. 296 assert((analysisState.hasDialectState( 297 func::FuncDialect::getDialectNamespace()) || 298 !analysisState.getOptions().bufferizeFunctionBoundaries) && 299 "must use ModuleBufferize to bufferize function boundaries"); 300 301 BufferizationState bufferizationState(analysisState); 302 if (failed(bufferizeOp(op, bufferizationState))) 303 return failure(); 304 return success(); 305 } 306 307 namespace { 308 /// A rewriter that keeps track of extra information during bufferization. 309 class BufferizationRewriter : public IRRewriter { 310 public: 311 BufferizationRewriter(MLIRContext *ctx, DenseSet<Operation *> &erasedOps, 312 DenseSet<Operation *> &toMemrefOps, 313 const BufferizationOptions &options, 314 const OpFilter *opFilter) 315 : IRRewriter(ctx), erasedOps(erasedOps), toMemrefOps(toMemrefOps), 316 options(options), opFilter(opFilter) {} 317 318 protected: 319 void notifyOperationRemoved(Operation *op) override { 320 IRRewriter::notifyOperationRemoved(op); 321 erasedOps.insert(op); 322 // Erase if present. 323 toMemrefOps.erase(op); 324 } 325 326 void notifyOperationInserted(Operation *op) override { 327 IRRewriter::notifyOperationInserted(op); 328 329 // Keep track of to_memref ops. 330 if (isa<ToMemrefOp>(op)) { 331 toMemrefOps.insert(op); 332 return; 333 } 334 335 // Skip to_tensor ops. 336 if (isa<ToTensorOp>(op)) 337 return; 338 339 // Skip non-tensor ops. 340 if (!hasTensorSemantics(op)) 341 return; 342 343 // Skip ops that are not allowed. 344 if (!options.isOpAllowed(op) || (opFilter && !opFilter->isOpAllowed(op))) 345 return; 346 347 // Adding new bufferizable ops is not allowed during bufferization. Such ops 348 // would not be analyzed and can lead to surprising behavior. 349 llvm_unreachable( 350 "creating new tensor ops is not allowed during bufferization"); 351 } 352 353 private: 354 /// A set of all erased ops. 355 DenseSet<Operation *> &erasedOps; 356 357 /// A set of all to_memref ops. 358 DenseSet<Operation *> &toMemrefOps; 359 360 /// The bufferization options. 361 /// Used for debug modes. 362 LLVM_ATTRIBUTE_UNUSED 363 const BufferizationOptions &options; 364 365 const OpFilter *opFilter; 366 }; 367 } // namespace 368 369 LogicalResult bufferization::bufferizeOp(Operation *op, 370 BufferizationState &bufferizationState, 371 const OpFilter *opFilter) { 372 const auto &options = bufferizationState.getOptions(); 373 assert(options.unknownTypeConversion != 374 BufferizationOptions::LayoutMapOption::InferLayoutMap && 375 "invalid layout map option"); 376 377 // Keep track of to_memref ops. 378 DenseSet<Operation *> toMemrefOps; 379 op->walk([&](ToMemrefOp toMemrefOp) { toMemrefOps.insert(toMemrefOp); }); 380 381 // Gather all bufferizable ops in top-to-bottom order. 382 // 383 // We should ideally know the exact memref type of all operands when 384 // bufferizing an op. (This is the case when bufferizing top-to-bottom.) 385 // Otherwise, we have to use a memref type with a fully dynamic layout map to 386 // avoid copies. We are currently missing patterns for layout maps to 387 // canonicalize away (or canonicalize to more precise layouts). 388 SmallVector<Operation *> worklist; 389 op->walk<WalkOrder::PreOrder>([&](Operation *op) { 390 if (hasTensorSemantics(op)) 391 worklist.push_back(op); 392 }); 393 394 // Keep track of all erased ops. 395 DenseSet<Operation *> erasedOps; 396 397 // Bufferize all ops. 398 BufferizationRewriter rewriter(op->getContext(), erasedOps, toMemrefOps, 399 bufferizationState.getOptions(), opFilter); 400 for (unsigned i = 0; i < worklist.size(); ++i) { 401 Operation *op = worklist[i]; 402 // Skip ops that were erased. 403 if (erasedOps.contains(op)) 404 continue; 405 // Skip ops that are not bufferizable or not allowed. 406 auto bufferizableOp = options.dynCastBufferizableOp(op); 407 if (!bufferizableOp) 408 continue; 409 if (opFilter && !opFilter->isOpAllowed(op)) 410 continue; 411 // Skip ops that no longer have tensor semantics. 412 if (!hasTensorSemantics(op)) 413 continue; 414 // Bufferize the op. 415 rewriter.setInsertionPoint(op); 416 if (failed(bufferizableOp.bufferize(rewriter, bufferizationState))) 417 return op->emitError("failed to bufferize op"); 418 } 419 420 // Fold all to_memref(to_tensor(x)) pairs. 421 for (Operation *op : toMemrefOps) { 422 rewriter.setInsertionPoint(op); 423 (void)bufferization::foldToMemrefToTensorPair(rewriter, 424 cast<ToMemrefOp>(op)); 425 } 426 427 /// Check the result of bufferization. Return an error if an op was not 428 /// bufferized, unless partial bufferization is allowed. 429 if (bufferizationState.getOptions().allowUnknownOps) 430 return success(); 431 432 for (Operation *op : worklist) { 433 // Skip ops that are entirely gone. 434 if (erasedOps.contains(op)) 435 continue; 436 // Ops that no longer have tensor semantics (because they were updated 437 // in-place) are allowed. 438 if (!hasTensorSemantics(op)) 439 continue; 440 // Continue ops that are not allowed. 441 if (!options.isOpAllowed(op)) 442 continue; 443 if (opFilter && !opFilter->isOpAllowed(op)) 444 continue; 445 // Ops without any uses and no side effects will fold away. 446 if (op->getUses().empty() && MemoryEffectOpInterface::hasNoEffect(op)) 447 continue; 448 return op->emitError("op was not bufferized"); 449 } 450 451 return success(); 452 } 453 454 namespace { 455 /// This a "no analysis, always copy" AnalysisState. In the absence of an 456 /// analysis, a buffer must be copied each time it is written to. Therefore, all 457 /// OpOperands that bufferize to a memory write must bufferize out-of-place. 458 class AlwaysCopyAnalysisState : public AnalysisState { 459 public: 460 AlwaysCopyAnalysisState(const BufferizationOptions &options) 461 : AnalysisState(options) { 462 // Note: Allocations must be deallocated with a subsequent run of the buffer 463 // deallocation pass. 464 assert(!options.createDeallocs && 465 "cannot create deallocs with AlwaysCopyBufferizationState"); 466 } 467 468 AlwaysCopyAnalysisState(const AlwaysCopyAnalysisState &) = delete; 469 470 virtual ~AlwaysCopyAnalysisState() = default; 471 472 /// Return `true` if the given OpResult has been decided to bufferize inplace. 473 bool isInPlace(OpOperand &opOperand) const override { 474 // OpOperands that bufferize to a memory write are out-of-place, i.e., an 475 // alloc and copy is inserted. 476 return !bufferizesToMemoryWrite(opOperand); 477 } 478 479 /// Return true if `v1` and `v2` bufferize to equivalent buffers. 480 bool areEquivalentBufferizedValues(Value v1, Value v2) const override { 481 // There is no analysis, so we do not know if the values are equivalent. The 482 // conservative answer is "false". 483 return false; 484 } 485 486 /// Return true if `v1` and `v2` may bufferize to aliasing buffers. 487 bool areAliasingBufferizedValues(Value v1, Value v2) const override { 488 // There is no analysis, so we do not know if the values are equivalent. The 489 // conservative answer is "true". 490 return true; 491 } 492 493 /// Return `true` if the given tensor has undefined contents. 494 bool hasUndefinedContents(OpOperand *opOperand) const override { 495 // There is no analysis, so the conservative answer is "false". 496 return false; 497 } 498 499 /// Return true if the given tensor (or an aliasing tensor) is yielded from 500 /// the containing block. Also include all aliasing tensors in the same block. 501 bool isTensorYielded(Value tensor) const override { 502 // There is no analysis, so conservatively answer "true". 503 return true; 504 } 505 }; 506 } // namespace 507 508 LogicalResult bufferization::bufferizeOp(Operation *op, 509 const BufferizationOptions &options) { 510 AlwaysCopyAnalysisState state(options); 511 return bufferizeOp(op, state); 512 } 513 514 BufferizationOptions bufferization::getPartialBufferizationOptions() { 515 BufferizationOptions options; 516 options.allowUnknownOps = true; 517 options.createDeallocs = false; 518 options.unknownTypeConversion = 519 BufferizationOptions::LayoutMapOption::IdentityLayoutMap; 520 return options; 521 } 522