[SimplifyCFG] SimplifyCFGPass emits incorrect branch_weight Metadata
Environment setting:
- commitid: 56d68e8d7a17c32d2fd0d08
- build command:
cmake -S llvm -B ./build -G "Ninja" -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS=clang
- test case(test.c):
extern void bar();
void foo(char a, char b, char c) {
char aa = 2 * a, bb = 2 * b, cc = 2 * c;
if (__builtin_expect(((aa == 2) || (bb == 2) || (cc == 0)), 0)) {
bar();
}
}
- compile command:
clang -S -O1 test.c -mllvm -print-after-all -mllvm -print-module-scope 2> trace
- version info:
clang version 15.0.0 ([email protected]:llvm/llvm-project.git 56d68e8d7a17c32d2fd0d0894fc0776df0d85673)
Target: x86_64-unknown-linux-gnu
Thread model: posix
Issue:
- IR before second SimplifyCFGPass(after InstCombinePass):
define dso_local void @foo(i8 noundef signext %0, i8 noundef signext %1, i8 noundef signext %2) local_unnamed_addr #0 {
%4 = and i8 %0, 127
%5 = icmp eq i8 %4, 1
%6 = and i8 %1, 127
%7 = icmp eq i8 %6, 1
%8 = or i1 %5, %7
br i1 %8, label %12, label %9, !prof !5
9: ; preds = %3
%10 = and i8 %2, 127
%11 = icmp eq i8 %10, 0
br label %12
12: ; preds = %9, %3
%13 = phi i1 [ true, %3 ], [ %11, %9 ]
br i1 %13, label %14, label %15, !prof !6
14: ; preds = %12
call void (...) @bar() #2
br label %15
15: ; preds = %14, %12
ret void
}
!5 = !{!"branch_weights", i32 4001, i32 4000000}
!6 = !{!"branch_weights", i32 1, i32 2000}
The probability of executing bar() is 1/2000, since entrance block and %9 both finally merged to %12, which is expected. The number 1 and 2000 are the default true/false branch weight value from LowerExpectIntrinsic.
- IR after second SimplifyCFGPass:
define dso_local void @foo(i8 noundef signext %0, i8 noundef signext %1, i8 noundef signext %2) local_unnamed_addr #0 {
%4 = and i8 %0, 127
%5 = icmp eq i8 %4, 1
%6 = and i8 %1, 127
%7 = icmp eq i8 %6, 1
%8 = or i1 %5, %7
%9 = and i8 %2, 127
%10 = icmp eq i8 %9, 0
%11 = or i1 %8, %10
br i1 %11, label %12, label %13, !prof !5
12: ; preds = %3
call void (...) @bar() #2
br label %13
13: ; preds = %3, %12
ret void
}
!5 = !{!"branch_weights", i32 6003000, i32 -294967296}
After the second SimplifyCFG, the probability of executing bar() is changed to 6003000/4000000000=6003/4000000≈3/2000, which is different from original 1/2000.
If the source code is using __builtin_expect_with_probability, for example changing the fourth line of source code to:
if (__builtin_expect_with_probability(((aa == 2) || (bb == 2) || (cc == 0)), 1, 0.0)) {
This means user expects the probability of executing bar() is 0.0%, but now the branch weight is !5 = !{!"branch_weights", i32 -2147483647, i32 2147483647} which means roughly 50%.
@ZhiZhuangMTK: Could you please elaborate?
@ZhiZhuangMTK: Could you please elaborate?
Hi, we committed a patch: https://github.com/llvm/llvm-project/commit/b49ee01fe288abda9269114cc3aef6caade6015a, and now the issue would not happen any more.
@ZhiZhuangMTK: Thank you for clarification!