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

[InstCombine] Missed optimization for `zext(trunc nuw(x))`

Open Il-Capitano opened this issue 2 years ago • 3 comments

Godbolt link: https://godbolt.org/z/Ws1jPz4rE

Instcombine transforms this function:

define i64 @test(i64 %n) {
    %trunc = trunc nuw i64 %n to i32
    %zext = zext i32 %trunc to i64
    ret i64 %zext
}

into this:

define i64 @test(i64 %n) {
  %zext = and i64 %n, 4294967295
  ret i64 %zext
}

However, because of the nuw flag on trunc, this could be simplified into this instead:

define i64 @test(i64 %n) {
    ret i64 %n
}

Il-Capitano avatar Jul 08 '24 12:07 Il-Capitano

See https://github.com/llvm/llvm-project/pull/88609.

nikic avatar Jul 08 '24 12:07 nikic

This also makes LLVM fail to replace loop with arithmetic sum progression in the following https://godbolt.org/z/n45nb95Tr

define i16 @sum(i8 %start, i8 %last) {
    br label %begin
begin:
    %last_w = zext i8 %last to i16
    %start_w = zext i8 %start to i16
    %end = add i16 1, %last_w
    br label %header

header:
    %i = phi i16 [%start_w, %begin],
                 [%next_i, %body]
    %sum_h = phi i16 [0, %begin], [%sum_b, %body]
    %cmp_res = icmp ult i16 %i, %end
    br i1 %cmp_res, label %body, label %finish
body:
    %current = trunc nuw i16 %i to i8
    %curr_ext = zext i8 %current to i16
    ; Uncomment to make LLVM succeed in removing the loop
    ;%curr_ext = and i16 %i, 255

    %sum_b = add i16 %sum_h, %curr_ext

    %next_i = add i16 %i, 1
    br label %header
finish:
    ret i16 %sum_h
}

It instead unrolls the loop and generates tons of vectorized code.

AngelicosPhosphoros avatar May 16 '26 22:05 AngelicosPhosphoros

closed by https://github.com/llvm/llvm-project/pull/204089

andjo403 avatar Aug 26 '26 16:08 andjo403