This extends the canonicalizeClampLike function to allow cases where the input is truncated, but still matching on the types of the ICmps. For example
%t = trunc i32 %X to i8 %a = add i32 %X, 128 %cmp = icmp ult i32 %a, 256 %c = icmp sgt i32 %X, -1 %f = select i1 %c, i8 High, i8 Low %r = select i1 %cmp, i8 %t, i8 %f
becomes
%c1 = icmp slt i32 %X, -128 %c2 = icmp sge i32 %X, 128 %s1 = select i1 %c1, i32 sext(Low), i32 %X %s2 = select i1 %c2, i32 sext(High), i32 %s1 %t = trunc i32 %s2 to i8
https://alive2.llvm.org/ce/z/vPzfxH
We limit the transform to constant High and Low values, where we know the sext are free.
If you're going to keep this in code, please can you simplify it (no entry: + better var names).