llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[InstCombine] Fold `!umul_overflow(x, K) && (x * K <u C)` to `x <u ceil(C / K)`

Open mariiakrasniuk opened this issue 2 months ago • 2 comments

Description

InstCombine appears to miss the following simplification for unsigned multiplication with overflow:

!umul_overflow(x, K) && (x * K <u C)
    ->
x <u ceil(C / K)

for K != 0 (in particular when K and C are constants).

I found this pattern in LLVM IR originating from the Linux kernel (linux__dmar_35, in dmar_free_unused_resources), where the relevant sequence is:

define i1 @src(i32 %x) {
  %e = sext i32 %x to i64
  %m = call {i64, i1} @llvm.umul.with.overflow.i64(i64 %e, i64 3)
  %ov = extractvalue {i64, i1} %m, 1
  %p = extractvalue {i64, i1} %m, 0
  %lt = icmp ult i64 %p, 41
  %noov = xor i1 %ov, true
  %r = and i1 %lt, %noov
  ret i1 %r
}

This can be simplified to:

define i1 @tgt(i32 %x) {
  %r = icmp ult i32 %x, 14
  ret i1 %r
}

because:

!overflow(x * 3) && (x * 3 <u 41)
    <=> x <u ceil(41 / 3)
    <=> x <u 14

Alive2 verifies the reduced transformation:

define i1 @src(i32 %x) {
  %m = call {i32, i1} @llvm.umul.with.overflow.i32(i32 %x, i32 3)
  %ov = extractvalue {i32, i1} %m, 1
  %p = extractvalue {i32, i1} %m, 0
  %lt = icmp ult i32 %p, 41
  %no = xor i1 %ov, true
  %r = and i1 %lt, %no
  ret i1 %r
}

define i1 @tgt(i32 %x) {
  %r = icmp ult i32 %x, 14
  ret i1 %r
}

Alive2: https://alive2.llvm.org/ce/z/vKSYMY

Generalization

The same identity can be expressed more generally as:

p, ov = umul.with.overflow(x, D)

!ov && (p <u C)
    <=>
x <u ceil(C / D)

for positive/non-zero D.

Alive2: https://alive2.llvm.org/ce/z/YLKuH9

mariiakrasniuk avatar Sep 10 '26 15:09 mariiakrasniuk

Hi @mariiakrasniuk,

I've opened a PR that fixes this: https://github.com/llvm/llvm-project/pull/227293

RS-Gits avatar Sep 29 '26 12:09 RS-Gits

@RS-Gits thank you!

mariiakrasniuk avatar Sep 29 '26 13:09 mariiakrasniuk