Issue 234546
Summary [LoopFlatten] Outer-loop load is re-executed on every flattened iteration and reads the inner loop's store
Labels miscompilation, loopoptim, generated by fuzzer
Assignees
Reporter ChoKyuWon
    ### reproducer
godbolt: https://godbolt.org/z/en6fjMoYs
alive: https://alive2.llvm.org/ce/z/VAxRBV

```llvm
@g = global i32 7

define i32 @main() {
entry:
  br label %outer

outer:
  %i = phi i32 [ 0, %entry ], [ %i.next, %outer.latch ]
  %x = load i32, ptr @g, align 4
  br label %inner

inner:
  %j = phi i32 [ 0, %outer ], [ %j.next, %inner.latch ]
  store i32 0, ptr @g, align 4
  br label %inner.latch

inner.latch:
 %j.next = add i32 %j, 1
  %j.cmp = icmp ult i32 %j.next, 2
  br i1 %j.cmp, label %inner, label %outer.latch

outer.latch:
  %i.next = add i32 %i, 1
 %i.cmp = icmp ult i32 %i.next, 1
  br i1 %i.cmp, label %outer, label %exit

exit:
  ret i32 %x
}
```

```console
$ opt -S -passes=loop-flatten repro.ll
define i32 @main() {
entry:
 %flatten.tripcount = mul i32 2, 1
  br label %outer

outer:
  %i = phi i32 [ 0, %entry ], [ %i.next, %outer.latch ]
  %x = load i32, ptr @g, align 4
  br label %inner

inner:
  %j = phi i32 [ 0, %outer ]
  store i32 0, ptr @g, align 4
  br label %inner.latch
...
outer.latch:
  %i.next = add i32 %i, 1
  %i.cmp = icmp ult i32 %i.next, %flatten.tripcount
  br i1 %i.cmp, label %outer, label %exit

exit:
  %x.lcssa = phi i32 [ %x, %outer.latch ]
  ret i32 %x.lcssa
}

$ llubi repro.ll; echo $?
7
$ opt -S -passes=loop-flatten repro.ll | llubi -; echo $?
0

$ alive-tv --disable-undef-input --disable-poison-input -passes=loop-flatten --src-unroll=2 --tgt-unroll=2 repro.ll
ERROR: Value mismatch
...
Source:
i32 %x = #x00000002 (2)
...
Target:
i32 %x = #x00000002 (2)
...
i32 %x#2 = #x00000000 (0)
...
Source value: #x00000002 (2)
Target value: #x00000000 (0)
```

### suggested fix
`checkOuterLoopInsts` only requires each outer-only instruction to pass `isSafeToSpeculativelyExecute`, but after flattening it runs once per inner iteration, so it must also produce the same value each time.
A load from a dereferenceable global passes that check and then observes the inner loop's stores.
Reject an outer-only instruction that `mayReadFromMemory()` when the loop nest may write to memory (or when AA/MemorySSA cannot show that nothing in the loop nest clobbers its location).

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

Reply via email to