[llvm] [ObjCARC] Change autorelease to release when the pool state is not changed between the autorelease and the pool pop (PR #152353)

via llvm-commits llvm-commits at lists.llvm.org
Thu Jan 22 09:34:57 PST 2026


https://github.com/AZero13 updated https://github.com/llvm/llvm-project/pull/152353

>From 0339fb3355b817d53f0dc2530692ba24d0c33099 Mon Sep 17 00:00:00 2001
From: AZero13 <gfunni234 at gmail.com>
Date: Wed, 6 Aug 2025 14:07:16 -0400
Subject: [PATCH 1/2] [ObjCARC] Change autorelease to release when the pool
 state is not changed between the autorelease and the pool pop

Co-Authored-By: Jon Roelofs <jroelofs at gmail.com>
---
 llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp   | 75 ++++++++++++++++++-
 .../ObjCARC/test_autorelease_pool.ll          |  6 +-
 2 files changed, 73 insertions(+), 8 deletions(-)

diff --git a/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp b/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
index 386e48f81a93f..ea211775b729d 100644
--- a/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
+++ b/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
@@ -121,6 +121,63 @@ static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
 /// \defgroup ARCOpt ARC Optimization.
 /// @{
 
+/// Check if there is an autoreleasePoolPop after the given autorelease
+/// instruction in the same basic block with no intervening calls that
+/// could affect the autorelease pool.
+static bool HasFollowingAutoreleasePoolPop(Instruction *AutoreleaseInst) {
+  assert(IsAutorelease(GetBasicARCInstKind(AutoreleaseInst)));
+  BasicBlock *BB = AutoreleaseInst->getParent();
+
+  // Look forward from the autorelease instruction
+  for (BasicBlock::iterator I = std::next(AutoreleaseInst->getIterator()),
+                            E = BB->end();
+       I != E; ++I) {
+    ARCInstKind Class = GetBasicARCInstKind(&*I);
+
+    switch (Class) {
+    case ARCInstKind::AutoreleasepoolPop:
+      // Found a pool pop - the autorelease will be drained
+      return true;
+
+    case ARCInstKind::AutoreleasepoolPush:
+      // A new pool started - this autorelease won't be drained by a later pop
+      return false;
+
+    case ARCInstKind::CallOrUser:
+    case ARCInstKind::Call:
+      // Unknown call could affect autorelease pool state or return autoreleased
+      // objects
+      return false;
+    case ARCInstKind::Retain:
+    case ARCInstKind::RetainRV:
+    case ARCInstKind::UnsafeClaimRV:
+    case ARCInstKind::RetainBlock:
+    case ARCInstKind::Release:
+    case ARCInstKind::Autorelease:
+    case ARCInstKind::AutoreleaseRV:
+    case ARCInstKind::NoopCast:
+    case ARCInstKind::FusedRetainAutorelease:
+    case ARCInstKind::FusedRetainAutoreleaseRV:
+    case ARCInstKind::LoadWeakRetained:
+    case ARCInstKind::StoreWeak:
+    case ARCInstKind::InitWeak:
+    case ARCInstKind::LoadWeak:
+    case ARCInstKind::MoveWeak:
+    case ARCInstKind::CopyWeak:
+    case ARCInstKind::DestroyWeak:
+    case ARCInstKind::StoreStrong:
+    case ARCInstKind::IntrinsicUser:
+    case ARCInstKind::User:
+    case ARCInstKind::None:
+      // Everything else is safe to ignore:
+      break;
+    }
+  }
+
+  // Reached end of basic block without finding a pool pop
+  return false;
+}
+
 // TODO: On code like this:
 //
 // objc_retain(%x)
@@ -977,12 +1034,22 @@ void ObjCARCOpt::OptimizeIndividualCallImpl(Function &F, Instruction *Inst,
     break;
   }
 
-  // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
+  // objc_autorelease(x) -> objc_release(x) if x is otherwise unused
+  // OR if this autorelease is followed by an autoreleasePoolPop.
   if (IsAutorelease(Class) && Inst->use_empty()) {
     CallInst *Call = cast<CallInst>(Inst);
     const Value *Arg = Call->getArgOperand(0);
     Arg = FindSingleUseIdentifiedObject(Arg);
-    if (Arg) {
+    bool ShouldConvert = (Arg != nullptr);
+    const char *Reason = "since x is otherwise unused";
+
+    // Also convert if this autorelease is followed by a pool pop
+    if (!ShouldConvert && HasFollowingAutoreleasePoolPop(Inst)) {
+      ShouldConvert = true;
+      Reason = "since it's followed by autoreleasePoolPop";
+    }
+
+    if (ShouldConvert) {
       Changed = true;
       ++NumAutoreleases;
 
@@ -996,8 +1063,8 @@ void ObjCARCOpt::OptimizeIndividualCallImpl(Function &F, Instruction *Inst,
                            MDNode::get(C, {}));
 
       LLVM_DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
-                           "since x is otherwise unused.\nOld: "
-                        << *Call << "\nNew: " << *NewCall << "\n");
+                        << Reason << ".\nOld: " << *Call
+                        << "\nNew: " << *NewCall << "\n");
 
       EraseInstruction(Call);
       Inst = NewCall;
diff --git a/llvm/test/Transforms/ObjCARC/test_autorelease_pool.ll b/llvm/test/Transforms/ObjCARC/test_autorelease_pool.ll
index 896717f92146f..150837f922c39 100644
--- a/llvm/test/Transforms/ObjCARC/test_autorelease_pool.ll
+++ b/llvm/test/Transforms/ObjCARC/test_autorelease_pool.ll
@@ -44,7 +44,7 @@ define void @test_multiple_autoreleases() {
 ; CHECK-NEXT:    call void @use_object(ptr [[OBJ1]])
 ; CHECK-NEXT:    [[TMP1:%.*]] = call ptr @llvm.objc.autorelease(ptr [[OBJ1]]) #[[ATTR0]]
 ; CHECK-NEXT:    call void @use_object(ptr [[OBJ2]])
-; CHECK-NEXT:    [[TMP2:%.*]] = call ptr @llvm.objc.autorelease(ptr [[OBJ2]]) #[[ATTR0]]
+; CHECK-NEXT:    call void @llvm.objc.release(ptr [[OBJ2]]) #[[ATTR0]], !clang.imprecise_release [[META0]]
 ; CHECK-NEXT:    call void @llvm.objc.autoreleasePoolPop(ptr [[POOL]]) #[[ATTR0]]
 ; CHECK-NEXT:    ret void
 ;
@@ -211,9 +211,7 @@ define void @test_complex_shadowing() {
 ; CHECK-NEXT:    [[OBJ3:%.*]] = call ptr @create_object()
 ; CHECK-NEXT:    call void @llvm.objc.release(ptr [[OBJ1]]) #[[ATTR0]], !clang.imprecise_release [[META0]]
 ; CHECK-NEXT:    call void @llvm.objc.release(ptr [[OBJ2]]) #[[ATTR0]], !clang.imprecise_release [[META0]]
-; CHECK-NEXT:    [[INNER2_POOL:%.*]] = call ptr @llvm.objc.autoreleasePoolPush() #[[ATTR0]]
-; CHECK-NEXT:    [[TMP1:%.*]] = call ptr @llvm.objc.autorelease(ptr [[OBJ3]]) #[[ATTR0]]
-; CHECK-NEXT:    call void @llvm.objc.autoreleasePoolPop(ptr [[INNER2_POOL]]) #[[ATTR0]]
+; CHECK-NEXT:    call void @llvm.objc.release(ptr [[OBJ3]]) #[[ATTR0]], !clang.imprecise_release [[META0]]
 ; CHECK-NEXT:    ret void
 ;
   %obj1 = call ptr @create_object()

>From f64f2d0dd2845c4bbb7b3456887209e7bb19fec6 Mon Sep 17 00:00:00 2001
From: AZero13 <gfunni234 at gmail.com>
Date: Thu, 22 Jan 2026 12:29:49 -0500
Subject: [PATCH 2/2] Prevent/mitigate quadradic scaling (O2)

---
 llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp | 97 ++++++++++++++++++---
 1 file changed, 84 insertions(+), 13 deletions(-)

diff --git a/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp b/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
index ea211775b729d..6a6b7a104147c 100644
--- a/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
+++ b/llvm/lib/Transforms/ObjCARC/ObjCARCOpts.cpp
@@ -124,9 +124,18 @@ static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
 /// Check if there is an autoreleasePoolPop after the given autorelease
 /// instruction in the same basic block with no intervening calls that
 /// could affect the autorelease pool.
-static bool HasFollowingAutoreleasePoolPop(Instruction *AutoreleaseInst) {
+static bool HasFollowingAutoreleasePoolPop(
+    Instruction *AutoreleaseInst,
+    DenseMap<Instruction *, bool> &Cache) {
   assert(IsAutorelease(GetBasicARCInstKind(AutoreleaseInst)));
+  
+  // Check cache first
+  auto It = Cache.find(AutoreleaseInst);
+  if (It != Cache.end())
+    return It->second;
+
   BasicBlock *BB = AutoreleaseInst->getParent();
+  bool Result = false;
 
   // Look forward from the autorelease instruction
   for (BasicBlock::iterator I = std::next(AutoreleaseInst->getIterator()),
@@ -137,17 +146,44 @@ static bool HasFollowingAutoreleasePoolPop(Instruction *AutoreleaseInst) {
     switch (Class) {
     case ARCInstKind::AutoreleasepoolPop:
       // Found a pool pop - the autorelease will be drained
-      return true;
-
-    case ARCInstKind::AutoreleasepoolPush:
-      // A new pool started - this autorelease won't be drained by a later pop
-      return false;
+      Result = true;
+      goto done;
+
+    case ARCInstKind::AutoreleasepoolPush: {
+      // A nested pool started. Skip to its matching pop and continue scanning,
+      // since the nested pool doesn't affect whether the outer pool will drain
+      // our autorelease. We can skip over everything inside the nested pool
+      // (retains, releases, calls, etc.) because the nested pool is isolated.
+      int Depth = 1;
+      BasicBlock::iterator J = std::next(I);
+      for (; J != E && Depth > 0; ++J) {
+        ARCInstKind NestedClass = GetBasicARCInstKind(&*J);
+        if (NestedClass == ARCInstKind::AutoreleasepoolPush)
+          ++Depth;
+        else if (NestedClass == ARCInstKind::AutoreleasepoolPop)
+          --Depth;
+        // Everything else (retains, releases, calls, etc.) inside the nested
+        // pool can be ignored - the nested pool is isolated and doesn't affect
+        // the outer pool's behavior.
+      }
+      // If we found the matching pop, continue scanning from after it
+      if (Depth == 0) {
+        // J points to after the matching pop. Set I to J-1 so that after
+        // the loop increment, we continue from after the pop.
+        I = std::prev(J);
+        continue;
+      }
+      // Unmatched push (reached end of BB) - this autorelease won't be drained
+      Result = false;
+      goto done;
+    }
 
     case ARCInstKind::CallOrUser:
     case ARCInstKind::Call:
       // Unknown call could affect autorelease pool state or return autoreleased
       // objects
-      return false;
+      Result = false;
+      goto done;
     case ARCInstKind::Retain:
     case ARCInstKind::RetainRV:
     case ARCInstKind::UnsafeClaimRV:
@@ -175,7 +211,12 @@ static bool HasFollowingAutoreleasePoolPop(Instruction *AutoreleaseInst) {
   }
 
   // Reached end of basic block without finding a pool pop
-  return false;
+  Result = false;
+
+done:
+  // Cache the result
+  Cache[AutoreleaseInst] = Result;
+  return Result;
 }
 
 // TODO: On code like this:
@@ -556,6 +597,10 @@ class ObjCARCOpt {
 
   DenseMap<BasicBlock *, ColorVector> BlockEHColors;
 
+  /// Cache for HasFollowingAutoreleasePoolPop results to avoid quadratic
+  /// scanning when multiple autoreleases are in the same basic block.
+  DenseMap<Instruction *, bool> AutoreleasePoolPopCache;
+
   bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
   void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
                                  ARCInstKind &Class);
@@ -818,6 +863,8 @@ void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
   LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
   // Reset all the flags in preparation for recomputing them.
   UsedInThisFunction = 0;
+  // Clear the autorelease pool pop cache for this function
+  AutoreleasePoolPopCache.clear();
 
   // Store any delayed AutoreleaseRV intrinsics, so they can be easily paired
   // with RetainRV and UnsafeClaimRV.
@@ -1044,7 +1091,7 @@ void ObjCARCOpt::OptimizeIndividualCallImpl(Function &F, Instruction *Inst,
     const char *Reason = "since x is otherwise unused";
 
     // Also convert if this autorelease is followed by a pool pop
-    if (!ShouldConvert && HasFollowingAutoreleasePoolPop(Inst)) {
+    if (!ShouldConvert && HasFollowingAutoreleasePoolPop(Inst, AutoreleasePoolPopCache)) {
       ShouldConvert = true;
       Reason = "since it's followed by autoreleasePoolPop";
     }
@@ -2571,9 +2618,35 @@ bool MayAutorelease(const CallBase &CB, unsigned Depth = 0) {
     if (!Callee->hasExactDefinition())
       return true;
     for (const BasicBlock &BB : *Callee) {
-      for (const Instruction &I : BB) {
-        // TODO: Ignore all instructions between autorelease pools
+      for (auto It = BB.begin(), E = BB.end(); It != E; ++It) {
+        const Instruction &I = *It;
         ARCInstKind InstKind = GetBasicARCInstKind(&I);
+        
+        // Skip over nested autorelease pools - autoreleases inside are drained
+        // by the nested pool and don't affect whether this function may autorelease.
+        if (InstKind == ARCInstKind::AutoreleasepoolPush) {
+          int Depth = 1;
+          auto J = std::next(It);
+          for (; J != E && Depth > 0; ++J) {
+            ARCInstKind NestedKind = GetBasicARCInstKind(&*J);
+            if (NestedKind == ARCInstKind::AutoreleasepoolPush)
+              ++Depth;
+            else if (NestedKind == ARCInstKind::AutoreleasepoolPop)
+              --Depth;
+          }
+          // If we found the matching pop, skip to after it
+          if (Depth == 0) {
+            It = std::prev(J);  // Will be incremented by loop to point after pop
+            continue;
+          }
+          // Unmatched push - continue scanning (conservative)
+          continue;
+        }
+        
+        // Skip pop instructions (we only process them when matching a push)
+        if (InstKind == ARCInstKind::AutoreleasepoolPop)
+          continue;
+        
         switch (InstKind) {
         case ARCInstKind::Autorelease:
         case ARCInstKind::AutoreleaseRV:
@@ -2596,8 +2669,6 @@ bool MayAutorelease(const CallBase &CB, unsigned Depth = 0) {
         case ARCInstKind::CopyWeak:
         case ARCInstKind::DestroyWeak:
         case ARCInstKind::StoreStrong:
-        case ARCInstKind::AutoreleasepoolPush:
-        case ARCInstKind::AutoreleasepoolPop:
           // These ObjC runtime functions don't produce autoreleases
           break;
 



More information about the llvm-commits mailing list