Missed Optimization: fold smax(a, -b) + b into smax(a + b, 0)
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
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.
Can I give it a try?
@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.
Hello, I would like to extend #167109 to fix this issue as well.