1 //===- BufferizableOpInterface.cpp - Bufferizable Ops ---=----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" 10 #include "mlir/Dialect/Bufferization/IR/Bufferization.h" 11 #include "mlir/Dialect/Func/IR/FuncOps.h" 12 #include "mlir/Dialect/MemRef/IR/MemRef.h" 13 #include "mlir/IR/AsmState.h" 14 #include "mlir/IR/BlockAndValueMapping.h" 15 #include "mlir/IR/BuiltinOps.h" 16 #include "mlir/IR/Operation.h" 17 #include "mlir/IR/TypeUtilities.h" 18 #include "mlir/IR/Value.h" 19 #include "llvm/Support/Debug.h" 20 21 namespace mlir { 22 namespace bufferization { 23 24 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.cpp.inc" 25 26 } // namespace bufferization 27 } // namespace mlir 28 29 #define DEBUG_TYPE "bufferizable-op-interface" 30 #define DBGS() (llvm::dbgs() << '[' << DEBUG_TYPE << "] ") 31 #define LDBG(X) LLVM_DEBUG(DBGS() << (X)) 32 33 using namespace mlir; 34 using namespace bufferization; 35 36 /// Attribute name used to mark region arguments that can be bufferized 37 /// in-place during linalg comprehensive bufferization. 38 constexpr const ::llvm::StringLiteral 39 bufferization::BufferizableOpInterface::kInplaceableAttrName; 40 41 /// Attribute name used to mark allocs that are created by the bufferization. 42 static const char *kBufferAllocationAttr = "bufferization.allocation"; 43 44 /// Attribute name used to mark allocs that should not be deallocated. 45 static const char *kSkipDeallocAttr = "bufferization.skip_dealloc"; 46 47 //===----------------------------------------------------------------------===// 48 // BufferizationOptions 49 //===----------------------------------------------------------------------===// 50 51 // Default constructor for BufferizationOptions. 52 BufferizationOptions::BufferizationOptions() = default; 53 54 bool BufferizationOptions::isOpAllowed(Operation *op) const { 55 // Special case: If function boundary bufferization is deactivated, do not 56 // allow ops that belong to the `func` dialect. 57 bool isFuncBoundaryOp = isa_and_nonnull<func::FuncDialect>(op->getDialect()); 58 if (!bufferizeFunctionBoundaries && isFuncBoundaryOp) 59 return false; 60 61 // All other ops: Allow/disallow according to filter. 62 bool isAllowed = !filterHasAllowRule(); 63 for (const OpFilterEntry &entry : opFilter) { 64 bool filterResult = entry.fn(op); 65 switch (entry.type) { 66 case OpFilterEntry::ALLOW: 67 isAllowed |= filterResult; 68 break; 69 case OpFilterEntry::DENY: 70 if (filterResult) 71 // DENY filter matches. This op is no allowed. (Even if other ALLOW 72 // filters may match.) 73 return false; 74 }; 75 } 76 return isAllowed; 77 } 78 79 BufferizableOpInterface 80 BufferizationOptions::dynCastBufferizableOp(Operation *op) const { 81 if (isOpAllowed(op)) 82 return dyn_cast<BufferizableOpInterface>(op); 83 return nullptr; 84 } 85 86 BufferizableOpInterface 87 BufferizationOptions::dynCastBufferizableOp(Value value) const { 88 if (auto bufferizableOp = value.getDefiningOp<BufferizableOpInterface>()) 89 if (isOpAllowed(bufferizableOp.getOperation())) 90 return bufferizableOp; 91 return nullptr; 92 } 93 94 void BufferizationOptions::addDialectStateInitializer( 95 StringRef name, const DialectStateInitFn &fn) { 96 stateInitializers.push_back( 97 [=](AnalysisState &state) { state.insertDialectState(name, fn()); }); 98 } 99 100 //===----------------------------------------------------------------------===// 101 // Helper functions for BufferizableOpInterface 102 //===----------------------------------------------------------------------===// 103 104 static void setInsertionPointAfter(OpBuilder &b, Value value) { 105 if (auto bbArg = value.dyn_cast<BlockArgument>()) { 106 b.setInsertionPointToStart(bbArg.getOwner()); 107 } else { 108 b.setInsertionPointAfter(value.getDefiningOp()); 109 } 110 } 111 112 /// Determine which OpOperand* will alias with `result` if the op is bufferized 113 /// in place. Return an empty vector if the op is not bufferizable. 114 SmallVector<OpOperand *> 115 AnalysisState::getAliasingOpOperand(OpResult result) const { 116 if (Operation *op = result.getDefiningOp()) 117 if (auto bufferizableOp = dyn_cast<BufferizableOpInterface>(op)) 118 return bufferizableOp.getAliasingOpOperand(result, *this); 119 return {}; 120 } 121 122 /// Determine which OpResult will alias with `opOperand` if the op is bufferized 123 /// in place. Return an empty vector if the op is not bufferizable. 124 SmallVector<OpResult> 125 AnalysisState::getAliasingOpResult(OpOperand &opOperand) const { 126 if (auto bufferizableOp = 127 dyn_cast<BufferizableOpInterface>(opOperand.getOwner())) 128 return bufferizableOp.getAliasingOpResult(opOperand, *this); 129 return {}; 130 } 131 132 /// Return true if `opOperand` bufferizes to a memory read. Return `true` if the 133 /// op is not bufferizable. 134 bool AnalysisState::bufferizesToMemoryRead(OpOperand &opOperand) const { 135 if (auto bufferizableOp = 136 dyn_cast<BufferizableOpInterface>(opOperand.getOwner())) 137 return bufferizableOp.bufferizesToMemoryRead(opOperand, *this); 138 139 // Unknown op that returns a tensor. The inplace analysis does not support it. 140 // Conservatively return true. 141 return true; 142 } 143 144 /// Return true if `opOperand` bufferizes to a memory write. Return 145 /// `true` if the op is not bufferizable. 146 bool AnalysisState::bufferizesToMemoryWrite(OpOperand &opOperand) const { 147 if (auto bufferizableOp = 148 dyn_cast<BufferizableOpInterface>(opOperand.getOwner())) 149 return bufferizableOp.bufferizesToMemoryWrite(opOperand, *this); 150 151 // Unknown op that returns a tensor. The inplace analysis does not support it. 152 // Conservatively return true. 153 return true; 154 } 155 156 /// Return true if `opOperand` does neither read nor write but bufferizes to an 157 /// alias. Return false if the op is not bufferizable. 158 bool AnalysisState::bufferizesToAliasOnly(OpOperand &opOperand) const { 159 if (auto bufferizableOp = 160 dyn_cast<BufferizableOpInterface>(opOperand.getOwner())) 161 return bufferizableOp.bufferizesToAliasOnly(opOperand, *this); 162 163 // Unknown op that returns a tensor. The inplace analysis does not support it. 164 // Conservatively return false. 165 return false; 166 } 167 168 /// Return true if the given value is read by an op that bufferizes to a memory 169 /// read. Also takes into account ops that create an alias but do not read by 170 /// themselves (e.g., ExtractSliceOp). 171 bool AnalysisState::isValueRead(Value value) const { 172 assert(value.getType().isa<TensorType>() && "expected TensorType"); 173 SmallVector<OpOperand *> workingSet; 174 for (OpOperand &use : value.getUses()) 175 workingSet.push_back(&use); 176 177 while (!workingSet.empty()) { 178 OpOperand *uMaybeReading = workingSet.pop_back_val(); 179 // Skip over all ops that neither read nor write (but create an alias). 180 if (bufferizesToAliasOnly(*uMaybeReading)) 181 for (OpResult opResult : getAliasingOpResult(*uMaybeReading)) 182 for (OpOperand &use : opResult.getUses()) 183 workingSet.push_back(&use); 184 if (bufferizesToMemoryRead(*uMaybeReading)) 185 return true; 186 } 187 188 return false; 189 } 190 191 // Starting from `value`, follow the use-def chain in reverse, always selecting 192 // the aliasing OpOperands. Find and return Values for which `condition` 193 // evaluates to true. OpOperands of such matching Values are not traversed any 194 // further. 195 llvm::SetVector<Value> AnalysisState::findValueInReverseUseDefChain( 196 Value value, llvm::function_ref<bool(Value)> condition) const { 197 llvm::SetVector<Value> result, workingSet; 198 workingSet.insert(value); 199 200 while (!workingSet.empty()) { 201 Value value = workingSet.pop_back_val(); 202 if (condition(value) || value.isa<BlockArgument>()) { 203 result.insert(value); 204 continue; 205 } 206 207 OpResult opResult = value.cast<OpResult>(); 208 SmallVector<OpOperand *> opOperands = getAliasingOpOperand(opResult); 209 if (opOperands.empty() || !options.isOpAllowed(value.getDefiningOp())) { 210 result.insert(value); 211 continue; 212 } 213 214 for (OpOperand *o : opOperands) 215 workingSet.insert(o->get()); 216 } 217 218 return result; 219 } 220 221 // Find the Values of the last preceding write of a given Value. 222 llvm::SetVector<Value> 223 AnalysisState::findLastPrecedingWrite(Value value) const { 224 return findValueInReverseUseDefChain(value, [&](Value value) { 225 Operation *op = value.getDefiningOp(); 226 if (!op) 227 return true; 228 auto bufferizableOp = options.dynCastBufferizableOp(op); 229 if (!bufferizableOp) 230 return true; 231 return bufferizableOp.isMemoryWrite(value.cast<OpResult>(), *this); 232 }); 233 } 234 235 AnalysisState::AnalysisState(const BufferizationOptions &options) 236 : options(options) { 237 for (const BufferizationOptions::AnalysisStateInitFn &fn : 238 options.stateInitializers) 239 fn(*this); 240 } 241 242 // bufferization.to_memref is not allowed to change the rank. 243 static void ensureToMemrefOpIsValid(Value tensor, Type memrefType) { 244 #ifndef NDEBUG 245 auto rankedTensorType = tensor.getType().dyn_cast<RankedTensorType>(); 246 assert((!rankedTensorType || memrefType.cast<MemRefType>().getRank() == 247 rankedTensorType.getRank()) && 248 "to_memref would be invalid: mismatching ranks"); 249 #endif 250 } 251 252 Value mlir::bufferization::lookupBuffer(RewriterBase &rewriter, Value tensor, 253 const BufferizationOptions &options) { 254 auto tensorType = tensor.getType().dyn_cast<TensorType>(); 255 assert(tensorType && "unexpected non-tensor type"); 256 257 // Replace "%t = to_tensor %m" with %m. 258 if (auto toTensorOp = tensor.getDefiningOp<bufferization::ToTensorOp>()) 259 return toTensorOp.memref(); 260 261 // Insert to_memref op. 262 OpBuilder::InsertionGuard g(rewriter); 263 setInsertionPointAfter(rewriter, tensor); 264 Type memrefType = getMemRefType(tensorType, options); 265 ensureToMemrefOpIsValid(tensor, memrefType); 266 return rewriter.create<bufferization::ToMemrefOp>(tensor.getLoc(), memrefType, 267 tensor); 268 } 269 270 /// Return the buffer (memref) for a given OpOperand (tensor). Allocate 271 /// a new buffer and copy over data from the existing buffer if out-of-place 272 /// bufferization was decided. 273 FailureOr<Value> 274 BufferizationState::getBuffer(RewriterBase &rewriter, OpOperand &opOperand, 275 Optional<ForceInPlacability> overrideInPlace, 276 Optional<Operation *> customCopyInsertionPoint) { 277 const BufferizationOptions &options = analysisState.getOptions(); 278 OpBuilder::InsertionGuard guard(rewriter); 279 Operation *op = opOperand.getOwner(); 280 Location loc = op->getLoc(); 281 SmallVector<OpResult> aliasingOpResults = 282 analysisState.getAliasingOpResult(opOperand); 283 Value operand = opOperand.get(); 284 Value operandBuffer = lookupBuffer(rewriter, operand, options); 285 286 // Can `operandBuffer` be used directly or do we need a copy? 287 bool inplace = 288 overrideInPlace != FORCE_OUT_OF_PLACE && 289 (overrideInPlace == FORCE_INPLACE || analysisState.isInPlace(opOperand)); 290 if (inplace) 291 return operandBuffer; 292 293 // Bufferizing out-of-place: Allocate a new buffer. 294 // Move insertion point right after `operandBuffer`. That is where the 295 // allocation should be inserted (in the absence of allocation hoisting). 296 setInsertionPointAfter(rewriter, operandBuffer); 297 // Allocate the result buffer. The buffer should be deallocated if the tensor 298 // is not yielded and deallocs are enabled in general. 299 bool dealloc = llvm::none_of(aliasingOpResults, [&](Value v) { 300 return getAnalysisState().isTensorYielded(v); 301 }); 302 FailureOr<Value> resultBuffer = createAlloc( 303 rewriter, loc, operandBuffer, dealloc && getOptions().createDeallocs); 304 if (failed(resultBuffer)) 305 return failure(); 306 // Do not copy the buffer if its contents are undefined. 307 if (analysisState.hasUndefinedContents(&opOperand)) 308 return resultBuffer; 309 // Do not copy if the copied data is never read. 310 if (!aliasingOpResults.empty() && 311 !analysisState.bufferizesToMemoryRead(opOperand) && 312 llvm::none_of(aliasingOpResults, [&](OpResult opResult) { 313 return analysisState.isValueRead(opResult); 314 })) 315 return resultBuffer; 316 // Do not copy if this op does not read the data, but writes it. 317 if (analysisState.bufferizesToMemoryWrite(opOperand) && 318 !analysisState.bufferizesToMemoryRead(opOperand)) 319 return resultBuffer; 320 321 if (customCopyInsertionPoint) { 322 rewriter.setInsertionPoint(*customCopyInsertionPoint); 323 } else { 324 // The copy happens right before the op that is bufferized. 325 rewriter.setInsertionPoint(op); 326 } 327 if (failed( 328 createMemCpy(rewriter, loc, operandBuffer, *resultBuffer, options))) 329 return failure(); 330 331 return resultBuffer; 332 } 333 334 /// Return the buffer type for a given OpOperand (tensor) after bufferization. 335 BaseMemRefType BufferizationState::getBufferType(OpOperand &opOperand) const { 336 Value tensor = opOperand.get(); 337 auto tensorType = tensor.getType().dyn_cast<TensorType>(); 338 assert(tensorType && "unexpected non-tensor type"); 339 340 if (auto toTensorOp = tensor.getDefiningOp<bufferization::ToTensorOp>()) 341 return toTensorOp.memref().getType().cast<BaseMemRefType>(); 342 343 return getMemRefType(tensorType, getOptions()); 344 } 345 346 void bufferization::replaceOpWithBufferizedValues(RewriterBase &rewriter, 347 Operation *op, 348 ValueRange values) { 349 assert(values.size() == op->getNumResults() && 350 "expected one value per OpResult"); 351 OpBuilder::InsertionGuard g(rewriter); 352 353 // Replace all OpResults with the given values. 354 SmallVector<Value> replacements; 355 for (OpResult opResult : op->getOpResults()) { 356 Value replacement = values[opResult.getResultNumber()]; 357 if (opResult.getType().isa<TensorType>()) { 358 // The OpResult is a tensor. Such values are replaced with memrefs during 359 // bufferization. 360 assert((replacement.getType().isa<MemRefType>() || 361 replacement.getType().isa<UnrankedMemRefType>()) && 362 "tensor op result should be replaced with a memref value"); 363 // The existing uses of the OpResult still expect a tensor. Insert a 364 // ToTensorOp. Throughout bufferization, this ToTensorOp will gradually 365 // loose all of its users and eventually DCE away. 366 rewriter.setInsertionPointAfter(op); 367 replacement = rewriter.create<bufferization::ToTensorOp>( 368 replacement.getLoc(), replacement); 369 } 370 replacements.push_back(replacement); 371 } 372 373 rewriter.replaceOp(op, replacements); 374 } 375 376 AlwaysCopyAnalysisState::AlwaysCopyAnalysisState( 377 const BufferizationOptions &options) 378 : AnalysisState(options) { 379 // Note: Allocations must be deallocated with a subsequent run of the buffer 380 // deallocation pass. 381 assert(!options.createDeallocs && 382 "cannot create deallocs with AlwaysCopyBufferizationState"); 383 } 384 385 /// Return `true` if the given OpResult has been decided to bufferize inplace. 386 bool AlwaysCopyAnalysisState::isInPlace(OpOperand &opOperand) const { 387 // OpOperands that bufferize to a memory write are out-of-place, i.e., an 388 // alloc and copy is inserted. 389 return !bufferizesToMemoryWrite(opOperand); 390 } 391 392 /// Return true if `v1` and `v2` bufferize to equivalent buffers. 393 bool AlwaysCopyAnalysisState::areEquivalentBufferizedValues(Value v1, 394 Value v2) const { 395 // There is no analysis, so we do not know if the values are equivalent. The 396 // conservative answer is "false". 397 return false; 398 } 399 400 /// Return `true` if the given tensor has undefined contents. 401 bool AlwaysCopyAnalysisState::hasUndefinedContents(OpOperand *opOperand) const { 402 // There is no analysis, so the conservative answer is "false". 403 return false; 404 } 405 406 /// Return true if the given tensor (or an aliasing tensor) is yielded from 407 /// the containing block. Also include all aliasing tensors in the same block. 408 bool AlwaysCopyAnalysisState::isTensorYielded(Value tensor) const { 409 // There is no analysis, so conservatively answer "true". 410 return true; 411 } 412 413 //===----------------------------------------------------------------------===// 414 // Bufferization-specific scoped alloc/dealloc insertion support. 415 //===----------------------------------------------------------------------===// 416 417 /// Create a memref allocation with the given type and dynamic extents. 418 static FailureOr<Value> createAlloc(OpBuilder &b, Location loc, MemRefType type, 419 ValueRange dynShape, 420 const BufferizationOptions &options) { 421 if (options.allocationFn) 422 return (*options.allocationFn)(b, loc, type, dynShape, 423 options.bufferAlignment); 424 425 // Default bufferallocation via AllocOp. 426 Value allocated = b.create<memref::AllocOp>( 427 loc, type, dynShape, b.getI64IntegerAttr(options.bufferAlignment)); 428 return allocated; 429 } 430 431 /// Creates a memref deallocation. The given memref buffer must have been 432 /// allocated using `createAlloc`. 433 LogicalResult 434 bufferization::createDealloc(OpBuilder &b, Location loc, Value allocatedBuffer, 435 const BufferizationOptions &options) { 436 if (options.deallocationFn) 437 return (*options.deallocationFn)(b, loc, allocatedBuffer); 438 439 // Default buffer deallocation via DeallocOp. 440 b.create<memref::DeallocOp>(loc, allocatedBuffer); 441 return success(); 442 } 443 444 /// Compute the type of the `memref` to use for allocating the buffer for 445 /// `shapedValue`. Also returns (by reference in `dynShape`), the value for the 446 /// dynamic dimensions in the returned `memref` type. 447 static MemRefType getAllocationTypeAndShape(OpBuilder &b, Location loc, 448 Value shapedValue, 449 SmallVectorImpl<Value> &dynShape) { 450 MemRefType allocMemRefType = 451 getContiguousMemRefType(shapedValue.getType().cast<ShapedType>()); 452 453 // Compute the dynamic part of the shape. 454 bool reifiedShapes = false; 455 if (auto rankedOp = dyn_cast_or_null<ReifyRankedShapedTypeOpInterface>( 456 shapedValue.getDefiningOp())) { 457 ReifiedRankedShapedTypeDims resultDims; 458 if (succeeded(rankedOp.reifyResultShapes(b, resultDims))) { 459 reifiedShapes = true; 460 OpResult resultValue = shapedValue.dyn_cast<OpResult>(); 461 auto &shape = resultDims[resultValue.getResultNumber()]; 462 for (const auto &dim : enumerate(allocMemRefType.getShape())) 463 if (ShapedType::isDynamic(dim.value())) 464 dynShape.push_back(shape[dim.index()]); 465 } 466 } 467 468 if (!reifiedShapes) { 469 for (const auto &dim : enumerate(allocMemRefType.getShape())) 470 if (ShapedType::isDynamic(dim.value())) { 471 assert((shapedValue.getType().isa<UnrankedMemRefType>() || 472 shapedValue.getType().isa<MemRefType>()) && 473 "expected MemRef type"); 474 dynShape.push_back( 475 b.create<memref::DimOp>(loc, shapedValue, dim.index())); 476 } 477 } 478 479 return allocMemRefType; 480 } 481 482 static Value createBufferAllocation(OpBuilder &b, Location loc, MemRefType type, 483 ValueRange dynShape, bool skipDealloc) { 484 auto allocaOp = b.create<memref::AllocaOp>(loc, type, dynShape); 485 allocaOp->setAttr(kBufferAllocationAttr, b.getUnitAttr()); 486 if (skipDealloc) 487 allocaOp->setAttr(kSkipDeallocAttr, b.getUnitAttr()); 488 return allocaOp.getResult(); 489 } 490 491 /// Create an allocation after `shapedValue.getDefiningOp` (or at the top of the 492 /// block in case of a bbArg). 493 FailureOr<Value> BufferizationState::createAlloc(OpBuilder &b, Location loc, 494 Value shapedValue, 495 Optional<bool> dealloc) { 496 // Take a guard before anything else. 497 OpBuilder::InsertionGuard g(b); 498 499 // Compute allocation memref type. 500 assert(shapedValue.getType().isa<ShapedType>()); 501 SmallVector<Value> dynShape; 502 MemRefType allocMemRefType = 503 getAllocationTypeAndShape(b, loc, shapedValue, dynShape); 504 505 // Should be the buffer be deallocated again or should we let it leak? 506 bool skipDealloc; 507 if (dealloc) { 508 skipDealloc = !dealloc.getValue(); 509 } else { 510 assert(shapedValue.getType().isa<TensorType>() && 511 "must specify `dealloc` if non-tensor value is passed"); 512 // Buffer should be not be deallocated if deallocs are generally deactivated 513 // or if the tensor is yielded from a block. 514 skipDealloc = !getOptions().createDeallocs || 515 getAnalysisState().isTensorYielded(shapedValue); 516 } 517 518 // Create the buffer allocation. 519 return createBufferAllocation(b, loc, allocMemRefType, dynShape, skipDealloc); 520 } 521 522 /// Create a memory copy between two memref buffers. 523 LogicalResult bufferization::createMemCpy(OpBuilder &b, Location loc, 524 Value from, Value to, 525 const BufferizationOptions &options) { 526 if (options.memCpyFn) 527 return (*options.memCpyFn)(b, loc, from, to); 528 529 b.create<memref::CopyOp>(loc, from, to); 530 return success(); 531 } 532 533 LogicalResult 534 bufferization::createAllocDeallocOps(Operation *op, 535 const BufferizationOptions &options, 536 bool onlyLeakingAllocs, bool *changed) { 537 IRRewriter rewriter(op->getContext()); 538 if (changed) 539 *changed = false; 540 541 // Bufferization creates memref.alloca ops. After bufferization, these must be 542 // rewritten to alloc/dealloc ops as specified in the bufferization options. 543 WalkResult status = op->walk([&](memref::AllocaOp allocaOp) { 544 // Ignore memref.alloca ops that were not created by the bufferization. 545 if (!allocaOp->hasAttr(kBufferAllocationAttr)) 546 return WalkResult::skip(); 547 // If `onlyLeakingAllocs`, process only ops that are marked as 548 // "skip dealloc". 549 bool skipDealloc = allocaOp->hasAttr(kSkipDeallocAttr); 550 if (onlyLeakingAllocs && !skipDealloc) 551 return WalkResult::skip(); 552 553 // Create alloc. 554 Block *block = allocaOp->getBlock(); 555 rewriter.setInsertionPoint(allocaOp); 556 FailureOr<Value> alloc = 557 createAlloc(rewriter, allocaOp->getLoc(), allocaOp.getType(), 558 allocaOp.dynamicSizes(), options); 559 if (failed(alloc)) 560 return WalkResult::interrupt(); 561 rewriter.replaceOp(allocaOp, *alloc); 562 if (changed) 563 *changed = true; 564 565 // Stop here if the buffer should not be deallocated. 566 if (skipDealloc) 567 return WalkResult::advance(); 568 569 // Create dealloc. 570 rewriter.setInsertionPoint(block->getTerminator()); 571 if (failed(createDealloc(rewriter, alloc->getLoc(), *alloc, options))) 572 return WalkResult::interrupt(); 573 574 return WalkResult::advance(); 575 }); 576 577 return success(!status.wasInterrupted()); 578 } 579 580 /// Try to hoist all new buffer allocations until the next hoisting barrier. 581 // TODO: Consolidate this function with the existing buffer hoisting pass. 582 LogicalResult 583 bufferization::hoistBufferAllocations(Operation *op, 584 const BufferizationOptions &options) { 585 // Nothing to do if allocation hoisting is deactivated. 586 if (!options.hoistAllocations) 587 return success(); 588 589 // Gather all buffer allocations that were created by the bufferization. 590 SmallVector<Operation *> allocaOps; 591 op->walk([&](memref::AllocaOp allocaOp) { 592 if (allocaOp->hasAttr(kBufferAllocationAttr)) 593 allocaOps.push_back(allocaOp); 594 }); 595 596 for (Operation *allocaOp : allocaOps) { 597 // TODO: Hoisting of allocs with dynamic shape not implemented. 598 if (!allocaOp->getOpOperands().empty()) 599 continue; 600 601 Operation *op = allocaOp->getParentOp(); 602 while (op) { 603 if (auto bufferizableOp = dyn_cast<BufferizableOpInterface>(op)) { 604 if (bufferizableOp.isAllocationHoistingBarrier()) { 605 break; 606 } 607 } else { 608 // Op is not bufferizable: It may not be safe to hoist across this op. 609 break; 610 } 611 op = op->getParentOp(); 612 } 613 614 // FuncOp is an allocation hoisting barrier, so this should never happen. 615 assert(op && "allocation hoisting barrier not found"); 616 617 // Nothing to do if the insertion point is in the same block. 618 if (op == allocaOp->getParentOp()) 619 continue; 620 621 // `op` may have multiple blocks. Make sure that we insert in the right one. 622 SmallVector<Block *> blocks; 623 for (Region &r : op->getRegions()) 624 for (Block &b : r.getBlocks()) 625 blocks.push_back(&b); 626 auto *insertionBlock = llvm::find_if( 627 blocks, [&](Block *b) { return b->findAncestorOpInBlock(*allocaOp); }); 628 assert(insertionBlock != blocks.end() && "owning block not found"); 629 630 // Move to the beginning of the block. 631 allocaOp->moveBefore(&(*insertionBlock)->front()); 632 } 633 634 return success(); 635 } 636 637 //===----------------------------------------------------------------------===// 638 // Bufferization-specific BlockAndValueMapping support with debugging. 639 //===----------------------------------------------------------------------===// 640 641 bool bufferization::isFunctionArgument(Value value) { 642 auto bbArg = value.dyn_cast<BlockArgument>(); 643 if (!bbArg) 644 return false; 645 return isa<func::FuncOp>(bbArg.getOwner()->getParentOp()); 646 } 647 648 MemRefType bufferization::getContiguousMemRefType(ShapedType shapedType, 649 Attribute memorySpace) { 650 MemRefLayoutAttrInterface layout = {}; 651 return MemRefType::get(shapedType.getShape(), shapedType.getElementType(), 652 layout, memorySpace); 653 } 654 655 BaseMemRefType bufferization::getMemRefType(TensorType tensorType, 656 const BufferizationOptions &options, 657 MemRefLayoutAttrInterface layout, 658 Attribute memorySpace) { 659 // Case 1: Unranked memref type. 660 if (auto unrankedTensorType = tensorType.dyn_cast<UnrankedTensorType>()) { 661 assert(!layout && "UnrankedTensorType cannot have a layout map"); 662 return UnrankedMemRefType::get(unrankedTensorType.getElementType(), 663 memorySpace); 664 } 665 666 // Case 2: Ranked memref type with specified layout. If fully dynamic layout 667 // maps are not requested, generate a type with `layout`, which is empty (no 668 // layout map) by default. 669 auto rankedTensorType = tensorType.cast<RankedTensorType>(); 670 if (layout || !options.fullyDynamicLayoutMaps) { 671 return MemRefType::get(rankedTensorType.getShape(), 672 rankedTensorType.getElementType(), layout, 673 memorySpace); 674 } 675 676 // Case 3: Ranked memref type with unspecified layout. Choose the most dynamic 677 // one. 678 // TODO: address space decisions to connect with the actual alloc. 679 int64_t dynamicOffset = ShapedType::kDynamicStrideOrOffset; 680 SmallVector<int64_t> dynamicStrides(rankedTensorType.getRank(), 681 ShapedType::kDynamicStrideOrOffset); 682 AffineMap stridedLayout = makeStridedLinearLayoutMap( 683 dynamicStrides, dynamicOffset, rankedTensorType.getContext()); 684 return MemRefType::get(rankedTensorType.getShape(), 685 rankedTensorType.getElementType(), stridedLayout, 686 memorySpace); 687 } 688