Path: csiph.com!weretis.net!feeder6.news.weretis.net!news.misty.com!news.iecc.com!.POSTED.news.iecc.com!nerds-end From: Thomas Koenig Newsgroups: comp.compilers Subject: Re: Undefined Behavior Optimizations in C Date: Fri, 20 Jan 2023 20:42:25 -0000 (UTC) Organization: news.netcologne.de Sender: johnl@iecc.com Approved: comp.compilers@iecc.com Message-ID: <23-01-067@comp.compilers> References: <23-01-027@comp.compilers> <23-01-031@comp.compilers> <23-01-041@comp.compilers> <23-01-062@comp.compilers> <23-01-065@comp.compilers> Injection-Info: gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="53399"; mail-complaints-to="abuse@iecc.com" Keywords: C, optimize Posted-Date: 20 Jan 2023 16:14:34 EST X-submission-address: compilers@iecc.com X-moderator-address: compilers-request@iecc.com X-FAQ-and-archives: http://compilers.iecc.com Xref: csiph.com comp.compilers:3335 Alexei A. Frounze schrieb: > I believe in a case like this a modern C/C++ compiler reasons that x must be > less than the maximum representable value and it generates code according > to this, possibly removing dead code that depends on x being the maximum > representable value. If the compiler's assumption that x is less than the > maximum is wrong, it's perfectly fine, it's UB, any "broken" code generated > is allowed. There are cases when compilers don't even use this knowledge. Take the function int add (int a, int b) { return a+b; } on an instruction set architecture which has only 64-bit arithmetic, such as POWER. This is translated by gcc, with optimization, to add 3,3,4 extsw 3,3 blr (which is an addition followed by a sign extension). The POWER ABi specifies that all values passed in registers are sign-extended, so the content of a register has the same value independent of the width of the signed integer it is being considered as. So, the compiler would be within its right to _not_ extend the sign of the result, because it could assume that no overflow occurs. This, however, would result in a violation of the ABI, so the compiler puts in the extra instruction just in case. If you replace int by long in the example above, the sign extension instruction is not generated. By comparision, MIPS gcc translates this to jr $31 addu $2,$4,$5 (note use of the delay slot), so no explicit sign extension is done, and the value returned in the register might have a different value if interpreted as a 64-bit value.