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

Missed Optimization: fold smax(a, -b) + b into smax(a + b, 0)

Open Leo0506 opened this issue 1 year ago • 4 comments

define i32 @src(i32 %arg0, i32 %arg1) {
  %v0 = sub nsw i32 0, %arg1
  %v1 = call i32 @llvm.smax.i32(i32 %arg0, i32 %v0)
  %v2 = add nuw nsw i32 %v1, %arg1
  ret i32 %v2
}


define i32 @tgt(i32 %arg0, i32 %arg1) {
  %v0 = add i32 %arg0, %arg1
  %v1 = call i32 @llvm.smax.i32(i32 %v0, i32 0)
  ret i32 %v1
}

alive2: https://alive2.llvm.org/ce/z/qqiS7X godbolt: https://godbolt.org/z/s67Tea5j6 Pattern found in: https://github.com/dtcxzyw/llvm-opt-benchmark/blob/main/bench/ffmpeg/optimized/ftr.ll

Leo0506 avatar Nov 07 '25 01:11 Leo0506

Just for reference this shows up exactly this way in the code even:

s->index += av_clip(n, -s->index, s->size_in_bits_plus8 - s->index); https://ffmpeg.org/doxygen/trunk/get__bits_8h_source.html#L281

which is trying to do s->index = av_clip(s->index + n, 0, s->size_in_bits_plus8);

Yes av_clip is defined like what you think. I think the only reason why it is written this way was because the person was concern with overflow. that is s->index + n might overflow while s->size_in_bits_plus8 - s->index won't.

pinskia avatar Nov 07 '25 06:11 pinskia

Can I give it a try?

Michael-Chen-NJU avatar Nov 07 '25 11:11 Michael-Chen-NJU

@Michael-Chen-NJU Sorry, as https://github.com/llvm/llvm-project/issues/167003 is similar to this issue and @ARandomDev99 has already submitted a patch, I'd assign this to @ARandomDev99 to avoid overlapping effort.

dtcxzyw avatar Nov 08 '25 09:11 dtcxzyw

Hello, I would like to extend #167109 to fix this issue as well.

NullSpaceBoy avatar Nov 08 '25 09:11 NullSpaceBoy