Skip to content

Commit bb9bd5f

Browse files
authored
[LoopUnroll] Fix assert fail on zeroed branch weights (#165938)
BranchProbability fails an assert when its denominator is zero. Reported at <llvm/llvm-project#159163 (review)>.
1 parent 5a11eea commit bb9bd5f

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

llvm/lib/Transforms/Utils/LoopUtils.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -992,9 +992,12 @@ BranchProbability llvm::getBranchProbability(BranchInst *B,
992992
uint64_t Weight0, Weight1;
993993
if (!extractBranchWeights(*B, Weight0, Weight1))
994994
return BranchProbability::getUnknown();
995+
uint64_t Denominator = Weight0 + Weight1;
996+
if (Denominator == 0)
997+
return BranchProbability::getUnknown();
995998
if (!ForFirstTarget)
996999
std::swap(Weight0, Weight1);
997-
return BranchProbability::getBranchProbability(Weight0, Weight0 + Weight1);
1000+
return BranchProbability::getBranchProbability(Weight0, Denominator);
9981001
}
9991002

10001003
bool llvm::setBranchProbability(BranchInst *B, BranchProbability P,
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
; Check that zeroed branch weights do not crash or otherwise break basic
2+
; LoopUnroll behavior when it tries to compute a probability from them.
3+
4+
; RUN: opt < %s -S -unroll-count=2 -passes='loop-unroll' 2>&1 | FileCheck %s
5+
6+
define void @test() {
7+
entry:
8+
br label %loop
9+
10+
loop:
11+
br i1 false, label %end, label %loop, !prof !0
12+
13+
end:
14+
ret void
15+
}
16+
17+
!0 = !{!"branch_weights", i32 0, i32 0}
18+
19+
; CHECK: define void @test() {
20+
; CHECK: entry:
21+
; CHECK: br label %loop
22+
; CHECK: loop:
23+
; CHECK: br i1 false, label %end, label %loop.1, !prof !0
24+
; CHECK: loop.1:
25+
; CHECK: br i1 false, label %end, label %loop, !prof !0, !llvm.loop !1
26+
; CHECK-NOT: loop.2
27+
; CHECK: end:
28+
; CHECK: ret void
29+
; CHECK: }
30+
; CHECK: !0 = !{!"branch_weights", i32 0, i32 0}

0 commit comments

Comments
 (0)