llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.32k stars 11.69k forks source link

printf("") needs to be considered as forward progress #96703

Open neldredge opened 3 months ago

neldredge commented 3 months ago

The C++ forward progress rules say that a program has UB unless it eventually does one of a certain list of things, one of which is "make a call to a library I/O function". Certainly printf should qualify. However, clang optimizes out printf("") and does not treat it as providing forward progress.

The following code:

#include <cstdio>
void foo() {
    bool b = true;
    while (b) {
        printf("");
    }
}

is compiled by clang -O3 into unreachable, i.e. no code at all. https://clang.godbolt.org/z/6cP9vxsh7 I believe this is wrong. By the letter of the rule it should be legal, and should actually execute an infinite loop (though it does not need to actually call printf, since that is indeed a no-op).

Related is #62057, where a similar thing happens when the loop contains an atomic load with no effect, and #96702, for atomic fences.

workingjubilee commented 3 months ago

...is an implementation of printf required to perform IO if the string is ""?

That is, is printf required to be considered a library I/O function if it will perform no actual I/O? Is the interpretation of "I/O function" meant to be effectual (any function in any header is an I/O function if it performs I/O" or is it meant to be "yes we meant <iostream> and <cstdio>".