[RFC] Add a freezing memcpy

In Rust we are discussing how to best expose freeze to programmers. We’d like to give them the ability to play tricks with uninitialized memory, and we expect this will also be useful to safely and efficiently expose SIMD operations where some lanes can become poison.

Currently, LLVM only has a freeze operation on SSA values. That’s not quite enough for a nice API in Rust, where we’d want to be able to do something similar also for types that are not stored in SSA values, but in alloca or generally behind a pointer indirection. (Which types are represented in-memory vs as SSA variables is an implementation detail so we’d like the Rust-level freeze to work for all types.) In my eyes, the most obvious way to express that is a “freezing memcpy”:

  • On the IR level, a freezing memcpy would be specified as being mostly like memcpy, except that any undef/poison bits from the source become arbitrary (non-deterministic) initialized bits in the destination. In other words, where memcpy is equivalent to a load-store loop (at byte type), freezing memcpy is equivalent to a load-freeze-store loop.
  • For optimizations, this means that when a freezing memcpy is replaced by load/store, a freeze has to be added. Furthermore, eliding such memcpy would need extra care – I do not know if LLVM today performs optimizations like “I know the source memory of this memcpy is fully uninitialized so I can elide the copy” or “I know the source and target memory are already identical so I can elide the copy”; neither of these would be valid for a freezing memcpy.
  • In backends, this can be compiled to a libcall as usual. At this level of the semantics, freeze becomes a NOP, so a freezing memcpy is just like a normal memcpy.

Without such an operation, I think the best a frontend can do is to emit a load-freeze-store loop, but that is unlikely to be as efficient as the native platform memcpy / libcall.

What do people think, does this make sense? Is there something frontends like Rust could do that avoids the need for a new LLVM-level operation? Are there problems/interactions that I missed?

2 Likes

+1

https://github.com/llvm/llvm-project/blob/00dc0b882bd3a168374e9eed3855224202a3909f/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp#L138-L144

We convert libcall memcpy into the intrinsic in LibCallSimplifier::optimizeMemCpy (middle-end). Should we switch to freeze memcpy here?

1 Like

In the context of MemCpyOptimizer (since I’ve worked on it lately), it comes up most often in the form of trailing padding, since the frontend often stores only to the useful parts, but does a memcpy over the whole object. In many cases like that though, I think we’ve seen in my experience that an initial zeroing can sometimes be a lot cheaper than freezing later, since it lets all the earlier passes also agree on what value it will become, thus enabling more optimizations than a later freeze.

Continuing my own train-of-thought here, I think the freezing memcpy is conflating two different sources of undef, which may or may not be the same for the Rust RFC.

One source of undef is the alloca contents, which can be modeled during allocation creation explicitly:

%trick = alloca
%freeze = freeze undef
store %freeze, %trick
memcpy %dst, %trick

But you may or may not actually want to do this over a store zero there – Julia used to do this, and the performance was not great. I think isel decided materialize it as a store to zero anyways, without any of the optimizer benefits of having known it was going to store a known bit pattern there. It was changed to just store zeros in Replace store of freeze in allocop and in emit new struct with memset since aggregate stores are bad by gbaraldi · Pull Request #55879 · JuliaLang/julia · GitHub.

And the other source is the operations themselves, which I think appears to be semantically equivalent to having the front-end put freeze on each store:

%trick = alloca
%freeze = freeze %maybeundef
store %freeze, %trick
memcpy %dst, %trick

I think the first is what actually matters to that Rust RFC. That might be better modeled with a new attribute for the allocator and alloca kinds that specifies the contents are frozen (right now you can only specify the allockind is undefined or zeroed).

To be correct a lowering of such memcpy would require a freezing load.

So, to add this new memcpy, I think this has to be very well justified. Can you tell us exactly which Rust API is blocked because of lack of a freezing memcpy? Seems strange to have a copy that initializes bits. Don’t you know which bits are these to initialize them by hand?

No, source-level memcpy libcalls are not freezing.

I meant “backend libcalls”. Maybe that’s not the right term. At some point, the intrinsic is turned into invocations of the memcpy function from libc. The new intrinsic should be compiled the same way.

I don’t see why the source of the undef matters. Undef is undef. freeze treats them all the same (and poison, too). So clearly there is precedent. I just need an operation that’s like “load, freeze, store”, but for a large type and compiled to an efficient memcpy.

