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 `BufferizationState` 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 `allowReturnMemref` 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/MemRef/IR/MemRef.h" 50 #include "mlir/IR/AsmState.h" 51 #include "mlir/IR/Dominance.h" 52 #include "mlir/IR/Operation.h" 53 #include "mlir/IR/TypeUtilities.h" 54 #include "mlir/Interfaces/ControlFlowInterfaces.h" 55 #include "llvm/ADT/DenseSet.h" 56 #include "llvm/ADT/SetVector.h" 57 58 using namespace mlir; 59 using namespace mlir::bufferization; 60 61 static bool isaTensor(Type t) { return t.isa<TensorType>(); } 62 63 //===----------------------------------------------------------------------===// 64 // Bufferization-specific attribute manipulation. 65 // These are for testing and debugging only. Bufferization information is 66 // stored in BufferizationAliasInfo. When run with `testAnalysisOnly`, the IR 67 // is annotated with the results of the analysis (copied from 68 // BufferizationAliasInfo), so that they can be checked in tests. 69 //===----------------------------------------------------------------------===// 70 71 /// Attribute marker to specify op results that can be bufferized inPlace. 72 constexpr StringLiteral kInPlaceResultsAttrName = "__inplace_operands_attr__"; 73 74 /// Mark whether OpOperand will be bufferized inplace. 75 static void setInPlaceOpOperand(OpOperand &opOperand, bool inPlace) { 76 Operation *op = opOperand.getOwner(); 77 auto attr = 78 op->getAttr(kInPlaceResultsAttrName).dyn_cast_or_null<ArrayAttr>(); 79 SmallVector<StringRef> inPlaceVector; 80 if (attr) { 81 inPlaceVector = SmallVector<StringRef>( 82 llvm::to_vector<4>(attr.getAsValueRange<StringAttr>())); 83 } else { 84 inPlaceVector = SmallVector<StringRef>(op->getNumOperands(), "none"); 85 for (OpOperand &opOperand : op->getOpOperands()) 86 if (opOperand.get().getType().isa<TensorType>()) 87 inPlaceVector[opOperand.getOperandNumber()] = "false"; 88 } 89 90 inPlaceVector[opOperand.getOperandNumber()] = inPlace ? "true" : "false"; 91 op->setAttr(kInPlaceResultsAttrName, 92 OpBuilder(op).getStrArrayAttr(inPlaceVector)); 93 } 94 95 //===----------------------------------------------------------------------===// 96 // BufferizationAliasInfo 97 //===----------------------------------------------------------------------===// 98 99 BufferizationAliasInfo::BufferizationAliasInfo(Operation *rootOp) { 100 rootOp->walk([&](Operation *op) { 101 for (Value v : op->getResults()) 102 if (v.getType().isa<TensorType>()) 103 createAliasInfoEntry(v); 104 for (Region &r : op->getRegions()) 105 for (Block &b : r.getBlocks()) 106 for (auto bbArg : b.getArguments()) 107 if (bbArg.getType().isa<TensorType>()) 108 createAliasInfoEntry(bbArg); 109 }); 110 } 111 112 /// Add a new entry for `v` in the `aliasInfo` and `equivalentInfo`. In the 113 /// beginning the alias and equivalence sets only contain `v` itself. 114 void BufferizationAliasInfo::createAliasInfoEntry(Value v) { 115 aliasInfo.insert(v); 116 equivalentInfo.insert(v); 117 } 118 119 /// Insert an info entry for `newValue` and merge its alias set with that of 120 /// `alias`. 121 void BufferizationAliasInfo::insertNewBufferAlias(Value newValue, Value alias) { 122 createAliasInfoEntry(newValue); 123 aliasInfo.unionSets(newValue, alias); 124 } 125 126 /// Insert an info entry for `newValue` and merge its alias set with that of 127 /// `alias`. Additionally, merge their equivalence classes. 128 void BufferizationAliasInfo::insertNewBufferEquivalence(Value newValue, 129 Value alias) { 130 insertNewBufferAlias(newValue, alias); 131 equivalentInfo.unionSets(newValue, alias); 132 } 133 134 /// Return `true` if a value was marked as in-place bufferized. 135 bool BufferizationAliasInfo::isInPlace(OpOperand &operand) const { 136 return inplaceBufferized.contains(&operand); 137 } 138 139 /// Set the inPlace bufferization spec to true. 140 void BufferizationAliasInfo::bufferizeInPlace(OpOperand &operand, 141 BufferizationState &state) { 142 markInPlace(operand); 143 if (OpResult result = state.getAliasingOpResult(operand)) 144 aliasInfo.unionSets(result, operand.get()); 145 } 146 147 /// Set the inPlace bufferization spec to false. 148 void BufferizationAliasInfo::bufferizeOutOfPlace(OpOperand &operand) { 149 assert(!inplaceBufferized.contains(&operand) && 150 "OpOperand was already decided to bufferize inplace"); 151 } 152 153 /// Apply `fun` to all the members of the equivalence class of `v`. 154 void BufferizationAliasInfo::applyOnEquivalenceClass( 155 Value v, function_ref<void(Value)> fun) const { 156 auto leaderIt = equivalentInfo.findLeader(v); 157 for (auto mit = leaderIt, meit = equivalentInfo.member_end(); mit != meit; 158 ++mit) { 159 fun(*mit); 160 } 161 } 162 163 /// Apply `fun` to all aliases of `v`. 164 void BufferizationAliasInfo::applyOnAliases( 165 Value v, function_ref<void(Value)> fun) const { 166 auto leaderIt = aliasInfo.findLeader(v); 167 for (auto mit = leaderIt, meit = aliasInfo.member_end(); mit != meit; ++mit) { 168 fun(*mit); 169 } 170 } 171 172 BufferizationAliasInfo::EquivalenceClassRangeType 173 BufferizationAliasInfo::getAliases(Value v) const { 174 DenseSet<Value> res; 175 auto it = aliasInfo.findValue(aliasInfo.getLeaderValue(v)); 176 for (auto mit = aliasInfo.member_begin(it), meit = aliasInfo.member_end(); 177 mit != meit; ++mit) { 178 res.insert(static_cast<Value>(*mit)); 179 } 180 return BufferizationAliasInfo::EquivalenceClassRangeType( 181 aliasInfo.member_begin(it), aliasInfo.member_end()); 182 } 183 184 //===----------------------------------------------------------------------===// 185 // AnalysisBufferizationState 186 //===----------------------------------------------------------------------===// 187 188 AnalysisBufferizationState::AnalysisBufferizationState( 189 Operation *op, const AnalysisBufferizationOptions &options) 190 : BufferizationState(options), aliasInfo(op) { 191 // Set up alias sets for OpResults that must bufferize in-place. This should 192 // be done before making any other bufferization decisions. 193 op->walk([&](BufferizableOpInterface bufferizableOp) { 194 if (!options.isOpAllowed(bufferizableOp)) 195 return WalkResult::skip(); 196 for (OpOperand &opOperand : bufferizableOp->getOpOperands()) { 197 if (opOperand.get().getType().isa<TensorType>()) 198 if (bufferizableOp.mustBufferizeInPlace(opOperand, *this)) { 199 if (OpResult opResult = 200 bufferizableOp.getAliasingOpResult(opOperand, *this)) 201 aliasInfo.unionAliasSets(opOperand.get(), opResult); 202 aliasInfo.markInPlace(opOperand); 203 } 204 } 205 return WalkResult::advance(); 206 }); 207 } 208 209 bool AnalysisBufferizationState::isInPlace(OpOperand &opOperand) const { 210 return aliasInfo.isInPlace(opOperand); 211 } 212 213 bool AnalysisBufferizationState::areEquivalentBufferizedValues(Value v1, 214 Value v2) const { 215 return aliasInfo.areEquivalentBufferizedValues(v1, v2); 216 } 217 218 //===----------------------------------------------------------------------===// 219 // Bufferization-specific alias analysis. 220 //===----------------------------------------------------------------------===// 221 222 /// Return true if opOperand has been decided to bufferize in-place. 223 static bool isInplaceMemoryWrite(OpOperand &opOperand, 224 const BufferizationAliasInfo &aliasInfo, 225 BufferizationState &state) { 226 // OpOperands that do not bufferize to a memory write do not write in-place. 227 if (!state.bufferizesToMemoryWrite(opOperand)) 228 return false; 229 // Check current bufferization decisions. 230 return aliasInfo.isInPlace(opOperand); 231 } 232 233 /// Return true if, under current bufferization decisions, the buffer of `value` 234 /// is not writable. 235 static bool aliasesNonWritableBuffer(Value value, 236 const BufferizationAliasInfo &aliasInfo, 237 BufferizationState &state) { 238 bool foundNonWritableBuffer = false; 239 aliasInfo.applyOnAliases(value, [&](Value v) { 240 // Query BufferizableOpInterface to see if the value is writable. 241 // TODO: Out-of-place bufferized value could be considered writable. 242 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(v)) 243 if (bufferizableOp && bufferizableOp.isWritable(v, state)) 244 return; 245 246 // Query BufferizableOpInterface to see if the BlockArgument is writable. 247 if (auto bbArg = v.dyn_cast<BlockArgument>()) 248 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp( 249 bbArg.getOwner()->getParentOp())) 250 if (bufferizableOp.isWritable(bbArg, state)) 251 return; 252 253 foundNonWritableBuffer = true; 254 }); 255 256 return foundNonWritableBuffer; 257 } 258 259 /// Return true if the buffer to which `operand` would bufferize is equivalent 260 /// to some buffer write. 261 static bool aliasesInPlaceWrite(Value value, 262 const BufferizationAliasInfo &aliasInfo, 263 BufferizationState &state) { 264 bool foundInplaceWrite = false; 265 aliasInfo.applyOnAliases(value, [&](Value v) { 266 for (auto &use : v.getUses()) { 267 if (isInplaceMemoryWrite(use, aliasInfo, state)) { 268 foundInplaceWrite = true; 269 return; 270 } 271 } 272 }); 273 return foundInplaceWrite; 274 } 275 276 /// Return true if `a` happens before `b`, i.e., `a` or one of its ancestors 277 /// properly dominates `b` and `b` is not inside `a`. 278 static bool happensBefore(Operation *a, Operation *b, 279 const DominanceInfo &domInfo) { 280 do { 281 // TODO: Instead of isProperAncestor + properlyDominates, we should use 282 // properlyDominatesImpl(a, b, /*enclosingOpOk=*/false) 283 if (a->isProperAncestor(b)) 284 return false; 285 if (domInfo.properlyDominates(a, b)) 286 return true; 287 } while ((a = a->getParentOp())); 288 return false; 289 } 290 291 /// Annotate IR with details about the detected RaW conflict. 292 static void annotateConflict(OpOperand *uRead, OpOperand *uConflictingWrite, 293 Value lastWrite) { 294 static uint64_t counter = 0; 295 Operation *readingOp = uRead->getOwner(); 296 Operation *conflictingWritingOp = uConflictingWrite->getOwner(); 297 298 OpBuilder b(conflictingWritingOp->getContext()); 299 std::string id = "C_" + std::to_string(counter++); 300 301 std::string conflictingWriteAttr = 302 id + 303 "[CONFL-WRITE: " + std::to_string(uConflictingWrite->getOperandNumber()) + 304 "]"; 305 conflictingWritingOp->setAttr(conflictingWriteAttr, b.getUnitAttr()); 306 307 std::string readAttr = 308 id + "[READ: " + std::to_string(uRead->getOperandNumber()) + "]"; 309 readingOp->setAttr(readAttr, b.getUnitAttr()); 310 311 if (auto opResult = lastWrite.dyn_cast<OpResult>()) { 312 std::string lastWriteAttr = id + "[LAST-WRITE: result " + 313 std::to_string(opResult.getResultNumber()) + 314 "]"; 315 opResult.getDefiningOp()->setAttr(lastWriteAttr, b.getUnitAttr()); 316 } else { 317 auto bbArg = lastWrite.cast<BlockArgument>(); 318 std::string lastWriteAttr = 319 id + "[LAST-WRITE: bbArg " + std::to_string(bbArg.getArgNumber()) + "]"; 320 bbArg.getOwner()->getParentOp()->setAttr(lastWriteAttr, b.getUnitAttr()); 321 } 322 } 323 324 /// Given sets of uses and writes, return true if there is a RaW conflict under 325 /// the assumption that all given reads/writes alias the same buffer and that 326 /// all given writes bufferize inplace. 327 /// 328 /// A conflict is: According to SSA use-def chains, a read R is supposed to read 329 /// the result of a write W1. But because of bufferization decisions, R actually 330 /// reads another write W2. 331 static bool hasReadAfterWriteInterference( 332 const DenseSet<OpOperand *> &usesRead, 333 const DenseSet<OpOperand *> &usesWrite, const DominanceInfo &domInfo, 334 BufferizationState &state, const BufferizationAliasInfo &aliasInfo) { 335 const BufferizationOptions &options = state.getOptions(); 336 337 for (OpOperand *uRead : usesRead) { 338 Operation *readingOp = uRead->getOwner(); 339 340 // Find most recent writes of uRead by following the SSA use-def chain. 341 // E.g.: 342 // 343 // %0 = "writing_op"(%t) : tensor<?x32> -> tensor<?xf32> 344 // %1 = "aliasing_op"(%0) : tensor<?x32> -> tensor<?xf32> 345 // %2 = "reading_op"(%1) : : tensor<?x32> -> not_a_tensor_type 346 // 347 // In the above example, if uRead is the OpOperand of reading_op, lastWrite 348 // is %0. Note that operations that create an alias but do not write (such 349 // as ExtractSliceOp) are skipped. 350 SetVector<Value> lastWrites = state.findLastPrecedingWrite(uRead->get()); 351 352 // Look for conflicting memory writes. Potential conflicts are writes to an 353 // alias that have been decided to bufferize inplace. 354 for (OpOperand *uConflictingWrite : usesWrite) { 355 // Throughout this loop, check for multiple requirements that have to be 356 // met for uConflictingWrite to be an actual conflict. 357 Operation *conflictingWritingOp = uConflictingWrite->getOwner(); 358 359 // No conflict if the readingOp dominates conflictingWritingOp, i.e., the 360 // write is not visible when reading. 361 if (happensBefore(readingOp, conflictingWritingOp, domInfo)) 362 continue; 363 364 // No conflict if the reading use equals the use of the conflicting write. 365 // A use cannot conflict with itself. Note: Just being the same op is not 366 // enough. It has to be the same use. 367 if (uConflictingWrite == uRead) 368 continue; 369 370 // No conflict if the op interface says so. 371 if (auto bufferizableOp = options.dynCastBufferizableOp(readingOp)) 372 if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state)) 373 continue; 374 375 if (conflictingWritingOp != readingOp) 376 if (auto bufferizableOp = 377 options.dynCastBufferizableOp(conflictingWritingOp)) 378 if (bufferizableOp.isNotConflicting(uRead, uConflictingWrite, state)) 379 continue; 380 381 // Ops are not conflicting if they are in mutually exclusive regions. 382 if (insideMutuallyExclusiveRegions(readingOp, conflictingWritingOp)) 383 continue; 384 385 // Check all possible last writes. 386 for (Value lastWrite : lastWrites) { 387 // No conflict if the conflicting write happens before the last 388 // write. 389 if (Operation *writingOp = lastWrite.getDefiningOp()) { 390 if (happensBefore(conflictingWritingOp, writingOp, domInfo)) 391 // conflictingWritingOp happens before writingOp. No conflict. 392 continue; 393 // No conflict if conflictingWritingOp is contained in writingOp. 394 if (writingOp->isProperAncestor(conflictingWritingOp)) 395 continue; 396 } else { 397 auto bbArg = lastWrite.cast<BlockArgument>(); 398 Block *block = bbArg.getOwner(); 399 if (!block->findAncestorOpInBlock(*conflictingWritingOp)) 400 // conflictingWritingOp happens outside of the block. No 401 // conflict. 402 continue; 403 } 404 405 // No conflict if the conflicting write and the last write are the same 406 // use. 407 if (state.getAliasingOpResult(*uConflictingWrite) == lastWrite) 408 continue; 409 410 // All requirements are met. Conflict found! 411 412 if (options.printConflicts) 413 annotateConflict(uRead, uConflictingWrite, lastWrite); 414 415 return true; 416 } 417 } 418 } 419 420 return false; 421 } 422 423 /// Return true if bufferizing `operand` inplace would create a conflict. A read 424 /// R and a write W of the same alias set is a conflict if inplace bufferization 425 /// of W changes the value read by R to a value different from the one that 426 /// would be expected by tracing back R's origin through SSA use-def chains. 427 /// A conflict can only be introduced by a new alias and/or an inplace 428 /// bufferization decision. 429 /// 430 /// Example: 431 /// %0 = tensor.extract_slice %t[...][...][1, 1] {inplace?} 432 /// %1 = vector.transfer_write %v1, %t {inplace} : vector<5xf32>, tensor<?xf32> 433 /// %e = tensor.extract_slice %1 434 /// %2 = vector.transfer_write %v2, %0 {inplace} : vector<6xf32>, tensor<?xf32> 435 /// %3 = vector.transfer_read %e, %cst : tensor<?xf32>, vector<7xf32> 436 /// 437 /// In the above example, the two TransferWriteOps have already been decided to 438 /// bufferize inplace. Bufferizing the ExtractSliceOp inplace would create a 439 /// conflict because: 440 /// * According to SSA use-def chains, we expect to read the result of %1. 441 /// * However, adding an alias {%0, %t} would mean that the second 442 /// TransferWriteOp overwrites the first one. Therefore, the TransferReadOp 443 /// would no longer be reading the result of %1. 444 /// 445 /// If `checkConsistencyOnly` is true, this function checks if there is a 446 /// read-after-write conflict without bufferizing `operand` inplace. This would 447 /// indicate a problem with the current inplace bufferization decisions. 448 /// 449 /// Note: If `checkConsistencyOnly`, this function may be called with a null 450 /// OpResult. In that case, only the consistency of bufferization decisions 451 /// involving aliases of the given OpOperand are checked. 452 static bool wouldCreateReadAfterWriteInterference( 453 OpOperand &operand, const DominanceInfo &domInfo, BufferizationState &state, 454 const BufferizationAliasInfo &aliasInfo, 455 bool checkConsistencyOnly = false) { 456 // Helper function to iterate on aliases of `root` and capture the reads. 457 auto getAliasingReads = [&](DenseSet<OpOperand *> &res, Value root) { 458 aliasInfo.applyOnAliases(root, [&](Value alias) { 459 for (auto &use : alias.getUses()) 460 // Read to a value that aliases root. 461 if (state.bufferizesToMemoryRead(use)) 462 res.insert(&use); 463 }); 464 }; 465 466 // Helper function to iterate on aliases of `root` and capture the writes. 467 auto getAliasingInplaceWrites = [&](DenseSet<OpOperand *> &res, Value root) { 468 aliasInfo.applyOnAliases(root, [&](Value alias) { 469 for (auto &use : alias.getUses()) 470 // Inplace write to a value that aliases root. 471 if (isInplaceMemoryWrite(use, aliasInfo, state)) 472 res.insert(&use); 473 }); 474 }; 475 476 // Collect reads and writes of all aliases of OpOperand and OpResult. 477 DenseSet<OpOperand *> usesRead, usesWrite; 478 getAliasingReads(usesRead, operand.get()); 479 getAliasingInplaceWrites(usesWrite, operand.get()); 480 if (OpResult result = state.getAliasingOpResult(operand)) { 481 getAliasingReads(usesRead, result); 482 getAliasingInplaceWrites(usesWrite, result); 483 } 484 if (!checkConsistencyOnly && state.bufferizesToMemoryWrite(operand)) 485 usesWrite.insert(&operand); 486 487 return hasReadAfterWriteInterference(usesRead, usesWrite, domInfo, state, 488 aliasInfo); 489 } 490 491 /// Return true if bufferizing `opOperand` inplace would create a write to a 492 /// non-writable buffer. 493 static bool 494 wouldCreateWriteToNonWritableBuffer(OpOperand &opOperand, 495 const BufferizationAliasInfo &aliasInfo, 496 BufferizationState &state) { 497 // Certain buffers are not writeable: 498 // 1. A function bbArg that is not inplaceable or 499 // 2. A constant op. 500 bool nonWritable = 501 aliasesNonWritableBuffer(opOperand.get(), aliasInfo, state); 502 if (!nonWritable) 503 return false; 504 505 // This is a problem only if the buffer is written to via some alias. 506 bool hasWrite = aliasesInPlaceWrite(opOperand.get(), aliasInfo, state) || 507 state.bufferizesToMemoryWrite(opOperand); 508 509 if (OpResult opResult = state.getAliasingOpResult(opOperand)) 510 hasWrite |= aliasesInPlaceWrite(opResult, aliasInfo, state); 511 512 return hasWrite; 513 } 514 515 //===----------------------------------------------------------------------===// 516 // Bufferization analyses. 517 //===----------------------------------------------------------------------===// 518 519 /// Determine if `operand` can be bufferized in-place. 520 static LogicalResult bufferizableInPlaceAnalysisImpl( 521 OpOperand &operand, BufferizationAliasInfo &aliasInfo, 522 BufferizationState &state, const DominanceInfo &domInfo) { 523 bool foundInterference = 524 wouldCreateWriteToNonWritableBuffer(operand, aliasInfo, state) || 525 wouldCreateReadAfterWriteInterference(operand, domInfo, state, aliasInfo); 526 527 if (foundInterference) 528 aliasInfo.bufferizeOutOfPlace(operand); 529 else 530 aliasInfo.bufferizeInPlace(operand, state); 531 532 return success(); 533 } 534 535 /// Analyze the `ops` to determine which OpOperands are inplaceable. Walk ops in 536 /// reverse and bufferize ops greedily. This is a good starter heuristic. 537 /// 538 /// Even if an op does not read or write, it may still create an alias when 539 /// bufferized in-place. An example of such ops is tensor.extract_slice. 540 /// 541 /// Rationale for bufferizing `%1 = tensor.extract_slice %0[...]` inplace: 542 /// 543 /// When bufferized out of place, an ExtractSliceOp lowers to alloc + copy. This 544 /// cannot change the flow of information for either the source or the 545 /// result buffers. 546 /// 547 /// When bufferized inplace, an ExtractSliceOp does not by itself create any 548 /// read or write from memory. Instead, it has the effect of merging the alias 549 /// sets of the source and the result buffers. 550 /// 551 /// An analysis is required to ensure inplace bufferization would not result in 552 /// RaW dependence violations. 553 static LogicalResult inPlaceAnalysis(SmallVector<Operation *> &ops, 554 BufferizationAliasInfo &aliasInfo, 555 BufferizationState &state, 556 const DominanceInfo &domInfo, 557 unsigned analysisFuzzerSeed = 0) { 558 if (analysisFuzzerSeed) { 559 // This is a fuzzer. For testing purposes only. Randomize the order in which 560 // operations are analyzed. The bufferization quality is likely worse, but 561 // we want to make sure that no assertions are triggered anywhere. 562 std::mt19937 g(analysisFuzzerSeed); 563 llvm::shuffle(ops.begin(), ops.end(), g); 564 } 565 566 // Walk ops in reverse for better interference analysis. 567 for (Operation *op : reverse(ops)) 568 for (OpOperand &opOperand : op->getOpOperands()) 569 if (opOperand.get().getType().isa<TensorType>()) 570 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) 571 if (failed(bufferizableInPlaceAnalysisImpl(opOperand, aliasInfo, 572 state, domInfo))) 573 return failure(); 574 575 return success(); 576 } 577 578 /// Return true if the given op has a tensor result or a tensor operand. 579 static bool hasTensorSemantics(Operation *op) { 580 bool hasTensorResult = any_of(op->getResultTypes(), isaTensor); 581 bool hasTensorOperand = any_of(op->getOperandTypes(), isaTensor); 582 return hasTensorResult || hasTensorOperand; 583 } 584 585 /// Analyze all ops that are contained in `op`. 586 static LogicalResult inPlaceAnalysis(Operation *op, 587 BufferizationAliasInfo &aliasInfo, 588 BufferizationState &state, 589 const DominanceInfo &domInfo, 590 unsigned analysisFuzzerSeed = 0) { 591 // Collect ops so we can build our own reverse traversal. 592 SmallVector<Operation *> ops; 593 op->walk([&](Operation *op) { 594 // No tensors => no buffers. 595 if (!hasTensorSemantics(op)) 596 return; 597 ops.push_back(op); 598 }); 599 600 return inPlaceAnalysis(ops, aliasInfo, state, domInfo, analysisFuzzerSeed); 601 } 602 603 /// Analyze equivalence of tied OpResult/OpOperand pairs of the given ops. 604 static void equivalenceAnalysis(SmallVector<Operation *> &ops, 605 BufferizationAliasInfo &aliasInfo, 606 BufferizationState &state) { 607 for (Operation *op : ops) 608 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) 609 for (OpResult opResult : op->getOpResults()) 610 if (opResult.getType().isa<TensorType>()) 611 for (OpOperand *opOperand : 612 bufferizableOp.getAliasingOpOperand(opResult, state)) 613 if (state.isInPlace(*opOperand)) 614 if (bufferizableOp.bufferRelation(opResult, state) == 615 BufferRelation::Equivalent) 616 aliasInfo.unionEquivalenceClasses(opResult, opOperand->get()); 617 } 618 619 /// Analyze equivalence of tied OpResult/OpOperand pairs of all ops contained 620 /// in `op`. 621 static void equivalenceAnalysis(Operation *op, 622 BufferizationAliasInfo &aliasInfo, 623 BufferizationState &state) { 624 // Traverse ops in PostOrder: Nested ops first, then enclosing ops. 625 SmallVector<Operation *> ops; 626 op->walk<WalkOrder::PostOrder>([&](Operation *op) { 627 // No tensors => no buffers. 628 if (none_of(op->getResultTypes(), isaTensor)) 629 return; 630 ops.push_back(op); 631 }); 632 633 equivalenceAnalysis(ops, aliasInfo, state); 634 } 635 636 /// Assert that the current bufferization decisions are consistent. 637 static LogicalResult 638 checkAliasInfoConsistency(Operation *op, const DominanceInfo &domInfo, 639 BufferizationState &state, 640 const BufferizationAliasInfo &aliasInfo) { 641 const BufferizationOptions &options = state.getOptions(); 642 Operation *inconsistentOp = nullptr; 643 WalkResult walkResult = op->walk([&](Operation *op) { 644 if (auto bufferizableOp = options.dynCastBufferizableOp(op)) 645 for (OpOperand &opOperand : op->getOpOperands()) 646 if (opOperand.get().getType().isa<TensorType>()) { 647 if (wouldCreateReadAfterWriteInterference( 648 opOperand, domInfo, state, aliasInfo, 649 /*checkConsistencyOnly=*/true)) { 650 // This error can happen if certain "mustBufferizeInPlace" interface 651 // methods are implemented incorrectly, such that the IR already has 652 // a RaW conflict before making any bufferization decisions. 653 inconsistentOp = op; 654 return WalkResult::interrupt(); 655 } 656 } 657 return WalkResult::advance(); 658 }); 659 660 if (walkResult.wasInterrupted()) 661 return inconsistentOp->emitError("input IR has RaW conflict"); 662 return success(); 663 } 664 665 /// Annotate the IR with the result of the analysis. For testing/debugging only. 666 static void 667 annotateOpsWithBufferizationMarkers(Operation *op, 668 const BufferizationAliasInfo &aliasInfo, 669 BufferizationState &state) { 670 op->walk([&](Operation *op) { 671 if (auto bufferizableOp = state.getOptions().dynCastBufferizableOp(op)) 672 for (OpOperand &opOperand : op->getOpOperands()) 673 if (opOperand.get().getType().isa<TensorType>()) 674 setInPlaceOpOperand(opOperand, aliasInfo.isInPlace(opOperand)); 675 }); 676 } 677 678 /// Assert that IR is in destination-passing style. I.e., every value that is 679 /// returned or yielded from a block is: 680 /// * aliasing a bbArg of that block or a parent block, or 681 /// * aliasing an OpResult of a op in a parent block. 682 /// 683 /// Example: 684 /// ``` 685 /// %0 = "some_op" : tensor<?xf32> 686 /// %1 = scf.if %c -> (tensor<?xf32>) { 687 /// scf.yield %0 : tensor<?xf32> 688 /// } else { 689 /// %t = linalg.init_tensor : tensor<?xf32> 690 /// scf.yield %t : tensor<?xf32> 691 /// } 692 /// ``` 693 /// In the above example, the first scf.yield op satifies destination-passing 694 /// style because the yielded value %0 is defined in the parent block. The 695 /// second scf.yield op does not satisfy destination-passing style because the 696 /// yielded value %t is defined in the same block as the scf.yield op. 697 // TODO: The current implementation checks for equivalent values instead of 698 // aliasing values, which is stricter than needed. We can currently not check 699 // for aliasing values because the analysis is a maybe-alias analysis and we 700 // need a must-alias analysis here. 701 struct AssertDestinationPassingStyle : public PostAnalysisStep { 702 LogicalResult run(Operation *op, BufferizationState &state, 703 BufferizationAliasInfo &aliasInfo, 704 SmallVector<Operation *> &newOps) override { 705 LogicalResult status = success(); 706 DominanceInfo domInfo(op); 707 op->walk([&](Operation *returnOp) { 708 if (!isRegionReturnLike(returnOp)) 709 return WalkResult::advance(); 710 711 for (OpOperand &returnValOperand : returnOp->getOpOperands()) { 712 Value returnVal = returnValOperand.get(); 713 // Skip non-tensor values. 714 if (!returnVal.getType().isa<TensorType>()) 715 continue; 716 717 bool foundEquivValue = false; 718 aliasInfo.applyOnEquivalenceClass(returnVal, [&](Value equivVal) { 719 if (auto bbArg = equivVal.dyn_cast<BlockArgument>()) { 720 Operation *definingOp = bbArg.getOwner()->getParentOp(); 721 if (definingOp->isProperAncestor(returnOp)) 722 foundEquivValue = true; 723 return; 724 } 725 726 Operation *definingOp = equivVal.getDefiningOp(); 727 if (definingOp->getBlock()->findAncestorOpInBlock( 728 *returnOp->getParentOp())) 729 // Skip ops that happen after `returnOp` and parent ops. 730 if (happensBefore(definingOp, returnOp, domInfo)) 731 foundEquivValue = true; 732 }); 733 734 if (!foundEquivValue) 735 status = 736 returnOp->emitError() 737 << "operand #" << returnValOperand.getOperandNumber() 738 << " of ReturnLike op does not satisfy destination passing style"; 739 } 740 741 return WalkResult::advance(); 742 }); 743 744 return status; 745 } 746 }; 747 748 LogicalResult bufferization::analyzeOp(Operation *op, 749 AnalysisBufferizationState &state) { 750 DominanceInfo domInfo(op); 751 BufferizationAliasInfo &aliasInfo = state.getAliasInfo(); 752 const auto &options = 753 static_cast<const AnalysisBufferizationOptions &>(state.getOptions()); 754 755 if (failed(checkAliasInfoConsistency(op, domInfo, state, aliasInfo))) 756 return failure(); 757 758 // If the analysis fails, just return. 759 if (failed(inPlaceAnalysis(op, aliasInfo, state, domInfo, 760 options.analysisFuzzerSeed))) 761 return failure(); 762 equivalenceAnalysis(op, aliasInfo, state); 763 764 for (const std::unique_ptr<PostAnalysisStep> &step : 765 options.postAnalysisSteps) { 766 SmallVector<Operation *> newOps; 767 if (failed(step->run(op, state, aliasInfo, newOps))) 768 return failure(); 769 // Analyze ops that were created by the PostAnalysisStep. 770 if (failed(inPlaceAnalysis(newOps, aliasInfo, state, domInfo))) 771 return failure(); 772 equivalenceAnalysis(newOps, aliasInfo, state); 773 } 774 775 if (!options.allowReturnMemref) { 776 SmallVector<Operation *> newOps; 777 if (failed( 778 AssertDestinationPassingStyle().run(op, state, aliasInfo, newOps))) 779 return failure(); 780 } 781 782 // Annotate operations if we only want to report the analysis. 783 if (options.testAnalysisOnly) 784 annotateOpsWithBufferizationMarkers(op, aliasInfo, state); 785 786 return success(); 787 } 788 789 LogicalResult bufferization::runOneShotBufferize( 790 Operation *op, std::unique_ptr<AnalysisBufferizationOptions> options) { 791 AnalysisBufferizationState state(op, *options); 792 if (failed(analyzeOp(op, state))) 793 return failure(); 794 if (options->testAnalysisOnly) 795 return success(); 796 return bufferizeOp(op, state); 797 } 798