← Back to Pull requests

[mlir][bufferization] In OptimizeAllocationLiveliness optimize `dealloc` placement for unused `alloc`'s #227975

Merged
pranavalavandi merged 2 files (32 lines) on Nov 13, 2026 09:24 UTC
View on GitHub
pranavalavandi pranavalavandi commented on Oct 01, 2026 06:28 UTC
Author

Addresses issue https://github.com/llvm/llvm-project/issues/227363

As of this PR (https://github.com/llvm/llvm-project/pull/229296). The position of the dealloc was correctly, and safely moved within OptimizeAllocationLiveliness.

Issue https://github.com/llvm/llvm-project/issues/227363 raises a missed optimization where if the alloc is unused, and the only other reference to that memory buffer is a dealloc the optimization is not run. This PR fixes this.

When a lastUser does not exist, implying the memref is unused, we can just hoist the dealloc to be as close to the allocOp as possible

Diff: 32 lines (+25 / -7) across 2 files Reviewer: matthias-springer Review duration: 62095m
All Vouch review confidence checks passed
Residual risk 0.03 = Change Risk (0.25) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.25 · 32 lines diff across 2 files
0.25
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.88 · 5 substantive comment(s)
0.88
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.209
Real PR Conversation Timeline
18 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 01, 2026 06:29 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-mlir

@llvm/pr-subscribers-mlir-bufferization

Author: Pranav Alavandi (pranavalavandi)

<details>
<summary>Changes</summary>

Addresses issue https://github.com/llvm/llvm-project/issues/227363

As I understand only a small change is needed when a lastUser does not exist, implying the memref is unused, we can just hoist the dealloc to be right after the allocOp

---
Full diff: https://github.com/llvm/llvm-project/pull/227975.diff

2 Files Affected:

  • (modified) mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp (+3)

  • (modified) mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir (+15)
  • ``````

    diff --git a/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp b/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp
    index 28ee5b8e32b99..3d4b8d2adb911 100644
    --- a/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp
    +++ b/mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp
    @@ -155,6 +155,9 @@ struct OptimizeAllocationLiveness
             }
           }
           if (lastUser == nullptr) {
    +        LDBG() << "Last user not found ";
    +        LDBG() << "Moved dealloc op after alloc: " << *allocOp;
    +        deallocOp->moveAfter(allocOp);
             return WalkResult::advance();
           }
           LDBG() << "Last user found: " << *lastUser;
    diff --git a/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir b/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir
    index b8fcccda8833a..07620859cc0bb 100644
    --- a/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir
    +++ b/mlir/test/Dialect/Bufferization/Transforms/optimize-allocation-liveness.mlir
    @@ -234,3 +234,18 @@ func.func private @test_alloc_with_multiple_results() -> () {
       memref.dealloc %alloc2 : memref<64xf32>
       return
     }
    +
    +// -----
    +func.func private @work()
    +// CHECK-LABEL:   func.func private @test_alloc_with_no_uses() {
    +// CHECK:           %[[ALLOC_0:.*]] = memref.alloc() : memref<1048576xi32>
    +// CHECK:           memref.dealloc %[[ALLOC_0]] : memref<1048576xi32>
    +// CHECK:           call @work() : () -> ()
    +// CHECK:           return
    +// CHECK:         }
    +func.func private @test_alloc_with_no_uses() -> () {
    +    %alloc = memref.alloc() : memref<1048576xi32>
    +    call @work() : () -> ()
    +    memref.dealloc %alloc : memref<1048576xi32>
    +    return
    +}
    
    
    ``````

    </details>

    matthias-springer matthias-springer commented on Oct 01, 2026 07:15 UTC
    Reviewer

    A coding agent found that this pass now produces invalid IR for such a test case (dominance violation):

    func.func @foo(%d: !gpu.async.token) {
      %a = gpu.alloc
      %w = gpu.wait async [%d]
      %done = gpu.dealloc async [%w] %a
      gpu.wait %done
      return
    }
    

    pranavalavandi pranavalavandi commented on Oct 01, 2026 08:03 UTC
    Author

    A coding agent found that this pass now produces invalid IR for such a test case (dominance violation):

    >
    > func.func @foo(%d: !gpu.async.token) {
    >   %a = gpu.alloc
    >   %w = gpu.wait async [%d]
    >   %done = gpu.dealloc async [%w] %a
    >   gpu.wait %done
    >   return
    > }
    > 

    Ah yeah that makes sense. I have a fix in my branch- the solution would be to only move the dealloc to be after the "lowest" operand to preserve dominance. However I realised that the code on main has an existing bug already:

    func.func @foo(%d: !gpu.async.token) {
      %c0 = arith.constant 0 : index
      %a = gpu.alloc () : memref<8xf32>
      %x = memref.load %a[%c0] : memref<8xf32>
      %w = gpu.wait async [%d]
      %done = gpu.dealloc async [%w] %a : memref<8xf32>
      gpu.wait [%done]
      return
    }
    

    And so since we currently move the code to be after the lastUser we do not check any operands when hoisting it.

    I think the fix here is to unconditionally check the positions of any operands for the dealloc op, and to only move it to be after that. If that is lower in the program than lastUser then that is the case.

    matthias-springer matthias-springer commented on Oct 02, 2026 02:59 UTC
    Reviewer

    I didn't have time to look into this any further, but here are two more test cases that were flagged by a coding agent:

    //--- crash.mlir
    // memref.realloc has a Free effect on %a, so it is selected as the freeing op.
    // Its first operand sets lastDeallocOperandDef to the local memref.alloc.
    // The defining op of %size is outside the scf.if body; findAncestorOpInBlock
    // returns nullptr, which is passed to happensBefore and dereferenced.
    // Expected: successful transformation that preserves operand dominance.
    // Actual: null dereference at OptimizeAllocationLiveness.cpp:166.
    func.func @realloc_outer_size(%cond: i1) {
      %size = arith.constant 16 : index
      scf.if %cond {
        %a = memref.alloc() : memref<8xf32>
        %b = memref.realloc %a(%size) : memref<8xf32> to memref<?xf32>
        memref.dealloc %b : memref<?xf32>
      }
      return
    }
    
    //--- async-ordering.mlir
    // The allocated memref has no user other than gpu.dealloc. The completion
    // token's gpu.wait is not included in the memref's use/alias analysis.
    // Expected: retain the wait before deallocation, or otherwise preserve the
    // allocation's completion dependency.
    // Actual order: gpu.alloc async -> gpu.dealloc -> gpu.wait.
    // The GPU async interface allows allocation to remain in flight until the
    // token is waited on; moving deallocation ahead of that wait loses ordering.
    func.func @async_alloc_with_dependency(%dep: !gpu.async.token) {
      %a, %token = gpu.alloc async [%dep] () : memref<8xf32>
      gpu.wait [%token]
      gpu.dealloc %a : memref<8xf32>
      return
    }
    

    pranavalavandi pranavalavandi commented on Oct 02, 2026 05:34 UTC
    Author

    Thanks for the additional tests I have missed. I am quite new to this project in terms of contributing but it seems as though we need to first do a round of fixup based on bugs on the existing code in main before we try to address the missed optimization that this PR originally intended.

    E.g. similar to your first example this would fail on main:

    func.func @foo() {
      %a = memref.alloc() : memref<8xf32>
      %b = memref.realloc %a : memref<8xf32> to memref<16xf32>
      memref.dealloc %b : memref<16xf32>
      return
    }
    

    Here the realloc would infact get moved to be after the dealloc

    Let me raise a PR to address these bugs first before we consider adding new code on top. Thanks a lot for your time for helping out re this

    matthias-springer matthias-springer commented on Oct 02, 2026 05:37 UTC
    Contributor

    Thank you. Some of this code is a bit in a rough state.

    pranavalavandi pranavalavandi commented on Nov 06, 2026 03:51 UTC
    Author

    Hey @matthias-springer, finally got back around to this.

    Have forced push the relevant change needed.

    After our previous PR: https://github.com/llvm/llvm-project/pull/229296, the change here now should be manageable, as in this commit.

    We can still try to optimize if lastUser is nullptr, since it will still try to move it as high as possible, considering the operands and users of the dealloc as per the last PR.

    github-actions[bot] github-actions[bot] commented on Nov 06, 2026 04:02 UTC
    Bot

    <!--PREMERGE ADVISOR COMMENT: Linux-->

    :penguin: Linux x64 Test Results

    12235 tests passed
    661 tests skipped

    :white_check_mark: The build succeeded and all tests passed.

    matthias-springer matthias-springer commented on code on Nov 09, 2026 08:30 UTC
    Code Review
    mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp:1
    @@ -121,6 +120,9 @@ struct OptimizeAllocationLiveness
                                                 Operation *lastUser) {
     
         auto *target = lastUser;
    +    if (!lastUser) {
    +      LDBG() << "We may crash now";

    What's the purpose of this comment? Why is there a crash?

    matthias-springer matthias-springer commented on Nov 09, 2026 08:34 UTC
    Reviewer

    Can you improve the commit message, so that it's self-standing and explains what is being changed here and why?

    pranavalavandi pranavalavandi commented on code on Nov 09, 2026 21:46 UTC
    Code Review
    mlir/lib/Dialect/Bufferization/Transforms/OptimizeAllocationLiveness.cpp:1
    @@ -121,6 +120,9 @@ struct OptimizeAllocationLiveness
                                                 Operation *lastUser) {
     
         auto *target = lastUser;
    +    if (!lastUser) {
    +      LDBG() << "We may crash now";

    Oh my bad 🤦 . I forgot to remove this code, it was just me adding some logs when testing

    matthias-springer matthias-springer commented on Nov 10, 2026 13:30 UTC
    Contributor

    Also update the commit message of the PR in Github. That's what's used when merging the PR.

    pranavalavandi pranavalavandi commented on Nov 10, 2026 20:21 UTC
    Author

    Also update the commit message of the PR in Github. That's what's used when merging the PR.

    Yep. Hopefully the new PR title is more informative.

    matthias-springer matthias-springer commented on Nov 11, 2026 09:34 UTC
    Contributor

    Oh I meant this part:

    As I understand only a small change is needed when a lastUser does not exist, implying the memref is unused, we can just hoist the dealloc to be right after the allocOp
    

    This doesn't look like something that we want to have in the permanent git history. (Just rephrase a bit.)

    pranavalavandi pranavalavandi commented on Nov 12, 2026 03:33 UTC
    Author

    Oh I meant this part:

    >
    > As I understand only a small change is needed when a lastUser does not exist, implying the memref is unused, we can just hoist the dealloc to be right after the allocOp
    > 

    > This doesn't look like something that we want to have in the permanent git history. (Just rephrase a bit.)

    🤦 . Sorry for misreading what you meant. Have updated the PR description.

    github-actions[bot] github-actions[bot] commented on Nov 12, 2026 03:40 UTC
    Bot

    <!--PREMERGE ADVISOR COMMENT: Windows-->

    :window: Windows x64 Test Results

    5915 tests passed
    476 tests skipped

    :white_check_mark: The build succeeded and all tests passed.

    matthias-springer matthias-springer approved these changes on Nov 13, 2026 09:23 UTC
    Approved Reviewer

    Approved these changes.

    Assignees
    pranavalavandi pranavalavandi
    Labels
    risk: low confidence: 89% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 25.4% (LOW) · Higher = larger blast radius
    25.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89% · Lower = rushed or shallow review
    89%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.8% · Safe to merge
    2.8%