1# Buffer Deallocation - Internals 2 3**Note:** This pass is deprecated. Please use the ownership-based buffer 4deallocation pass instead. 5 6This section covers the internal functionality of the BufferDeallocation 7transformation. The transformation consists of several passes. The main pass 8called BufferDeallocation can be applied via “-buffer-deallocation” on MLIR 9programs. 10 11[TOC] 12 13## Requirements 14 15In order to use BufferDeallocation on an arbitrary dialect, several control-flow 16interfaces have to be implemented when using custom operations. This is 17particularly important to understand the implicit control-flow dependencies 18between different parts of the input program. Without implementing the following 19interfaces, control-flow relations cannot be discovered properly and the 20resulting program can become invalid: 21 22* Branch-like terminators should implement the `BranchOpInterface` to query 23 and manipulate associated operands. 24* Operations involving structured control flow have to implement the 25 `RegionBranchOpInterface` to model inter-region control flow. 26* Terminators yielding values to their parent operation (in particular in the 27 scope of nested regions within `RegionBranchOpInterface`-based operations), 28 should implement the `ReturnLike` trait to represent logical “value 29 returns”. 30 31Example dialects that are fully compatible are the “std” and “scf” dialects with 32respect to all implemented interfaces. 33 34During Bufferization, we convert immutable value types (tensors) to mutable 35types (memref). This conversion is done in several steps and in all of these 36steps the IR has to fulfill SSA like properties. The usage of memref has to be 37in the following consecutive order: allocation, write-buffer, read- buffer. In 38this case, there are only buffer reads allowed after the initial full buffer 39write is done. In particular, there must be no partial write to a buffer after 40the initial write has been finished. However, partial writes in the initializing 41is allowed (fill buffer step by step in a loop e.g.). This means, all buffer 42writes needs to dominate all buffer reads. 43 44Example for breaking the invariant: 45 46```mlir 47func.func @condBranch(%arg0: i1, %arg1: memref<2xf32>) { 48 %0 = memref.alloc() : memref<2xf32> 49 cf.cond_br %arg0, ^bb1, ^bb2 50^bb1: 51 cf.br ^bb3() 52^bb2: 53 partial_write(%0, %0) 54 cf.br ^bb3() 55^bb3(): 56 test.copy(%0, %arg1) : (memref<2xf32>, memref<2xf32>) -> () 57 return 58} 59``` 60 61The maintenance of the SSA like properties is only needed in the bufferization 62process. Afterwards, for example in optimization processes, the property is no 63longer needed. 64 65## Detection of Buffer Allocations 66 67The first step of the BufferDeallocation transformation is to identify 68manageable allocation operations that implement the `SideEffects` interface. 69Furthermore, these ops need to apply the effect `MemoryEffects::Allocate` to a 70particular result value while not using the resource 71`SideEffects::AutomaticAllocationScopeResource` (since it is currently reserved 72for allocations, like `Alloca` that will be automatically deallocated by a 73parent scope). Allocations that have not been detected in this phase will not be 74tracked internally, and thus, not deallocated automatically. However, 75BufferDeallocation is fully compatible with “hybrid” setups in which tracked and 76untracked allocations are mixed: 77 78```mlir 79func.func @mixedAllocation(%arg0: i1) { 80 %0 = memref.alloca() : memref<2xf32> // aliases: %2 81 %1 = memref.alloc() : memref<2xf32> // aliases: %2 82 cf.cond_br %arg0, ^bb1, ^bb2 83^bb1: 84 use(%0) 85 cf.br ^bb3(%0 : memref<2xf32>) 86^bb2: 87 use(%1) 88 cf.br ^bb3(%1 : memref<2xf32>) 89^bb3(%2: memref<2xf32>): 90 ... 91} 92``` 93 94Example of using a conditional branch with alloc and alloca. BufferDeallocation 95can detect and handle the different allocation types that might be intermixed. 96 97Note: the current version does not support allocation operations returning 98multiple result buffers. 99 100## Conversion from AllocOp to AllocaOp 101 102The PromoteBuffersToStack-pass converts AllocOps to AllocaOps, if possible. In 103some cases, it can be useful to use such stack-based buffers instead of 104heap-based buffers. The conversion is restricted to several constraints like: 105 106* Control flow 107* Buffer Size 108* Dynamic Size 109 110If a buffer is leaving a block, we are not allowed to convert it into an alloca. 111If the size of the buffer is large, we could convert it, but regarding stack 112overflow, it makes sense to limit the size of these buffers and only convert 113small ones. The size can be set via a pass option. The current default value is 1141KB. Furthermore, we can not convert buffers with dynamic size, since the 115dimension is not known a priori. 116 117## Movement and Placement of Allocations 118 119Using the buffer hoisting pass, all buffer allocations are moved as far upwards 120as possible in order to group them and make upcoming optimizations easier by 121limiting the search space. Such a movement is shown in the following graphs. In 122addition, we are able to statically free an alloc, if we move it into a 123dominator of all of its uses. This simplifies further optimizations (e.g. buffer 124fusion) in the future. However, movement of allocations is limited by external 125data dependencies (in particular in the case of allocations of dynamically 126shaped types). Furthermore, allocations can be moved out of nested regions, if 127necessary. In order to move allocations to valid locations with respect to their 128uses only, we leverage Liveness information. 129 130The following code snippets shows a conditional branch before running the 131BufferHoisting pass: 132 133 134 135```mlir 136func.func @condBranch(%arg0: i1, %arg1: memref<2xf32>, %arg2: memref<2xf32>) { 137 cf.cond_br %arg0, ^bb1, ^bb2 138^bb1: 139 cf.br ^bb3(%arg1 : memref<2xf32>) 140^bb2: 141 %0 = memref.alloc() : memref<2xf32> // aliases: %1 142 use(%0) 143 cf.br ^bb3(%0 : memref<2xf32>) 144^bb3(%1: memref<2xf32>): // %1 could be %0 or %arg1 145 test.copy(%1, %arg2) : (memref<2xf32>, memref<2xf32>) -> () 146 return 147} 148``` 149 150Applying the BufferHoisting pass on this program results in the following piece 151of code: 152 153 154 155```mlir 156func.func @condBranch(%arg0: i1, %arg1: memref<2xf32>, %arg2: memref<2xf32>) { 157 %0 = memref.alloc() : memref<2xf32> // moved to bb0 158 cf.cond_br %arg0, ^bb1, ^bb2 159^bb1: 160 cf.br ^bb3(%arg1 : memref<2xf32>) 161^bb2: 162 use(%0) 163 cf.br ^bb3(%0 : memref<2xf32>) 164^bb3(%1: memref<2xf32>): 165 test.copy(%1, %arg2) : (memref<2xf32>, memref<2xf32>) -> () 166 return 167} 168``` 169 170The alloc is moved from bb2 to the beginning and it is passed as an argument to 171bb3. 172 173The following example demonstrates an allocation using dynamically shaped types. 174Due to the data dependency of the allocation to %0, we cannot move the 175allocation out of bb2 in this case: 176 177```mlir 178func.func @condBranchDynamicType( 179 %arg0: i1, 180 %arg1: memref<?xf32>, 181 %arg2: memref<?xf32>, 182 %arg3: index) { 183 cf.cond_br %arg0, ^bb1, ^bb2(%arg3: index) 184^bb1: 185 cf.br ^bb3(%arg1 : memref<?xf32>) 186^bb2(%0: index): 187 %1 = memref.alloc(%0) : memref<?xf32> // cannot be moved upwards to the data 188 // dependency to %0 189 use(%1) 190 cf.br ^bb3(%1 : memref<?xf32>) 191^bb3(%2: memref<?xf32>): 192 test.copy(%2, %arg2) : (memref<?xf32>, memref<?xf32>) -> () 193 return 194} 195``` 196 197## Introduction of Clones 198 199In order to guarantee that all allocated buffers are freed properly, we have to 200pay attention to the control flow and all potential aliases a buffer allocation 201can have. Since not all allocations can be safely freed with respect to their 202aliases (see the following code snippet), it is often required to introduce 203copies to eliminate them. Consider the following example in which the 204allocations have already been placed: 205 206```mlir 207func.func @branch(%arg0: i1) { 208 %0 = memref.alloc() : memref<2xf32> // aliases: %2 209 cf.cond_br %arg0, ^bb1, ^bb2 210^bb1: 211 %1 = memref.alloc() : memref<2xf32> // resides here for demonstration purposes 212 // aliases: %2 213 cf.br ^bb3(%1 : memref<2xf32>) 214^bb2: 215 use(%0) 216 cf.br ^bb3(%0 : memref<2xf32>) 217^bb3(%2: memref<2xf32>): 218 … 219 return 220} 221``` 222 223The first alloc can be safely freed after the live range of its post-dominator 224block (bb3). The alloc in bb1 has an alias %2 in bb3 that also keeps this buffer 225alive until the end of bb3. Since we cannot determine the actual branches that 226will be taken at runtime, we have to ensure that all buffers are freed correctly 227in bb3 regardless of the branches we will take to reach the exit block. This 228makes it necessary to introduce a copy for %2, which allows us to free %alloc0 229in bb0 and %alloc1 in bb1. Afterwards, we can continue processing all aliases of 230%2 (none in this case) and we can safely free %2 at the end of the sample 231program. This sample demonstrates that not all allocations can be safely freed 232in their associated post-dominator blocks. Instead, we have to pay attention to 233all of their aliases. 234 235Applying the BufferDeallocation pass to the program above yields the following 236result: 237 238```mlir 239func.func @branch(%arg0: i1) { 240 %0 = memref.alloc() : memref<2xf32> 241 cf.cond_br %arg0, ^bb1, ^bb2 242^bb1: 243 %1 = memref.alloc() : memref<2xf32> 244 %3 = bufferization.clone %1 : (memref<2xf32>) -> (memref<2xf32>) 245 memref.dealloc %1 : memref<2xf32> // %1 can be safely freed here 246 cf.br ^bb3(%3 : memref<2xf32>) 247^bb2: 248 use(%0) 249 %4 = bufferization.clone %0 : (memref<2xf32>) -> (memref<2xf32>) 250 cf.br ^bb3(%4 : memref<2xf32>) 251^bb3(%2: memref<2xf32>): 252 … 253 memref.dealloc %2 : memref<2xf32> // free temp buffer %2 254 memref.dealloc %0 : memref<2xf32> // %0 can be safely freed here 255 return 256} 257``` 258 259Note that a temporary buffer for %2 was introduced to free all allocations 260properly. Note further that the unnecessary allocation of %3 can be easily 261removed using one of the post-pass transformations or the canonicalization pass. 262 263The presented example also works with dynamically shaped types. 264 265BufferDeallocation performs a fix-point iteration taking all aliases of all 266tracked allocations into account. We initialize the general iteration process 267using all tracked allocations and their associated aliases. As soon as we 268encounter an alias that is not properly dominated by our allocation, we mark 269this alias as *critical* (needs to be freed and tracked by the internal 270fix-point iteration). The following sample demonstrates the presence of critical 271and non-critical aliases: 272 273 274 275```mlir 276func.func @condBranchDynamicTypeNested( 277 %arg0: i1, 278 %arg1: memref<?xf32>, // aliases: %3, %4 279 %arg2: memref<?xf32>, 280 %arg3: index) { 281 cf.cond_br %arg0, ^bb1, ^bb2(%arg3: index) 282^bb1: 283 cf.br ^bb6(%arg1 : memref<?xf32>) 284^bb2(%0: index): 285 %1 = memref.alloc(%0) : memref<?xf32> // cannot be moved upwards due to the data 286 // dependency to %0 287 // aliases: %2, %3, %4 288 use(%1) 289 cf.cond_br %arg0, ^bb3, ^bb4 290^bb3: 291 cf.br ^bb5(%1 : memref<?xf32>) 292^bb4: 293 cf.br ^bb5(%1 : memref<?xf32>) 294^bb5(%2: memref<?xf32>): // non-crit. alias of %1, since %1 dominates %2 295 cf.br ^bb6(%2 : memref<?xf32>) 296^bb6(%3: memref<?xf32>): // crit. alias of %arg1 and %2 (in other words %1) 297 cf.br ^bb7(%3 : memref<?xf32>) 298^bb7(%4: memref<?xf32>): // non-crit. alias of %3, since %3 dominates %4 299 test.copy(%4, %arg2) : (memref<?xf32>, memref<?xf32>) -> () 300 return 301} 302``` 303 304Applying BufferDeallocation yields the following output: 305 306 307 308```mlir 309func.func @condBranchDynamicTypeNested( 310 %arg0: i1, 311 %arg1: memref<?xf32>, 312 %arg2: memref<?xf32>, 313 %arg3: index) { 314 cf.cond_br %arg0, ^bb1, ^bb2(%arg3 : index) 315^bb1: 316 // temp buffer required due to alias %3 317 %5 = bufferization.clone %arg1 : (memref<?xf32>) -> (memref<?xf32>) 318 cf.br ^bb6(%5 : memref<?xf32>) 319^bb2(%0: index): 320 %1 = memref.alloc(%0) : memref<?xf32> 321 use(%1) 322 cf.cond_br %arg0, ^bb3, ^bb4 323^bb3: 324 cf.br ^bb5(%1 : memref<?xf32>) 325^bb4: 326 cf.br ^bb5(%1 : memref<?xf32>) 327^bb5(%2: memref<?xf32>): 328 %6 = bufferization.clone %1 : (memref<?xf32>) -> (memref<?xf32>) 329 memref.dealloc %1 : memref<?xf32> 330 cf.br ^bb6(%6 : memref<?xf32>) 331^bb6(%3: memref<?xf32>): 332 cf.br ^bb7(%3 : memref<?xf32>) 333^bb7(%4: memref<?xf32>): 334 test.copy(%4, %arg2) : (memref<?xf32>, memref<?xf32>) -> () 335 memref.dealloc %3 : memref<?xf32> // free %3, since %4 is a non-crit. alias of %3 336 return 337} 338``` 339 340Since %3 is a critical alias, BufferDeallocation introduces an additional 341temporary copy in all predecessor blocks. %3 has an additional (non-critical) 342alias %4 that extends the live range until the end of bb7. Therefore, we can 343free %3 after its last use, while taking all aliases into account. Note that %4 344does not need to be freed, since we did not introduce a copy for it. 345 346The actual introduction of buffer copies is done after the fix-point iteration 347has been terminated and all critical aliases have been detected. A critical 348alias can be either a block argument or another value that is returned by an 349operation. Copies for block arguments are handled by analyzing all predecessor 350blocks. This is primarily done by querying the `BranchOpInterface` of the 351associated branch terminators that can jump to the current block. Consider the 352following example which involves a simple branch and the critical block argument 353%2: 354 355```mlir 356 custom.br ^bb1(..., %0, : ...) 357 ... 358 custom.br ^bb1(..., %1, : ...) 359 ... 360^bb1(%2: memref<2xf32>): 361 ... 362``` 363 364The `BranchOpInterface` allows us to determine the actual values that will be 365passed to block bb1 and its argument %2 by analyzing its predecessor blocks. 366Once we have resolved the values %0 and %1 (that are associated with %2 in this 367sample), we can introduce a temporary buffer and clone its contents into the new 368buffer. Afterwards, we rewire the branch operands to use the newly allocated 369buffer instead. However, blocks can have implicitly defined predecessors by 370parent ops that implement the `RegionBranchOpInterface`. This can be the case if 371this block argument belongs to the entry block of a region. In this setting, we 372have to identify all predecessor regions defined by the parent operation. For 373every region, we need to get all terminator operations implementing the 374`ReturnLike` trait, indicating that they can branch to our current block. 375Finally, we can use a similar functionality as described above to add the 376temporary copy. This time, we can modify the terminator operands directly 377without touching a high-level interface. 378 379Consider the following inner-region control-flow sample that uses an imaginary 380“custom.region_if” operation. It either executes the “then” or “else” region and 381always continues to the “join” region. The “custom.region_if_yield” operation 382returns a result to the parent operation. This sample demonstrates the use of 383the `RegionBranchOpInterface` to determine predecessors in order to infer the 384high-level control flow: 385 386```mlir 387func.func @inner_region_control_flow( 388 %arg0 : index, 389 %arg1 : index) -> memref<?x?xf32> { 390 %0 = memref.alloc(%arg0, %arg0) : memref<?x?xf32> 391 %1 = custom.region_if %0 : memref<?x?xf32> -> (memref<?x?xf32>) 392 then(%arg2 : memref<?x?xf32>) { // aliases: %arg4, %1 393 custom.region_if_yield %arg2 : memref<?x?xf32> 394 } else(%arg3 : memref<?x?xf32>) { // aliases: %arg4, %1 395 custom.region_if_yield %arg3 : memref<?x?xf32> 396 } join(%arg4 : memref<?x?xf32>) { // aliases: %1 397 custom.region_if_yield %arg4 : memref<?x?xf32> 398 } 399 return %1 : memref<?x?xf32> 400} 401``` 402 403 404 405Non-block arguments (other values) can become aliases when they are returned by 406dialect-specific operations. BufferDeallocation supports this behavior via the 407`RegionBranchOpInterface`. Consider the following example that uses an “scf.if” 408operation to determine the value of %2 at runtime which creates an alias: 409 410```mlir 411func.func @nested_region_control_flow(%arg0 : index, %arg1 : index) -> memref<?x?xf32> { 412 %0 = arith.cmpi "eq", %arg0, %arg1 : index 413 %1 = memref.alloc(%arg0, %arg0) : memref<?x?xf32> 414 %2 = scf.if %0 -> (memref<?x?xf32>) { 415 scf.yield %1 : memref<?x?xf32> // %2 will be an alias of %1 416 } else { 417 %3 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> // nested allocation in a div. 418 // branch 419 use(%3) 420 scf.yield %1 : memref<?x?xf32> // %2 will be an alias of %1 421 } 422 return %2 : memref<?x?xf32> 423} 424``` 425 426In this example, a dealloc is inserted to release the buffer within the else 427block since it cannot be accessed by the remainder of the program. Accessing the 428`RegionBranchOpInterface`, allows us to infer that %2 is a non-critical alias of 429%1 which does not need to be tracked. 430 431```mlir 432func.func @nested_region_control_flow(%arg0: index, %arg1: index) -> memref<?x?xf32> { 433 %0 = arith.cmpi "eq", %arg0, %arg1 : index 434 %1 = memref.alloc(%arg0, %arg0) : memref<?x?xf32> 435 %2 = scf.if %0 -> (memref<?x?xf32>) { 436 scf.yield %1 : memref<?x?xf32> 437 } else { 438 %3 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> 439 use(%3) 440 memref.dealloc %3 : memref<?x?xf32> // %3 can be safely freed here 441 scf.yield %1 : memref<?x?xf32> 442 } 443 return %2 : memref<?x?xf32> 444} 445``` 446 447Analogous to the previous case, we have to detect all terminator operations in 448all attached regions of “scf.if” that provides a value to its parent operation 449(in this sample via scf.yield). Querying the `RegionBranchOpInterface` allows us 450to determine the regions that “return” a result to their parent operation. Like 451before, we have to update all `ReturnLike` terminators as described above. 452Reconsider a slightly adapted version of the “custom.region_if” example from 453above that uses a nested allocation: 454 455```mlir 456func.func @inner_region_control_flow_div( 457 %arg0 : index, 458 %arg1 : index) -> memref<?x?xf32> { 459 %0 = memref.alloc(%arg0, %arg0) : memref<?x?xf32> 460 %1 = custom.region_if %0 : memref<?x?xf32> -> (memref<?x?xf32>) 461 then(%arg2 : memref<?x?xf32>) { // aliases: %arg4, %1 462 custom.region_if_yield %arg2 : memref<?x?xf32> 463 } else(%arg3 : memref<?x?xf32>) { 464 %2 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> // aliases: %arg4, %1 465 custom.region_if_yield %2 : memref<?x?xf32> 466 } join(%arg4 : memref<?x?xf32>) { // aliases: %1 467 custom.region_if_yield %arg4 : memref<?x?xf32> 468 } 469 return %1 : memref<?x?xf32> 470} 471``` 472 473Since the allocation %2 happens in a divergent branch and cannot be safely 474deallocated in a post-dominator, %arg4 will be considered a critical alias. 475Furthermore, %arg4 is returned to its parent operation and has an alias %1. This 476causes BufferDeallocation to introduce additional copies: 477 478```mlir 479func.func @inner_region_control_flow_div( 480 %arg0 : index, 481 %arg1 : index) -> memref<?x?xf32> { 482 %0 = memref.alloc(%arg0, %arg0) : memref<?x?xf32> 483 %1 = custom.region_if %0 : memref<?x?xf32> -> (memref<?x?xf32>) 484 then(%arg2 : memref<?x?xf32>) { 485 %4 = bufferization.clone %arg2 : (memref<?x?xf32>) -> (memref<?x?xf32>) 486 custom.region_if_yield %4 : memref<?x?xf32> 487 } else(%arg3 : memref<?x?xf32>) { 488 %2 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> 489 %5 = bufferization.clone %2 : (memref<?x?xf32>) -> (memref<?x?xf32>) 490 memref.dealloc %2 : memref<?x?xf32> 491 custom.region_if_yield %5 : memref<?x?xf32> 492 } join(%arg4: memref<?x?xf32>) { 493 %4 = bufferization.clone %arg4 : (memref<?x?xf32>) -> (memref<?x?xf32>) 494 memref.dealloc %arg4 : memref<?x?xf32> 495 custom.region_if_yield %4 : memref<?x?xf32> 496 } 497 memref.dealloc %0 : memref<?x?xf32> // %0 can be safely freed here 498 return %1 : memref<?x?xf32> 499} 500``` 501 502## Placement of Deallocs 503 504After introducing allocs and copies, deallocs have to be placed to free 505allocated memory and avoid memory leaks. The deallocation needs to take place 506after the last use of the given value. The position can be determined by 507calculating the common post-dominator of all values using their remaining 508non-critical aliases. A special-case is the presence of back edges: since such 509edges can cause memory leaks when a newly allocated buffer flows back to another 510part of the program. In these cases, we need to free the associated buffer 511instances from the previous iteration by inserting additional deallocs. 512 513Consider the following “scf.for” use case containing a nested structured 514control-flow if: 515 516```mlir 517func.func @loop_nested_if( 518 %lb: index, 519 %ub: index, 520 %step: index, 521 %buf: memref<2xf32>, 522 %res: memref<2xf32>) { 523 %0 = scf.for %i = %lb to %ub step %step 524 iter_args(%iterBuf = %buf) -> memref<2xf32> { 525 %1 = arith.cmpi "eq", %i, %ub : index 526 %2 = scf.if %1 -> (memref<2xf32>) { 527 %3 = memref.alloc() : memref<2xf32> // makes %2 a critical alias due to a 528 // divergent allocation 529 use(%3) 530 scf.yield %3 : memref<2xf32> 531 } else { 532 scf.yield %iterBuf : memref<2xf32> 533 } 534 scf.yield %2 : memref<2xf32> 535 } 536 test.copy(%0, %res) : (memref<2xf32>, memref<2xf32>) -> () 537 return 538} 539``` 540 541In this example, the *then* branch of the nested “scf.if” operation returns a 542newly allocated buffer. 543 544Since this allocation happens in the scope of a divergent branch, %2 becomes a 545critical alias that needs to be handled. As before, we have to insert additional 546copies to eliminate this alias using copies of %3 and %iterBuf. This guarantees 547that %2 will be a newly allocated buffer that is returned in each iteration. 548However, “returning” %2 to its alias %iterBuf turns %iterBuf into a critical 549alias as well. In other words, we have to create a copy of %2 to pass it to 550%iterBuf. Since this jump represents a back edge, and %2 will always be a new 551buffer, we have to free the buffer from the previous iteration to avoid memory 552leaks: 553 554```mlir 555func.func @loop_nested_if( 556 %lb: index, 557 %ub: index, 558 %step: index, 559 %buf: memref<2xf32>, 560 %res: memref<2xf32>) { 561 %4 = bufferization.clone %buf : (memref<2xf32>) -> (memref<2xf32>) 562 %0 = scf.for %i = %lb to %ub step %step 563 iter_args(%iterBuf = %4) -> memref<2xf32> { 564 %1 = arith.cmpi "eq", %i, %ub : index 565 %2 = scf.if %1 -> (memref<2xf32>) { 566 %3 = memref.alloc() : memref<2xf32> // makes %2 a critical alias 567 use(%3) 568 %5 = bufferization.clone %3 : (memref<2xf32>) -> (memref<2xf32>) 569 memref.dealloc %3 : memref<2xf32> 570 scf.yield %5 : memref<2xf32> 571 } else { 572 %6 = bufferization.clone %iterBuf : (memref<2xf32>) -> (memref<2xf32>) 573 scf.yield %6 : memref<2xf32> 574 } 575 %7 = bufferization.clone %2 : (memref<2xf32>) -> (memref<2xf32>) 576 memref.dealloc %2 : memref<2xf32> 577 memref.dealloc %iterBuf : memref<2xf32> // free backedge iteration variable 578 scf.yield %7 : memref<2xf32> 579 } 580 test.copy(%0, %res) : (memref<2xf32>, memref<2xf32>) -> () 581 memref.dealloc %0 : memref<2xf32> // free temp copy %0 582 return 583} 584``` 585 586Example for loop-like control flow. The CFG contains back edges that have to be 587handled to avoid memory leaks. The bufferization is able to free the backedge 588iteration variable %iterBuf. 589 590## Private Analyses Implementations 591 592The BufferDeallocation transformation relies on one primary control-flow 593analysis: BufferPlacementAliasAnalysis. Furthermore, we also use dominance and 594liveness to place and move nodes. The liveness analysis determines the live 595range of a given value. Within this range, a value is alive and can or will be 596used in the course of the program. After this range, the value is dead and can 597be discarded - in our case, the buffer can be freed. To place the allocs, we 598need to know from which position a value will be alive. The allocs have to be 599placed in front of this position. However, the most important analysis is the 600alias analysis that is needed to introduce copies and to place all 601deallocations. 602 603# Post Phase 604 605In order to limit the complexity of the BufferDeallocation transformation, some 606tiny code-polishing/optimization transformations are not applied on-the-fly 607during placement. Currently, a canonicalization pattern is added to the clone 608operation to reduce the appearance of unnecessary clones. 609 610Note: further transformations might be added to the post-pass phase in the 611future. 612 613## Clone Canonicalization 614 615During placement of clones it may happen, that unnecessary clones are inserted. 616If these clones appear with their corresponding dealloc operation within the 617same block, we can use the canonicalizer to remove these unnecessary operations. 618Note, that this step needs to take place after the insertion of clones and 619deallocs in the buffer deallocation step. The canonicalization inludes both, the 620newly created target value from the clone operation and the source operation. 621 622## Canonicalization of the Source Buffer of the Clone Operation 623 624In this case, the source of the clone operation can be used instead of its 625target. The unused allocation and deallocation operations that are defined for 626this clone operation are also removed. Here is a working example generated by 627the BufferDeallocation pass that allocates a buffer with dynamic size. A deeper 628analysis of this sample reveals that the highlighted operations are redundant 629and can be removed. 630 631```mlir 632func.func @dynamic_allocation(%arg0: index, %arg1: index) -> memref<?x?xf32> { 633 %1 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> 634 %2 = bufferization.clone %1 : (memref<?x?xf32>) -> (memref<?x?xf32>) 635 memref.dealloc %1 : memref<?x?xf32> 636 return %2 : memref<?x?xf32> 637} 638``` 639 640Will be transformed to: 641 642```mlir 643func.func @dynamic_allocation(%arg0: index, %arg1: index) -> memref<?x?xf32> { 644 %1 = memref.alloc(%arg0, %arg1) : memref<?x?xf32> 645 return %1 : memref<?x?xf32> 646} 647``` 648 649In this case, the additional copy %2 can be replaced with its original source 650buffer %1. This also applies to the associated dealloc operation of %1. 651 652## Canonicalization of the Target Buffer of the Clone Operation 653 654In this case, the target buffer of the clone operation can be used instead of 655its source. The unused deallocation operation that is defined for this clone 656operation is also removed. 657 658Consider the following example where a generic test operation writes the result 659to %temp and then copies %temp to %result. However, these two operations can be 660merged into a single step. Canonicalization removes the clone operation and 661%temp, and replaces the uses of %temp with %result: 662 663```mlir 664func.func @reuseTarget(%arg0: memref<2xf32>, %result: memref<2xf32>){ 665 %temp = memref.alloc() : memref<2xf32> 666 test.generic { 667 args_in = 1 : i64, 668 args_out = 1 : i64, 669 indexing_maps = [#map0, #map0], 670 iterator_types = ["parallel"]} %arg0, %temp { 671 ^bb0(%gen2_arg0: f32, %gen2_arg1: f32): 672 %tmp2 = math.exp %gen2_arg0 : f32 673 test.yield %tmp2 : f32 674 }: memref<2xf32>, memref<2xf32> 675 %result = bufferization.clone %temp : (memref<2xf32>) -> (memref<2xf32>) 676 memref.dealloc %temp : memref<2xf32> 677 return 678} 679``` 680 681Will be transformed to: 682 683```mlir 684func.func @reuseTarget(%arg0: memref<2xf32>, %result: memref<2xf32>){ 685 test.generic { 686 args_in = 1 : i64, 687 args_out = 1 : i64, 688 indexing_maps = [#map0, #map0], 689 iterator_types = ["parallel"]} %arg0, %result { 690 ^bb0(%gen2_arg0: f32, %gen2_arg1: f32): 691 %tmp2 = math.exp %gen2_arg0 : f32 692 test.yield %tmp2 : f32 693 }: memref<2xf32>, memref<2xf32> 694 return 695} 696``` 697 698## Known Limitations 699 700BufferDeallocation introduces additional clones from “memref” dialect 701(“bufferization.clone”). Analogous, all deallocations use the “memref” 702dialect-free operation “memref.dealloc”. The actual copy process is realized 703using “test.copy”. Furthermore, buffers are essentially immutable after their 704creation in a block. Another limitations are known in the case using 705unstructered control flow. 706