[llvm] MachineBlockPlacement: Add tolerance to comparisons (PR #67197)

Rahman Lavaee via llvm-commits llvm-commits at lists.llvm.org
Thu Oct 5 18:30:15 PDT 2023


================
@@ -1750,12 +1753,33 @@ MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
     //                 +-------------------------------------+
     //                 V                                     |
     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
-    if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
+    if (BestFreq > BlockFrequency(0) &&
+        (ReverseOrder ^ (BestFreq >= CandidateFreq)))
       continue;
 
-    BestBlock = MBB;
     BestFreq = CandidateFreq;
   }
+  // Perform a 2nd pass to make the output more stable: Check for blocks with
+  // almost the same frequency as `BestFreq` and prefer the one that is already
+  // a successor to `ChainEnd` first or whichever comes first in `WorkList`.
+  MachineBasicBlock *BestBlock = nullptr;
+  for (MachineBasicBlock *MBB : WorkList) {
+    BlockChain &SuccChain = *BlockToChain[MBB];
+    if (&SuccChain == &Chain)
+      continue;
+    BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
+    if (!ReverseOrder) {
+      if (!BestFreq.almostEqual(CandidateFreq))
+        continue;
+    } else if (!CandidateFreq.almostEqual(BestFreq)) {
+      continue;
+    }
+    // Give precedence to the block already following `ChainEnd`, otherwise take
+    // the first one we encounter.
+    if (BestBlock == nullptr || ChainEnd->isLayoutSuccessor(MBB)) {
----------------
rlavaee wrote:

Another performance concern is that the almostEqual condition could be highly mispredicted branch. While the others are easier to predict.

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


More information about the llvm-commits mailing list