[llvm] Llvm ir2vec vocab read refactor (PR #177361)
Nishant Sachdeva via llvm-commits
llvm-commits at lists.llvm.org
Thu Jan 22 05:40:21 PST 2026
https://github.com/nishant-sachdeva created https://github.com/llvm/llvm-project/pull/177361
Modifying llvm-ir2vec vocab reading pipeline to use Vocabulary::fromFile instead of a full pass invocation
>From f423e0b328069a9a9e871e93e24fadb9f5d897da Mon Sep 17 00:00:00 2001
From: svkeerthy <venkatakeerthy at gmail.com>
Date: Thu, 22 Jan 2026 17:45:04 +0530
Subject: [PATCH 1/2] [IR2Vec] Changes to support programmatic creation of
Vocabulary
---
llvm/include/llvm/Analysis/IR2Vec.h | 21 +-
llvm/lib/Analysis/IR2Vec.cpp | 91 +++++----
llvm/unittests/Analysis/IR2VecTest.cpp | 268 +++++++++++++++++++++++++
3 files changed, 339 insertions(+), 41 deletions(-)
diff --git a/llvm/include/llvm/Analysis/IR2Vec.h b/llvm/include/llvm/Analysis/IR2Vec.h
index 5957a3743f22e..2bf1c2adc0d4f 100644
--- a/llvm/include/llvm/Analysis/IR2Vec.h
+++ b/llvm/include/llvm/Analysis/IR2Vec.h
@@ -327,6 +327,16 @@ class Vocabulary {
Vocabulary(Vocabulary &&) = default;
Vocabulary &operator=(Vocabulary &&Other) = delete;
+ /// Create a Vocabulary by loading embeddings from a JSON file.
+ /// This is the primary entry point for programmatic vocabulary creation,
+ /// suitable for use in Python bindings or other contexts where command-line
+ /// options are not available. Weights are applied to scale the embeddings
+ /// for opcodes, types, and arguments respectively.
+ LLVM_ABI static Expected<Vocabulary> fromFile(StringRef VocabFilePath,
+ float OpcWeight = 1.0,
+ float TypeWeight = 0.5,
+ float ArgWeight = 0.2);
+
LLVM_ABI bool isValid() const {
return Storage.size() == NumCanonicalEntries;
}
@@ -513,6 +523,12 @@ class Vocabulary {
assert(Index < MaxPredicateKinds && "Invalid predicate index");
return getPredicateFromLocalIndex(Index);
}
+
+ using VocabMap = std::map<std::string, Embedding>;
+
+ /// Generate VocabStorage from vocabulary maps.
+ static VocabStorage buildVocabStorage(VocabMap &OpcVocab, VocabMap &TypeVocab,
+ VocabMap &ArgVocab);
};
/// Embedder provides the interface to generate embeddings (vector
@@ -612,13 +628,8 @@ class LLVM_ABI FlowAwareEmbedder : public Embedder {
/// mapping between an entity of the IR (like opcode, type, argument, etc.) and
/// its corresponding embedding.
class IR2VecVocabAnalysis : public AnalysisInfoMixin<IR2VecVocabAnalysis> {
- using VocabMap = std::map<std::string, ir2vec::Embedding>;
std::optional<ir2vec::VocabStorage> Vocab;
- Error readVocabulary(VocabMap &OpcVocab, VocabMap &TypeVocab,
- VocabMap &ArgVocab);
- void generateVocabStorage(VocabMap &OpcVocab, VocabMap &TypeVocab,
- VocabMap &ArgVocab);
void emitError(Error Err, LLVMContext &Ctx);
public:
diff --git a/llvm/lib/Analysis/IR2Vec.cpp b/llvm/lib/Analysis/IR2Vec.cpp
index 85b5372c961c1..4c187fe9ce804 100644
--- a/llvm/lib/Analysis/IR2Vec.cpp
+++ b/llvm/lib/Analysis/IR2Vec.cpp
@@ -476,18 +476,16 @@ VocabStorage Vocabulary::createDummyVocabForTest(unsigned Dim) {
return VocabStorage(std::move(Sections));
}
-// ==----------------------------------------------------------------------===//
-// IR2VecVocabAnalysis
-//===----------------------------------------------------------------------===//
-
-// FIXME: Make this optional. We can avoid file reads
-// by auto-generating a default vocabulary during the build time.
-Error IR2VecVocabAnalysis::readVocabulary(VocabMap &OpcVocab,
- VocabMap &TypeVocab,
- VocabMap &ArgVocab) {
- auto BufOrError = MemoryBuffer::getFileOrSTDIN(VocabFile, /*IsText=*/true);
+namespace {
+using VocabMap = std::map<std::string, Embedding>;
+
+/// Read vocabulary JSON file and populate the section maps.
+Error readVocabularyFromFile(StringRef VocabFilePath, VocabMap &OpcVocab,
+ VocabMap &TypeVocab, VocabMap &ArgVocab) {
+ auto BufOrError =
+ MemoryBuffer::getFileOrSTDIN(VocabFilePath, /*IsText=*/true);
if (!BufOrError)
- return createFileError(VocabFile, BufOrError.getError());
+ return createFileError(VocabFilePath, BufOrError.getError());
auto Content = BufOrError.get()->getBuffer();
@@ -514,10 +512,12 @@ Error IR2VecVocabAnalysis::readVocabulary(VocabMap &OpcVocab,
return Error::success();
}
+} // anonymous namespace
-void IR2VecVocabAnalysis::generateVocabStorage(VocabMap &OpcVocab,
- VocabMap &TypeVocab,
- VocabMap &ArgVocab) {
+/// Generate VocabStorage from vocabulary maps.
+VocabStorage Vocabulary::buildVocabStorage(VocabMap &OpcVocab,
+ VocabMap &TypeVocab,
+ VocabMap &ArgVocab) {
// Helper for handling missing entities in the vocabulary.
// Currently, we use a zero vector. In the future, we will throw an error to
@@ -589,19 +589,48 @@ void IR2VecVocabAnalysis::generateVocabStorage(VocabMap &OpcVocab,
// Create section-based storage instead of flat vocabulary
// Order must match Vocabulary::Section enum
std::vector<std::vector<Embedding>> Sections(4);
- Sections[static_cast<unsigned>(Vocabulary::Section::Opcodes)] =
+ Sections[static_cast<unsigned>(Section::Opcodes)] =
std::move(NumericOpcodeEmbeddings); // Section::Opcodes
- Sections[static_cast<unsigned>(Vocabulary::Section::CanonicalTypes)] =
+ Sections[static_cast<unsigned>(Section::CanonicalTypes)] =
std::move(NumericTypeEmbeddings); // Section::CanonicalTypes
- Sections[static_cast<unsigned>(Vocabulary::Section::Operands)] =
+ Sections[static_cast<unsigned>(Section::Operands)] =
std::move(NumericArgEmbeddings); // Section::Operands
- Sections[static_cast<unsigned>(Vocabulary::Section::Predicates)] =
+ Sections[static_cast<unsigned>(Section::Predicates)] =
std::move(NumericPredEmbeddings); // Section::Predicates
// Create VocabStorage from organized sections
- Vocab.emplace(std::move(Sections));
+ return VocabStorage(std::move(Sections));
}
+// ==----------------------------------------------------------------------===//
+// Vocabulary
+//===----------------------------------------------------------------------===//
+
+Expected<Vocabulary> Vocabulary::fromFile(StringRef VocabFilePath,
+ float OpcWeight, float TypeWeight,
+ float ArgWeight) {
+ VocabMap OpcVocab, TypeVocab, ArgVocab;
+ if (auto Err =
+ readVocabularyFromFile(VocabFilePath, OpcVocab, TypeVocab, ArgVocab))
+ return std::move(Err);
+
+ // Scale the vocabulary sections based on the provided weights
+ auto scaleVocabSection = [](VocabMap &Vocab, float Weight) {
+ for (auto &Entry : Vocab)
+ Entry.second *= Weight;
+ };
+ scaleVocabSection(OpcVocab, OpcWeight);
+ scaleVocabSection(TypeVocab, TypeWeight);
+ scaleVocabSection(ArgVocab, ArgWeight);
+
+ // Generate the numeric lookup vocabulary
+ return Vocabulary(buildVocabStorage(OpcVocab, TypeVocab, ArgVocab));
+}
+
+// ==----------------------------------------------------------------------===//
+// IR2VecVocabAnalysis
+//===----------------------------------------------------------------------===//
+
void IR2VecVocabAnalysis::emitError(Error Err, LLVMContext &Ctx) {
handleAllErrors(std::move(Err), [&](const ErrorInfoBase &EI) {
Ctx.emitError("Error reading vocabulary: " + EI.message());
@@ -615,7 +644,7 @@ IR2VecVocabAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
if (Vocab.has_value())
return Vocabulary(std::move(Vocab.value()));
- // Otherwise, try to read from the vocabulary file.
+ // Otherwise, try to read from the vocabulary file specified via CLI.
if (VocabFile.empty()) {
// FIXME: Use default vocabulary
Ctx->emitError("IR2Vec vocabulary file path not specified; You may need to "
@@ -623,25 +652,15 @@ IR2VecVocabAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
return Vocabulary(); // Return invalid result
}
- VocabMap OpcVocab, TypeVocab, ArgVocab;
- if (auto Err = readVocabulary(OpcVocab, TypeVocab, ArgVocab)) {
- emitError(std::move(Err), *Ctx);
+ // Use the static factory method to load the vocabulary.
+ auto VocabOrErr =
+ Vocabulary::fromFile(VocabFile, OpcWeight, TypeWeight, ArgWeight);
+ if (!VocabOrErr) {
+ emitError(VocabOrErr.takeError(), *Ctx);
return Vocabulary();
}
- // Scale the vocabulary sections based on the provided weights
- auto scaleVocabSection = [](VocabMap &Vocab, double Weight) {
- for (auto &Entry : Vocab)
- Entry.second *= Weight;
- };
- scaleVocabSection(OpcVocab, OpcWeight);
- scaleVocabSection(TypeVocab, TypeWeight);
- scaleVocabSection(ArgVocab, ArgWeight);
-
- // Generate the numeric lookup vocabulary
- generateVocabStorage(OpcVocab, TypeVocab, ArgVocab);
-
- return Vocabulary(std::move(Vocab.value()));
+ return std::move(*VocabOrErr);
}
// ==----------------------------------------------------------------------===//
diff --git a/llvm/unittests/Analysis/IR2VecTest.cpp b/llvm/unittests/Analysis/IR2VecTest.cpp
index 1aa0e423d363a..e085568a135fe 100644
--- a/llvm/unittests/Analysis/IR2VecTest.cpp
+++ b/llvm/unittests/Analysis/IR2VecTest.cpp
@@ -14,7 +14,9 @@
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Error.h"
+#include "llvm/Support/FileSystem.h"
#include "llvm/Support/JSON.h"
+#include "llvm/Support/raw_ostream.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
@@ -979,4 +981,270 @@ TEST(VocabStorageTest, IteratorComparison) {
EXPECT_EQ(it1, it2);
}
+// Helper class for creating temporary vocabulary files for testing
+class VocabFileTest : public ::testing::Test {
+protected:
+ SmallString<128> TempFilePath;
+ int TempFD = -1;
+
+ void SetUp() override { TempFilePath.clear(); }
+
+ void TearDown() override {
+ if (!TempFilePath.empty())
+ sys::fs::remove(TempFilePath);
+ }
+
+ // Create a temporary file with the given content
+ bool createTempFile(StringRef Content) {
+ if (auto EC = sys::fs::createTemporaryFile("vocab", "json", TempFD,
+ TempFilePath)) {
+ return false;
+ }
+ raw_fd_ostream OS(TempFD, /*shouldClose=*/true);
+ OS << Content;
+ return true;
+ }
+
+ // Generate a minimal valid vocabulary JSON with given dimension
+ static std::string generateMinimalVocabJSON(unsigned Dim) {
+ std::string JSON = "{\n \"Opcodes\": {\n";
+
+ // Add all required opcodes
+ const char *Opcodes[] = {"Ret",
+ "Br",
+ "Switch",
+ "IndirectBr",
+ "Invoke",
+ "Resume",
+ "Unreachable",
+ "CleanupRet",
+ "CatchRet",
+ "CatchSwitch",
+ "CallBr",
+ "FNeg",
+ "Add",
+ "FAdd",
+ "Sub",
+ "FSub",
+ "Mul",
+ "FMul",
+ "UDiv",
+ "SDiv",
+ "FDiv",
+ "URem",
+ "SRem",
+ "FRem",
+ "Shl",
+ "LShr",
+ "AShr",
+ "And",
+ "Or",
+ "Xor",
+ "Alloca",
+ "Load",
+ "Store",
+ "GetElementPtr",
+ "Fence",
+ "AtomicCmpXchg",
+ "AtomicRMW",
+ "Trunc",
+ "ZExt",
+ "SExt",
+ "FPToUI",
+ "FPToSI",
+ "UIToFP",
+ "SIToFP",
+ "FPTrunc",
+ "FPExt",
+ "PtrToInt",
+ "IntToPtr",
+ "BitCast",
+ "AddrSpaceCast",
+ "ICmp",
+ "FCmp",
+ "PHI",
+ "Call",
+ "Select",
+ "UserOp1",
+ "UserOp2",
+ "VAArg",
+ "ExtractElement",
+ "InsertElement",
+ "ShuffleVector",
+ "ExtractValue",
+ "InsertValue",
+ "LandingPad",
+ "Freeze",
+ "PtrToAddr",
+ "AddrToPtr",
+ "CleanupPad",
+ "CatchPad"};
+
+ bool First = true;
+ for (const char *Op : Opcodes) {
+ if (!First)
+ JSON += ",\n";
+ First = false;
+ JSON += " \"";
+ JSON += Op;
+ JSON += "\": [";
+ for (unsigned I = 0; I < Dim; ++I) {
+ if (I > 0)
+ JSON += ", ";
+ JSON += "1.0";
+ }
+ JSON += "]";
+ }
+
+ JSON += "\n },\n \"Types\": {\n";
+
+ // Add all required types
+ const char *Types[] = {"VoidTy", "FloatTy", "LabelTy", "MetadataTy",
+ "VectorTy", "TokenTy", "IntegerTy", "FunctionTy",
+ "PointerTy", "StructTy", "ArrayTy", "UnknownTy"};
+
+ First = true;
+ for (const char *Ty : Types) {
+ if (!First)
+ JSON += ",\n";
+ First = false;
+ JSON += " \"";
+ JSON += Ty;
+ JSON += "\": [";
+ for (unsigned I = 0; I < Dim; ++I) {
+ if (I > 0)
+ JSON += ", ";
+ JSON += "0.5";
+ }
+ JSON += "]";
+ }
+
+ JSON += "\n },\n \"Arguments\": {\n";
+
+ // Add all required argument types
+ const char *Args[] = {"Function", "Pointer", "Constant", "Variable"};
+
+ First = true;
+ for (const char *Arg : Args) {
+ if (!First)
+ JSON += ",\n";
+ First = false;
+ JSON += " \"";
+ JSON += Arg;
+ JSON += "\": [";
+ for (unsigned I = 0; I < Dim; ++I) {
+ if (I > 0)
+ JSON += ", ";
+ JSON += "0.2";
+ }
+ JSON += "]";
+ }
+
+ JSON += "\n }\n}\n";
+ return JSON;
+ }
+};
+
+TEST_F(VocabFileTest, FromFileSuccess) {
+ std::string VocabJSON = generateMinimalVocabJSON(3);
+ ASSERT_TRUE(createTempFile(VocabJSON));
+
+ auto VocabOrErr = Vocabulary::fromFile(TempFilePath);
+ ASSERT_TRUE(static_cast<bool>(VocabOrErr))
+ << "Failed to load vocabulary: " << toString(VocabOrErr.takeError());
+
+ Vocabulary &V = *VocabOrErr;
+ EXPECT_TRUE(V.isValid());
+ EXPECT_EQ(V.getDimension(), 3u);
+}
+
+TEST_F(VocabFileTest, FromFileNonExistent) {
+ auto VocabOrErr = Vocabulary::fromFile("/nonexistent/path/vocab.json");
+ EXPECT_FALSE(static_cast<bool>(VocabOrErr));
+
+ // Consume the error
+ std::string ErrMsg = toString(VocabOrErr.takeError());
+ EXPECT_FALSE(ErrMsg.empty());
+}
+
+TEST_F(VocabFileTest, FromFileInvalidJSON) {
+ ASSERT_TRUE(createTempFile("{ invalid json }"));
+
+ auto VocabOrErr = Vocabulary::fromFile(TempFilePath);
+ EXPECT_FALSE(static_cast<bool>(VocabOrErr));
+
+ std::string ErrMsg = toString(VocabOrErr.takeError());
+ EXPECT_FALSE(ErrMsg.empty());
+}
+
+TEST_F(VocabFileTest, FromFileMissingSections) {
+ // JSON with only Opcodes section, missing Types and Arguments
+ ASSERT_TRUE(createTempFile(R"({
+ "Opcodes": { "Ret": [1.0, 2.0] }
+ })"));
+
+ auto VocabOrErr = Vocabulary::fromFile(TempFilePath);
+ EXPECT_FALSE(static_cast<bool>(VocabOrErr));
+
+ std::string ErrMsg = toString(VocabOrErr.takeError());
+ EXPECT_FALSE(ErrMsg.empty());
+}
+
+TEST_F(VocabFileTest, FromFileWithWeights) {
+ std::string VocabJSON = generateMinimalVocabJSON(2);
+ ASSERT_TRUE(createTempFile(VocabJSON));
+
+ // Load with custom weights
+ float OpcWeight = 2.0f;
+ float TypeWeight = 1.0f;
+ float ArgWeight = 0.5f;
+
+ auto VocabOrErr =
+ Vocabulary::fromFile(TempFilePath, OpcWeight, TypeWeight, ArgWeight);
+ ASSERT_TRUE(static_cast<bool>(VocabOrErr))
+ << "Failed to load vocabulary: " << toString(VocabOrErr.takeError());
+
+ Vocabulary &V = *VocabOrErr;
+ EXPECT_TRUE(V.isValid());
+ EXPECT_EQ(V.getDimension(), 2u);
+
+ // Verify that weights are applied by checking embedding values
+ // Original opcode values are [1.0, 1.0], with weight 2.0 -> [2.0, 2.0]
+ const Embedding &RetEmb = V[Instruction::Ret];
+ EXPECT_TRUE(RetEmb.approximatelyEquals(Embedding(2, 2.0)));
+
+ // Original type values are [0.5, 0.5], with weight 1.0 -> [0.5, 0.5]
+ const Embedding &IntTyEmb = V[Type::IntegerTyID];
+ EXPECT_TRUE(IntTyEmb.approximatelyEquals(Embedding(2, 0.5)));
+}
+
+TEST_F(VocabFileTest, FromFileDefaultWeights) {
+ std::string VocabJSON = generateMinimalVocabJSON(2);
+ ASSERT_TRUE(createTempFile(VocabJSON));
+
+ // Load with default weights (1.0, 0.5, 0.2)
+ auto VocabOrErr = Vocabulary::fromFile(TempFilePath);
+ ASSERT_TRUE(static_cast<bool>(VocabOrErr))
+ << "Failed to load vocabulary: " << toString(VocabOrErr.takeError());
+
+ Vocabulary &V = *VocabOrErr;
+ EXPECT_TRUE(V.isValid());
+
+ // Original opcode values are [1.0, 1.0], with default weight 1.0 ->
+ // [1.0, 1.0]
+ const Embedding &RetEmb = V[Instruction::Ret];
+ EXPECT_TRUE(RetEmb.approximatelyEquals(Embedding(2, 1.0)));
+
+ // Original type values are [0.5, 0.5], with default weight 0.5 -> [0.25,
+ // 0.25]
+ const Embedding &IntTyEmb = V[Type::IntegerTyID];
+ EXPECT_TRUE(IntTyEmb.approximatelyEquals(Embedding(2, 0.25)));
+
+ // Original arg values are [0.2, 0.2], with default weight 0.2 -> [0.04, 0.04]
+ LLVMContext Ctx;
+ Constant *C = ConstantInt::get(Type::getInt32Ty(Ctx), 42);
+ const Embedding &ConstEmb = V[*C];
+ EXPECT_TRUE(ConstEmb.approximatelyEquals(Embedding(2, 0.04)));
+}
+
} // end anonymous namespace
>From cfc8077573982ea844af62d2d11798e2aeff242f Mon Sep 17 00:00:00 2001
From: nishant_sachdeva <nishant.sachdeva at research.iiit.ac.in>
Date: Thu, 22 Jan 2026 19:07:42 +0530
Subject: [PATCH 2/2] Modifying llvm-ir2vec vocab reading pipeline to use
Vocabulary::fromFile instead of a full pass invocation
---
llvm/include/llvm/Analysis/IR2Vec.h | 1 +
llvm/lib/Analysis/IR2Vec.cpp | 2 +-
llvm/tools/llvm-ir2vec/lib/Utils.cpp | 18 ++++++++++--------
llvm/tools/llvm-ir2vec/lib/Utils.h | 4 ++--
llvm/tools/llvm-ir2vec/llvm-ir2vec.cpp | 8 +++++++-
5 files changed, 21 insertions(+), 12 deletions(-)
diff --git a/llvm/include/llvm/Analysis/IR2Vec.h b/llvm/include/llvm/Analysis/IR2Vec.h
index 2bf1c2adc0d4f..a7f88d9efdc3d 100644
--- a/llvm/include/llvm/Analysis/IR2Vec.h
+++ b/llvm/include/llvm/Analysis/IR2Vec.h
@@ -77,6 +77,7 @@ LLVM_ABI extern cl::opt<float> OpcWeight;
LLVM_ABI extern cl::opt<float> TypeWeight;
LLVM_ABI extern cl::opt<float> ArgWeight;
LLVM_ABI extern cl::opt<IR2VecKind> IR2VecEmbeddingKind;
+LLVM_ABI extern cl::opt<std::string> VocabFile;
/// Embedding is a datatype that wraps std::vector<double>. It provides
/// additional functionality for arithmetic and comparison operations.
diff --git a/llvm/lib/Analysis/IR2Vec.cpp b/llvm/lib/Analysis/IR2Vec.cpp
index 4c187fe9ce804..c421926d12ab1 100644
--- a/llvm/lib/Analysis/IR2Vec.cpp
+++ b/llvm/lib/Analysis/IR2Vec.cpp
@@ -40,7 +40,7 @@ namespace ir2vec {
cl::OptionCategory IR2VecCategory("IR2Vec Options");
// FIXME: Use a default vocab when not specified
-static cl::opt<std::string>
+cl::opt<std::string>
VocabFile("ir2vec-vocab-path", cl::Optional,
cl::desc("Path to the vocabulary file for IR2Vec"), cl::init(""),
cl::cat(IR2VecCategory));
diff --git a/llvm/tools/llvm-ir2vec/lib/Utils.cpp b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
index a655ae069f642..c7c10ee1ff43f 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.cpp
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.cpp
@@ -41,14 +41,16 @@ namespace llvm {
namespace ir2vec {
-bool IR2VecTool::initializeVocabulary() {
- // Register and run the IR2Vec vocabulary analysis
- // The vocabulary file path is specified via --ir2vec-vocab-path global
- // option
- MAM.registerPass([&] { return PassInstrumentationAnalysis(); });
- MAM.registerPass([&] { return IR2VecVocabAnalysis(); });
- // This will throw an error if vocab is not found or invalid
- Vocab = &MAM.getResult<IR2VecVocabAnalysis>(M);
+bool IR2VecTool::initializeVocabulary(StringRef VocabPath) {
+ auto VocabOrErr = Vocabulary::fromFile(VocabPath);
+
+ if (!VocabOrErr) {
+ llvm::errs() << "Failed to load vocabulary: "
+ << toString(VocabOrErr.takeError()) << "\n";
+ return false;
+ }
+
+ Vocab = std::make_unique<Vocabulary>(std::move(*VocabOrErr));
return Vocab->isValid();
}
diff --git a/llvm/tools/llvm-ir2vec/lib/Utils.h b/llvm/tools/llvm-ir2vec/lib/Utils.h
index 34474b7808463..29e8ce4f1c0ad 100644
--- a/llvm/tools/llvm-ir2vec/lib/Utils.h
+++ b/llvm/tools/llvm-ir2vec/lib/Utils.h
@@ -87,13 +87,13 @@ class IR2VecTool {
private:
Module &M;
ModuleAnalysisManager MAM;
- const Vocabulary *Vocab = nullptr;
+ std::unique_ptr<Vocabulary> Vocab;
public:
explicit IR2VecTool(Module &M) : M(M) {}
/// Initialize the IR2Vec vocabulary analysis
- bool initializeVocabulary();
+ bool initializeVocabulary(StringRef VocabPath);
/// Generate triplets for a single function
/// Returns a TripletResult with:
diff --git a/llvm/tools/llvm-ir2vec/llvm-ir2vec.cpp b/llvm/tools/llvm-ir2vec/llvm-ir2vec.cpp
index d240e7c6e5201..56a5183ad7850 100644
--- a/llvm/tools/llvm-ir2vec/llvm-ir2vec.cpp
+++ b/llvm/tools/llvm-ir2vec/llvm-ir2vec.cpp
@@ -153,7 +153,13 @@ static Error processModule(Module &M, raw_ostream &OS) {
if (EmbeddingsSubCmd) {
// Initialize vocabulary for embedding generation
// Note: Requires --ir2vec-vocab-path option to be set
- auto VocabStatus = Tool.initializeVocabulary();
+ // and this value will be populated in the var VocabFile
+ if (VocabFile.empty()) {
+ return createStringError(errc::invalid_argument,
+ "IR2Vec vocabulary file path not specified; "
+ "You may need to set it using --ir2vec-vocab-path");
+ }
+ auto VocabStatus = Tool.initializeVocabulary(VocabFile);
assert(VocabStatus && "Failed to initialize IR2Vec vocabulary");
(void)VocabStatus;
More information about the llvm-commits
mailing list