12 ms·
Also, FYI (sibling post because my first one is already locked): this isn't about what the programmer tells the compiler. It's about what the compiler can infer
by derefr 6y ago
Also, FYI (sibling post because my first one is already locked): this isn't about what the programmer tells the compiler. It's about what the compiler can infer on its own, through dataflow analysis.
"const", as a qualifier, isn't novel information about a variable for the compiler — compilers already know whether a variable is used mutably or not, just like they know when and where a variable has its last access and goes dead.
"const" is an instruction to the compiler that if it finds, by its own independent analysis, that the variable cannot be const in that context, then the program is invalid and compilation should error out.
As such, "const" only even has a meaning, if the compiler already independently knows which declared variables are or are not const "in practice."
That information is what would be used to decide whether to do the copy.
> B could end up having to perform another copy for that call
At worst, that's no worse than what happens under the current ABI, where A passes data by value to B, which passes it by value to C.
(Do also remember, as I said in another comment, that ABIs/calling conventions are only "about" functions with external linkage. Functions with "static" linkage do whatever the compiler likes; as do their callers.)
I think, in the specific situation you're describing, there's also prelink-time cross-unit optimizations that can be done here to eliminate redundant copies even further — but that's getting close to just expecting C to do Rust-like ownership analysis, so I wouldn't claim that to be practical in any production compiler in the near future.