This is an archive of the discontinued LLVM Phabricator instance.

[mlir] fix a memory leak in NestedPattern
ClosedPublic

Authored by ftynse on Mar 12 2021, 3:26 AM.

Details

Summary

NestedPattern uses a BumpPtrAllocator to store child (nested) pattern
objects to decrease the overhead of dynamic allocation. This assumes all
allocations happen inside the allocator that will be freed as a whole.
However, NestedPattern contains std::function as a member, which
allocates internally using new, unaware of the BumpPtrAllocator. Since
NestedPattern only holds pointers to the nested patterns allocated in
the BumpPtrAllocator, it never calls their destructors, so the
destructor of the std::functions they contain are never called either,
leaking the allocated memory.

Make NestedPattern explicitly call destructors of nested patterns. This
additionally requires to actually copy the nested patterns in
copy-construction and copy-assignment instead of just sharing the
pointer to the arena-allocated list of children to avoid double-free. An
alternative solution would be to add reference counting to the list of
arena-allocated list of children.

Diff Detail

Event Timeline

ftynse created this revision.Mar 12 2021, 3:26 AM
ftynse requested review of this revision.Mar 12 2021, 3:26 AM
Herald added a project: Restricted Project. · View Herald TranscriptMar 12 2021, 3:26 AM
nicolasvasilache accepted this revision.Mar 12 2021, 5:55 AM
This revision is now accepted and ready to land.Mar 12 2021, 5:55 AM
This revision was automatically updated to reflect the committed changes.

Thanks, Alex!

Thanks!

Do we relies on the owning behavior of std::function for users of NestedPattern or could we switch it to function_ref?

Thanks!

Do we relies on the owning behavior of std::function for users of NestedPattern or could we switch it to function_ref?

It does. function_ref was the first thing I tried.

rriddle added inline comments.Mar 13 2021, 2:40 AM
mlir/include/mlir/Analysis/NestedMatcher.h
132

Is this always allocating the same type? You could switch to SpecificBumpPtrAllocator, which does call the destructors (IIRC).