Hacker News new | ask | show | jobs
by 1718627440 189 days ago
Ah, you are right. It theoretically should be able to do it, but even with -flto, there are likely cases, where it doesn't. It is less of a problem with C, since you explicitly tell the compiler, whether you want things to get passed as value or pointer. Also I typically annotate ownership, so it it easy to forget that the compiler doesn't actually knows this. This is a weird limitation, there should be just a parameter attribute to do that.
1 comments

> It theoretically should be able to do it, but even with -flto, there are likely cases, where it doesn't.

Note that link time optimization only works on a particular binary. What if the function is implemented in a shared library?

> It is less of a problem with C, since you explicitly tell the compiler, whether you want things to get passed as value or pointer.

It works the exact same way in C++, though.

> What if the function is implemented in a shared library

If it is in the public API/ABI of a shared library, than the calling semantics including lifetime and ownership rules are part of the public interface, so of course the compiler can't just change it. You the programmer are responsible for drawing abstraction boundaries and choosing the interface.

> It works the exact same way in C++, though.

Only if write C in C++. The issue here are references, of which the compiler figures out whether this should work like a value or like a pointer. This doesn't exist in C, there the programmer needs to make up its mind and choose. The whole type conversion by making a copy issue also doesn't exist there, because either the type matches or the compiler throws an error.

Maybe I misunderstood, but I thought that you were arguing that with link-time optimization the compiler could see through cases such as the one I have given. As a counterargument, I brought up functions that are implemented in shared libraries, which are essential a blackbox to the compiler.

> The issue here are references, of which the compiler figures out whether this should work like a value or like a pointer.

I'm not sure I understand. A C++ reference always has reference semantics. Can you give an example?