1 //===- OneShotAnalysis.cpp - One-Shot (Single Pass) Analysis --------------===// 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 // One-Shot Analysis analyzes function bodies. Function boundaries (FuncOp 10 // bbArgs, CallOps, ReturnOps) are treated as "unknown" ops. 11 // ModuleBufferization.cpp is an extension of One-Shot Analysis for simple 12 // call graphs. 13 // 14 // One-Shot Bufferize consists of two phases. 15 // 16 // 1. Analyze ops to decide which OpResults can bufferize inplace, i.e., without 17 // inserting buffer copies. The analysis queries op bufferization semantics 18 // via `BufferizableOpInterface`. 19 // 2. Bufferize ops by calling `BufferizableOpInterface::bufferize`. This 20 // function does not generate buffer copies for OpResults that were decided 21 // to bufferize inplace during the analysis phase. 22 // 23 // This file contains only the analysis. The actual bufferization is implemented 24 // via `bufferizeOp` (Bufferize.h). For convenience, this file also contains a 25 // helper function `runOneShotBufferize` that analyzes an op (and its nested 26 // ops) and then bufferizes it. 27 // 28 // Inplace bufferization decisions are passed from the analysis to the 29 // bufferization phase via `AnalysisState` and `BufferizationAliasInfo`. 30 // They can be printed for debugging purposes with `testAnalysisOnly`. 31 // 32 // Ops that do not implement `BufferizableOpInterface` can be analyzed but are 33 // treated conservatively. E.g., the analysis has to assume that their tensor 34 // OpOperands bufferize to memory writes. While such ops can be analyzed, they 35 // are not bufferized and remain in the IR. to_tensor and to_memref ops are 36 // inserted at the bufferization boundary. 37 // 38 // This analysis caters to high-performance codegen where buffer reuse is deemed 39 // critical: the analysis should fail if the bufferized form of the function 40 // needs to return a buffer, unless `allowReturnAllocs` is enabled. 41 42 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h" 43 44 #include <random> 45 46 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" 47 #include "mlir/Dialect/Bufferization/IR/Bufferization.h" 48 #include "mlir/Dialect/Bufferization/Transforms/Bufferize.h" 49 #include "mlir/Dialect/Func/IR/FuncOps.h" 50 #include "mlir/Dialect/MemRef/IR/MemRef.h" 51 #include "mlir/IR/AsmState.h" 52 #include "mlir/IR/Dominance.h" 53 #include "mlir/IR/Operation.h" 54 #include "mlir/IR/TypeUtilities.h" 55 #include "mlir/Interfaces/ControlFlowInterfaces.h" 56 #include "llvm/ADT/DenseSet.h" 57 #include "llvm/ADT/SetVector.h" 58 59 using namespace mlir; 60 using namespace mlir::bufferization; 61 62 static bool isaTensor(Type t) { return t.isa<TensorType>(); } 63 64 //===----------------------------------------------------------------------===// 65 // Bufferization-specific attribute manipulation. 66 // These are for testing and debugging only. Bufferization information is 67 // stored in BufferizationAliasInfo. When run with `testAnalysisOnly`, the IR 68 // is annotated with the results of the analysis (copied from 69 // BufferizationAliasInfo), so that they can be checked in tests. 70 //===----------------------------------------------------------------------===// 71 72 /// Attribute marker to specify op results that can be bufferized inPlace. 73 constexpr StringLiteral kInPlaceResultsAttrName = "__inplace_operands_attr__"; 74 75 /// Mark whether OpOperand will be bufferized inplace. 76 static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace) { 77 Operation *op = opOperand.getOwner(); 78 auto attr = 79 op->getAttr(kInPlaceResultsAttrName).dyn_cast_or_null<ArrayAttr>(); 80 SmallVector<StringRef> inPlaceVector; 81 if (attr) { 82 inPlaceVector = SmallVector<StringRef>( 83 llvm::to_vector<4>(attr.getAsValueRange<StringAttr>())); 84 } else { 85 inPlaceVector = SmallVector<StringRef>(op->getNumOperands(), "none"); 86 for (OpOperand &opOperand : op->getOpOperands()) 87 if (opOperand.get().getType().isa<TensorType>()) 88 inPlaceVector[opOperand.getOperandNumber()] = "false"; 89 } 90 91 inPlaceVector[opOperand.getOperandNumber()] = inPlace ? "true" : "false"; 92 op->setAttr(kInPlaceResultsAttrName, 93 OpBuilder(op).getStrArrayAttr(inPlaceVector)); 94 } 95 96 //===----------------------------------------------------------------------===// 97 // BufferizationAliasInfo 98 //===----------------------------------------------------------------------===// 99 100 BufferizationAliasInfo::BufferizationAliasInfo(Operation *rootOp) { 101 rootOp->walk([&](Operation *op) { 102 for (Value v : op->getResults()) 103 if (v.getType().isa<TensorType>()) 104 createAliasInfoEntry(v); 105 for (Region &r : op->getRegions()) 106 for (Block &b : r.getBlocks()) 107 for (auto bbArg : b.getArguments()) 108 if (bbArg.getType().isa<TensorType>()) 109 createAliasInfoEntry(bbArg); 110 }); 111 } 112 113 /// Add a new entry for `v` in the `aliasInfo` and `equivalentInfo`. In the 114 /// beginning the alias and equivalence sets only contain `v` itself. 115 void BufferizationAliasInfo::createAliasInfoEntry(Value v) { 116 aliasInfo.insert(v); 117 equivalentInfo.insert(v); 118 } 119 120 /// Insert an info entry for `newValue` and merge its alias set with that of 121 /// `alias`. 122 void BufferizationAliasInfo::insertNewBufferAlias(Value newValue, Value alias) { 123 createAliasInfoEntry(newValue); 124 aliasInfo.unionSets(newValue, alias); 125 } 126 127 /// Insert an info entry for `newValue` and merge its alias set with that of 128 /// `alias`. Additionally, merge their equivalence classes. 129 void BufferizationAliasInfo::insertNewBufferEquivalence(Value newValue, 130 Value alias) { 131 insertNewBufferAlias(newValue, alias); 132 equivalentInfo.unionSets(newValue, alias); 133 } 134 135 /// Return `true` if a value was marked as in-place bufferized. 136 bool BufferizationAliasInfo::isInPlace(OpOperand &operand) const { 137 return inplaceBufferized.contains(&operand); 138 } 139 140 /// Set the inPlace bufferization spec to true. 141 void BufferizationAliasInfo::bufferizeInPlace(OpOperand &operand, 142 AnalysisState &state) { 143 markInPlace(operand); 144 for (OpResult result : state.getAliasingOpResult(operand)) 145 aliasInfo.unionSets(result, operand.get()); 146 } 147 148 /// Set the inPlace bufferization spec to false. 149 void BufferizationAliasInfo::bufferizeOutOfPlace(OpOperand &operand) { 150 assert(!inplaceBufferized.contains(&operand) && 151 "OpOperand was already decided to bufferize inplace"); 152 } 153 154 /// Apply `fun` to all the members of the equivalence class of `v`. 155 void BufferizationAliasInfo::applyOnEquivalenceClass( 156 Value v, function_ref<void(Value)> fun) const { 157 auto leaderIt = equivalentInfo.findLeader(v); 158 for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit; 159 ++mit) { 160 fun(*mit); 161 } 162 } 163 164 /// Apply `fun` to all aliases of `v`. 165 void BufferizationAliasInfo::applyOnAliases( 166 Value v, function_ref<void(Value)> fun) const { 167 auto leaderIt = aliasInfo.findLeader(v); 168 for (auto mit = leaderIt, meit = aliasInfo.member_end(); mit != meit; ++mit) { 169 fun(*mit); 170 } 171 } 172 173 BufferizationAliasInfo::EquivalenceClassRangeType 174 BufferizationAliasInfo::getAliases(Value v) const { 175 DenseSet<Value> res; 176 auto it = aliasInfo.findValue(aliasInfo.getLeaderValue(v)); 177 for (auto mit = aliasInfo.member_begin(it), meit = aliasInfo.member_end(); 178 mit != meit; ++mit) { 179 res.insert(static_cast<Value>(*mit)); 180 } 181 return BufferizationAliasInfo::EquivalenceClassRangeType( 182 aliasInfo.member_begin(it), aliasInfo.member_end()); 183 } 184 185 //===----------------------------------------------------------------------===// 186 // OneShotAnalysisState 187 //===----------------------------------------------------------------------===// 188 189 OneShotAnalysisState::OneShotAnalysisState( 190 Operation *op, const OneShotBufferizationOptions &options) 191 : AnalysisState(options), aliasInfo(op) { 192 // Set up alias sets for OpResults that must bufferize in-place. This should 193 // be done before making any other bufferization decisions. 194 op->walk([&](BufferizableOpInterface bufferizableOp) { 195 if (!options.isOpAllowed(bufferizableOp)) 196 return WalkResult::skip(); 197 for (OpOperand &opOperand : bufferizableOp->getOpOperands()) { 198 if (opOperand.get().getType().isa<TensorType>()) 199 if (bufferizableOp.mustBufferizeInPlace(opOperand, *this)) { 200 for (OpResult opResult : 201 bufferizableOp.getAliasingOpResult(opOperand, *this)) 202 aliasInfo.unionAliasSets(opOperand.get(), opResult); 203 aliasInfo.markInPlace(opOperand); 204 } 205 } 206 return WalkResult::advance(); 207 }); 208 } 209 210 bool OneShotAnalysisState::isInPlace(OpOperand &opOperand) const { 211 return aliasInfo.isInPlace(opOperand); 212 } 213 214 bool OneShotAnalysisState::areEquivalentBufferizedValues(Value v1, 215 Value v2) const { 216 return aliasInfo.areEquivalentBufferizedValues(v1, v2); 217 } 218 219 // Gather yielded tensors in `yieldedTensors` by querying all aliases. This is 220 // to ensure that such information is available during bufferization time. 221 // Alias information can no longer be queried through BufferizationAliasInfo 222 // once we have started modifying the IR. 223 void OneShotAnalysisState::gatherYieldedTensors(Operation *op) { 224 op->walk([&](Operation *returnOp) { 225 if (!isRegionReturnLike(returnOp) || !getOptions().isOpAllowed(returnOp)) 226 return WalkResult::advance(); 227 228 for (OpOperand &returnValOperand : returnOp->getOpOperands()) { 229 Value returnVal = returnValOperand.get(); 230 // Skip non-tensor values. 231 if (!returnVal.getType().isa<TensorType>()) 232 continue; 233 234 // Add all aliases of the returned value. But only the ones that are in 235 // the same block. 236 aliasInfo.applyOnAliases(returnVal, [&](Value v) { 237 if (auto bbArg = v.dyn_cast<BlockArgument>()) { 238 if (bbArg.getOwner()->getParentOp() == returnOp->getParentOp()) 239 yieldedTensors.insert(bbArg); 240 return; 241 } 242 Operation *definingOp = v.getDefiningOp(); 243 if (definingOp->getParentOp() == returnOp->getParentOp()) 244 yieldedTensors.insert(v); 245 }); 246 } 247 248 return WalkResult::advance(); 249 }); 250 } 251 252 bool OneShotAnalysisState::isTensorYielded(Value tensor) const { 253 return yieldedTensors.contains(tensor); 254 } 255 256 //===----------------------------------------------------------------------===// 257 // Bufferization-specific alias analysis. 258 //===----------------------------------------------------------------------===// 259 260 /// Return true if opOperand has been decided to bufferize in-place. 261 static bool isInplaceMemoryWrite(OpOperand &opOperand, 262 const BufferizationAliasInfo &aliasInfo, 263 AnalysisState &state) { 264 // OpOperands that do not bufferize to a memory write do not write in-place. 265 if (!state.bufferizesToMemoryWrite(opOperand)) 266 return false; 267 // Check current bufferization decisions. 268 return aliasInfo.isInPlace(opOperand); 269 } 270 271 /// Return true if, under current bufferization decisions, the buffer of `value` 272 /// is not writable. 273 static bool aliasesNonWritableBuffer(Value value, 274 const BufferizationAliasInfo &aliasInfo, 275 AnalysisState &state) { 276 bool foundNonWritableBuffer = false; 277 aliasInfo.applyOnAliases(value, [&](Value v) { 278 // Query BufferizableOpInterface to see if the value is writable. 279 // TODO: Out-of-place bufferized value could be considered writable. 280 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(v)) 281 if (bufferizableOp && bufferizableOp.isWritable(v, state)) 282 return; 283 284 // Query BufferizableOpInterface to see if the BlockArgument is writable. 285 if (auto bbArg = v.dyn_cast<BlockArgument>()) 286 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp( 287 bbArg.getOwner()->getParentOp())) 288 if (bufferizableOp.isWritable(bbArg, state)) 289 return; 290 291 foundNonWritableBuffer = true; 292 }); 293 294 return foundNonWritableBuffer; 295 } 296 297 /// Return true if the buffer to which `operand` would bufferize is equivalent 298 /// to some buffer write. 299 static bool aliasesInPlaceWrite(Value value, 300 const BufferizationAliasInfo &aliasInfo, 301 AnalysisState &state) { 302 bool foundInplaceWrite = false; 303 aliasInfo.applyOnAliases(value, [&](Value v) { 304 for (auto &use : v.getUses()) { 305 if (isInplaceMemoryWrite(use, aliasInfo, state)) { 306 foundInplaceWrite = true; 307 return; 308 } 309 } 310 }); 311 return foundInplaceWrite; 312 } 313 314 /// Return true if `a` happens before `b`, i.e., `a` or one of its ancestors 315 /// properly dominates `b` and `b` is not inside `a`. 316 static bool happensBefore(Operation *a, Operation *b, 317 const DominanceInfo &domInfo) { 318 do { 319 // TODO: Instead of isProperAncestor + properlyDominates, we should use 320 // properlyDominatesImpl(a, b, /*enclosingOpOk=*/false) 321 if (a->isProperAncestor(b)) 322 return false; 323 if (domInfo.properlyDominates(a, b)) 324 return true; 325 } while ((a = a->getParentOp())); 326 return false; 327 } 328 329 /// For each given value, find the closest enclosing repetitive region. If this 330 /// is the same region for each value, return it. Otherwise return None. 331 /// Note: If there is no enclosing repetitive region, return nullptr. 332 static Optional<Region *> 333 getCommonEnclosingRepetitiveRegion(ArrayRef<Value> values) { 334 if (values.empty()) 335 return None; 336 Region *r = getEnclosingRepetitiveRegion(values.front()); 337 for (Value value : values.drop_front()) 338 if (getEnclosingRepetitiveRegion(value) != r) 339 return None; 340 return r; 341 } 342 343 /// Return `true` if the given tensor value is a memory write. Most values are 344 /// tensor writes, but ops that define a tensor SSA value without specifying its 345 /// contents (e.g., init_tensor) are not. 346 static bool isMemoryWrite(Value value, const AnalysisState &state) { 347 auto opResult = value.dyn_cast<OpResult>(); 348 if (!opResult) 349 return true; 350 auto bufferizableOp = state.getOptions().dynCastBufferizableOp(value); 351 if (!bufferizableOp) 352 return true; 353 return bufferizableOp.isMemoryWrite(opResult, state); 354 } 355 356 /// Annotate IR with details about the detected RaW conflict. 357 static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite, 358 Value lastWrite) { 359 static uint64_t counter = 0; 360 Operation *readingOp = uRead->getOwner(); 361 Operation *conflictingWritingOp = uConflictingWrite->getOwner(); 362 363 OpBuilder b(conflictingWritingOp->getContext()); 364 std::string id = "C_" + std::to_string(counter++); 365 366 std::string conflictingWriteAttr = 367 id + 368 "[CONFL-WRITE: " + std::to_string(uConflictingWrite->getOperandNumber()) + 369 "]"; 370 conflictingWritingOp->setAttr(conflictingWriteAttr, b.getUnitAttr()); 371 372 std::string readAttr = 373 id + "[READ: " + std::to_string(uRead->getOperandNumber()) + "]"; 374 readingOp->setAttr(readAttr, b.getUnitAttr()); 375 376 if (auto opResult = lastWrite.dyn_cast<OpResult>()) { 377 std::string lastWriteAttr = id + "[LAST-WRITE: result " + 378 std::to_string(opResult.getResultNumber()) + 379 "]"; 380 opResult.getDefiningOp()->setAttr(lastWriteAttr, b.getUnitAttr()); 381 } else { 382 auto bbArg = lastWrite.cast<BlockArgument>(); 383 std::string lastWriteAttr = 384 id + "[LAST-WRITE: bbArg " + std::to_string(bbArg.getArgNumber()) + "]"; 385 bbArg.getOwner()->getParentOp()->setAttr(lastWriteAttr, b.getUnitAttr()); 386 } 387 } 388 389 /// Given sets of uses and writes, return true if there is a RaW conflict under 390 /// the assumption that all given reads/writes alias the same buffer and that 391 /// all given writes bufferize inplace. 392 /// 393 /// A conflict is: According to SSA use-def chains, a read R is supposed to read 394 /// the result of a write W1. But because of bufferization decisions, R actually 395 /// reads another write W2. 396 static bool hasReadAfterWriteInterference( 397 const DenseSet<OpOperand *> &usesRead, 398 const DenseSet<OpOperand *> &usesWrite, const DominanceInfo &domInfo, 399 AnalysisState &state, const BufferizationAliasInfo &aliasInfo) { 400 const BufferizationOptions &options = state.getOptions(); 401 402 // Gather all written aliases. Skip over aliases that are not actual writes. 403 SmallVector<Value> writtenAliases; 404 for (OpOperand *uWrite : usesWrite) 405 if (isMemoryWrite(uWrite->get(), state)) 406 writtenAliases.push_back(uWrite->get()); 407 // Find the inner-most enclosing repetitive region of each alias. If this is 408 // the same region for every alias, save it in `repetitiveRegionOfWrites`. 409 Optional<Region *> repetitiveRegionOfWrites = 410 getCommonEnclosingRepetitiveRegion(writtenAliases); 411 412 for (OpOperand *uRead : usesRead) { 413 Operation *readingOp = uRead->getOwner(); 414 415 // Find most recent writes of uRead by following the SSA use-def chain. 416 // E.g.: 417 // 418 // %0 = "writing_op"(%t) : tensor<?x32> -> tensor<?xf32> 419 // %1 = "aliasing_op"(%0) : tensor<?x32> -> tensor<?xf32> 420 // %2 = "reading_op"(%1) : : tensor<?x32> -> not_a_tensor_type 421 // 422 // In the above example, if uRead is the OpOperand of reading_op, lastWrite 423 // is %0. Note that operations that create an alias but do not write (such 424 // as ExtractSliceOp) are skipped. 425 SetVector<Value> lastWrites = state.findLastPrecedingWrite(uRead->get()); 426 427 // Look for conflicting memory writes. Potential conflicts are writes to an 428 // alias that have been decided to bufferize inplace. 429 for (OpOperand *uConflictingWrite : usesWrite) { 430 // Throughout this loop, check for multiple requirements that have to be 431 // met for uConflictingWrite to be an actual conflict. 432 Operation *conflictingWritingOp = uConflictingWrite->getOwner(); 433 434 // Check if conflictingWritingOp is in the same repetitive region as all 435 // written aliases. If this is not the case, there is no meaningful 436 // `happensBefore` relationship because conflictingWritingOp may be 437 // executed multiple times. E.g.: 438 // 439 // %0 = ... : tensor<?xf32> 440 // scf.for ... { 441 // "reading_op"(%0) : tensor<?xf32> 442 // %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32> 443 // ... 444 // } 445 // 446 // In the above example, reading_op happens before writing_op according to 447 // op dominance. However, both ops may happen multiple times; in 448 // particular, the second execution of reading_op happens after the first 449 // execution of writing_op. This is problematic if the tensor they operate 450 // on (%0) is defined outside of the loop. 451 // 452 // Counter example: 453 // 454 // scf.for ... { 455 // %0 = ... : tensor<?xf32> 456 // "reading_op"(%0) : tensor<?xf32> 457 // %1 = "writing_op"(%0) : tensor<?xf32> -> tensor<?xf32> 458 // ... 459 // } 460 // 461 // In this example, %0 is in the same repetitive region as 462 // conflictingWritingOp, so op dominance can be used to compute the 463 // `happensBefore` relationship. 464 // 465 // Note: iter_args of loops are not aliases of their respective block 466 // arguments, so op domanice can be used when analyzing ops that operate 467 // on them. 468 // 469 // Note: If `writtenAliases` is empty, there are no memory writes outside 470 // of the repetitive region of conflictingWritingOp, which means that all 471 // relevant aliases are inside the same repetitive region. 472 bool canUseOpDominance = 473 writtenAliases.empty() || 474 repetitiveRegionOfWrites == 475 getEnclosingRepetitiveRegion(conflictingWritingOp); 476 477 // No conflict if the readingOp dominates conflictingWritingOp, i.e., the 478 // write is not visible when reading. 479 // 480 // Note: If ops are executed multiple times (e.g., because they are inside 481 // a loop), there may be no meaningful `happensBefore` relationship. 482 if (canUseOpDominance && 483 happensBefore(readingOp, conflictingWritingOp, domInfo)) 484 continue; 485 486 // No conflict if the reading use equals the use of the conflicting write. 487 // A use cannot conflict with itself. 488 // 489 // Note: Just being the same op is not enough. It has to be the same use. 490 // Note: If the op is executed multiple times (e.g., because it is inside 491 // a loop), it may be conflicting with itself. 492 if (canUseOpDominance && uConflictingWrite == uRead) 493 continue; 494 495 // No conflict if the op interface says so. 496 if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp)) 497 if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state)) 498 continue; 499 500 if (conflictingWritingOp != readingOp) 501 if (auto bufferizableOp = 502 options.dynCastBufferizableOp(conflictingWritingOp)) 503 if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state)) 504 continue; 505 506 // Ops are not conflicting if they are in mutually exclusive regions. 507 // 508 // Note: If ops are executed multiple times (e.g., because they are inside 509 // a loop), mutually exclusive regions may be executed multiple 510 // times. 511 if (canUseOpDominance && 512 insideMutuallyExclusiveRegions(readingOp, conflictingWritingOp)) 513 continue; 514 515 // Check all possible last writes. 516 for (Value lastWrite : lastWrites) { 517 // No conflict if the conflicting write happens before the last 518 // write. 519 if (Operation *writingOp = lastWrite.getDefiningOp()) { 520 if (happensBefore(conflictingWritingOp, writingOp, domInfo)) 521 // conflictingWritingOp happens before writingOp. No conflict. 522 continue; 523 // No conflict if conflictingWritingOp is contained in writingOp. 524 if (writingOp->isProperAncestor(conflictingWritingOp)) 525 continue; 526 } else { 527 auto bbArg = lastWrite.cast<BlockArgument>(); 528 Block *block = bbArg.getOwner(); 529 if (!block->findAncestorOpInBlock(*conflictingWritingOp)) 530 // conflictingWritingOp happens outside of the block. No 531 // conflict. 532 continue; 533 } 534 535 // No conflict if the conflicting write and the last write are the same 536 // use. 537 SmallVector<OpResult> aliasingOpResult = 538 state.getAliasingOpResult(*uConflictingWrite); 539 if (aliasingOpResult.size() == 1 && aliasingOpResult[0] == lastWrite) 540 continue; 541 542 // All requirements are met. Conflict found! 543 544 if (options.printConflicts) 545 annotateConflict(uRead, uConflictingWrite, lastWrite); 546 547 return true; 548 } 549 } 550 } 551 552 return false; 553 } 554 555 /// Return true if bufferizing `operand` inplace would create a conflict. A read 556 /// R and a write W of the same alias set is a conflict if inplace bufferization 557 /// of W changes the value read by R to a value different from the one that 558 /// would be expected by tracing back R's origin through SSA use-def chains. 559 /// A conflict can only be introduced by a new alias and/or an inplace 560 /// bufferization decision. 561 /// 562 /// Example: 563 /// %0 = tensor.extract_slice %t[...][...][1, 1] {inplace?} 564 /// %1 = vector.transfer_write %v1, %t {inplace} : vector<5xf32>, tensor<?xf32> 565 /// %e = tensor.extract_slice %1 566 /// %2 = vector.transfer_write %v2, %0 {inplace} : vector<6xf32>, tensor<?xf32> 567 /// %3 = vector.transfer_read %e, %cst : tensor<?xf32>, vector<7xf32> 568 /// 569 /// In the above example, the two TransferWriteOps have already been decided to 570 /// bufferize inplace. Bufferizing the ExtractSliceOp inplace would create a 571 /// conflict because: 572 /// * According to SSA use-def chains, we expect to read the result of %1. 573 /// * However, adding an alias {%0, %t} would mean that the second 574 /// TransferWriteOp overwrites the first one. Therefore, the TransferReadOp 575 /// would no longer be reading the result of %1. 576 /// 577 /// If `checkConsistencyOnly` is true, this function checks if there is a 578 /// read-after-write conflict without bufferizing `operand` inplace. This would 579 /// indicate a problem with the current inplace bufferization decisions. 580 /// 581 /// Note: If `checkConsistencyOnly`, this function may be called with a null 582 /// OpResult. In that case, only the consistency of bufferization decisions 583 /// involving aliases of the given OpOperand are checked. 584 static bool wouldCreateReadAfterWriteInterference( 585 OpOperand &operand, const DominanceInfo &domInfo, AnalysisState &state, 586 const BufferizationAliasInfo &aliasInfo, 587 bool checkConsistencyOnly = false) { 588 // Helper function to iterate on aliases of `root` and capture the reads. 589 auto getAliasingReads = [&](DenseSet<OpOperand *> &res, Value root) { 590 aliasInfo.applyOnAliases(root, [&](Value alias) { 591 for (auto &use : alias.getUses()) 592 // Read to a value that aliases root. 593 if (state.bufferizesToMemoryRead(use)) 594 res.insert(&use); 595 }); 596 }; 597 598 // Helper function to iterate on aliases of `root` and capture the writes. 599 auto getAliasingInplaceWrites = [&](DenseSet<OpOperand *> &res, Value root) { 600 aliasInfo.applyOnAliases(root, [&](Value alias) { 601 for (auto &use : alias.getUses()) 602 // Inplace write to a value that aliases root. 603 if (isInplaceMemoryWrite(use, aliasInfo, state)) 604 res.insert(&use); 605 }); 606 }; 607 608 // Collect reads and writes of all aliases of OpOperand and OpResult. 609 DenseSet<OpOperand *> usesRead, usesWrite; 610 getAliasingReads(usesRead, operand.get()); 611 getAliasingInplaceWrites(usesWrite, operand.get()); 612 for (OpResult result : state.getAliasingOpResult(operand)) { 613 getAliasingReads(usesRead, result); 614 getAliasingInplaceWrites(usesWrite, result); 615 } 616 if (!checkConsistencyOnly && state.bufferizesToMemoryWrite(operand)) 617 usesWrite.insert(&operand); 618 619 return hasReadAfterWriteInterference(usesRead, usesWrite, domInfo, state, 620 aliasInfo); 621 } 622 623 /// Return true if bufferizing `opOperand` inplace would create a write to a 624 /// non-writable buffer. 625 static bool 626 wouldCreateWriteToNonWritableBuffer(OpOperand &opOperand, 627 const BufferizationAliasInfo &aliasInfo, 628 AnalysisState &state) { 629 // Certain buffers are not writeable: 630 // 1. A function bbArg that is not inplaceable or 631 // 2. A constant op. 632 bool nonWritable = 633 aliasesNonWritableBuffer(opOperand.get(), aliasInfo, state); 634 if (!nonWritable) 635 return false; 636 637 // This is a problem only if the buffer is written to via some alias. 638 bool hasWrite = aliasesInPlaceWrite(opOperand.get(), aliasInfo, state) || 639 state.bufferizesToMemoryWrite(opOperand); 640 641 for (OpResult opResult : state.getAliasingOpResult(opOperand)) 642 hasWrite |= aliasesInPlaceWrite(opResult, aliasInfo, state); 643 644 return hasWrite; 645 } 646 647 //===----------------------------------------------------------------------===// 648 // Bufferization analyses. 649 //===----------------------------------------------------------------------===// 650 651 /// Determine if `operand` can be bufferized in-place. 652 static LogicalResult bufferizableInPlaceAnalysisImpl( 653 OpOperand &operand, BufferizationAliasInfo &aliasInfo, AnalysisState &state, 654 const DominanceInfo &domInfo) { 655 bool foundInterference = 656 wouldCreateWriteToNonWritableBuffer(operand, aliasInfo, state) || 657 wouldCreateReadAfterWriteInterference(operand, domInfo, state, aliasInfo); 658 659 if (foundInterference) 660 aliasInfo.bufferizeOutOfPlace(operand); 661 else 662 aliasInfo.bufferizeInPlace(operand, state); 663 664 return success(); 665 } 666 667 /// Analyze the `ops` to determine which OpOperands are inplaceable. Walk ops in 668 /// reverse and bufferize ops greedily. This is a good starter heuristic. 669 /// 670 /// Even if an op does not read or write, it may still create an alias when 671 /// bufferized in-place. An example of such ops is tensor.extract_slice. 672 /// 673 /// Rationale for bufferizing `%1 = tensor.extract_slice %0[...]` inplace: 674 /// 675 /// When bufferized out of place, an ExtractSliceOp lowers to alloc + copy. This 676 /// cannot change the flow of information for either the source or the 677 /// result buffers. 678 /// 679 /// When bufferized inplace, an ExtractSliceOp does not by itself create any 680 /// read or write from memory. Instead, it has the effect of merging the alias 681 /// sets of the source and the result buffers. 682 /// 683 /// An analysis is required to ensure inplace bufferization would not result in 684 /// RaW dependence violations. 685 static LogicalResult inPlaceAnalysis(SmallVector<Operation *> &ops, 686 BufferizationAliasInfo &aliasInfo, 687 AnalysisState &state, 688 const DominanceInfo &domInfo, 689 unsigned analysisFuzzerSeed = 0) { 690 if (analysisFuzzerSeed) { 691 // This is a fuzzer. For testing purposes only. Randomize the order in which 692 // operations are analyzed. The bufferization quality is likely worse, but 693 // we want to make sure that no assertions are triggered anywhere. 694 std::mt19937 g(analysisFuzzerSeed); 695 llvm::shuffle(ops.begin(), ops.end(), g); 696 } 697 698 // Walk ops in reverse for better interference analysis. 699 for (Operation *op : reverse(ops)) 700 for (OpOperand &opOperand : op->getOpOperands()) 701 if (opOperand.get().getType().isa<TensorType>()) 702 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) 703 if (failed(bufferizableInPlaceAnalysisImpl(opOperand, aliasInfo, 704 state, domInfo))) 705 return failure(); 706 707 return success(); 708 } 709 710 /// Return true if the given op has a tensor result or a tensor operand. 711 static bool hasTensorSemantics(Operation *op) { 712 bool hasTensorResult = any_of(op->getResultTypes(), isaTensor); 713 bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor); 714 return hasTensorResult || hasTensorOperand; 715 } 716 717 /// Analyze all ops that are contained in `op`. 718 static LogicalResult inPlaceAnalysis(Operation *op, 719 BufferizationAliasInfo &aliasInfo, 720 AnalysisState &state, 721 const DominanceInfo &domInfo, 722 unsigned analysisFuzzerSeed = 0) { 723 // Collect ops so we can build our own reverse traversal. 724 SmallVector<Operation *> ops; 725 op->walk([&](Operation *op) { 726 // No tensors => no buffers. 727 if (!hasTensorSemantics(op)) 728 return; 729 ops.push_back(op); 730 }); 731 732 return inPlaceAnalysis(ops, aliasInfo, state, domInfo, analysisFuzzerSeed); 733 } 734 735 /// Analyze equivalence of tied OpResult/OpOperand pairs of the given ops. 736 static void equivalenceAnalysis(SmallVector<Operation *> &ops, 737 BufferizationAliasInfo &aliasInfo, 738 AnalysisState &state) { 739 for (Operation *op : ops) 740 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) 741 for (OpResult opResult : op->getOpResults()) 742 if (opResult.getType().isa<TensorType>()) 743 for (OpOperand *opOperand : 744 bufferizableOp.getAliasingOpOperand(opResult, state)) 745 if (state.isInPlace(*opOperand)) 746 if (bufferizableOp.bufferRelation(opResult, state) == 747 BufferRelation::Equivalent) 748 aliasInfo.unionEquivalenceClasses(opResult, opOperand->get()); 749 } 750 751 /// Analyze equivalence of tied OpResult/OpOperand pairs of all ops contained 752 /// in `op`. 753 static void equivalenceAnalysis(Operation *op, 754 BufferizationAliasInfo &aliasInfo, 755 AnalysisState &state) { 756 // Traverse ops in PostOrder: Nested ops first, then enclosing ops. 757 SmallVector<Operation *> ops; 758 op->walk<WalkOrder::PostOrder>([&](Operation *op) { 759 // No tensors => no buffers. 760 if (none_of(op->getResultTypes(), isaTensor)) 761 return; 762 ops.push_back(op); 763 }); 764 765 equivalenceAnalysis(ops, aliasInfo, state); 766 } 767 768 /// Assert that the current bufferization decisions are consistent. 769 static LogicalResult 770 checkAliasInfoConsistency(Operation *op, const DominanceInfo &domInfo, 771 AnalysisState &state, 772 const BufferizationAliasInfo &aliasInfo) { 773 const BufferizationOptions &options = state.getOptions(); 774 Operation *inconsistentOp = nullptr; 775 WalkResult walkResult = op->walk([&](Operation *op) { 776 if (auto bufferizableOp = options.dynCastBufferizableOp(op)) 777 for (OpOperand &opOperand : op->getOpOperands()) 778 if (opOperand.get().getType().isa<TensorType>()) { 779 if (wouldCreateReadAfterWriteInterference( 780 opOperand, domInfo, state, aliasInfo, 781 /*checkConsistencyOnly=*/true)) { 782 // This error can happen if certain "mustBufferizeInPlace" interface 783 // methods are implemented incorrectly, such that the IR already has 784 // a RaW conflict before making any bufferization decisions. 785 inconsistentOp = op; 786 return WalkResult::interrupt(); 787 } 788 } 789 return WalkResult::advance(); 790 }); 791 792 if (walkResult.wasInterrupted()) 793 return inconsistentOp->emitError("input IR has RaW conflict"); 794 return success(); 795 } 796 797 /// Annotate the IR with the result of the analysis. For testing/debugging only. 798 static void 799 annotateOpsWithBufferizationMarkers(Operation *op, 800 const BufferizationAliasInfo &aliasInfo, 801 AnalysisState &state) { 802 op->walk([&](Operation *op) { 803 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) 804 for (OpOperand &opOperand : op->getOpOperands()) 805 if (opOperand.get().getType().isa<TensorType>()) 806 setInPlaceOpOperand(opOperand, aliasInfo.isInPlace(opOperand)); 807 }); 808 } 809 810 /// Assert that IR is in destination-passing style. I.e., every value that is 811 /// returned or yielded from a block is: 812 /// * aliasing a bbArg of that block or a parent block, or 813 /// * aliasing an OpResult of a op in a parent block. 814 /// 815 /// Example: 816 /// ``` 817 /// %0 = "some_op" : tensor<?xf32> 818 /// %1 = scf.if %c -> (tensor<?xf32>) { 819 /// scf.yield %0 : tensor<?xf32> 820 /// } else { 821 /// %t = linalg.init_tensor : tensor<?xf32> 822 /// scf.yield %t : tensor<?xf32> 823 /// } 824 /// ``` 825 /// In the above example, the first scf.yield op satifies destination-passing 826 /// style because the yielded value %0 is defined in the parent block. The 827 /// second scf.yield op does not satisfy destination-passing style because the 828 /// yielded value %t is defined in the same block as the scf.yield op. 829 // TODO: The current implementation checks for equivalent values instead of 830 // aliasing values, which is stricter than needed. We can currently not check 831 // for aliasing values because the analysis is a maybe-alias analysis and we 832 // need a must-alias analysis here. 833 static LogicalResult 834 assertDestinationPassingStyle(Operation *op, AnalysisState &state, 835 BufferizationAliasInfo &aliasInfo, 836 SmallVector<Operation *> &newOps) { 837 LogicalResult status = success(); 838 DominanceInfo domInfo(op); 839 op->walk([&](Operation *returnOp) { 840 if (!isRegionReturnLike(returnOp) || 841 !state.getOptions().isOpAllowed(returnOp)) 842 return WalkResult::advance(); 843 844 for (OpOperand &returnValOperand : returnOp->getOpOperands()) { 845 Value returnVal = returnValOperand.get(); 846 // Skip non-tensor values. 847 if (!returnVal.getType().isa<TensorType>()) 848 continue; 849 850 bool foundEquivValue = false; 851 aliasInfo.applyOnEquivalenceClass(returnVal, [&](Value equivVal) { 852 if (auto bbArg = equivVal.dyn_cast<BlockArgument>()) { 853 Operation *definingOp = bbArg.getOwner()->getParentOp(); 854 if (definingOp->isProperAncestor(returnOp)) 855 foundEquivValue = true; 856 return; 857 } 858 859 Operation *definingOp = equivVal.getDefiningOp(); 860 if (definingOp->getBlock()->findAncestorOpInBlock( 861 *returnOp->getParentOp())) 862 // Skip ops that happen after `returnOp` and parent ops. 863 if (happensBefore(definingOp, returnOp, domInfo)) 864 foundEquivValue = true; 865 }); 866 867 if (!foundEquivValue) 868 status = 869 returnOp->emitError() 870 << "operand #" << returnValOperand.getOperandNumber() 871 << " of ReturnLike op does not satisfy destination passing style"; 872 } 873 874 return WalkResult::advance(); 875 }); 876 877 return status; 878 } 879 880 LogicalResult bufferization::analyzeOp(Operation *op, 881 OneShotAnalysisState &state) { 882 DominanceInfo domInfo(op); 883 BufferizationAliasInfo &aliasInfo = state.getAliasInfo(); 884 const auto &options = 885 static_cast<const OneShotBufferizationOptions &>(state.getOptions()); 886 887 // Catch incorrect API usage. 888 assert((state.hasDialectState(func::FuncDialect::getDialectNamespace()) || 889 !options.bufferizeFunctionBoundaries) && 890 "must use ModuleBufferize to bufferize function boundaries"); 891 892 if (failed(checkAliasInfoConsistency(op, domInfo, state, aliasInfo))) 893 return failure(); 894 895 // If the analysis fails, just return. 896 if (failed(inPlaceAnalysis(op, aliasInfo, state, domInfo, 897 options.analysisFuzzerSeed))) 898 return failure(); 899 equivalenceAnalysis(op, aliasInfo, state); 900 901 for (const PostAnalysisStepFn &fn : options.postAnalysisSteps) { 902 SmallVector<Operation *> newOps; 903 if (failed(fn(op, state, aliasInfo, newOps))) 904 return failure(); 905 // Analyze ops that were created by the PostAnalysisStepFn. 906 if (failed(inPlaceAnalysis(newOps, aliasInfo, state, domInfo))) 907 return failure(); 908 equivalenceAnalysis(newOps, aliasInfo, state); 909 } 910 911 bool failedAnalysis = false; 912 if (!options.allowReturnAllocs) { 913 SmallVector<Operation *> newOps; 914 failedAnalysis |= 915 failed(assertDestinationPassingStyle(op, state, aliasInfo, newOps)); 916 } 917 918 // Gather all yielded tensors. 919 state.gatherYieldedTensors(op); 920 921 // Analysis verification: After setting up alias/equivalence sets, each op 922 // can check for expected invariants/limitations and fail the analysis if 923 // necessary. 924 op->walk([&](Operation *op) { 925 if (BufferizableOpInterface bufferizableOp = 926 options.dynCastBufferizableOp(op)) 927 failedAnalysis |= failed(bufferizableOp.verifyAnalysis(state)); 928 }); 929 930 // Annotate operations if we only want to report the analysis. 931 if (options.testAnalysisOnly) 932 annotateOpsWithBufferizationMarkers(op, aliasInfo, state); 933 934 return success(!failedAnalysis); 935 } 936 937 LogicalResult 938 bufferization::runOneShotBufferize(Operation *op, 939 const OneShotBufferizationOptions &options) { 940 OneShotAnalysisState state(op, options); 941 if (failed(analyzeOp(op, state))) 942 return failure(); 943 if (options.testAnalysisOnly) 944 return success(); 945 return bufferizeOp(op, state); 946 } 947