The C11 standard says this, 6.8.5/6:
An iteration statement whose controlling expression is not a constant expression,156) that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression-3, may be assumed by the implementation to terminate.157)
The two foot notes are not normative but provide useful information:
156) An omitted controlling expression is replaced by a nonzero constant, which is a constant expression.
157) This is intended to allow compiler transformations such as removal of empty loops even when termination cannot be proven.
In your case, while(1)
is a crystal clear constant expression, so it may not be assumed by the implementation to terminate. Such an implementation would be hopelessly broken, since "for-ever" loops is a common programming construct.
What happens to the "unreachable code" after the loop is however, as far as I know, not well-defined. However, clang does indeed behave very strange. Comparing the machine code with gcc (x86):
gcc 9.2 -O3 -std=c11 -pedantic-errors
.LC0:
.string "begin"
main:
sub rsp, 8
mov edi, OFFSET FLAT:.LC0
call puts
.L2:
jmp .L2
clang 9.0.0 -O3 -std=c11 -pedantic-errors
main: # @main
push rax
mov edi, offset .Lstr
call puts
.Lstr:
.asciz "begin"
gcc generates the loop, clang just runs into the woods and exits with error 255.
I'm leaning towards this being non-compliant behavior of clang. Because I tried to expand your example further like this:
#include <stdio.h>
#include <setjmp.h>
static _Noreturn void die() {
while(1)
;
}
int main(void) {
jmp_buf buf;
_Bool first = !setjmp(buf);
printf("begin\n");
if(first)
{
die();
longjmp(buf, 1);
}
printf("unreachable\n");
}
I added C11 _Noreturn
in an attempt to help the compiler further along. It should be clear that this function will hang up, from that keyword alone.
setjmp
will return 0 upon first execution, so this program should just smash into the while(1)
and stop there, only printing "begin" (assuming \n flushes stdout). This happens with gcc.
If the loop was simply removed, it should print "begin" 2 times then print "unreachable". On clang however (godbolt), it prints "begin" 1 time and then "unreachable" before returning exit code 0. That's just plain wrong no matter how you put it.
I can find no case for claiming undefined behavior here, so my take is that this is a bug in clang. At any rate, this behavior makes clang 100% useless for programs like embedded systems, where you simply must be able to rely on eternal loops hanging the program (while waiting for a watchdog etc).
You need to insert an expression that may cause a side-effect.
The simplest solution:
static void die() {
while(1)
__asm("");
}
Godbolt link
Other answers already covered ways to make Clang emit the infinite loop, with inline assembly language or other side effects. I just want to confirm that this was indeed a compiler bug. Specifically, it was a long-standing LLVM bug - it applied the C++ concept of "all loops without side-effects must terminate" to languages where it shouldn't, such as C. The bug was finally fixed in LLVM 12.
For example, the Rust programming language also allows infinite loops and uses LLVM as a backend, and it had this same issue.
LLVM 12 added a mustprogress
attribute that frontends can omit to indicate when functions don't necessarily return, and clang 12 was updated to account for it. You can see that your example compiles correctly with clang 12.0.0 whereas it did not with clang 11.0.1
... when inlining a function containing an infinite loop. The behaviour is different when while(1);
appears directly in main, which smells very buggy to me.
See @Arnavion's answer for a summary and links. The rest of this answer was written before I had confirmation that it was a bug, let alone a known bug.
To answer the title question: How do I make an infinite empty loop that won't be optimized away?? -
make die()
a macro, not a function, to work around this bug in Clang 3.9 and later. (Earlier Clang versions either keeps the loop or emits a call
to a non-inline version of the function with the infinite loop.) That appears to be safe even if the print;while(1);print;
function inlines into its caller (Godbolt). -std=gnu11
vs. -std=gnu99
doesn't change anything.
If you only care about GNU C, P__J__'s __asm__("");
inside the loop also works, and shouldn't hurt optimization of any surrounding code for any compilers that understand it. GNU C Basic asm statements are implicitly volatile
, so this counts as a visible side-effect that has to "execute" as many times as it would in the C abstract machine. (And yes, Clang implements the GNU dialect of C, as documented by the GCC manual.)
Some people have argued that it might be legal to optimize away an empty infinite loop. I don't agree1, but even if we accept that, it can't also be legal for Clang to assume statements after the loop are unreachable, and let execution fall off the end of the function into the next function, or into garbage that decodes as random instructions.
(That would be standards-compliant for Clang++ (but still not very useful); infinite loops without any side effects are UB in C++, but not C.
Is while(1); undefined behavior in C? UB lets the compiler emit basically anything for code on a path of execution that will definitely encounter UB. An asm
statement in the loop would avoid this UB for C++. But in practice, Clang compiling as C++ doesn't remove constant-expression infinite empty loops except when inlining, same as when compiling as C.)
Manually inlining while(1);
changes how Clang compiles it: infinite loop present in asm. This is what we'd expect from a rules-lawyer POV.
#include <stdio.h>
int main() {
printf("begin\n");
while(1);
//infloop_nonconst(1);
//infloop();
printf("unreachable\n");
}
On the Godbolt compiler explorer, Clang 9.0 -O3 compiling as C (-xc
) for x86-64:
main: # @main
push rax # re-align the stack by 16
mov edi, offset .Lstr # non-PIE executable can use 32-bit absolute addresses
call puts
.LBB3_1: # =>This Inner Loop Header: Depth=1
jmp .LBB3_1 # infinite loop
.section .rodata
...
.Lstr:
.asciz "begin"
The same compiler with the same options compiles a main
that calls infloop() { while(1); }
to the same first puts
, but then just stops emitting instructions for main
after that point. So as I said, execution just falls off the end of the function, into whatever function is next (but with the stack misaligned for function entry so it's not even a valid tailcall).
The valid options would be to
label: jmp label
infinite loopreturn 0
from main
.Crashing or otherwise continuing without printing "unreachable" is clearly not ok for a C11 implementation, unless there's UB that I haven't noticed.
Footnote 1:
For the record, I agree with @Lundin's answer which cites the standard for evidence that C11 doesn't allow assumption of termination for constant-expression infinite loops, even when they're empty (no I/O, volatile, synchronization, or other visible side-effects).
This is the set of conditions that would let a loop be compiled to an empty asm loop for a normal CPU. (Even if the body wasn't empty in the source, assignments to variables can't be visible to other threads or signal handlers without data-race UB while the loop is running. So a conforming implementation could remove such loop bodies if it wanted to. Then that leaves the question of whether the loop itself can be removed. ISO C11 explicitly says no.)
Given that C11 singles out that case as one where the implementation can't assume the loop terminates (and that it's not UB), it seems clear they intend the loop to be present at run-time. An implementation that targets CPUs with an execution model that can't do an infinite amount of work in finite time has no justification for removing an empty constant infinite loop. Or even in general, the exact wording is about whether they can be "assumed to terminate" or not. If a loop can't terminate, that means later code is not reachable, no matter what arguments you make about math and infinities and how long it takes to do an infinite amount of work on some hypothetical machine.
Further to that, Clang isn't merely an ISO C compliant DeathStation 9000, it's intended to be useful for real-world low-level systems programming, including kernels and embedded stuff. So whether or not you accept arguments about C11 allowing removal of while(1);
, it doesn't make sense that Clang would want to actually do that. If you write while(1);
, that probably wasn't an accident. Removal of loops that end up infinite by accident (with runtime variable control expressions) can be useful, and it makes sense for compilers to do that.
It's rare that you want to just spin until the next interrupt, but if you write that in C that's definitely what you expect to happen. (And what does happen in GCC and Clang, except for Clang when the infinite loop is inside a wrapper function).
For example, in a primitive OS kernel, when the scheduler has no tasks to run it might run the idle task. A first implementation of that might be while(1);
.
Or for hardware without any power-saving idle feature, that might be the only implementation. (Until the early 2000s, that was I think not rare on x86. Although the hlt
instruction did exist, IDK if it saved a meaningful amount of power until CPUs started having low-power idle states.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With