Issue 237503
Summary [IndVarSimplify] Latch condition replaced with its first-iteration value; loop runs past its trip count (LLVM 22, fixed in 23)
Labels new issue
Assignees
Reporter kansosystem-admin
    ### Summary

On LLVM 22, `indvars` replaces a loop's latch condition `iv + 1 < smax(n, 0)` with its value on the first iteration (`1 <u smax(n, 0)`, named `%.first_iter`). With `n = 4` the loop then never leaves through the latch. It keeps running until a second exit, a bounds check `iv < n`, fires at `iv = 4`.

The C source has no undefined behaviour; UBSan and ASan at `-O0` report nothing. Every one of these gives the right result:
- clang 22 at `-O0` and `-O2`
- clang 18 at every level
- GCC 13 at `-O1` and `-O2`
- `opt` from LLVM 23.1.5 running the same pass on the same IR

So this looks fixed on main. I am filing it for LLVM 22, which Ubuntu 26.04 LTS ships as its default toolchain (`clang-22` from the Ubuntu archive). A pointer to the fixing commit would let distributions backport it.

### Versions

- Wrong: `Ubuntu clang version 22.1.8 (++20260714014902+ca7933e47d3a-1~exp1~20260714135019.80)` (apt.llvm.org, noble), and clang 22 from Ubuntu 26.04's own archive
- Right: `Ubuntu LLVM version 23.1.5`, and clang 18.1.3
- Target: x86_64-pc-linux-gnu

### Reproducer 1: IR, the pass alone (`reduced.ll`, attached)

```sh
opt -S -passes='loop(indvars)' reduced.ll -o after.ll
clang -O0 reduced.ll -o before && ./before   # prints: ok
clang -O0 after.ll   -o after  && ./after # prints: index 4 out of range (len 4)
```

The loop in `@save` before the pass (`%3` and `%8` load the same field, and nothing in the loop stores):

```llvm
5:
  %6 = phi i64 [ %12, %11 ], [ 0, %1 ]
  %8 = load i64, ptr %7, align 8
  %9 = icmp slt i64 %6, %8
  br i1 %9, label %11, label %10        ; %10 calls @out_of_range, unreachable
11:
  %12 = add i64 %6, 1
  %14 = call i64 @llvm.smax.i64(i64 %3, i64 0)
  %15 = icmp slt i64 %12, %14
  %16 = select i1 %13, i1 %15, i1 false
  br i1 %16, label %5, label %17
```

After `indvars` (LLVM 22):

```llvm
.preheader:
  %smax = call i64 @llvm.smax.i64(i64 %3, i64 0)
  %.first_iter = icmp ult i64 1, %smax
  ...
11:
  %12 = add nuw nsw i64 %6, 1
  %13 = select i1 true, i1 %.first_iter, i1 false
  br i1 %13, label %5, label %.loopexit
```

The latch test no longer depends on the induction variable. For `n = 4`, `%.first_iter` is true, so the loop leaves only through the bounds-check exit, at `iv = 4`.

### Reproducer 2: C (`repro.c`, attached)

```sh
clang-22 -O1 repro.c && ./a.out   # prints: index 4 out of range (len 4); expected: ok
```

It is sensitive to layout: removing the unused first field of `Cache` hides it. So does writing the bounds check as one unsigned comparison, `(unsigned long)i >= (unsigned long)n`, which is the workaround we use now.

`-mllvm -opt-bisect-limit` names `indvars on loop in function save` as the first pass that makes the wrong code. `-indvars-predicate-loops=false`, `-replexitval=never` and `-disable-lftr` do not avoid it.

### Possibly related

- #236050 (a `samesign` comparison replaced with its loop-entry value). Our IR has no `samesign`, so it may be a different path to the same kind of fault.
- #183906 / #194202 (exit predication in `optimizeLoopExits`).

### reduced.ll
```llvm
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
target triple = "x86_64-pc-linux-gnu"

%struct.Cache = type { i64, %struct.List, i64 }
%struct.List = type { ptr, i64 }

@.str = constant [34 x i8] c"index %ld out of range (len %ld)\0A\00"
@str = constant [3 x i8] c"ok\00"

define void @out_of_range(i64 %0) {
  %2 = call i32 (ptr, ...) @printf(ptr noundef nonnull dereferenceable(1) @.str, i64 %0, i64 %0)
 call void @exit()
  unreachable
}

declare i32 @printf(ptr, ...)

declare void @exit()

define void @save(ptr %0) {
  %2 = getelementptr i8, ptr %0, i64 16
  %3 = load i64, ptr %2, align 8
  %4 = icmp slt i64 %3, 1
  br i1 %4, label %17, label %5

5: ; preds = %11, %1
  %6 = phi i64 [ %12, %11 ], [ 0, %1 ]
  %7 = getelementptr i8, ptr %0, i64 16
  %8 = load i64, ptr %7, align 8
  %9 = icmp slt i64 %6, %8
  br i1 %9, label %11, label %10

10: ; preds = %5
  call void @out_of_range(i64 %6)
  unreachable

11: ; preds = %5
  %12 = add i64 %6, 1
  %13 = icmp ne i64 1, 0
 %14 = call i64 @llvm.smax.i64(i64 %3, i64 0)
  %15 = icmp slt i64 %12, %14
 %16 = select i1 %13, i1 %15, i1 false
  br i1 %16, label %5, label %17

17:                                               ; preds = %11, %1
 ret void
}

define i32 @main() {
  %1 = alloca %struct.Cache, align 8
 %2 = getelementptr inbounds nuw i8, ptr %1, i64 16
  store i64 4, ptr %2, align 8
  call void @save(ptr nonnull %1)
  %3 = call i32 @puts(ptr noundef nonnull dereferenceable(1) @str)
  ret i32 0
}

declare i32 @puts(ptr)

declare i64 @llvm.smax.i64(i64, i64)

```

### repro.c
```c
/* Expected output: "ok". clang 22 at -O1 prints "index 4 out of range (len 4)". */
#include <stdio.h>
#include <stdlib.h>

typedef struct { long start, step, len; } Range;
typedef struct { long tokens, made; } Slot;
typedef struct { Slot *ptr; long len; } List;
typedef struct { long seen; List slots; long requests; } Cache;   /* without `seen` the bug hides */

__attribute__((noinline, noreturn)) void out_of_range(long i, long n) {
    printf("index %ld out of range (len %ld)\n", i, n);
    exit(1);
}

static Slot get(const List *l, long i) {
    if (i < 0 || i >= l->len) out_of_range(i, l->len);
    return l->ptr[i];
}

static Range range(long start, long stop, long step) {
 long len = 0;
    if (step > 0 && stop > start) {
        unsigned long span = stop - start, st = step;
        len = (long)((span + st - 1) / st);
    }
    return (Range){start, step, len};
}

static long age(Slot s) { return s.tokens > 0 ? s.made : 0; }

/* The slot that holds `want`, or else the oldest; the loop must stop at r.len. */
__attribute__((noinline)) void save(Cache *c, long want) {
    long slot = 0;
    Range r = range(0, c->slots.len, 1);
    for (long i = 0; i < r.len; i = (long)((unsigned long)i + 1)) {
        Slot s = get(&c->slots, i);
        if (s.tokens == want) { slot = i; break; }
        if (age(s) < age(get(&c->slots, slot))) slot = i;
    }
    c->slots.ptr[slot].made = c->requests;
}

int main(void) {
    Slot s[4] = {{3, 1}, {5, 2}, {7, 3}, {9, 4}};
    Cache c = {0, {s, 4}, 5};
    save(&c, 11);
    printf("ok\n");
    return 0;
}

```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to