@@ -7732,19 +7732,24 @@ static bool simplifySwitchOfPowersOfTwo(SwitchInst *SI, IRBuilder<> &Builder,
77327732 // label. The other is those powers of 2 that don't appear in the case
77337733 // statement. We don't know the distribution of the values coming in, so
77347734 // the safest is to split 50-50 the original probability to `default`.
7735- uint64_t OrigDenominator = sum_of ( map_range (
7736- Weights, []( const auto &V) { return static_cast <uint64_t >(V); } ));
7735+ uint64_t OrigDenominator =
7736+ sum_of ( map_range ( Weights, StaticCastTo <uint64_t >));
77377737 SmallVector<uint64_t > NewWeights (2 );
77387738 NewWeights[1 ] = Weights[0 ] / 2 ;
77397739 NewWeights[0 ] = OrigDenominator - NewWeights[1 ];
77407740 setFittedBranchWeights (*BI, NewWeights, /* IsExpected=*/ false );
7741-
7742- // For the original switch, we reduce the weight of the default by the
7743- // amount by which the previous branch contributes to getting to default,
7744- // and then make sure the remaining weights have the same relative ratio
7745- // wrt eachother.
7741+ // The probability of executing the default block stays constant. It was
7742+ // p_d = Weights[0] / OrigDenominator
7743+ // we rewrite as W/D
7744+ // We want to find the probability of the default branch of the switch
7745+ // statement. Let's call it X. We have W/D = W/2D + X * (1-W/2D)
7746+ // i.e. the original probability is the probability we go to the default
7747+ // branch from the BI branch, or we take the default branch on the SI.
7748+ // Meaning X = W / (2D - W), or (W/2) / (D - W/2)
7749+ // This matches using W/2 for the default branch probability numerator and
7750+ // D-W/2 as the denominator.
7751+ Weights[0 ] = NewWeights[1 ];
77467752 uint64_t CasesDenominator = OrigDenominator - Weights[0 ];
7747- Weights[0 ] /= 2 ;
77487753 for (auto &W : drop_begin (Weights))
77497754 W = NewWeights[0 ] * static_cast <double >(W) / CasesDenominator;
77507755
0 commit comments