[flang-commits] [flang] [flang][cuda] Fix invalid host free of managed allocatable function results (PR #209945)

Zhen Wang via flang-commits flang-commits at lists.llvm.org
Thu Jul 16 10:00:21 PDT 2026


================
@@ -1972,25 +1973,52 @@ genUserCall(Fortran::lower::PreparedActualArguments &loweredActuals,
     // Allocatable result must be freed, other results are stack allocated.
     const auto *allocatable = result.getBoxOf<fir::MutableBoxValue>();
     const bool mustFree = allocatable != nullptr;
+    // A CUDA allocatable result is allocated with the CUDA allocator and must
+    // be released with the CUDA-aware deallocation, not the host free emitted
+    // by the plain hlfir.expr move + destroy path.
+    const Fortran::semantics::Symbol *resultSym = nullptr;
+    cuf::DataAttributeAttr resultCudaAttr;
+    if (mustFree && caller.getInterfaceDetails()) {
+      resultSym = &caller.getResultSymbol();
+      resultCudaAttr = Fortran::lower::translateSymbolCUFDataAttribute(
+          builder.getContext(), *resultSym);
+    }
+    const bool isCudaAllocatableResult = static_cast<bool>(resultCudaAttr);
+    auto genCudaResultCleanUp = [&]() {
+      callContext.stmtCtx.attachCleanup([&converter = callContext.converter,
+                                         loc, box = *allocatable, resultSym]() {
+        Fortran::lower::genDeallocateIfAllocated(converter, box, loc,
+                                                 resultSym);
+      });
+    };
     resultEntity = loadTrivialScalar(loc, builder, resultEntity);
----------------
wangzpgi wrote:

Thanks, that's much cleaner. Updated.

https://github.com/llvm/llvm-project/pull/209945


More information about the flang-commits mailing list