| Issue |
241247
|
| Summary |
[clang][CodeGen] C loop `while (1.0)` gets mustprogress (checkIfLoopMustProgress uses EvaluateAsInt) (miscompile at -O3)
|
| Labels |
clang
|
| Assignees |
|
| Reporter |
jeffchen006
|
In C11 and later, a loop whose controlling _expression_ is a constant _expression_ may not be assumed to terminate. Clang marks `while (1.0);` as `mustprogress` because its constant check works only for integer types, and LoopDeletion removes the infinite loop.
**Reproducer** (`repro.c`)
```c
/* while (1.0) is a loop whose controlling _expression_ is a constant _expression_,
so it may NOT be assumed to terminate (C11 6.8.5p6). Correct: the program
never ends and prints nothing (clang -O0, gcc). clang -O3 prints "end". */
int printf(const char *, ...);
int k = 1;
int main(void) {
if (k)
while (1.0)
;
printf("end\n");
return 0;
}
```
**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang -O0 repro.c -o ./o0
$ timeout 3 ./o0
O0 rc=124 (124 = still running = correct)
$ clang -O3 repro.c -o ./o3
$ timeout 3 ./o3
end
O3 rc=0 (prints end = wrong)
```
Expected (as `-O0`): the program does not stop and prints nothing (`timeout` gives rc 124). `-O3` prints `end` and exits.
**Why the expected output is right**
C11/C17 6.8.5p6 allows the termination assumption only if the controlling _expression_ is not a constant _expression_. `1.0` is an arithmetic constant _expression_ (6.6p8). UBSan/ASan/MSan at -O0 are clean.
**Possible Root cause**
`clang/lib/CodeGenUtils/StmtUtils.cpp`, `CodeGenUtils::checkIfLoopMustProgress`: `CondIsConstInt = ControllingExpression->EvaluateAsInt(Result, Ctx) && Result.Val.isInt()`. In C the condition `1.0` keeps type `double`, `EvaluateAsInt` fails, so the loop counts as non-constant and gets `llvm.loop.mustprogress`. `while ("x");` and `while (0.5 + 0.5);` have the same problem.
**Possible Proposed fix**
```diff
- Expr::EvalResult Result;
- bool CondIsConstInt =
- !ControllingExpression ||
- (ControllingExpression->EvaluateAsInt(Result, Ctx) && Result.Val.isInt());
- bool CondIsTrue = CondIsConstInt && (!ControllingExpression ||
- Result.Val.getInt().getBoolValue());
+ bool CondVal = true;
+ bool CondIsConst = !ControllingExpression ||
+ ControllingExpression->EvaluateAsBooleanCondition(CondVal, Ctx);
+ bool CondIsTrue = CondIsConst && CondVal;
```
(and rename `CondIsConstInt` -> `CondIsConst` below; CIR uses the same helper.)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs