EnzymeAD / Enzyme

High-performance automatic differentiation of LLVM and MLIR.
https://enzyme.mit.edu
Other
1.29k stars 109 forks source link

Enzyme warns `freeing without malloc` on allocated pointers #2070

Open dime10 opened 2 months ago

dime10 commented 2 months ago

Context: I'm not sure whether this is a bug or I'm not understanding what Enzyme is warning me about, so some information on possible sources of the error would be really appreciated. The error message is freeing without malloc, but inspecting the IR it looks to me like the pointer being freed was clearly allocated in all ancestors.

Issue: Specifically, Enzyme produces this warning in connection with a PHI node:

freeing without malloc   %.pn1130 = phi ptr [ %first, %.start ], [ %second, %.critedge ]

Both operands %first and %second are allocated with a custom allocation function _mlir_memref_to_llvm_alloc, and the result is freed with _mlir_memref_to_llvm_free. See full snippet below.

One thing I noticed is without the llvm.memcpy.p0.p0.i64 call the error does not reproduce.

Reproducer: This snippet was generated with llvm-reduce but I think it still preserves the core issue:

@enzyme_dupnoneed = external constant i8

declare void @__enzyme_autodiff0(...)

declare void @_mlir_memref_to_llvm_free(ptr)

declare ptr @_mlir_memref_to_llvm_alloc(i64)

define void @my_model.cloned(ptr %0, ptr %1, i64 %2, i64 %3, i64 %4, i64 %5, i64 %6, ptr %7, ptr %8, i64 %9, i64 %10, i64 %11, i64 %12, i64 %13, ptr %14, ptr %15, i64 %16, ptr %17, ptr %18, i64 %19, i64 %20, i64 %21) {
.start:
  %first = call ptr @_mlir_memref_to_llvm_alloc(i64 32)
  br label %.critedge

.critedge:                                        ; preds = %.critedge, %.start
  %.pn1130 = phi ptr [ %first, %.start ], [ %second, %.critedge ]
  call void @llvm.memcpy.p0.p0.i64(ptr null, ptr %.pn1130, i64 1, i1 false)
  call void @_mlir_memref_to_llvm_free(ptr %.pn1130)
  %second = call ptr @_mlir_memref_to_llvm_alloc(i64 32)
  br label %.critedge
}

define { ptr, ptr, i64, [3 x i64], [3 x i64] } @my_model.fullgrad1() {
  tail call void (...) @__enzyme_autodiff0(ptr nonnull @my_model.cloned, ptr null, ptr null, ptr null, ptr null, i64 0, i64 0, i64 0, i64 0, i64 0, ptr null, ptr null, ptr null, ptr null, i64 0, i64 0, i64 0, i64 0, i64 0, ptr null, ptr null, ptr null, ptr null, i64 0, ptr null, ptr null, ptr nonnull @enzyme_dupnoneed, ptr null, ptr null, i64 0, i64 0, i64 0)
  ret { ptr, ptr, i64, [3 x i64], [3 x i64] } zeroinitializer
}

; Function Attrs: nocallback nofree nounwind willreturn memory(argmem: readwrite)
declare void @llvm.memcpy.p0.p0.i64(ptr noalias nocapture writeonly, ptr noalias nocapture readonly, i64, i1 immarg)

Versions: llvm=3a8316216807d64a586b971f51695e23883331f7 enzyme=v0.0.130

dime10 commented 2 days ago

Bump to see if anyone is available to give me some insight into what might be going wrong here :)