LTO removal of memory written but not read in embedded baremetal app
⚓ Rust 📅 2025-09-25 👤 surdeus 👁️ 8Our team is doing some baremetal no_std Rust on an embedded ARM platform. We aren't really using any of the embedded WG code, but that's not really relevant. One thing we are doing is writing some system memory with data and data structures that is not read back by the application itself (it's intended to be read by another application, which could be written in C or Rust or whatever, but will run at a later time). So this could be considered to be FFI-related I guess.
The fundamental problem is that when LTO is enabled (as it was for our release build), the toolchain basically looks at that memory that is written and considers it ripe for optimizing away because it is never read back after being written. We had a similar problem earlier where this was happening within a compilation unit, in our dev/debug build with lto=false,  and we addressed that using black_box. But this issue is now happening at the link stage with LTO.
After some research, we now think only volatile can really address this (based on Volatile | lokathor.github.io and the referenced LLVM doc, LLVM Language Reference Manual — LLVM 22.0.0git documentation), and prototypes show that it works. But we wanted to see if the community had some thoughts on using unsafe core::ptr::write_volatile or whether there is another suggested approach. The only other thought that we had was using some dummy inline asm, but that really seems like a hack.
6 posts - 3 participants
🏷️ Rust_feed