1 //===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===// 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/Dialect/SCF/Transforms/BufferizableOpInterfaceImpl.h" 10 11 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" 12 #include "mlir/Dialect/Bufferization/IR/Bufferization.h" 13 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h" 14 #include "mlir/Dialect/MemRef/IR/MemRef.h" 15 #include "mlir/Dialect/SCF/IR/SCF.h" 16 #include "mlir/Dialect/Tensor/IR/Tensor.h" 17 #include "mlir/IR/Dialect.h" 18 #include "mlir/IR/Operation.h" 19 #include "mlir/IR/PatternMatch.h" 20 21 using namespace mlir; 22 using namespace mlir::bufferization; 23 using namespace mlir::scf; 24 25 namespace mlir { 26 namespace scf { 27 namespace { 28 29 // bufferization.to_memref is not allowed to change the rank. 30 static void ensureToMemrefOpIsValid(Value tensor, Type memrefType) { 31 #ifndef NDEBUG 32 auto rankedTensorType = tensor.getType().dyn_cast<RankedTensorType>(); 33 assert((!rankedTensorType || (memrefType.cast<MemRefType>().getRank() == 34 rankedTensorType.getRank())) && 35 "to_memref would be invalid: mismatching ranks"); 36 #endif 37 } 38 39 /// Bufferization of scf.execute_region. Can be analyzed, but bufferization not 40 /// fully implemented at the moment. 41 struct ExecuteRegionOpInterface 42 : public BufferizableOpInterface::ExternalModel<ExecuteRegionOpInterface, 43 scf::ExecuteRegionOp> { 44 SmallVector<OpOperand *> 45 getAliasingOpOperand(Operation *op, OpResult opResult, 46 const AnalysisState &state) const { 47 // ExecuteRegionOps do not have tensor OpOperands. The yielded value can be 48 // any SSA value that is in scope. To allow for use-def chain traversal 49 // through ExecuteRegionOps in the analysis, the corresponding yield value 50 // is considered to be aliasing with the result. 51 auto executeRegionOp = cast<scf::ExecuteRegionOp>(op); 52 size_t resultNum = std::distance(op->getOpResults().begin(), 53 llvm::find(op->getOpResults(), opResult)); 54 // TODO: Support multiple blocks. 55 assert(executeRegionOp.getRegion().getBlocks().size() == 1 && 56 "expected exactly 1 block"); 57 auto yieldOp = dyn_cast<scf::YieldOp>( 58 executeRegionOp.getRegion().front().getTerminator()); 59 assert(yieldOp && "expected scf.yield terminator in scf.execute_region"); 60 return {&yieldOp->getOpOperand(resultNum)}; 61 } 62 63 // TODO: For better bufferization results, this could return `true` only if 64 // there is a memory write in the region. 65 bool isMemoryWrite(Operation *op, OpResult opResult, 66 const AnalysisState &state) const { 67 // Similar to scf.if, results of this op are always considered memory writes 68 // in the analysis. This is a useful pattern for all ops that have tensor 69 // OpResults but no tensor OpOperands. By default, `isMemoryWrite` is 70 // implemented in terms of `bufferizesToMemoryWrite`, which does not work on 71 // ops without OpOperands. 72 return true; 73 } 74 75 LogicalResult bufferize(Operation *op, RewriterBase &rewriter, 76 const BufferizationOptions &options) const { 77 auto executeRegionOp = cast<scf::ExecuteRegionOp>(op); 78 assert(executeRegionOp.getRegion().getBlocks().size() == 1 && 79 "only 1 block supported"); 80 auto yieldOp = 81 cast<scf::YieldOp>(executeRegionOp.getRegion().front().getTerminator()); 82 TypeRange newResultTypes(yieldOp.getResults()); 83 84 // Create new op and move over region. 85 auto newOp = 86 rewriter.create<scf::ExecuteRegionOp>(op->getLoc(), newResultTypes); 87 newOp.getRegion().takeBody(executeRegionOp.getRegion()); 88 89 // Update all uses of the old op. 90 rewriter.setInsertionPointAfter(newOp); 91 SmallVector<Value> newResults; 92 for (const auto &it : llvm::enumerate(executeRegionOp->getResultTypes())) { 93 if (it.value().isa<TensorType>()) { 94 newResults.push_back(rewriter.create<bufferization::ToTensorOp>( 95 executeRegionOp.getLoc(), newOp->getResult(it.index()))); 96 } else { 97 newResults.push_back(newOp->getResult(it.index())); 98 } 99 } 100 101 // Replace old op. 102 rewriter.replaceOp(executeRegionOp, newResults); 103 104 return success(); 105 } 106 107 BufferRelation bufferRelation(Operation *op, OpResult opResult, 108 const AnalysisState &state) const { 109 return BufferRelation::Equivalent; 110 } 111 }; 112 113 /// Bufferization of scf.if. Replace with a new scf.if that yields memrefs. 114 struct IfOpInterface 115 : public BufferizableOpInterface::ExternalModel<IfOpInterface, scf::IfOp> { 116 SmallVector<OpOperand *> 117 getAliasingOpOperand(Operation *op, OpResult opResult, 118 const AnalysisState &state) const { 119 // IfOps do not have tensor OpOperands. The yielded value can be any SSA 120 // value that is in scope. To allow for use-def chain traversal through 121 // IfOps in the analysis, both corresponding yield values from the then/else 122 // branches are considered to be aliasing with the result. 123 auto ifOp = cast<scf::IfOp>(op); 124 size_t resultNum = std::distance(op->getOpResults().begin(), 125 llvm::find(op->getOpResults(), opResult)); 126 return {&ifOp.thenYield()->getOpOperand(resultNum), 127 &ifOp.elseYield()->getOpOperand(resultNum)}; 128 } 129 130 // TODO: For better bufferization results, this could return `true` only if 131 // there is a memory write in one (or both) of the branches. Since this is not 132 // allowed at the moment, we should never encounter scf.ifs that yield 133 // unmodified tensors. Such scf.yield ops could just fold away. 134 bool isMemoryWrite(Operation *op, OpResult opResult, 135 const AnalysisState &state) const { 136 // IfOp results are always considered memory writes in the analysis. This 137 // design decision simplifies the analysis considerably. E.g., consider the 138 // following test case: 139 // 140 // %0 = "some_writing_op" : tensor<?xf32> 141 // %r = scf.if %c -> (tensor<?xf32>) { 142 // scf.yield %0 143 // } else { 144 // %1 = "another_writing_op"(%0) : tensor<?xf32> 145 // } 146 // "some_reading_op"(%r) 147 // 148 // "another_writing_op" in the above example should be able to bufferize 149 // inplace in the absence of another read of %0. However, if the scf.if op 150 // would not be considered a "write", the analysis would detect the 151 // following conflict: 152 // 153 // * read = some_reading_op 154 // * lastWrite = %0 (Note: The last write of %r would be a set: {%0, %1}.) 155 // * conflictingWrite = %1 156 // 157 // For more details, check the "scf.IfOp" section of the design document. 158 return true; 159 } 160 161 LogicalResult bufferize(Operation *op, RewriterBase &rewriter, 162 const BufferizationOptions &options) const { 163 OpBuilder::InsertionGuard g(rewriter); 164 auto ifOp = cast<scf::IfOp>(op); 165 auto thenYieldOp = cast<scf::YieldOp>(ifOp.thenBlock()->getTerminator()); 166 auto elseYieldOp = cast<scf::YieldOp>(ifOp.elseBlock()->getTerminator()); 167 168 // Reconcile type mismatches between then/else branches by inserting memref 169 // casts. 170 SmallVector<Value> thenResults, elseResults; 171 bool insertedCast = false; 172 for (unsigned i = 0; i < thenYieldOp.getResults().size(); ++i) { 173 Value thenValue = thenYieldOp.getResults()[i]; 174 Value elseValue = elseYieldOp.getResults()[i]; 175 if (thenValue.getType() == elseValue.getType()) { 176 thenResults.push_back(thenValue); 177 elseResults.push_back(elseValue); 178 continue; 179 } 180 181 // Type mismatch between then/else yield value. Cast both to a memref type 182 // with a fully dynamic layout map. 183 auto thenMemrefType = thenValue.getType().cast<BaseMemRefType>(); 184 auto elseMemrefType = elseValue.getType().cast<BaseMemRefType>(); 185 if (thenMemrefType.getMemorySpaceAsInt() != 186 elseMemrefType.getMemorySpaceAsInt()) 187 return op->emitError("inconsistent memory space on then/else branches"); 188 rewriter.setInsertionPoint(thenYieldOp); 189 BaseMemRefType memrefType = getMemRefTypeWithFullyDynamicLayout( 190 ifOp.getResultTypes()[i].cast<TensorType>(), 191 thenMemrefType.getMemorySpaceAsInt()); 192 thenResults.push_back(rewriter.create<memref::CastOp>( 193 thenYieldOp.getLoc(), memrefType, thenValue)); 194 rewriter.setInsertionPoint(elseYieldOp); 195 elseResults.push_back(rewriter.create<memref::CastOp>( 196 elseYieldOp.getLoc(), memrefType, elseValue)); 197 insertedCast = true; 198 } 199 200 if (insertedCast) { 201 rewriter.setInsertionPoint(thenYieldOp); 202 rewriter.replaceOpWithNewOp<scf::YieldOp>(thenYieldOp, thenResults); 203 rewriter.setInsertionPoint(elseYieldOp); 204 rewriter.replaceOpWithNewOp<scf::YieldOp>(elseYieldOp, elseResults); 205 } 206 207 // Create new op. 208 rewriter.setInsertionPoint(ifOp); 209 ValueRange resultsValueRange(thenResults); 210 TypeRange newTypes(resultsValueRange); 211 auto newIfOp = 212 rewriter.create<scf::IfOp>(ifOp.getLoc(), newTypes, ifOp.getCondition(), 213 /*withElseRegion=*/true); 214 215 // Move over then/else blocks. 216 rewriter.mergeBlocks(ifOp.thenBlock(), newIfOp.thenBlock()); 217 rewriter.mergeBlocks(ifOp.elseBlock(), newIfOp.elseBlock()); 218 219 // Replace op results. 220 replaceOpWithBufferizedValues(rewriter, op, newIfOp->getResults()); 221 222 return success(); 223 } 224 225 BufferRelation bufferRelation(Operation *op, OpResult opResult, 226 const AnalysisState &state) const { 227 // IfOp results are equivalent to their corresponding yield values if both 228 // yield values are equivalent to each other. 229 auto bufferizableOp = cast<BufferizableOpInterface>(op); 230 SmallVector<OpOperand *> yieldValues = 231 bufferizableOp.getAliasingOpOperand(opResult, state); 232 assert(yieldValues.size() == 2 && "expected 2 yield values"); 233 bool equivalentYields = state.areEquivalentBufferizedValues( 234 yieldValues[0]->get(), yieldValues[1]->get()); 235 return equivalentYields ? BufferRelation::Equivalent : BufferRelation::None; 236 } 237 }; 238 239 /// Helper function for loop bufferization. Return the indices of all values 240 /// that have a tensor type. 241 static DenseSet<int64_t> getTensorIndices(ValueRange values) { 242 DenseSet<int64_t> result; 243 for (const auto &it : llvm::enumerate(values)) 244 if (it.value().getType().isa<TensorType>()) 245 result.insert(it.index()); 246 return result; 247 } 248 249 /// Helper function for loop bufferization. Return the indices of all 250 /// bbArg/yielded value pairs who's buffer relation is "Equivalent". 251 DenseSet<int64_t> getEquivalentBuffers(Block::BlockArgListType bbArgs, 252 ValueRange yieldedValues, 253 const AnalysisState &state) { 254 unsigned int minSize = std::min(bbArgs.size(), yieldedValues.size()); 255 DenseSet<int64_t> result; 256 for (unsigned int i = 0; i < minSize; ++i) { 257 if (!bbArgs[i].getType().isa<TensorType>() || 258 !yieldedValues[i].getType().isa<TensorType>()) 259 continue; 260 if (state.areEquivalentBufferizedValues(bbArgs[i], yieldedValues[i])) 261 result.insert(i); 262 } 263 return result; 264 } 265 266 /// Helper function for loop bufferization. Cast the given buffer to the given 267 /// memref type. 268 static Value castBuffer(OpBuilder &b, Value buffer, Type type) { 269 assert(type.isa<BaseMemRefType>() && "expected BaseMemRefType"); 270 assert(buffer.getType().isa<BaseMemRefType>() && "expected BaseMemRefType"); 271 // If the buffer already has the correct type, no cast is needed. 272 if (buffer.getType() == type) 273 return buffer; 274 // TODO: In case `type` has a layout map that is not the fully dynamic 275 // one, we may not be able to cast the buffer. In that case, the loop 276 // iter_arg's layout map must be changed (see uses of `castBuffer`). 277 assert(memref::CastOp::areCastCompatible(buffer.getType(), type) && 278 "scf.while op bufferization: cast incompatible"); 279 return b.create<memref::CastOp>(buffer.getLoc(), type, buffer).getResult(); 280 } 281 282 /// Helper function for loop bufferization. Return the bufferized values of the 283 /// given OpOperands. If an operand is not a tensor, return the original value. 284 static SmallVector<Value> getBuffers(RewriterBase &rewriter, 285 MutableArrayRef<OpOperand> operands, 286 const BufferizationOptions &options) { 287 SmallVector<Value> result; 288 for (OpOperand &opOperand : operands) { 289 if (opOperand.get().getType().isa<TensorType>()) { 290 Value resultBuffer = getBuffer(rewriter, opOperand.get(), options); 291 result.push_back(resultBuffer); 292 } else { 293 result.push_back(opOperand.get()); 294 } 295 } 296 return result; 297 } 298 299 /// Helper function for loop bufferization. Compute the buffer that should be 300 /// yielded from a loop block (loop body or loop condition). 301 static Value getYieldedBuffer(RewriterBase &rewriter, Value tensor, 302 BaseMemRefType type, 303 const BufferizationOptions &options) { 304 assert(tensor.getType().isa<TensorType>() && "expected tensor"); 305 ensureToMemrefOpIsValid(tensor, type); 306 Value yieldedVal = getBuffer(rewriter, tensor, options); 307 return castBuffer(rewriter, yieldedVal, type); 308 } 309 310 /// Helper function for loop bufferization. Given a range of values, apply 311 /// `func` to those marked in `tensorIndices`. Otherwise, store the unmodified 312 /// value in the result vector. 313 static SmallVector<Value> 314 convertTensorValues(ValueRange values, const DenseSet<int64_t> &tensorIndices, 315 llvm::function_ref<Value(Value, int64_t)> func) { 316 SmallVector<Value> result; 317 for (const auto &it : llvm::enumerate(values)) { 318 size_t idx = it.index(); 319 Value val = it.value(); 320 result.push_back(tensorIndices.contains(idx) ? func(val, idx) : val); 321 } 322 return result; 323 } 324 325 /// Helper function for loop bufferization. Given a list of pre-bufferization 326 /// yielded values, compute the list of bufferized yielded values. 327 SmallVector<Value> getYieldedValues(RewriterBase &rewriter, ValueRange values, 328 TypeRange bufferizedTypes, 329 const DenseSet<int64_t> &tensorIndices, 330 const BufferizationOptions &options) { 331 return convertTensorValues( 332 values, tensorIndices, [&](Value val, int64_t index) { 333 return getYieldedBuffer(rewriter, val, 334 bufferizedTypes[index].cast<BaseMemRefType>(), 335 options); 336 }); 337 } 338 339 /// Helper function for loop bufferization. Given a list of bbArgs of the new 340 /// (bufferized) loop op, wrap the bufferized tensor args (now memrefs) into 341 /// ToTensorOps, so that the block body can be moved over to the new op. 342 SmallVector<Value> 343 getBbArgReplacements(RewriterBase &rewriter, Block::BlockArgListType bbArgs, 344 const DenseSet<int64_t> &tensorIndices) { 345 return convertTensorValues( 346 bbArgs, tensorIndices, [&](Value val, int64_t index) { 347 return rewriter.create<bufferization::ToTensorOp>(val.getLoc(), val); 348 }); 349 } 350 351 /// Bufferization of scf.for. Replace with a new scf.for that operates on 352 /// memrefs. 353 struct ForOpInterface 354 : public BufferizableOpInterface::ExternalModel<ForOpInterface, 355 scf::ForOp> { 356 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, 357 const AnalysisState &state) const { 358 // scf::ForOp alone doesn't bufferize to a memory read, one of the uses of 359 // its matching bbArg may. 360 auto forOp = cast<scf::ForOp>(op); 361 return state.isValueRead(forOp.getRegionIterArgForOpOperand(opOperand)); 362 } 363 364 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, 365 const AnalysisState &state) const { 366 // Tensor iter_args of scf::ForOps are always considered as a write. 367 return true; 368 } 369 370 SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand, 371 const AnalysisState &state) const { 372 auto forOp = cast<scf::ForOp>(op); 373 return {forOp.getResultForOpOperand(opOperand)}; 374 } 375 376 BufferRelation bufferRelation(Operation *op, OpResult opResult, 377 const AnalysisState &state) const { 378 // ForOp results are equivalent to their corresponding init_args if the 379 // corresponding iter_args and yield values are equivalent. 380 auto forOp = cast<scf::ForOp>(op); 381 OpOperand &forOperand = forOp.getOpOperandForResult(opResult); 382 auto bbArg = forOp.getRegionIterArgForOpOperand(forOperand); 383 auto yieldOp = 384 cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator()); 385 bool equivalentYield = state.areEquivalentBufferizedValues( 386 bbArg, yieldOp->getOperand(opResult.getResultNumber())); 387 return equivalentYield ? BufferRelation::Equivalent : BufferRelation::None; 388 } 389 390 bool isWritable(Operation *op, Value value, 391 const AnalysisState &state) const { 392 // Interestingly, scf::ForOp's bbArg can **always** be viewed 393 // inplace from the perspective of ops nested under: 394 // 1. Either the matching iter operand is not bufferized inplace and an 395 // alloc + optional copy makes the bbArg itself inplaceable. 396 // 2. Or the matching iter operand is bufferized inplace and bbArg just 397 // bufferizes to that too. 398 return true; 399 } 400 401 LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter, 402 const AnalysisState &state) const { 403 auto bufferizableOp = cast<BufferizableOpInterface>(op); 404 if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state))) 405 return failure(); 406 407 if (!state.getOptions().enforceAliasingInvariants) 408 return success(); 409 410 // According to the `getAliasing...` implementations, a bufferized OpResult 411 // may alias only with the corresponding bufferized init_arg and with no 412 // other buffers. I.e., the i-th OpResult may alias with the i-th init_arg; 413 // but not with any other OpOperand. If a corresponding OpResult/init_arg 414 // pair bufferizes to equivalent buffers, this aliasing requirement is 415 // satisfied. Otherwise, we cannot be sure and must yield a new buffer copy. 416 // (New buffer copies do not alias with any buffer.) 417 auto forOp = cast<scf::ForOp>(op); 418 auto yieldOp = 419 cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator()); 420 OpBuilder::InsertionGuard g(rewriter); 421 rewriter.setInsertionPoint(yieldOp); 422 423 // Indices of all iter_args that have tensor type. These are the ones that 424 // are bufferized. 425 DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs()); 426 // For every yielded value, is the value equivalent to its corresponding 427 // bbArg? 428 DenseSet<int64_t> equivalentYields = getEquivalentBuffers( 429 forOp.getRegionIterArgs(), yieldOp.getResults(), state); 430 SmallVector<Value> yieldValues; 431 for (int64_t idx = 0; 432 idx < static_cast<int64_t>(yieldOp.getResults().size()); ++idx) { 433 Value value = yieldOp.getResults()[idx]; 434 if (!indices.contains(idx) || equivalentYields.contains(idx)) { 435 yieldValues.push_back(value); 436 continue; 437 } 438 Value alloc = allocateTensorForShapedValue(rewriter, yieldOp.getLoc(), 439 value, /*escape=*/true); 440 yieldValues.push_back(alloc); 441 } 442 443 rewriter.updateRootInPlace( 444 yieldOp, [&]() { yieldOp.getResultsMutable().assign(yieldValues); }); 445 return success(); 446 } 447 448 LogicalResult bufferize(Operation *op, RewriterBase &rewriter, 449 const BufferizationOptions &options) const { 450 auto forOp = cast<scf::ForOp>(op); 451 Block *oldLoopBody = &forOp.getLoopBody().front(); 452 453 // Indices of all iter_args that have tensor type. These are the ones that 454 // are bufferized. 455 DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs()); 456 457 // The new memref init_args of the loop. 458 SmallVector<Value> initArgs = 459 getBuffers(rewriter, forOp.getIterOpOperands(), options); 460 461 // Construct a new scf.for op with memref instead of tensor values. 462 auto newForOp = rewriter.create<scf::ForOp>( 463 forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(), 464 forOp.getStep(), initArgs); 465 newForOp->setAttrs(forOp->getAttrs()); 466 ValueRange initArgsRange(initArgs); 467 TypeRange initArgsTypes(initArgsRange); 468 Block *loopBody = &newForOp.getLoopBody().front(); 469 470 // Set up new iter_args. The loop body uses tensors, so wrap the (memref) 471 // iter_args of the new loop in ToTensorOps. 472 rewriter.setInsertionPointToStart(loopBody); 473 SmallVector<Value> iterArgs = 474 getBbArgReplacements(rewriter, newForOp.getRegionIterArgs(), indices); 475 iterArgs.insert(iterArgs.begin(), newForOp.getInductionVar()); 476 477 // Erase terminator if present. 478 if (iterArgs.size() == 1) 479 rewriter.eraseOp(loopBody->getTerminator()); 480 481 // Move loop body to new loop. 482 rewriter.mergeBlocks(oldLoopBody, loopBody, iterArgs); 483 484 // Update scf.yield of new loop. 485 auto yieldOp = cast<scf::YieldOp>(loopBody->getTerminator()); 486 rewriter.setInsertionPoint(yieldOp); 487 SmallVector<Value> yieldValues = getYieldedValues( 488 rewriter, yieldOp.getResults(), initArgsTypes, indices, options); 489 yieldOp.getResultsMutable().assign(yieldValues); 490 491 // Replace loop results. 492 replaceOpWithBufferizedValues(rewriter, op, newForOp->getResults()); 493 494 return success(); 495 } 496 497 /// Assert that yielded values of an scf.for op are equivalent to their 498 /// corresponding bbArgs. In that case, the buffer relations of the 499 /// corresponding OpResults are "Equivalent". 500 /// 501 /// If this is not the case, an allocs+copies are inserted and yielded from 502 /// the loop. This could be a performance problem, so it must be explicitly 503 /// activated with `alloc-return-allocs`. 504 LogicalResult verifyAnalysis(Operation *op, 505 const AnalysisState &state) const { 506 const auto &options = 507 static_cast<const OneShotBufferizationOptions &>(state.getOptions()); 508 if (options.allowReturnAllocs) 509 return success(); 510 511 auto forOp = cast<scf::ForOp>(op); 512 auto yieldOp = 513 cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator()); 514 for (OpResult opResult : op->getOpResults()) { 515 if (!opResult.getType().isa<TensorType>()) 516 continue; 517 518 // Note: This is overly strict. We should check for aliasing bufferized 519 // values. But we don't have a "must-alias" analysis yet. 520 if (bufferRelation(op, opResult, state) != BufferRelation::Equivalent) 521 return yieldOp->emitError() 522 << "Yield operand #" << opResult.getResultNumber() 523 << " is not equivalent to the corresponding iter bbArg"; 524 } 525 526 return success(); 527 } 528 }; 529 530 /// Bufferization of scf.while. Replace with a new scf.while that operates on 531 /// memrefs. 532 struct WhileOpInterface 533 : public BufferizableOpInterface::ExternalModel<WhileOpInterface, 534 scf::WhileOp> { 535 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, 536 const AnalysisState &state) const { 537 // Tensor iter_args of scf::WhileOps are always considered as a read. 538 return true; 539 } 540 541 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, 542 const AnalysisState &state) const { 543 // Tensor iter_args of scf::WhileOps are always considered as a write. 544 return true; 545 } 546 547 SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand, 548 const AnalysisState &state) const { 549 auto whileOp = cast<scf::WhileOp>(op); 550 unsigned int idx = opOperand.getOperandNumber(); 551 552 // The OpResults and OpOperands may not match. They may not even have the 553 // same type. The number of OpResults and OpOperands can also differ. 554 if (idx >= op->getNumResults() || 555 opOperand.get().getType() != op->getResult(idx).getType()) 556 return {}; 557 558 // The only aliasing OpResult may be the one at the same index. 559 return {whileOp->getResult(idx)}; 560 } 561 562 BufferRelation bufferRelation(Operation *op, OpResult opResult, 563 const AnalysisState &state) const { 564 // WhileOp results are equivalent to their corresponding init_args if the 565 // corresponding iter_args and yield values are equivalent (for both the 566 // "before" and the "after" block). 567 unsigned int resultNumber = opResult.getResultNumber(); 568 auto whileOp = cast<scf::WhileOp>(op); 569 570 // The "before" region bbArgs and the OpResults may not match. 571 if (resultNumber >= whileOp.getBeforeArguments().size()) 572 return BufferRelation::None; 573 if (opResult.getType() != 574 whileOp.getBeforeArguments()[resultNumber].getType()) 575 return BufferRelation::None; 576 577 auto conditionOp = whileOp.getConditionOp(); 578 BlockArgument conditionBbArg = whileOp.getBeforeArguments()[resultNumber]; 579 Value conditionOperand = conditionOp.getArgs()[resultNumber]; 580 bool equivCondition = 581 state.areEquivalentBufferizedValues(conditionBbArg, conditionOperand); 582 583 auto yieldOp = whileOp.getYieldOp(); 584 BlockArgument bodyBbArg = whileOp.getAfterArguments()[resultNumber]; 585 Value yieldOperand = yieldOp.getOperand(resultNumber); 586 bool equivYield = 587 state.areEquivalentBufferizedValues(bodyBbArg, yieldOperand); 588 589 return equivCondition && equivYield ? BufferRelation::Equivalent 590 : BufferRelation::None; 591 } 592 593 bool isWritable(Operation *op, Value value, 594 const AnalysisState &state) const { 595 // Interestingly, scf::WhileOp's bbArg can **always** be viewed 596 // inplace from the perspective of ops nested under: 597 // 1. Either the matching iter operand is not bufferized inplace and an 598 // alloc + optional copy makes the bbArg itself inplaceable. 599 // 2. Or the matching iter operand is bufferized inplace and bbArg just 600 // bufferizes to that too. 601 return true; 602 } 603 604 LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter, 605 const AnalysisState &state) const { 606 auto bufferizableOp = cast<BufferizableOpInterface>(op); 607 if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state))) 608 return failure(); 609 610 if (!state.getOptions().enforceAliasingInvariants) 611 return success(); 612 613 // According to the `getAliasing...` implementations, a bufferized OpResult 614 // may alias only with the corresponding bufferized init_arg and with no 615 // other buffers. I.e., the i-th OpResult may alias with the i-th init_arg; 616 // but not with any other OpOperand. If a corresponding OpResult/init_arg 617 // pair bufferizes to equivalent buffers, this aliasing requirement is 618 // satisfied. Otherwise, we cannot be sure and must yield a new buffer copy. 619 // (New buffer copies do not alias with any buffer.) 620 OpBuilder::InsertionGuard g(rewriter); 621 auto whileOp = cast<scf::WhileOp>(op); 622 auto conditionOp = whileOp.getConditionOp(); 623 auto yieldOp = whileOp.getYieldOp(); 624 625 // Indices of all bbArgs that have tensor type. These are the ones that 626 // are bufferized. The "before" and "after" regions may have different args. 627 DenseSet<int64_t> indicesBefore = getTensorIndices(whileOp.getInits()); 628 DenseSet<int64_t> indicesAfter = 629 getTensorIndices(whileOp.getAfterArguments()); 630 631 // For every yielded value, is the value equivalent to its corresponding 632 // bbArg? 633 DenseSet<int64_t> equivalentYieldsBefore = getEquivalentBuffers( 634 whileOp.getBeforeArguments(), conditionOp.getArgs(), state); 635 DenseSet<int64_t> equivalentYieldsAfter = getEquivalentBuffers( 636 whileOp.getAfterArguments(), whileOp.getYieldOp().getResults(), state); 637 638 // Update "before" region. 639 rewriter.setInsertionPoint(conditionOp); 640 SmallVector<Value> beforeYieldValues; 641 for (int64_t idx = 0; 642 idx < static_cast<int64_t>(conditionOp.getArgs().size()); ++idx) { 643 Value value = conditionOp.getArgs()[idx]; 644 if (!indicesBefore.contains(idx) || 645 equivalentYieldsBefore.contains(idx)) { 646 beforeYieldValues.push_back(value); 647 continue; 648 } 649 Value alloc = allocateTensorForShapedValue(rewriter, conditionOp.getLoc(), 650 value, /*escape=*/true); 651 beforeYieldValues.push_back(alloc); 652 } 653 rewriter.updateRootInPlace(conditionOp, [&]() { 654 conditionOp.getArgsMutable().assign(beforeYieldValues); 655 }); 656 657 // Update "after" region. 658 rewriter.setInsertionPoint(yieldOp); 659 SmallVector<Value> afterYieldValues; 660 for (int64_t idx = 0; 661 idx < static_cast<int64_t>(yieldOp.getResults().size()); ++idx) { 662 Value value = yieldOp.getResults()[idx]; 663 if (!indicesAfter.contains(idx) || equivalentYieldsAfter.contains(idx)) { 664 afterYieldValues.push_back(value); 665 continue; 666 } 667 Value alloc = allocateTensorForShapedValue(rewriter, yieldOp.getLoc(), 668 value, /*escape=*/true); 669 afterYieldValues.push_back(alloc); 670 } 671 rewriter.updateRootInPlace(yieldOp, [&]() { 672 yieldOp.getResultsMutable().assign(afterYieldValues); 673 }); 674 675 return success(); 676 } 677 678 LogicalResult bufferize(Operation *op, RewriterBase &rewriter, 679 const BufferizationOptions &options) const { 680 auto whileOp = cast<scf::WhileOp>(op); 681 682 assert(whileOp.getBefore().getBlocks().size() == 1 && 683 "regions with multiple blocks not supported"); 684 Block *beforeBody = &whileOp.getBefore().front(); 685 assert(whileOp.getAfter().getBlocks().size() == 1 && 686 "regions with multiple blocks not supported"); 687 Block *afterBody = &whileOp.getAfter().front(); 688 689 // Indices of all bbArgs that have tensor type. These are the ones that 690 // are bufferized. The "before" and "after" regions may have different args. 691 DenseSet<int64_t> indicesBefore = getTensorIndices(whileOp.getInits()); 692 DenseSet<int64_t> indicesAfter = 693 getTensorIndices(whileOp.getAfterArguments()); 694 695 // The new memref init_args of the loop. 696 SmallVector<Value> initArgs = 697 getBuffers(rewriter, whileOp->getOpOperands(), options); 698 699 // The result types of a WhileOp are the same as the "after" bbArg types. 700 SmallVector<Type> argsTypesAfter = llvm::to_vector( 701 llvm::map_range(whileOp.getAfterArguments(), [&](BlockArgument bbArg) { 702 return bufferization::getBufferType(bbArg, options).cast<Type>(); 703 })); 704 705 // Construct a new scf.while op with memref instead of tensor values. 706 ValueRange argsRangeBefore(initArgs); 707 TypeRange argsTypesBefore(argsRangeBefore); 708 auto newWhileOp = rewriter.create<scf::WhileOp>(whileOp.getLoc(), 709 argsTypesAfter, initArgs); 710 711 // Add before/after regions to the new op. 712 SmallVector<Location> bbArgLocsBefore(initArgs.size(), whileOp.getLoc()); 713 SmallVector<Location> bbArgLocsAfter(argsTypesAfter.size(), 714 whileOp.getLoc()); 715 Block *newBeforeBody = &newWhileOp.getBefore().emplaceBlock(); 716 newWhileOp.getBefore().addArguments(argsTypesBefore, bbArgLocsBefore); 717 Block *newAfterBody = &newWhileOp.getAfter().emplaceBlock(); 718 newWhileOp.getAfter().addArguments(argsTypesAfter, bbArgLocsAfter); 719 720 // Set up new iter_args and move the loop condition block to the new op. 721 // The old block uses tensors, so wrap the (memref) bbArgs of the new block 722 // in ToTensorOps. 723 rewriter.setInsertionPointToStart(newBeforeBody); 724 SmallVector<Value> newBeforeArgs = getBbArgReplacements( 725 rewriter, newWhileOp.getBeforeArguments(), indicesBefore); 726 rewriter.mergeBlocks(beforeBody, newBeforeBody, newBeforeArgs); 727 728 // Update scf.condition of new loop. 729 auto newConditionOp = newWhileOp.getConditionOp(); 730 rewriter.setInsertionPoint(newConditionOp); 731 // Only equivalent buffers or new buffer allocations may be yielded to the 732 // "after" region. 733 // TODO: This could be relaxed for better bufferization results. 734 SmallVector<Value> newConditionArgs = 735 getYieldedValues(rewriter, newConditionOp.getArgs(), argsTypesAfter, 736 indicesAfter, options); 737 newConditionOp.getArgsMutable().assign(newConditionArgs); 738 739 // Set up new iter_args and move the loop body block to the new op. 740 // The old block uses tensors, so wrap the (memref) bbArgs of the new block 741 // in ToTensorOps. 742 rewriter.setInsertionPointToStart(newAfterBody); 743 SmallVector<Value> newAfterArgs = getBbArgReplacements( 744 rewriter, newWhileOp.getAfterArguments(), indicesAfter); 745 rewriter.mergeBlocks(afterBody, newAfterBody, newAfterArgs); 746 747 // Update scf.yield of the new loop. 748 auto newYieldOp = newWhileOp.getYieldOp(); 749 rewriter.setInsertionPoint(newYieldOp); 750 // Only equivalent buffers or new buffer allocations may be yielded to the 751 // "before" region. 752 // TODO: This could be relaxed for better bufferization results. 753 SmallVector<Value> newYieldValues = 754 getYieldedValues(rewriter, newYieldOp.getResults(), argsTypesBefore, 755 indicesBefore, options); 756 newYieldOp.getResultsMutable().assign(newYieldValues); 757 758 // Replace loop results. 759 replaceOpWithBufferizedValues(rewriter, op, newWhileOp->getResults()); 760 761 return success(); 762 } 763 764 /// Assert that yielded values of an scf.while op are equivalent to their 765 /// corresponding bbArgs. In that case, the buffer relations of the 766 /// corresponding OpResults are "Equivalent". 767 /// 768 /// If this is not the case, allocs+copies are inserted and yielded from 769 /// the loop. This could be a performance problem, so it must be explicitly 770 /// activated with `alloc-return-allocs`. 771 /// 772 /// Not: In contrast to scf::ForOp, scf::WhileOp has two regions and the 773 /// equivalence condition must be checked for both. 774 LogicalResult verifyAnalysis(Operation *op, 775 const AnalysisState &state) const { 776 auto whileOp = cast<scf::WhileOp>(op); 777 const auto &options = 778 static_cast<const OneShotBufferizationOptions &>(state.getOptions()); 779 if (options.allowReturnAllocs) 780 return success(); 781 782 auto conditionOp = whileOp.getConditionOp(); 783 for (const auto &it : llvm::enumerate(conditionOp.getArgs())) { 784 if (!it.value().getType().isa<TensorType>()) 785 continue; 786 if (!state.areEquivalentBufferizedValues( 787 it.value(), conditionOp->getBlock()->getArgument(it.index()))) 788 return conditionOp->emitError() 789 << "Condition arg #" << it.index() 790 << " is not equivalent to the corresponding iter bbArg"; 791 } 792 793 auto yieldOp = whileOp.getYieldOp(); 794 for (const auto &it : llvm::enumerate(yieldOp.getResults())) { 795 if (!it.value().getType().isa<TensorType>()) 796 continue; 797 if (!state.areEquivalentBufferizedValues( 798 it.value(), yieldOp->getBlock()->getArgument(it.index()))) 799 return yieldOp->emitError() 800 << "Yield operand #" << it.index() 801 << " is not equivalent to the corresponding iter bbArg"; 802 } 803 804 return success(); 805 } 806 }; 807 808 /// Bufferization of scf.yield. Bufferized as part of their enclosing ops, so 809 /// this is for analysis only. 810 struct YieldOpInterface 811 : public BufferizableOpInterface::ExternalModel<YieldOpInterface, 812 scf::YieldOp> { 813 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, 814 const AnalysisState &state) const { 815 return true; 816 } 817 818 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, 819 const AnalysisState &state) const { 820 return false; 821 } 822 823 SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand, 824 const AnalysisState &state) const { 825 if (isa<scf::IfOp>(op->getParentOp())) 826 return {op->getParentOp()->getResult(opOperand.getOperandNumber())}; 827 if (isa<scf::ExecuteRegionOp>(op->getParentOp())) 828 return {op->getParentOp()->getResult(opOperand.getOperandNumber())}; 829 return {}; 830 } 831 832 bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand, 833 const AnalysisState &state) const { 834 // Yield operands always bufferize inplace. Otherwise, an alloc + copy 835 // may be generated inside the block. We should not return/yield allocations 836 // when possible. 837 return true; 838 } 839 840 LogicalResult bufferize(Operation *op, RewriterBase &rewriter, 841 const BufferizationOptions &options) const { 842 auto yieldOp = cast<scf::YieldOp>(op); 843 if (!isa<scf::ExecuteRegionOp, scf::IfOp, scf::ForOp, scf::WhileOp>( 844 yieldOp->getParentOp())) 845 return yieldOp->emitError("unsupported scf::YieldOp parent"); 846 847 // TODO: Bufferize scf.yield inside scf.while/scf.for here. 848 // (Currently bufferized together with scf.while/scf.for.) 849 if (isa<scf::ForOp, scf::WhileOp>(yieldOp->getParentOp())) 850 return success(); 851 852 SmallVector<Value> newResults; 853 for (const auto &it : llvm::enumerate(yieldOp.getResults())) { 854 Value value = it.value(); 855 if (value.getType().isa<TensorType>()) { 856 Value buffer = getBuffer(rewriter, value, options); 857 newResults.push_back(buffer); 858 } else { 859 newResults.push_back(value); 860 } 861 } 862 863 replaceOpWithNewBufferizedOp<scf::YieldOp>(rewriter, op, newResults); 864 return success(); 865 } 866 }; 867 868 using tensor::ExtractSliceOp; 869 870 /// Return the destinations that an ForeachThreadOp is inserting into. One per 871 /// ParallelInsertSliceOp. 872 static SmallVector<OpOperand *> 873 getInsertionDest(ForeachThreadOp foreachThreadOp) { 874 PerformConcurrentlyOp terminator = foreachThreadOp.getTerminator(); 875 SmallVector<OpOperand *> result; 876 terminator.walk([&](ParallelInsertSliceOp insertOp) { 877 result.push_back(&insertOp->getOpOperand(1) /*dest*/); 878 }); 879 return result; 880 } 881 882 /// Bufferization of ForeachThreadOp. This also bufferizes the terminator of the 883 /// region. There are op interfaces for the terminators (PerformConcurrentlyOp 884 /// and ParallelInsertSliceOp), but these are only used during analysis. Not 885 /// for bufferization. 886 struct ForeachThreadOpInterface 887 : public BufferizableOpInterface::ExternalModel<ForeachThreadOpInterface, 888 ForeachThreadOp> { 889 SmallVector<OpOperand *> 890 getAliasingOpOperand(Operation *op, OpResult opResult, 891 const AnalysisState &state) const { 892 // Get OpOperand (dest) from corresponding ParallelInsertSliceOp. 893 auto foreachThreadOp = cast<ForeachThreadOp>(op); 894 return {getInsertionDest(foreachThreadOp)[opResult.getResultNumber()]}; 895 } 896 897 bool isMemoryWrite(Operation *op, OpResult opResult, 898 const AnalysisState &state) const { 899 // This op is a memory write. Stop lookup here to avoid finding false 900 // conflicts involving this op and one of the ops in the region. This is 901 // similar to how scf.if ops are analyzed. 902 return true; 903 } 904 905 BufferRelation bufferRelation(Operation *op, OpResult opResult, 906 const AnalysisState &state) const { 907 return BufferRelation::Equivalent; 908 } 909 910 LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter, 911 const AnalysisState &state) const { 912 auto bufferizableOp = cast<BufferizableOpInterface>(op); 913 if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state))) 914 return failure(); 915 916 OpBuilder::InsertionGuard g(rewriter); 917 auto foreachThreadOp = cast<ForeachThreadOp>(op); 918 for (OpResult opResult : foreachThreadOp->getOpResults()) { 919 SmallVector<OpOperand *> destOperands = 920 state.getAliasingOpOperand(opResult); 921 assert(destOperands.size() == 1 && 922 "expected exactly one aliasing OpOperand"); 923 assert(isa<ParallelInsertSliceOp>(destOperands.front()->getOwner()) && 924 "expected ParallelInsertSliceOp"); 925 926 // Nothing to do if there is no conflict. 927 if (state.isInPlace(*destOperands.front())) 928 continue; 929 930 // Insert tensor allocation. 931 bool isYielded = state.isTensorYielded(opResult); 932 Value alloc = allocateTensorForShapedValue(rewriter, op->getLoc(), 933 destOperands.front()->get(), 934 /*escape=*/isYielded); 935 936 // Update terminator operand. 937 rewriter.updateRootInPlace(destOperands.front()->getOwner(), 938 [&]() { destOperands.front()->set(alloc); }); 939 } 940 941 return success(); 942 } 943 944 LogicalResult bufferize(Operation *op, RewriterBase &rewriter, 945 const BufferizationOptions &options) const { 946 auto foreachThreadOp = cast<ForeachThreadOp>(op); 947 948 #ifndef NDEBUG 949 // ParallelInsertSliceOpInterface replaces all uses. 950 for (OpResult opResult : foreachThreadOp->getOpResults()) 951 assert(opResult.getUses().empty() && 952 "expected that all uses were already replaced"); 953 #endif // NDEBUG 954 955 // Create new ForeachThreadOp without any results and drop the automatically 956 // introduced terminator. 957 TypeRange newResultTypes; 958 auto newForeachThreadOp = rewriter.create<ForeachThreadOp>( 959 foreachThreadOp.getLoc(), newResultTypes, 960 foreachThreadOp.getNumThreads()); 961 newForeachThreadOp.getBody()->getTerminator()->erase(); 962 963 // Move over block contents of the old op. 964 rewriter.mergeBlocks(foreachThreadOp.getBody(), 965 newForeachThreadOp.getBody(), 966 {newForeachThreadOp.getBody()->getArguments()}); 967 968 // Remove the old op. 969 rewriter.eraseOp(op); 970 971 return success(); 972 } 973 }; 974 975 /// Nothing to do for PerformConcurrentlyOp. 976 struct PerformConcurrentlyOpInterface 977 : public BufferizableOpInterface::ExternalModel< 978 PerformConcurrentlyOpInterface, PerformConcurrentlyOp> { 979 LogicalResult bufferize(Operation *op, RewriterBase &b, 980 const BufferizationOptions &options) const { 981 llvm_unreachable("op does not have any tensor OpOperands / OpResults"); 982 return failure(); 983 } 984 }; 985 986 /// Return true if the (ExtractSliceOp, ParallelInsertSliceOp) pair match (i.e. 987 /// equivalent operand / result and same offset/sizes/strides specification). 988 static bool areEquivalentExtractSliceOps(const AnalysisState &state, 989 ExtractSliceOp st, 990 ParallelInsertSliceOp sti) { 991 if (!st || !sti) 992 return false; 993 if (st != sti && 994 !state.areEquivalentBufferizedValues(st.getSource(), sti.getDest())) 995 return false; 996 if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue)) 997 return false; 998 return true; 999 } 1000 1001 /// Return true if `value` is originating from an ExtractSliceOp that matches 1002 /// the given InsertSliceOp. 1003 static bool hasMatchingExtractSliceOp(const AnalysisState &state, Value value, 1004 ParallelInsertSliceOp insertOp) { 1005 auto condition = [&](Value val) { 1006 if (auto extractOp = val.getDefiningOp<ExtractSliceOp>()) 1007 if (areEquivalentExtractSliceOps(state, extractOp, insertOp)) 1008 return true; 1009 return false; 1010 }; 1011 1012 return llvm::all_of(state.findValueInReverseUseDefChain(value, condition), 1013 condition); 1014 } 1015 1016 /// Analysis of ParallelInsertSliceOp. 1017 struct ParallelInsertSliceOpInterface 1018 : public BufferizableOpInterface::ExternalModel< 1019 ParallelInsertSliceOpInterface, ParallelInsertSliceOp> { 1020 SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand, 1021 const AnalysisState &state) const { 1022 if (&opOperand != &op->getOpOperand(1) /*dest*/) 1023 return {}; 1024 1025 // ParallelInsertSliceOp itself has no results. Tensors are returned via 1026 // the parent op. 1027 auto foreachThreadOp = op->getParentOfType<ForeachThreadOp>(); 1028 assert(foreachThreadOp && 1029 "could not find valid owner of parallel_insert_slice"); 1030 1031 // The i-th ParallelInsertSliceOp result is returned via the i-th OpResult 1032 // of the parent ForeachThreadOp. 1033 Block *block = op->getBlock(); 1034 unsigned int opIdx = 0; 1035 for (ParallelInsertSliceOp insertOp : 1036 block->getOps<ParallelInsertSliceOp>()) { 1037 if (insertOp.getOperation() == op) 1038 break; 1039 ++opIdx; 1040 } 1041 assert(opIdx < foreachThreadOp->getNumResults() && 1042 "could not find op inside terminator op"); 1043 1044 return {foreachThreadOp->getResult(opIdx)}; 1045 } 1046 1047 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, 1048 const AnalysisState &state) const { 1049 return true; 1050 } 1051 1052 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, 1053 const AnalysisState &state) const { 1054 return &opOperand == &op->getOpOperand(1) /*dest*/; 1055 } 1056 1057 BufferRelation bufferRelation(Operation *op, OpResult opResult, 1058 const AnalysisState &state) const { 1059 return BufferRelation::Equivalent; 1060 } 1061 1062 LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter, 1063 const AnalysisState &state) const { 1064 return success(); 1065 } 1066 1067 LogicalResult bufferize(Operation *op, RewriterBase &rewriter, 1068 const BufferizationOptions &options) const { 1069 OpBuilder::InsertionGuard g(rewriter); 1070 auto insertOp = cast<ParallelInsertSliceOp>(op); 1071 auto performConcurrentlyOp = cast<PerformConcurrentlyOp>(op->getParentOp()); 1072 auto foreachThreadOp = 1073 cast<ForeachThreadOp>(performConcurrentlyOp->getParentOp()); 1074 1075 // If the op bufferizes out-of-place, allocate the copy before the 1076 // ForeachThreadOp. 1077 rewriter.setInsertionPoint(foreachThreadOp); 1078 Value destBuffer = getBuffer(rewriter, insertOp.getDest(), options); 1079 1080 // Bufferize the ParallelInsertSliceOp outside of the PerformConcurrentlyOp. 1081 rewriter.setInsertionPoint(performConcurrentlyOp); 1082 Value srcBuffer = getBuffer(rewriter, insertOp.getSource(), options); 1083 Value subview = rewriter.create<memref::SubViewOp>( 1084 insertOp.getLoc(), destBuffer, insertOp.getMixedOffsets(), 1085 insertOp.getMixedSizes(), insertOp.getMixedStrides()); 1086 // This memcpy will fold away if everything bufferizes in-place. 1087 if (failed(options.createMemCpy(rewriter, insertOp.getLoc(), srcBuffer, 1088 subview))) 1089 return failure(); 1090 rewriter.eraseOp(op); 1091 1092 // Replace all uses of ForeachThreadOp (just the corresponding result). 1093 rewriter.setInsertionPointAfter(foreachThreadOp); 1094 Value toTensorOp = 1095 rewriter.create<ToTensorOp>(foreachThreadOp.getLoc(), destBuffer); 1096 unsigned resultNum = 0; 1097 for (Operation &nextOp : performConcurrentlyOp.yieldingOps()) { 1098 if (&nextOp == op) 1099 break; 1100 resultNum++; 1101 } 1102 assert(resultNum < foreachThreadOp->getNumResults() && 1103 "ParallelInsertSliceOp not found in PerformConcurrentlyOp"); 1104 SmallVector<OpOperand *> resultUses = llvm::to_vector( 1105 llvm::map_range(foreachThreadOp->getResult(resultNum).getUses(), 1106 [](OpOperand &use) { return &use; })); 1107 for (OpOperand *use : resultUses) { 1108 rewriter.updateRootInPlace(use->getOwner(), 1109 [&]() { use->set(toTensorOp); }); 1110 } 1111 return success(); 1112 } 1113 1114 // TODO: This is copied from TensorInterfaceImpl.cpp. Find a way to share 1115 // the code. 1116 bool isNotConflicting(Operation *op, OpOperand *uRead, 1117 OpOperand *uConflictingWrite, 1118 const AnalysisState &state) const { 1119 Operation *readingOp = uRead->getOwner(); 1120 Operation *conflictingWritingOp = uConflictingWrite->getOwner(); 1121 1122 // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If 1123 // uRead is an InsertSliceOp... 1124 if (auto insertSliceOp = dyn_cast<ParallelInsertSliceOp>(readingOp)) { 1125 // As an example, consider the following IR. 1126 // 1127 // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] } 1128 // %1 = linalg.fill %cst, %0 {inplace= [true] } 1129 // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1] 1130 // {inplace= [true] } 1131 1132 // TODO: Use insertSliceOp.getDestOpOperand etc. when available. 1133 if (uRead == &insertSliceOp->getOpOperand(1) /*dest*/ && 1134 hasMatchingExtractSliceOp(state, uConflictingWrite->get(), 1135 insertSliceOp)) 1136 // Case 1: The main insight is that InsertSliceOp reads only part of 1137 // the destination tensor. The overwritten area is not read. If 1138 // uConflictingWrite writes into exactly the memory location that is 1139 // being read by uRead, this is not a conflict. 1140 // 1141 // In the above example: 1142 // uRead = OpOperand 1 (%t) of tensor.insert_slice 1143 // uConflictingWrite = OpOperand 1 (%0) of linalg.fill 1144 // 1145 // The read of %t does not conflict with the write of the FillOp 1146 // (same aliases!) because the area that the FillOp operates on is 1147 // exactly the one that is *not* read via %t. 1148 return true; 1149 1150 if (uRead == &insertSliceOp->getOpOperand(0) /*source*/ && 1151 uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ && 1152 hasMatchingExtractSliceOp(state, uRead->get(), insertSliceOp)) 1153 // Case 2: The read of the source tensor and the write to the dest 1154 // tensor via an InsertSliceOp is not a conflict if the read is 1155 // reading exactly that part of an equivalent tensor that the 1156 // InsertSliceOp is writing. 1157 // 1158 // In the above example: 1159 // uRead = OpOperand 0 (%1) of tensor.insert_slice 1160 // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice 1161 return true; 1162 } 1163 1164 // If uConflictingWrite is an InsertSliceOp... 1165 if (auto insertSliceOp = 1166 dyn_cast<ParallelInsertSliceOp>(conflictingWritingOp)) 1167 // As an example, consider the following IR. 1168 // 1169 // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] } 1170 // %1 = linalg.fill %cst, %0 {inplace= [true] } 1171 // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1] 1172 // {inplace= [true] } 1173 // %3 = vector.transfer_read %1, %cst 1174 // 1175 // In the above example: 1176 // uRead = OpOperand 0 (%1) of vector.transfer_read 1177 // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice 1178 // lastWrite = %1 1179 // 1180 // This is not a conflict because the InsertSliceOp overwrites the 1181 // memory segment of %1 with the exact same data. (Effectively, there 1182 // is no memory write here.) 1183 if (uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ && 1184 state.areEquivalentBufferizedValues(uRead->get(), 1185 insertSliceOp.getSource()) && 1186 hasMatchingExtractSliceOp(state, insertSliceOp.getSource(), 1187 insertSliceOp)) 1188 return true; 1189 1190 return false; 1191 } 1192 }; 1193 1194 } // namespace 1195 } // namespace scf 1196 } // namespace mlir 1197 1198 void mlir::scf::registerBufferizableOpInterfaceExternalModels( 1199 DialectRegistry ®istry) { 1200 registry.addExtension(+[](MLIRContext *ctx, scf::SCFDialect *dialect) { 1201 ExecuteRegionOp::attachInterface<ExecuteRegionOpInterface>(*ctx); 1202 ForOp::attachInterface<ForOpInterface>(*ctx); 1203 IfOp::attachInterface<IfOpInterface>(*ctx); 1204 ForeachThreadOp::attachInterface<ForeachThreadOpInterface>(*ctx); 1205 ParallelInsertSliceOp::attachInterface<ParallelInsertSliceOpInterface>( 1206 *ctx); 1207 PerformConcurrentlyOp::attachInterface<PerformConcurrentlyOpInterface>( 1208 *ctx); 1209 WhileOp::attachInterface<WhileOpInterface>(*ctx); 1210 YieldOp::attachInterface<YieldOpInterface>(*ctx); 1211 }); 1212 } 1213