Reputation: 23
I playing with LLVM and tried to compile simple C++ code using it
#include <stdio.h>
#include <stdlib.h>
int main()
{
int test = rand();
if (test % 2)
test += 522;
else
test *= 333;
printf("test %d\n", test);
}
Especially to test how LLVM treats code branches Result I got is very strange, it gives valid result on execution, but looks unefficient
; Function Attrs: nounwind
define i32 @main() local_unnamed_addr #0 {
%1 = tail call i32 @rand() #3
%2 = and i32 %1, 1
%3 = icmp eq i32 %2, 0
%4 = add nsw i32 %1, 522
%5 = mul nsw i32 %1, 333
%6 = select i1 %3, i32 %5, i32 %4
%7 = tail call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @.str, i64 0, i64 0), i32 %6)
ret i32 0
}
It looks like it executing both ways even if only one is needen My question is: Should not LLVM in this case generate labels and why? Thank you
P.S. I'm using http://ellcc.org/demo/index.cgi for this test
Upvotes: 2
Views: 84
Reputation: 370092
Branches can be expensive, so generating code without branches at the cost of one unnecessary add
or mul
instruction, will usually work out to be faster in practice.
If you make the branches of your if
longer, you'll see that it'll eventually become a proper branch instead of a select
.
The compiler tends to have a good understanding of which option is faster in which case, so I'd trust it unless you have specific benchmarks that show the version with select
to be slower than a version that branches.
Upvotes: 4