# [llvm] r203413 - SimplifyCFG: Simplify the weight scaling algorithm.

Sun Mar 9 07:42:55 PDT 2014

```Author: d0k
Date: Sun Mar  9 09:42:55 2014
New Revision: 203413

URL: http://llvm.org/viewvc/llvm-project?rev=203413&view=rev
Log:
SimplifyCFG: Simplify the weight scaling algorithm.

No change in functionality.

Modified:
llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp

Modified: llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp?rev=203413&r1=203412&r2=203413&view=diff
==============================================================================
--- llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp (original)
+++ llvm/trunk/lib/Transforms/Utils/SimplifyCFG.cpp Sun Mar  9 09:42:55 2014
@@ -732,8 +732,7 @@ static void GetBranchWeights(TerminatorI
assert(MD);
for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
-    ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(i));
-    assert(CI);
+    ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
Weights.push_back(CI->getValue().getZExtValue());
}

@@ -750,19 +749,11 @@ static void GetBranchWeights(TerminatorI

/// Keep halving the weights until all can fit in uint32_t.
static void FitWeights(MutableArrayRef<uint64_t> Weights) {
-  while (true) {
-    bool Halve = false;
-    for (unsigned i = 0; i < Weights.size(); ++i)
-      if (Weights[i] > UINT_MAX) {
-        Halve = true;
-        break;
-      }
-
-    if (! Halve)
-      return;
-
-    for (unsigned i = 0; i < Weights.size(); ++i)
-      Weights[i] /= 2;
+  uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
+  if (Max > UINT_MAX) {
+    unsigned Offset = 32 - countLeadingZeros(Max);
+    for (uint64_t &I : Weights)
+      I >>= Offset;
}
}

```