[llvm] [VPlan] Thread branch weights into VPlan and use them for cost (NFCI) (PR #209309)

Luke Lau via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 15 00:11:15 PDT 2026


================
@@ -2514,9 +2530,26 @@ uint64_t LoopVectorizationCostModel::getPredBlockCostDivisor(
   uint64_t BBFreq = getBFI().getBlockFreq(BB).getFrequency();
   assert(HeaderFreq >= BBFreq &&
          "Header has smaller block freq than dominated BB?");
+  // Treat a zero frequency (e.g. a block BFI considers unreachable) as
+  // always-executed, avoiding a division by zero.
+  if (BBFreq == 0)
+    return 1;
   return std::round((double)HeaderFreq / BBFreq);
 }
 
+MDNode *
+LoopVectorizationCostModel::getEstimatedPredBlockWeights(const BasicBlock *BB) {
+  // A block entered on true and skipped on false with reciprocal probability R
+  // maps to weights {1, R - 1}. Saturate R - 1 to the 32-bit range MDBuilder
+  // requires.
+  uint64_t R = getReciprocalPredBlockProbability(BB);
+  if (R <= 1)
+    return nullptr;
+  MDBuilder MDB(TheLoop->getHeader()->getContext());
+  return MDB.createBranchWeights(
+      1, std::min<uint64_t>(R - 1, std::numeric_limits<uint32_t>::max()));
----------------
lukel97 wrote:

Is there a particular reason why we're now storing the probability as an `MDNode`? It's maybe a bit confusing because we're now storing block probabilities as branch frequencies. 

> And additional follow-ups will use it for adding branch weights to conditional branches in replicate regions and other elegible instructions.

Can we instead create the `MDNode::BranchWeights` during execution?

https://github.com/llvm/llvm-project/pull/209309


More information about the llvm-commits mailing list