94 points · by erwan · 8y ago · 107 comments
Additionally, some compilers can insert code to detect signed integer overflow at runtime. Clang has the -fsanitize=undefined flag [1].
[1] https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
[1] https://github.com/openbsd/src/blob/master/lib/libc/stdlib/r...
Mozilla has a CheckedInt (C++) type that checks all operations for overflow. You can see examples of how this is actually implemented here: <https://searchfox.org/mozilla-central/source/mfbt/CheckedInt.... You can derive similar C implementations if you work through all of the template magic.
Be warned that the definition of what is undefined, implementation-specific, and well-defined varies depending on the exact version of the C or C++ standard you use.
I get very tired of people trying to make this "really" about "undefined behavior" sanity when real compilers are real software with real behavior. And here there is a clearly desired behavior (whether or not it got written into a standard somehwere), and clang implemented something else. That's wrong.
Here's an example of what can happen if the compiler doesn't perform these optimizations: https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759...
The loop codegen when the optimization is not performed is pretty atrocious. That is the bug, and solving that bug is the reason why compilers assume signed overflow cannot happen.
If you want to blame something, blame the C language. Compiler developers are just doing their jobs.
That's a great article, although I don't think it shows the advantage of assuming that undefined behavior will never occur. Rather than assuming "no undefined behavior", wouldn't it be legal (and preferable) for a compiler to just let the overflow (or lack of overflow) occur, and make the same optimization? For me the entire point of contention is the difference between "undefined" and "implementation defined". Maybe I'm wrong about the details here, but I think this is a case where a compiler could be just as fast without the nasal daemons.
Compiler developers are doing a fantastic job, and I absolutely do blame the C language and standard.
For the cases referenced in the article, it seems to me that the preferred solutions would be making int 64-bits and leaning on the restrict keyword rather than the semi-disaster that is strict aliasing (https://blog.regehr.org/archives/1307).
The most popular architecture today is 64-bit, with ABI specifying that the integer type is 32-bits wide.
So when faced with performing an operation on two 32-bit signed integers, on a 64-bit platform, you have to either:
1) perform the operation in 32-bit registers - if available - and even if available, usually far far far fewer in number thus massive performance & resource penalties to code
2) perform the operation in 64-bit registers, then add code to check the result, and if it would overflow in 32-bit, compute what the overflowed result would have looked like in a 32-bit register, and return that instead - again quite a performance hit
3) perform the operation in 64-bit registers, and just return the lower 32-bits, whatever that might be
The standard declined to pick a choice, which is why we have UB here.
(For unsigned integers, you can just truncate the result and it works every time, which is why the standard defines the result)
False for x86-64. There are sixteen 32-bit general-purpose registers: eax, ebx, ..., r8d, ..., r16d. There are sixteen 64-bit registers too: rax, rbx, ..., r8, ..., r16.
I'm surprised to see that for unsigned ints modular semantics are guaranteed by the spec
"Please tell me again how unsigned ints are broken" It seems this meme seems to be the C version of anti-vaxxers.
Basically, a great tool for static analysis and/or Frama-C for just the range analysis. Then, a coding style that facilitates such analysis. That should cover analysis. Idiomatic might be a problem because I see so many overflows in C code that it seems idiomatic for it to have them. ;)
For example, not only is it undefined behavior to overflow on signed integer addition, in Zig it's also undefined behavior to overflow on unsigned integer addition. If you want wrapping integer addition, you have to use the wrapping integer addition operator, which is defined to wraparound on overflow.
Here's the trick though - Zig catches most kinds of undefined behavior before they have a chance to cause problems in release builds. Some undefined behavior is caught at compile time, and otherwise most undefined behavior is caught at runtime, in debug builds. And finally, if you are not confident in the level of testing your software has undergone, you can make a "release-safe" build, which has optimizations on, but includes undefined behavior checks and will crash (or invoke user-defined panic function) rather than invoke undefined behavior.
You can see some examples of this here: https://ziglang.org/documentation/master/#Undefined-Behavior
The entire point of undefined behavior is that anything can happen. Wrap-around, segmentation faults, elided security checks or even ravenous polar bears, anything goes, and you can't know in advance what will.
When I write C and C++ code, I try to make my logic portable and standards-compliant so that it will work on all platforms. So instead of assuming int is 32 bits, I am only allowed to assume that int is at least 16 bits wide. I assume that sizeof(char) could equal sizeof(int) and both could be 64 bits. I avoid bitwise manipulation on negative numbers, because they're not guaranteed to be two's complement. Keeping all of these pessimistic assumptions in mind while I code is a mental burden that I don't experience in other languages.
Regarding integer promotions, here is one tricky situation I reasoned about and asked in https://stackoverflow.com/questions/39964651/is-masking-befo... . Suppose you want to compute:
uint32_t a = UINT32_C(0xFFFFFFFF);
uint32_t b = a << 31;
b should be 0x80000000
Looks innocent, eh? Left-shifting an unsigned integer will discard the top bits and never cause undefined behavior. Except, this reasoning can be wrong on some platforms. Suppose: typedef unsigned short uint32_t;
typedef int int48_t;
Now (uint32_t)a → (unsigned short)a → (int)a → (int48_t)a, due to typedefs and integer promotion. But because a is a signed integer, it is undefined behavior to shift 1's into the sign bit. Kaboom.This seems purely theoretical, as there is no reasonable architectures that are not using two's complement. It will be defined as two's complement in C++20. (but still with signed overflow UB, to keep some optimizations possible)
If you're writing serious C, you should be using tools like valgrind on debug-mode executables to make sure you aren't relying on undefined behavior. The tools are there. It's just not something a lot of people do.
Undefined behavior gets a bad rap, but it's not always evil.
Probably true, but make sure that you are distinguishing between undefined and implementation defined.
Compilers and executables would be a lot slower if they had to account for these cases.
Maybe, but I'd like to see better quantification for "a lot". My instinct (unsourced) is that it's usually minimal for most C, and quite significant for templated C++. But I'd interested in seeing firm numbers on this.
If you're writing serious C, you should be using tools like valgrind on debug-mode executables to make sure you aren't relying on undefined behavior.
This is where I think you veer off into being mostly wrong. I grew up with Valgrind, but I don't think it really has much use any more. You are almost always better off with one of the now built-in "sanitizers": https://github.com/google/sanitizers/wiki/AddressSanitizerCo....
But while you should be using these to catch bugs, neither the sanitizers nor Valgrind are able to catch the dangerous forms of undefined behavior shown in the examples in the article. UBSan is great and should be more used than it is (https://medium.com/@lucianoalmeida1/the-undefined-behavior-s...) but it is not going to catch anything near all the problems with undefined behavior!
Here's a summary of the unfortunate state of the art: https://blog.regehr.org/archives/1520. While there are underutilized tools that can help, "using tools like valgrind on debug-mode executables to make sure you aren't relying on undefined behavior" is likely to give you misplaced confidence that you are free from the dangers.
From Regehr's blog post that you linked:
> An issue with mitigating integer UBs is the overhead. For example, they cause SPEC CPU 2006 to run about 30% slower.
Although perhaps it can be used an an upper bound on the boost provided UB-free optimizations? That is, the overflow checking has both a direct cost, and prevents certain beneficial optimizations. Thus we can assume that the optimization benefit (on SPEC CPU 2006) is something less than 30%. That is to say, real, but not enormous compared to an algorithmic difference.
Just use the flags that Linux has forced on the compiler developers in order to be able to make use of C or else give up on writing correct code. http://www.yodaiken.com/2018/11/17/standard-c-is-more-fun-th...
What? Sure there are. John Regehr publishes work in this area. https://www.cs.utah.edu/~regehr/papers/undef-pldi17.pdf has performance numbers on taming some undefined behavior, for example (note the regressions).
Anyway, only accepting "published studies" is pretty silly. UB is an engineering concern, not an academic one. Optimizations based on it arose because customers demanded them. Sometimes they can be quite significant: see https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759... for a good explanation of why signed overflow UB matters a lot for optimization of loops, for instance.
There's this weird myth that compiler developers like implementing clever complicated optimizations just because they hate programmers or are trying to make busy work for themselves or something. Compiler developers, like other developers, don't like to do work for no reason. They implemented these optimizations because customers filed bug reports indicating "missed optimizations", and they needed to exploit undefined behavior to satisfy those customers.
The absence of any actual studies showing benefits of UB "optimizations" is glaring. I don't care about motivations, which could simply be incompetance.
It's trivial to show that if you try to completely eliminate undefined behavior from the C language then performance will collapse. Even register allocation depends on exploiting undefined behavior—who's to say that some wild pointer you created didn't accidentally point to some local variable? The reason why you don't see any studies on it is that it's obvious.
When it comes to signed overflow, the status quo comes from two inconvenient facts: (1) lots of C code out there loops over arrays using int for indices; (2) lots of C code out there assumes int is 32 bits. The latter means that, during the 64-bit transition, no compiler could switch to ILP64 and was forced to settle on LP64 (or LLP64 in the case of Windows). Confronted with these facts, compiler developers did the best they could, exploiting signed overflow in order to provide sensible codegen for idiomatic loops in C on 64-bit. The real world is complicated, and sometimes the right solution to an engineering problem is messy.
Regarding the charge of incompetence, with all due respect, my friends who work on Clang and GCC are better programmers than 99% of commenters on this site.
Let's not forget that the standards committee even suggests "behaving during translation or program execution in a documented manner characteristic of the environment" (that's the exact wording from the standard) as one of the possible outcomes of UB, and it's the one that C programmers are most familiar with and also the one most aligned with the spirit of the language.
Thus IMHO the blame falls entirely on the compiler authors for not making reasonable choices. The whole argument that UB makes for great optimisations is not supported by compilers like Intel's ICC, which has historically been much less likely to exploit UB, yet can generate far better code than GCC --- because it is much better at instruction selection/scheduling.
“People often ask why the compiler doesn't produce warnings when it is taking advantage of undefined behavior to do an optimization, since any such case might actually be a bug in the user code. The challenges with this approach are that it is 1) likely to generate far too many warnings to be useful - because these optimizations kick in all the time when there is no bug, 2) it is really tricky to generate these warnings only when people want them, and 3) we have no good way to express (to the user) how a series of optimizations combined to expose the opportunity being optimized.”
Granted, this was written in 2011, so there’s a chance that something has changed, but the points brought up there seem like it isn’t that easy to fix.
[0]: http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
(Note that -O3 is usually not that good an idea: aggressive loop unrolling can sometimes decrease performance because of cache issues, for instance. To optimize code properly, you have to make benchmarks and adjust both the code and compiler flags accordingly, in a well-thought feedback cycle. The use of aggressive optimizations in the blog post is to make the examples trip UB more clearly.)
EDIT: Per https://wiki.gentoo.org/wiki/GCC_optimization#What_about_-O_... it's `enabled = (level >= 3);`
This actually makes me wonder, if I do want wrapping overflow on signed integers in C, how do I request it? Is there some compiler builtin or stdlib function to say "please add/multiply/whatever these signed integers with overflow"?
I think this is used in "type punning" in union structures. This is a related comment by Linus Torvalds on the kernel list:
Yet they can be and often are by using the union trick.
To decide whether to use the union trick requires a discussion of a program's desired portability which-- while usually desirable-- is a separate issue from undefined behavior.
7 An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object, — a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
— a character type