[llvm-dev] enable optimization of integer multiplication and modulo using faster operations?

Peng Yu via llvm-dev llvm-dev at lists.llvm.org
Tue Mar 5 20:34:47 PST 2019


Hi,

$ clang -Wall -pedantic -O3 -S -emit-llvm -c -o - main.c

When I compile the following .c file using the above clang command, I
still get mul in the IR code. But isn't that 31 is just 32 - 1, so
that the implementation can use left shift by 4 and subtract the
original number?

#include <stdio.h>
int f(int x) {
    return x * 31;
}
int main() {
    int x=1;
    printf("%d\n", f(x));
    return 0;
}

; Function Attrs: norecurse nounwind readnone ssp uwtable
define i32 @f(i32) local_unnamed_addr #0 {
  %2 = mul nsw i32 %0, 31
  ret i32 %2
}

Also, I see this comment. But % is just translated to `srem` by clang.

"Turns out if you do a modulo by a constant, the compiler knows a
bunch of tricks to make this fast."
https://probablydance.com/2017/02/26/i-wrote-the-fastest-hashtable/

Is clang able to produce optimized code for integer multiplication and
modulo operations? Thanks.

-- 
Regards,
Peng


More information about the llvm-dev mailing list