by rtpg · 10y ago · 0 comments
For example, people rely on how C lays things out in memory, so C compilers have to lay things out in memory in specific ways. Haskell doesn't have this constraint and so can do a bunch of tricks.
And then there are things where C cannot move a variable/optimise out a variable because it's unknown whether some unrelated bit of code my go poke at its memory.
Now one might say "well if you know what you're doing then you can get the compiler to do what you want." Everything's possible, since everything's turing complete. But I would consider "variables need to be somewhere in memory" to be mandatory overhead.
This is not just a theoretical thing; at a certain point in the past, both LLVM and GCC had such an optimization, driven by PGO. I think it got removed because it just didn't trigger often enough and didn't give enough benefits to justify the complexity.
Scalar replacement of structs/arrays is of course routinely done by all major compilers and allows to completely optimize away non-escaping local objects.
One can rely on C compilers laying out things in memory in a specific way only within a struct and when compiler-specific alignment/packing attributes are used. All other assumptions about variables being adjacent in memory are wrong and lead to undefined behavior.