Issue 240702
Summary [FastISel] Unused call to a memory(read) function without willreturn is deleted at -O0, but kept by SelectionDAG and IR-level DCE
Labels new issue
Assignees
Reporter selim0h
    FastISel drops a call whose result is unused if the callee is `memory(read)`, even though the callee is not `willreturn` and contains a side-effect-free infinite loop. SelectionDAG (`-fast-isel=false`) keeps the call, and IR-level DCE (`wouldInstructionBeTriviallyDead`) also keeps it because it checks `willReturn()`. The input has no UB.

Reproducer:

```llvm
@G = global i1 false

define internal void @loopfunc() #0 {
entry:
  %l = load i1, ptr @G
  br i1 %l, label %ret, label %loop
loop:
  br label %loop
ret:
  ret void
}

define i32 @main() {
  call void @loopfunc()
  ret i32 0
}

attributes #0 = { noinline nounwind memory(read) }
```

Number of `call` instructions in the generated assembly (local LLVM 18 build):

| command | calls |
|---|---|
| `llc -O0` | 0 |
| `llc -O0 -fast-isel=false` | 1 |
| `llc -O2` | 1 |

Same on Godbolt with `llc` (trunk): `-O0` has no call in `main` (https://godbolt.org/z/zrM7EMK55), `-O0 -fast-isel=false` has `call loopfunc` (https://godbolt.org/z/91Yfdsedc).

With FastISel, `main` returns immediately instead of hanging in `loopfunc`, so the program's termination behavior changes. Removing `nounwind` does not change this, so FastISel does not look at `nounwind` either (I only tested the missing attribute, not a callee that actually throws).

I think the cause is `isFoldedOrDeadInstruction` in `SelectionDAGISel.cpp`, which the FastISel loop uses to skip instructions. On current `main`:

```cpp
static bool isFoldedOrDeadInstruction(const Instruction *I,
 const FunctionLoweringInfo &FuncInfo) {
  return !I->mayWriteToMemory() &&
         !I->isTerminator() &&
 !I->isEHPad() &&
         !FuncInfo.isExportedInst(I);
}
```

A call to a `memory(read)` function with no uses satisfies this, and there is no `willReturn()` check, unlike `wouldInstructionBeTriviallyDead` in `Local.cpp`. As far as I understand LangRef, `memory(read)` does not imply the function returns, and loops without side effects are allowed in IR without `mustprogress`. I have not tried a patch.

Dropping unused calls to readonly functions at -O0 is expected for functions that are known to return. My case is a function that is *not* `willreturn`, e.g. what `opt -O2` infers (`nofree norecurse nosync nounwind memory(read, ...)`, no `willreturn`/`mustprogress`) and which I then compile with `clang -O0` in a differential-testing setup.

Is this intended for FastISel, or should it check `willReturn()` like the IR-level DCE does?
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to