by userbinator · 9y ago · 0 comments
as NeverCalled may have been called from, for example, a global constructor in another file before main is run
clang doesn't analyse across module boundaries --- even when it theoretically could --- so it doesn't know for certain that NeverCalled() is indeed never called.
Throughout the years I've grown increasingly displeased at how compilers handle even trivial cases like this[1][2][3], and in particular their treatment of UB[4][5][6][7]; as one of the comments on the article implies, UB was unlikely intended by the standard's authors as a "you should let the most inane things happen" but more as a "do what makes the most sense".
A more sensical approach to analysing this program, e.g. as employed by a human, would be to see that NeverCalled() is the only function that can write Do, but then further ascertain whether it is actually called. Since this is the entire program, it's trivial to see that it's not, and thus that possibility should also have been removed from the set of possible values for Do. Thus, Do can neither be EraseAll nor 0 --- so a "contradiction" has occurred, the code is likely bugged or the programmer intentionally wants the UB, and the sane choice at this point would be to forget about trying to optimise and just generate the obvious code. "I can't figure out how to optimise this, so I'll do the simplest thing that works."
The question then becomes, why can a human see something so straightforward but the compiler can't? I think that's the deeper issue here with how the compilers like gcc/clang today work --- they're too opaque and complex, and their authors take The Holy Standard as gospel while ignoring the practical realities of their decisions.
Unfortunately a lot of programmers have gotten the notion that they can rely on the compiler to do "amazing" optimisation, and therefore they can write horrible code, leading to horribly unintuitive and "overly aggressive" optimisation like this.
I'm sure that me, along with quite a few others, have some ideas for how to make a C/C++ compiler which is both powerful in optimisation and code generation, but more predictable and "obvious" in terms of UB. Unfortunately, I'm also sure that we don't have the time to do it.
[1] https://news.ycombinator.com/item?id=15006090
[2] https://news.ycombinator.com/item?id=9397924
[3] https://news.ycombinator.com/item?id=15188416
[4] https://news.ycombinator.com/item?id=11147598
[5] http://blog.metaobject.com/2014/04/cc-osmartass.html
more sensical approach to analysing this program, e.g. as employed by a human, would be to see that NeverCalled() is the only function that can write Do
It is not only non-trivial but also impossible (even) for a human to see if NeverCalled is ever called. Since NeverCalled is visible to other translation units, it can be called, for instance, by a global constructor before main is called.Adapting thinkings such as
"I can't figure out how to optimise this, so I'll do the simplest thing that works."
will disable the compiler from many non-trivial optimizations. Consider eliminating a branch predicated on `w < w + c`: this expression can be, a check for signed-integer-overflow, coming from a macro-expansion and expected by the programmer to be eliminated, a result of constant-progagation, or a result of other optimizations.Saying you have ideas but don't have time to make a better compiler only makes you an armchair compiler-writer.
The compiler is also doing the linking in this case, being given the complete command line, and it very much knows all the "translation units" which will be present, and none of them call that function.
Consider eliminating a branch predicated on `w < w + c`: this expression can be, a check for signed-integer-overflow, coming from a macro-expansion and expected by the programmer to be eliminated, a result of constant-progagation, or a result of other optimizations.
A bit of range analysis, like what an intelligent human would do, suffices to determine whether that expression will be a constant. If all the terms of the expression are constant, then so will the result be; and the sane thing to do, in the face of incomplete information, is to assume that a variable can take on any value.
Only in the static linking case. In the dynamic linking case, part of the linking is done by the linker called from the compiler, and part of the linking is done by the dynamic linker every time the program is executed.
"These people simply don't understand what C programmers want": https://groups.google.com/forum/#!msg/boring-crypto/48qa1kWi...
"please don't do this, you're not producing value": http://blog.metaobject.com/2014/04/cc-osmartass.html (also in the above list, but why not have it twice?)
"No sane compiler writer would ever assume it allowed the compiler to 'do anything' with your code": http://article.gmane.org/gmane.os.plan9.general/76989
"Everyone is fired": http://web.archive.org/web/20160309163927/http://robertoconc...
Is it really the entire program, in the presence of things like LD_PRELOAD and global constructors? What prevents a library loaded by LD_PRELOAD from calling NeverCalled() before main() starts?
In other words, programs do not exist in a void and a compiler can never predict what other things will happen in the runtime environment, especially in the not-uncommon situation of modules written in other languages, so compilers should not be making risky assumptions with this partial information.
Wouldn't that be all sorts of undefined behavior, however? While LD_PRELOAD and constructors are well-defined, calling arbitrary non-exported functions is not (the functions might not exist due to inlining, might exist more than once, might have an alternate ABI, and so on). Modifying the code has the same problem; not only is what the compiler generates unpredictable, but also the compile code might depend on its exact instruction sequence (using code as data, for instance, or jumping into the middle of an instruction sequence through a computed pointer).
The compiler output does not exist in a void, true, but there is a "contract" that both the compiler and the runtime environment should follow. Things like "the first argument to a function will be in the x10 register" and "the compiled code will only be entered through an exported function or a function pointer". Without that "contract", neither would be able to do their work; for instance, how would a compiler generate code if said code could be entered absolutely anywhere?
It's really nice to be able to use abstractions that cost nothing because the compiler is smart. In this particular case, you might have a function pointer that exists for future expansion, but which currently only ever holds one value. In a case like that, it's really nice if the compiler can remove the indirection (and potentially go further and do clever things like inline the callee or do cross-call optimizations).
The other piece of this puzzle is straightforward data flow analysis. The compiler knows that there are only two possible values for this function pointer: NULL and EraseAll. It also knows that it can't be NULL at the call site. Thus, it must be EraseAll.
For every person complaining that the compiler is screwing them over with stuff like this, there's another person who would complain that the compiler is too stupid to figure out obvious optimizations.
I'm very much in favor of making things safer, but I don't think avoiding optimizations like this is the answer. C just does not accommodate safety well. For this particular scenario, the language should encode the nullability of Do as part of the type. If it's non-nullable, then it should require explicit initialization. If it's nullable, then it should require an explicit check before making the call. The trouble with C isn't clever optimizers, it's that basic things like nullability are context-dependent rather than being spelled out.
Ah, this is obviously some strange use of the word "can't" that I wasn't previously aware of. Or possibly of "be" or "at".
The pointer clearly is NULL at the call site. Observe: http://lpaste.net/358687. Hypotheticals about the program being linked against some library that that calls NeverCalled are just that, hypothetical. In the actual program that is actually executed, the pointer is NULL.
In what sense is the function pointer "not NULL", then, given that – in what one might call the "factual" sense – it is NULL?
If the pointer is NULL, dereferencing it destroys the universe. If the universe is destroyed, the program never existed. Therefore, in any universe where the program exists, the pointer is not NULL. Q.E.D.
Exercise 1: Propose a less parochial definition of universe that doesn't lead to colorful threats from major stakeholders.
I assume you don't like that, but I wonder if you'd apply that to other optimizations? For a random example:
int x = 42;
SomeFunc();
printf("%d\n", x);
Should the compiler be allowed to hard-code 42 as the second parameter to printf, or should it always store 42 to the stack before calling SomeFunc(), then loading back out? SomeFunc might lightly smash the stack and change the value of x, after all.But the compiler is not smart. It's screwing up in certain cases. In this example if it was smart it would have figured out that the value never was initialized.
> In this particular case, you might have a function pointer that exists for future expansion, but which currently only ever holds one value.
Then define it as a regular function for now. The fact that you only thought of one function that needs it means you're making abstractions before you really needed them. And if you need a second function soon you'll loose the speed of the optimization anyways. And you did profile it first to figure out that this one tiny optimization actually matters, right? :)
But let's say you really needed to do it that way for whatever reason. If the compiler was smart enough to warn you that it wasn't initialized you could have made an empty function and initialized it to that. Problem solved and the compiler would be free to optimize it away.
> In a case like that, it's really nice if the compiler can remove the indirection (and potentially go further and do clever things like inline the callee or do cross-call optimizations).
Sure. Do a full program optimization and figure out that the function to initialize the pointer was actually called. Then do all those clever optimizations. The issue is that the compiler writers want the benefits of the optimization without doing the work making the optimization safe by making the compiler smarter. They just hide behind the "undefined behavior" mantra and let the programmer pick up the pieces when it goes wrong.
> For this particular scenario, the language should encode the nullability of Do as part of the type. If it's non-nullable, then it should require explicit initialization.
This. I 100% agree that this is the proper solution. But it would require a whole program pass to figure out that it's actually initialized somewhere. As I said above, the compiler writers could have done that without a change to the language.
But a lot of UB could be avoided by language changes. That's what many people have done when designing new languages. With C however we're stuck with what we have and need to make the compiler smarter before it slaps every optimization in its tool belt at every piece of code.
Maybe the C language needs to slowly evolve and add those changes to start getting rid of UB. But there has been zero progress in that direction. The compiler writers are perfectly content to squeeze out every last cycle of performance using any new UB loophole they can find.
When safety finally becomes a priority to them over benchmarks then maybe we'll start seeing some progress.
But that's false, which just goes to show that the compiler writers know way more about this than you do. There's nothing stopping this from being linked into a binary which doesn't even call main, or which calls NeverCalled, etc. And I bet you will also insist stamping your feet that of course programmers should be able to construct function pointers - to functions like, y'know, Never called - from arbitrary bit patterns. You know nothing, but you're convinced you know so much more than those stupid compiler writers.
And that really is the crux of the issue. Despite the significant amount of discussion around the problems of C UB, there is precious little work being done to actually "solve" the problems.
https://blog.regehr.org/archives/1287
> Since we published the Friendly C proposal, people have been asking me how it’s going. This post is a long-winded way of saying that I lost faith in my ability to push the work forward. However, I still think it’s a great idea and that there are people besides me who can make it happen.