allocsize: change from 3.9 to 4.0

Hi all,
I added support for the allocsize function attribute to our compiler (LDC), thinking that that would enable removal of function calls when the allocated memory is not used.

For example:

declare i8* @my_malloc(i32) allocsize(0)

define void @test_malloc() {

%1 = call i8* @my_malloc(i32 100)
ret void

}

I thought the my_alloc call in test_malloc would be removed, but opt -O3 doesn’t do that (LLVM 4.0 and trunk). However, LLVM3.9’s opt does remove the call.

I can’t find out why this was changed.
(if the call is to “malloc”, it is removed because LLVM recognizes the function name)

Thanks for the explanation,
Kind regards,
Johan

Hello!

The short story is that this optimization we were performing was invalid. allocsize is speced to only tell us how many bytes exist at a returned pointer, but we were assuming it also meant the function with allocsize was malloc-like (e.g. had no other side effects, …). I realized this mistake when I added alloc_size – which lowers to LLVM’s allocsize – to clang, and broke things in the land of FreeBSD: https://www.mail-archive.com/cfe-commits@lists.llvm.org/msg45128.html . In particular, this visibly broke realloc, which has the side effect of potentially freeing memory.

The commit that fixed this behavior is r290397. There’s a FIXME in there that says we might be able to tag allocsize functions as allocation functions, but I’m unsure if “allocation function” will let us be as aggressive as you’d like.

(if the call is to “malloc”, it is removed because LLVM recognizes the function name)

FWIW, the prior behavior was that we’d pretend any allocsize function was present in http://llvm.org/docs/doxygen/html/MemoryBuiltins_8cpp_source.html#l00054 and was “MallocLike”. Looks like our friends in the Rust world keep https://github.com/rust-lang/llvm/commit/cca16c06fbec672b7d1dd9753491783a006bdfe5 for just this purpose. :slight_smile:

Sorry for any confusion,
George

Hello!

The short story is ...

Thanks for the explanation and links.

(if the call is to "malloc", it is removed because LLVM recognizes the
function name)

FWIW, the prior behavior was that we'd pretend any `allocsize` function was
present in
LLVM: lib/Analysis/MemoryBuiltins.cpp Source File and
was "MallocLike". Looks like our friends in the Rust world keep
https://github.com/rust-lang/llvm/commit/cca16c06fbec672b7d1dd9753491783a006bdfe5
for just this purpose. :slight_smile:

Yeah that is exactly the reason I want it :slight_smile: (we use vanilla LLVM for LDC)
Perhaps the best solution is to add functions that enables users (us)
to append to `AllocationFnData` and friends.

cheers,
  Johan