I don’t think so. The memcpy we lower to today is already considered to be outside the Abstract Machine. So I think using the existing memcpy is fine. If we want to allow inlining the memcpy implementation into the program in places where the intrinsic was used, that’ll require a bunch of changes even for the existing memcpy (since memcpy can be called on uninit data but the types used in the implementation may be considered noundef by the compiler).

It’s a natural generalization of freeze, which also doesn’t know which bits are initialized. I would describe the current state as rather odd, where we allow this on SSA value “copies” but not on memory copies.

The proposed core low-level API is something like this:

impl MaybeUninit<T> {
  /// Make a copy of `self` where every uninitialized byte is non-deterministically initialized.
  fn frozen(&self) -> MaybeUninit<T>;
}

The use-cases mentioned above can then be built on top of this.

If we lower mempy with byte load/store, it’s a perfect forward. Nothing is broken or magic (I hope).

Sure, and those need a freeze if we do the transformation in the IR. I was talking about what I assumed to be the default case, which is to invoke the libc / compiler-builtins memcpy function.

this reminds me that I’ve wanted a more general memcpy – maybe we can use this opportunity to fix other issues at the same time?

I think we’d want to have the input and output independently be able to specify if that half of the memcpy is volatile, atomic (and the atomic element size), and/or aligned (since currently volatile memcpy pessimizes whatever half of the memcpy that doesn’t need to be volatile but is because we can’t express it, e.g. when converting to loads/stores). Also if the memcpy is freezing and/or inline.

we’d also want to support most of that on other similar operations such as memmove and memset

Any thoughts on “freezing memcpy” intrinsic vs. just a “freeze memory” intrinsic? They’re sort of equivalent (“freezing memcpy” is just “memcpy” + “freeze memory”, and “freeze memory” is just “freezing memmove with src==dst”). But it seems easier to reason about a standalone “freeze memory”.

iirc llvm requires memcpy to operate correctly when src == dest, so “freeze memory” could also just be a freezing memcpy with the same source and destination.

freeze memory would need to write to every page in the memory range to ensure the OS won’t arbitrarily discard it (e.g. madvise MADV_FREE)

Is a “freeze memory” intrinsic lowered to a noop in the final codegen? So it acts as a barrier in LLVM IR and the SDAG?

It can’t be in general, since you can tell the OS (e.g. with madvise MADV_FREE) that a page in memory can randomly be zeroed – writing to it then tells the OS it’s active again so its contents will be preserved.

a memory freeze is writing – replacing all undef bits with arbitrary bits, so it needs to also do a write to each page so the OS preseves the contents, otherwise the page is still effectively undef since its contents can arbitrarily change (to zeros) at any time.

As Jake said, “freeze memory” needs to actually iterate the target memory and touch at least one byte on each page. Otherwise it will not behave correctly for MADV_FREE memory on Linux: such memory can get reset to 0 any time by the kernel, i.e., it observably behaves like undef in that reading it multiple times without any writes in between can produce different results.

Freezing memcpy does not have to worry about this because an actual store to the target memory is happening, so we can be sure that there are actual stable pages backing that memory.

as long as your memcpy doesn’t early-exit as a no-op when the source and dest pointers are equal.

I was assuming that overlap is UB, but using LLVM’s memcpy semantics where equal pointers are allowed, that would indeed be a concern. We could avoid that by making freezing memcpy UB on equal ranges, though that could surprise LLVM users.

I would expect LLVM to want to convert between load-freeze-store and freezing memcpy, so that seems like an unfortunate case of UB that is unlikely to get noticed.

Musl’s memmove has that problem:

@RalfJung @programmerjake Can you please spell out how exactly you imagine MADV_FREE to be modeled at the AM level? I find it hard to evaluate whether we really need to care about this otherwise.

Edit: To clarify, we generally do not consider whether memory was (non-volatile) written to be an observable AM effect. It sounds like for MADV_FREE dropping a store(p, load(p)) round trip could change observable behavior, because the write goes away. This makes me think that MADV_FREE is just another of those weird mmap things that are technically UB and just happen to mostly work out in practice. If this is the case, we should also not give it any consideration in this context.

It is already modeled correctly by uninitialized memory. Both undef and poison should work for this.

No, that roundtrip is a NOP – it loads undef/poison, then stores it back. So it’s fine to drop it.

2 Likes

FWIW, I randomly came across this previous PR and discussion on half-volatile memcpy from 2023, which apparently went nowhere.