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