[llvm] [llvm-ir2vec] adding function-embedding map API to ir2vec python bindings (PR #177166)
Nishant Sachdeva via llvm-commits
llvm-commits at lists.llvm.org
Sat Jan 31 00:57:05 PST 2026
https://github.com/nishant-sachdeva updated https://github.com/llvm/llvm-project/pull/177166
>From f10e3f14257611993118c6b950f3a0c1789d1912 Mon Sep 17 00:00:00 2001
From: nishant-sachdeva <nishant.sachdeva at research.iiit.ac.in>
Date: Wed, 21 Jan 2026 18:20:16 +0530
Subject: [PATCH 1/2] Adding getFuncEmbMap functionality to ir2vec python
bindings
---
llvm/test/tools/llvm-ir2vec/Inputs/input.ll | 24 +++++++++++++
.../llvm-ir2vec/bindings/ir2vec-bindings.py | 17 +++++++++
llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp | 35 +++++++++++++++++--
llvm/tools/llvm-ir2vec/lib/Utils.cpp | 35 +++++++++++++++++++
llvm/tools/llvm-ir2vec/lib/Utils.h | 9 +++++
5 files changed, 118 insertions(+), 2 deletions(-)
diff --git a/llvm/test/tools/llvm-ir2vec/Inputs/input.ll b/llvm/test/tools/llvm-ir2vec/Inputs/input.ll
index 1ca881faa0141..93e77be51b8e9 100644
--- a/llvm/test/tools/llvm-ir2vec/Inputs/input.ll
+++ b/llvm/test/tools/llvm-ir2vec/Inputs/input.ll
@@ -3,3 +3,27 @@ entry:
%sum = add i32 %a, %b
ret i32 %sum
}
+
+define i32 @multiply(i32 %x, i32 %y) {
+entry:
+ %prod = mul i32 %x, %y
+ ret i32 %prod
+}
+
+define i32 @conditional(i32 %n) {
+entry:
+ %cmp = icmp sgt i32 %n, 0
+ br i1 %cmp, label %positive, label %negative
+
+positive:
+ %pos_val = add i32 %n, 10
+ br label %exit
+
+negative:
+ %neg_val = sub i32 %n, 10
+ br label %exit
+
+exit:
+ %result = phi i32 [ %pos_val, %positive ], [ %neg_val, %negative ]
+ ret i32 %result
+}
diff --git a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
index 4038277667a47..b84499786e939 100644
--- a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
+++ b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
@@ -12,5 +12,22 @@
print("SUCCESS: Tool initialized")
print(f"Tool type: {type(tool).__name__}")
+ # Test getFuncEmbMap
+ func_emb_map = tool.getFuncEmbMap()
+ print(f"Number of functions: {len(func_emb_map)}")
+
+ # Check that all three functions are present
+ expected_funcs = ["add", "multiply", "conditional"]
+ for func_name in expected_funcs:
+ if func_name in func_emb_map:
+ emb = func_emb_map[func_name]
+ print(f"Function '{func_name}': embedding shape = {emb.shape}")
+ else:
+ print(f"ERROR: Function '{func_name}' not found")
+
# CHECK: SUCCESS: Tool initialized
# CHECK: Tool type: IR2VecTool
+# CHECK: Number of functions: 3
+# CHECK: Function 'add': embedding shape =
+# CHECK: Function 'multiply': embedding shape =
+# CHECK: Function 'conditional': embedding shape =
diff --git a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
index 530adee8e052e..346faf879c855 100644
--- a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
+++ b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
@@ -42,12 +42,18 @@ class PyIR2VecTool {
std::unique_ptr<LLVMContext> Ctx;
std::unique_ptr<Module> M;
std::unique_ptr<IR2VecTool> Tool;
+ IR2VecKind EmbKind;
public:
PyIR2VecTool(const std::string &Filename, const std::string &Mode,
const std::string &VocabPath) {
- if (Mode != "sym" && Mode != "fa")
+ EmbKind = [](const std::string &Mode) -> IR2VecKind {
+ if (Mode == "sym")
+ return IR2VecKind::Symbolic;
+ if (Mode == "fa")
+ return IR2VecKind::FlowAware;
throw nb::value_error("Invalid mode. Use 'sym' or 'fa'");
+ }(Mode);
if (VocabPath.empty())
throw nb::value_error("Empty Vocab Path not allowed");
@@ -62,6 +68,27 @@ class PyIR2VecTool {
.c_str());
}
}
+
+ nb::dict getFuncEmbMap() {
+ auto result = Tool->getFunctionEmbeddings(EmbKind);
+ nb::dict nb_result;
+
+ for (const auto &[func_ptr, embedding] : result) {
+ std::string func_name = func_ptr->getName().str();
+ auto data = embedding.getData();
+ size_t shape[1] = {data.size()};
+ double *data_ptr = new double[data.size()];
+ std::copy(data.data(), data.data() + data.size(), data_ptr);
+
+ auto nb_array = nb::ndarray<nb::numpy, double>(
+ data_ptr, {data.size()}, nb::capsule(data_ptr, [](void *p) noexcept {
+ delete[] static_cast<double *>(p);
+ }));
+ nb_result[nb::str(func_name.c_str())] = nb_array;
+ }
+
+ return nb_result;
+ }
};
} // namespace
@@ -72,7 +99,11 @@ NB_MODULE(ir2vec, m) {
nb::class_<PyIR2VecTool>(m, "IR2VecTool")
.def(nb::init<const std::string &, const std::string &,
const std::string &>(),
- nb::arg("filename"), nb::arg("mode"), nb::arg("vocabPath"));
+ nb::arg("filename"), nb::arg("mode"), nb::arg("vocabPath"))
+ .def("getFuncEmbMap", &PyIR2VecTool::getFuncEmbMap,
+ "Generate function-level embeddings for all functions\n"
+ "Returns: dict[str, ndarray[float64]] - "
+ "{function_name: embedding}");
m.def(
"initEmbedding",
diff --git a/llvm/tools/llvm-ir2vec/lib/Utils.cpp b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
index 190d9259e45b3..4e8589885e019 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.cpp
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
@@ -151,6 +151,41 @@ void IR2VecTool::writeEntitiesToStream(raw_ostream &OS) {
OS << Entities[EntityID] << '\t' << EntityID << '\n';
}
+std::pair<const Function *, Embedding>
+IR2VecTool::getFunctionEmbedding(const Function &F, IR2VecKind Kind) const {
+ assert(Vocab && Vocab->isValid() && "Vocabulary not initialized");
+
+ if (F.isDeclaration())
+ return {nullptr, Embedding()};
+
+ auto Emb = Embedder::create(Kind, F, *Vocab);
+ if (!Emb) {
+ return {nullptr, Embedding()};
+ }
+
+ auto FuncVec = Emb->getFunctionVector();
+
+ return {&F, std::move(FuncVec)};
+}
+
+FuncEmbMap IR2VecTool::getFunctionEmbeddings(IR2VecKind Kind) const {
+ assert(Vocab && Vocab->isValid() && "Vocabulary not initialized");
+
+ FuncEmbMap Result;
+
+ for (const Function &F : M) {
+ if (F.isDeclaration())
+ continue;
+
+ auto Emb = getFunctionEmbedding(F, Kind);
+ if (Emb.first != nullptr) {
+ Result.try_emplace(Emb.first, std::move(Emb.second));
+ }
+ }
+
+ return Result;
+}
+
void IR2VecTool::writeEmbeddingsToStream(raw_ostream &OS,
EmbeddingLevel Level) const {
if (!Vocab->isValid()) {
diff --git a/llvm/tools/llvm-ir2vec/lib/Utils.h b/llvm/tools/llvm-ir2vec/lib/Utils.h
index d9715b03c3082..d115d9a26ca90 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.h
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.h
@@ -16,6 +16,7 @@
#define LLVM_TOOLS_LLVM_IR2VEC_UTILS_UTILS_H
#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
#include "llvm/Analysis/IR2Vec.h"
#include "llvm/CodeGen/MIR2Vec.h"
#include "llvm/CodeGen/MIRParser/MIRParser.h"
@@ -72,6 +73,7 @@ struct TripletResult {
/// Entity mappings: [entity_name]
using EntityList = std::vector<std::string>;
+using FuncEmbMap = DenseMap<const Function *, ir2vec::Embedding>;
namespace ir2vec {
@@ -112,6 +114,13 @@ class IR2VecTool {
/// Returns EntityList containing all entity strings
static EntityList collectEntityMappings();
+ // Get embedding for a single function
+ std::pair<const Function *, Embedding>
+ getFunctionEmbedding(const Function &F, IR2VecKind Kind) const;
+
+ /// Get embeddings for all functions in the module
+ FuncEmbMap getFunctionEmbeddings(IR2VecKind Kind) const;
+
/// Dump entity ID to string mappings
static void writeEntitiesToStream(raw_ostream &OS);
>From 90bb87e7f9943d9b5b384c9d2d65b63a8e5c2ed7 Mon Sep 17 00:00:00 2001
From: nishant-sachdeva <nishant.sachdeva at research.iiit.ac.in>
Date: Wed, 21 Jan 2026 19:36:48 +0530
Subject: [PATCH 2/2] Changing unit-test structure for function embeddings
---
.../llvm-ir2vec/bindings/ir2vec-bindings.py | 26 +++++++++----------
1 file changed, 13 insertions(+), 13 deletions(-)
diff --git a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
index b84499786e939..a209a47cba42e 100644
--- a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
+++ b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
@@ -13,21 +13,21 @@
print(f"Tool type: {type(tool).__name__}")
# Test getFuncEmbMap
+ print("\n=== Function Embeddings ===")
func_emb_map = tool.getFuncEmbMap()
- print(f"Number of functions: {len(func_emb_map)}")
- # Check that all three functions are present
- expected_funcs = ["add", "multiply", "conditional"]
- for func_name in expected_funcs:
- if func_name in func_emb_map:
- emb = func_emb_map[func_name]
- print(f"Function '{func_name}': embedding shape = {emb.shape}")
- else:
- print(f"ERROR: Function '{func_name}' not found")
+ # Sorting the function names for fixed-ordered output
+ for func_name in sorted(func_emb_map.keys()):
+ emb = func_emb_map[func_name]
+ print(f"Function: {func_name}")
+ print(f" Embedding: {emb.tolist()}")
# CHECK: SUCCESS: Tool initialized
# CHECK: Tool type: IR2VecTool
-# CHECK: Number of functions: 3
-# CHECK: Function 'add': embedding shape =
-# CHECK: Function 'multiply': embedding shape =
-# CHECK: Function 'conditional': embedding shape =
+# CHECK: === Function Embeddings ===
+# CHECK: Function: add
+# CHECK-NEXT: Embedding: [38.0, 40.0, 42.0]
+# CHECK: Function: conditional
+# CHECK-NEXT: Embedding: [413.20000000298023, 421.20000000298023, 429.20000000298023]
+# CHECK: Function: multiply
+# CHECK-NEXT: Embedding: [50.0, 52.0, 54.0]
More information about the llvm-commits
mailing list