[llvm] Add a pass to calculate machine function's cfg hash to detect whether… (PR #84145)

Rahman Lavaee via llvm-commits llvm-commits at lists.llvm.org
Mon Apr 15 11:05:54 PDT 2024


================
@@ -0,0 +1,73 @@
+//===-- MachineFunctionHashBuilder.cpp ----------------------------------*-
+// C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file contains the implementation of pass about calculating machine
+/// function hash.
+//===----------------------------------------------------------------------===//
+#include "llvm/CodeGen/MachineFunctionHashBuilder.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/MD5.h"
+#include "llvm/Support/raw_ostream.h"
+#include <queue>
+#include <unordered_map>
+#include <unordered_set>
+
+using namespace llvm;
+
+// Calculate machine function hash in level order traversal.
+// The control flow graph is uniquely represented by its level-order traversal.
+static uint64_t calculateMBBCFGHash(const MachineFunction &MF) {
+  if (MF.empty())
+    return 0;
+  std::unordered_set<const MachineBasicBlock *> Visited;
+  MD5 Hash;
+  std::queue<const MachineBasicBlock *> WorkList;
+  WorkList.push(&*MF.begin());
+  while (!WorkList.empty()) {
+    const MachineBasicBlock *CurrentBB = WorkList.front();
+    WorkList.pop();
+    uint32_t Value = support::endian::byte_swap<uint32_t, endianness::little>(
+        CurrentBB->getBBID()->BaseID);
+    uint32_t Size = support::endian::byte_swap<uint32_t, endianness::little>(
+        CurrentBB->succ_size());
+    Hash.update(ArrayRef((uint8_t *)&Value, sizeof(Value)));
----------------
rlavaee wrote:

You may update the hash several times with the same element. A single item may be inserted and visited several times since `Visited.count(CurrentBB)` is checked later. I think this is unnecessary. You can do this check before pushing items in the worklist. Also, please initialize `Visited` with the entry block.

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


More information about the llvm-commits mailing list