LLVM 24.0.0git
MIR2Vec.cpp
Go to the documentation of this file.
1//===- MIR2Vec.cpp - Implementation of MIR2Vec ---------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM
4// Exceptions. See the LICENSE file for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements the MIR2Vec algorithm for Machine IR embeddings.
11///
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/Statistic.h"
19#include "llvm/IR/Module.h"
21#include "llvm/Pass.h"
22#include "llvm/Support/Errc.h"
24#include "llvm/Support/Regex.h"
26#include <array>
27
28using namespace llvm;
29using namespace mir2vec;
30
31#define DEBUG_TYPE "mir2vec"
32
33STATISTIC(MIRVocabMissCounter,
34 "Number of lookups to MIR entities not present in the vocabulary");
35STATISTIC(MIRClasslessRegCounter,
36 "Number of register operands with no register class");
37
38namespace llvm {
39namespace mir2vec {
41
42// FIXME: Use a default vocab when not specified
44 VocabFile("mir2vec-vocab-path",
45 cl::desc("Path to the vocabulary file for MIR2Vec"), cl::init(""),
47static cl::opt<float>
48 OpcWeight("mir2vec-opc-weight", cl::init(1.0),
49 cl::desc("Weight for machine opcode embeddings"),
51static cl::opt<float>
52 CommonOperandWeight("mir2vec-common-operand-weight", cl::init(1.0),
53 cl::desc("Weight for common operand embeddings"),
55static cl::opt<float>
56 RegOperandWeight("mir2vec-reg-operand-weight", cl::init(1.0),
57 cl::desc("Weight for register operand embeddings"),
60 "mir2vec-kind",
62 "Generate symbolic embeddings for MIR")),
63 cl::init(MIR2VecKind::Symbolic), cl::desc("MIR2Vec embedding kind"),
65
67 "mir2vec-print-all-vocab-entries", cl::init(false),
68 cl::desc("Print all vocabulary entries including zero embeddings"),
70
71} // namespace mir2vec
72} // namespace llvm
73
74//===----------------------------------------------------------------------===//
75// Vocabulary
76//===----------------------------------------------------------------------===//
77
78MIRVocabulary::MIRVocabulary(VocabMap &&OpcodeMap, VocabMap &&CommonOperandMap,
79 VocabMap &&PhysicalRegisterMap,
80 VocabMap &&VirtualRegisterMap,
81 const TargetInstrInfo &TII,
83 : TII(TII), TRI(TRI) {
84 buildCanonicalOpcodeMapping();
85 unsigned CanonicalOpcodeCount = UniqueBaseOpcodeNames.size();
86 assert(CanonicalOpcodeCount > 0 &&
87 "No canonical opcodes found for target - invalid vocabulary");
88
89 buildRegisterOperandMapping();
90
91 // Define layout of vocabulary sections
92 Layout.OpcodeBase = 0;
93 Layout.CommonOperandBase = CanonicalOpcodeCount;
94 // We expect same classes for physical and virtual registers
95 Layout.PhyRegBase = Layout.CommonOperandBase + std::size(CommonOperands);
96 Layout.VirtRegBase = Layout.PhyRegBase + RegisterOperandNames.size();
97
98 generateStorage(OpcodeMap, CommonOperandMap, PhysicalRegisterMap,
99 VirtualRegisterMap);
100 Layout.TotalEntries = Storage.size();
101}
102
104 VocabMap &&CommonOperandMap,
105 VocabMap &&PhyRegMap,
106 VocabMap &&VirtRegMap,
107 const TargetInstrInfo &TII,
108 const TargetRegisterInfo &TRI) {
109 if (OpcodeMap.empty() || CommonOperandMap.empty() || PhyRegMap.empty() ||
110 VirtRegMap.empty())
112 "Empty vocabulary entries provided");
113
114 MIRVocabulary Vocab(std::move(OpcodeMap), std::move(CommonOperandMap),
115 std::move(PhyRegMap), std::move(VirtRegMap), TII, TRI);
116
117 // Validate Storage after construction
118 if (!Vocab.Storage.isValid())
120 "Failed to create valid vocabulary storage");
121 Vocab.ZeroEmbedding = Embedding(Vocab.Storage.getDimension(), 0.0);
122 return std::move(Vocab);
123}
124
126 // Extract base instruction name using regex to capture letters and
127 // underscores Examples: "ADD32rr" -> "ADD", "ARITH_FENCE" -> "ARITH_FENCE"
128 //
129 // TODO: Consider more sophisticated extraction:
130 // - Handle complex prefixes like "AVX1_SETALLONES" correctly (Currently, it
131 // would naively map to "AVX")
132 // - Extract width suffixes (8,16,32,64) as separate features
133 // - Capture addressing mode suffixes (r,i,m,ri,etc.) for better analysis
134 // (Currently, instances like "MOV32mi" map to "MOV", but "ADDPDrr" would map
135 // to "ADDPDrr")
136
137 assert(!InstrName.empty() && "Instruction name should not be empty");
138
139 // Use regex to extract initial sequence of letters and underscores
140 static const Regex BaseOpcodeRegex("([a-zA-Z_]+)");
142
143 if (BaseOpcodeRegex.match(InstrName, &Matches) && Matches.size() > 1) {
144 StringRef Match = Matches[1];
145 // Trim trailing underscores
146 while (!Match.empty() && Match.back() == '_')
147 Match = Match.drop_back();
148 return Match.str();
149 }
150
151 // Fallback to original name if no pattern matches
152 return InstrName.str();
153}
154
156 assert(!UniqueBaseOpcodeNames.empty() && "Canonical mapping not built");
157 auto It = llvm::lower_bound(UniqueBaseOpcodeNames, BaseName);
158 assert(It != UniqueBaseOpcodeNames.end() && *It == BaseName &&
159 "Base name not found in unique opcodes");
160 return std::distance(UniqueBaseOpcodeNames.begin(), It);
161}
162
163unsigned MIRVocabulary::getCanonicalOpcodeIndex(unsigned Opcode) const {
164 assert(Opcode < OpcodeToCanonicalIndex.size() && "Opcode out of bounds");
165 return OpcodeToCanonicalIndex[Opcode];
166}
167
168unsigned
170 auto It = llvm::find_if(CommonOperands, [&](const CommonOperandEntry &E) {
171 return E.Name == OperandName;
172 });
173 assert(It != std::end(CommonOperands) &&
174 "Operand name not found in common operands");
175 return Layout.CommonOperandBase +
176 std::distance(std::begin(CommonOperands), It);
177}
178
179unsigned
181 bool IsPhysical) const {
182 auto It = std::find(RegisterOperandNames.begin(), RegisterOperandNames.end(),
183 RegName);
184 assert(It != RegisterOperandNames.end() &&
185 "Register name not found in register operands");
186 unsigned LocalIndex = std::distance(RegisterOperandNames.begin(), It);
187 return (IsPhysical ? Layout.PhyRegBase : Layout.VirtRegBase) + LocalIndex;
188}
189
190std::string MIRVocabulary::getStringKey(unsigned Pos) const {
191 assert(Pos < Layout.TotalEntries && "Position out of bounds in vocabulary");
192
193 // Handle opcodes section
194 if (Pos < Layout.CommonOperandBase) {
195 // Convert canonical index back to base opcode name
196 assert(Pos < UniqueBaseOpcodeNames.size() &&
197 "Canonical index out of bounds in opcode section");
198 return UniqueBaseOpcodeNames[Pos];
199 }
200
201 auto getLocalIndex = [](unsigned Pos, size_t BaseOffset, size_t Bound,
202 const char *Msg) {
203 unsigned LocalIndex = Pos - BaseOffset;
204 assert(LocalIndex < Bound && Msg);
205 return LocalIndex;
206 };
207
208 // Handle common operands section
209 if (Pos < Layout.PhyRegBase) {
210 unsigned LocalIndex =
211 getLocalIndex(Pos, Layout.CommonOperandBase, std::size(CommonOperands),
212 "Local index out of bounds in common operands");
213 return CommonOperands[LocalIndex].Name.str();
214 }
215
216 // Handle physical registers section
217 if (Pos < Layout.VirtRegBase) {
218 unsigned LocalIndex =
219 getLocalIndex(Pos, Layout.PhyRegBase, RegisterOperandNames.size(),
220 "Local index out of bounds in physical registers");
221 return "PhyReg_" + RegisterOperandNames[LocalIndex];
222 }
223
224 // Handle virtual registers section
225 unsigned LocalIndex =
226 getLocalIndex(Pos, Layout.VirtRegBase, RegisterOperandNames.size(),
227 "Local index out of bounds in virtual registers");
228 return "VirtReg_" + RegisterOperandNames[LocalIndex];
229}
230
231void MIRVocabulary::generateStorage(const VocabMap &OpcodeMap,
232 const VocabMap &CommonOperandsMap,
233 const VocabMap &PhyRegMap,
234 const VocabMap &VirtRegMap) {
235
236 // Helper for handling missing entities in the vocabulary.
237 // Currently, we use a zero vector. In the future, we will throw an error to
238 // ensure that *all* known entities are present in the vocabulary.
239 auto handleMissingEntity = [](StringRef Key) {
240 LLVM_DEBUG(errs() << "MIR2Vec: Missing vocabulary entry for " << Key
241 << "; using zero vector. This will result in an error "
242 "in the future.\n");
243 ++MIRVocabMissCounter;
244 };
245
246 // Initialize opcode embeddings section
247 unsigned EmbeddingDim = OpcodeMap.begin()->second.size();
248 std::vector<Embedding> OpcodeEmbeddings(Layout.CommonOperandBase,
249 Embedding(EmbeddingDim));
250
251 // Populate opcode embeddings using canonical mapping
252 for (auto COpcodeName : UniqueBaseOpcodeNames) {
253 if (auto It = OpcodeMap.find(COpcodeName); It != OpcodeMap.end()) {
254 auto COpcodeIndex = getCanonicalIndexForBaseName(COpcodeName);
255 assert(COpcodeIndex < Layout.CommonOperandBase &&
256 "Canonical index out of bounds");
257 OpcodeEmbeddings[COpcodeIndex] = It->second;
258 } else {
259 handleMissingEntity(COpcodeName);
260 }
261 }
262
263 // Initialize common operand embeddings section
264 std::vector<Embedding> CommonOperandEmbeddings(std::size(CommonOperands),
265 Embedding(EmbeddingDim));
266 unsigned OperandIndex = 0;
267 for (const CommonOperandEntry &Entry : CommonOperands) {
268 if (auto It = CommonOperandsMap.find(Entry.Name.str());
269 It != CommonOperandsMap.end()) {
270 CommonOperandEmbeddings[OperandIndex] = It->second;
271 } else {
272 handleMissingEntity(Entry.Name);
273 }
274 ++OperandIndex;
275 }
276
277 // Helper lambda for creating register operand embeddings
278 auto createRegisterEmbeddings = [&](const VocabMap &RegMap) {
279 std::vector<Embedding> RegEmbeddings(RegisterOperandNames.size(),
280 Embedding(EmbeddingDim));
281 unsigned RegOperandIndex = 0;
282 for (const auto &RegOperandName : RegisterOperandNames) {
283 if (auto It = RegMap.find(RegOperandName); It != RegMap.end())
284 RegEmbeddings[RegOperandIndex] = It->second;
285 else
286 handleMissingEntity(RegOperandName);
287 ++RegOperandIndex;
288 }
289 return RegEmbeddings;
290 };
291
292 // Initialize register operand embeddings sections
293 std::vector<Embedding> PhyRegEmbeddings = createRegisterEmbeddings(PhyRegMap);
294 std::vector<Embedding> VirtRegEmbeddings =
295 createRegisterEmbeddings(VirtRegMap);
296
297 // Scale the vocabulary sections based on the provided weights
298 auto scaleVocabSection = [](std::vector<Embedding> &Embeddings,
299 double Weight) {
300 for (auto &Embedding : Embeddings)
301 Embedding *= Weight;
302 };
303 scaleVocabSection(OpcodeEmbeddings, OpcWeight);
304 scaleVocabSection(CommonOperandEmbeddings, CommonOperandWeight);
305 scaleVocabSection(PhyRegEmbeddings, RegOperandWeight);
306 scaleVocabSection(VirtRegEmbeddings, RegOperandWeight);
307
308 std::vector<std::vector<Embedding>> Sections(
309 static_cast<unsigned>(Section::MaxSections));
310 Sections[static_cast<unsigned>(Section::Opcodes)] =
311 std::move(OpcodeEmbeddings);
312 Sections[static_cast<unsigned>(Section::CommonOperands)] =
313 std::move(CommonOperandEmbeddings);
314 Sections[static_cast<unsigned>(Section::PhyRegisters)] =
315 std::move(PhyRegEmbeddings);
316 Sections[static_cast<unsigned>(Section::VirtRegisters)] =
317 std::move(VirtRegEmbeddings);
318
319 Storage = ir2vec::VocabStorage(std::move(Sections));
320}
321
322void MIRVocabulary::buildCanonicalOpcodeMapping() {
323 // Check if already built
324 if (!UniqueBaseOpcodeNames.empty())
325 return;
326
327 // Build mapping from opcodes to canonical base opcode indices
328 unsigned NumOpcodes = TII.getNumOpcodes();
329 SmallVector<std::string, 0> BaseOpcodes;
330 BaseOpcodes.reserve(NumOpcodes);
331 for (unsigned Opcode = 0; Opcode < NumOpcodes; ++Opcode)
332 BaseOpcodes.push_back(extractBaseOpcodeName(TII.getName(Opcode)));
333
334 UniqueBaseOpcodeNames = BaseOpcodes;
335 llvm::sort(UniqueBaseOpcodeNames);
336 UniqueBaseOpcodeNames.erase(llvm::unique(UniqueBaseOpcodeNames),
337 UniqueBaseOpcodeNames.end());
338
339 OpcodeToCanonicalIndex.reserve(NumOpcodes);
340 for (const std::string &BaseOpcode : BaseOpcodes)
341 OpcodeToCanonicalIndex.push_back(getCanonicalIndexForBaseName(BaseOpcode));
342
343 LLVM_DEBUG(dbgs() << "MIR2Vec: Built canonical mapping for target with "
344 << UniqueBaseOpcodeNames.size()
345 << " unique base opcodes\n");
346}
347
348void MIRVocabulary::buildRegisterOperandMapping() {
349 // Check if already built
350 if (!RegisterOperandNames.empty())
351 return;
352
353 for (unsigned RC = 0; RC < TRI.getNumRegClasses(); ++RC) {
354 const TargetRegisterClass *RegClass = TRI.getRegClass(RC);
355 if (!RegClass)
356 continue;
357
358 // Get the register class name
359 StringRef ClassName = TRI.getRegClassName(RegClass);
360 RegisterOperandNames.push_back(ClassName.str());
361 }
362 assert(RegisterOperandNames.size() == TRI.getNumRegClasses() &&
363 "Register operand names must be indexed by register class ID");
364 assert(!is_contained(RegisterOperandNames, NoRegClassName) &&
365 "Register class name collides with NoRegClass");
366 RegisterOperandNames.push_back(NoRegClassName.str());
367}
368
369std::optional<unsigned> MIRVocabulary::getCommonOperandIndex(
370 MachineOperand::MachineOperandType OperandType) const {
371 assert(OperandType != MachineOperand::MO_Register &&
372 "Expected non-register operand type");
373 assert(OperandType <= MachineOperand::MO_Last &&
374 "Operand type out of bounds");
375 static constexpr unsigned InvalidIndex = ~0u;
376 static constexpr auto OperandTypeToIndex = [] {
377 std::array<unsigned, MachineOperand::MO_Last + 1> Map{};
378 for (unsigned &I : Map)
379 I = InvalidIndex;
380 for (unsigned I = 0; I < std::size(CommonOperands); ++I)
381 Map[CommonOperands[I].Type] = I;
382 return Map;
383 }();
384 unsigned Index = OperandTypeToIndex[OperandType];
385 if (Index == InvalidIndex)
386 return std::nullopt;
387 return Index;
388}
389
390unsigned
391MIRVocabulary::getRegisterOperandIndex(Register Reg,
392 const MachineRegisterInfo &MRI) const {
393 assert(!RegisterOperandNames.empty() && "Register operand mapping not built");
394 assert(Reg.isValid() && "Invalid register; not expected here");
395 assert((Reg.isPhysical() || Reg.isVirtual()) &&
396 "Expected a physical or virtual register");
397
398 const TargetRegisterClass *RegClass = nullptr;
399
400 // For physical registers, use TRI to get minimal register class as a
401 // physical register can belong to multiple classes. For virtual
402 // registers, use MRI to uniquely identify the assigned register class.
403 if (Reg.isPhysical())
404 RegClass = TRI.getMinimalPhysRegClass(Reg);
405 else
406 RegClass = MRI.getRegClassOrNull(Reg);
407
408 // Not every register belongs to a register class. This can happen for
409 // physical registers, e.g. X86's $mxcsr and $fpcw or AMDGPU's $mode, for
410 // which getMinimalPhysRegClass() returns nullptr. It can also happen for
411 // generic virtual registers that have not yet been through (or completed)
412 // GlobalISel's register bank selection, and thus carry an LLT or a
413 // RegisterBank instead of a TargetRegisterClass, for which
414 // getRegClassOrNull() returns nullptr.
415 // TODO: Key generic vregs on their LLT or RegisterBank instead.
416 if (!RegClass) {
417 LLVM_DEBUG(errs() << "MIR2Vec: No register class for register " << Reg.id()
418 << ", using NoRegClass.\n");
419 ++MIRClasslessRegCounter;
420 return RegisterOperandNames.size() - 1;
421 }
422
423 return RegClass->getID();
424}
425
427 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, unsigned Dim) {
428 assert(Dim > 0 && "Dimension must be greater than zero");
429
430 float DummyVal = 0.1f;
431
432 VocabMap DummyOpcMap, DummyOperandMap, DummyPhyRegMap, DummyVirtRegMap;
433
434 // Process opcodes directly without creating temporary vocabulary
435 for (unsigned Opcode = 0; Opcode < TII.getNumOpcodes(); ++Opcode) {
436 std::string BaseOpcode = extractBaseOpcodeName(TII.getName(Opcode));
437 if (DummyOpcMap.count(BaseOpcode) == 0) { // Only add if not already present
438 DummyOpcMap[BaseOpcode] = Embedding(Dim, DummyVal);
439 DummyVal += 0.1f;
440 }
441 }
442
443 // Add common operands
444 for (const CommonOperandEntry &Entry : CommonOperands) {
445 DummyOperandMap[Entry.Name.str()] = Embedding(Dim, DummyVal);
446 DummyVal += 0.1f;
447 }
448
449 // Process register classes directly
450 for (unsigned RC = 0; RC < TRI.getNumRegClasses(); ++RC) {
451 const TargetRegisterClass *RegClass = TRI.getRegClass(RC);
452 if (!RegClass)
453 continue;
454
455 std::string ClassName = TRI.getRegClassName(RegClass);
456 DummyPhyRegMap[ClassName] = Embedding(Dim, DummyVal);
457 DummyVirtRegMap[ClassName] = Embedding(Dim, DummyVal);
458 DummyVal += 0.1f;
459 }
460 DummyPhyRegMap[NoRegClassName.str()] = Embedding(Dim, DummyVal);
461 DummyVirtRegMap[NoRegClassName.str()] = Embedding(Dim, DummyVal);
462
463 // Create vocabulary directly without temporary instance
465 std::move(DummyOpcMap), std::move(DummyOperandMap),
466 std::move(DummyPhyRegMap), std::move(DummyVirtRegMap), TII, TRI);
467}
468
469//===----------------------------------------------------------------------===//
470// MIR2VecVocabProvider and MIR2VecVocabLegacyAnalysis
471//===----------------------------------------------------------------------===//
472
473using VocabMap = std::map<std::string, Embedding>;
474
475static Error readVocabulary(VocabMap &OpcodeVocab, VocabMap &CommonOperandVocab,
476 VocabMap &PhyRegVocabMap,
477 VocabMap &VirtRegVocabMap) {
478 if (VocabFile.empty())
479 return createStringError(
481 "MIR2Vec vocabulary file path not specified; set it "
482 "using --mir2vec-vocab-path");
483
484 auto BufOrError = MemoryBuffer::getFileOrSTDIN(VocabFile, /*IsText=*/true);
485 if (!BufOrError)
486 return createFileError(VocabFile, BufOrError.getError());
487
488 auto Content = BufOrError.get()->getBuffer();
489
490 Expected<json::Value> ParsedVocabValue = json::parse(Content);
491 if (!ParsedVocabValue)
492 return ParsedVocabValue.takeError();
493
494 unsigned OpcodeDim = 0, CommonOperandDim = 0, PhyRegOperandDim = 0,
495 VirtRegOperandDim = 0;
497 "Opcodes", *ParsedVocabValue, OpcodeVocab, OpcodeDim))
498 return Err;
499
501 "CommonOperands", *ParsedVocabValue, CommonOperandVocab,
502 CommonOperandDim))
503 return Err;
504
506 "PhysicalRegisters", *ParsedVocabValue, PhyRegVocabMap,
507 PhyRegOperandDim))
508 return Err;
509
511 "VirtualRegisters", *ParsedVocabValue, VirtRegVocabMap,
512 VirtRegOperandDim))
513 return Err;
514
515 // All sections must have the same embedding dimension
516 if (!(OpcodeDim == CommonOperandDim && CommonOperandDim == PhyRegOperandDim &&
517 PhyRegOperandDim == VirtRegOperandDim)) {
518 return createStringError(
520 "MIR2Vec vocabulary sections have different dimensions");
521 }
522
523 return Error::success();
524}
525
528 VocabMap OpcVocab, CommonOperandVocab, PhyRegVocabMap, VirtRegVocabMap;
529
530 if (Error Err = readVocabulary(OpcVocab, CommonOperandVocab, PhyRegVocabMap,
531 VirtRegVocabMap))
532 return std::move(Err);
533
535 std::move(OpcVocab), std::move(CommonOperandVocab),
536 std::move(PhyRegVocabMap), std::move(VirtRegVocabMap), *ST.getInstrInfo(),
537 *ST.getRegisterInfo());
538}
539
542 auto Defs = M.getFunctionDefs();
543 if (Defs.empty())
545 "No function definitions found in module");
546 return buildVocabulary(*MMI.getTarget().getSubtargetImpl(*Defs.begin()));
547}
548
551 "MIR2Vec Vocabulary Analysis", false, true)
554 "MIR2Vec Vocabulary Analysis", false, true)
555
556StringRef MIR2VecVocabLegacyAnalysis::getPassName() const {
557 return "MIR2Vec Vocabulary Analysis";
558}
559
560AnalysisKey MIR2VecVocabAnalysis::Key;
561
563 ModuleAnalysisManager::Invalidator &Inv) const {
564 return !PA.getChecker<MIR2VecVocabAnalysis>().preservedWhenStateless();
565}
566
569 auto VocabOrErr =
570 MIR2VecVocabProvider(MAM.getResult<MachineModuleAnalysis>(M).getMMI())
571 .getVocabulary(M);
572 if (!VocabOrErr)
573 reportFatalUsageError(VocabOrErr.takeError());
574 return std::move(*VocabOrErr);
575}
576
577//===----------------------------------------------------------------------===//
578// MIREmbedder and its subclasses
579//===----------------------------------------------------------------------===//
580
581std::unique_ptr<MIREmbedder> MIREmbedder::create(MIR2VecKind Mode,
582 const MachineFunction &MF,
583 const MIRVocabulary &Vocab) {
584 switch (Mode) {
586 return std::make_unique<SymbolicMIREmbedder>(MF, Vocab);
587 }
588 return nullptr;
589}
590
596
599
600 // Get instruction info for opcode name resolution
601 const auto &Subtarget = MF.getSubtarget();
602 const auto *TII = Subtarget.getInstrInfo();
603 if (!TII) {
604 MF.getFunction().getContext().emitError(
605 "MIR2Vec: No TargetInstrInfo available; cannot compute embeddings");
606 return MBBVector;
607 }
608
609 // Process each machine instruction in the basic block
610 for (const auto &MI : MBB) {
611 // Skip debug instructions and other metadata
612 if (MI.isDebugInstr())
613 continue;
615 }
616
617 return MBBVector;
618}
619
621 Embedding MFuncVector(Dimension, 0);
622
623 if (MF.empty())
624 return MFuncVector;
625
626 // Consider all reachable machine basic blocks in the function
627 for (const auto *MBB : depth_first(&MF))
628 MFuncVector += computeEmbeddings(*MBB);
629 return MFuncVector;
630}
631
635
636std::unique_ptr<SymbolicMIREmbedder>
638 const MIRVocabulary &Vocab) {
639 return std::make_unique<SymbolicMIREmbedder>(MF, Vocab);
640}
641
643 // Skip debug instructions and other metadata
644 if (MI.isDebugInstr())
645 return Embedding(Dimension, 0);
646
647 // Opcode embedding
648 Embedding InstructionEmbedding = Vocab[MI.getOpcode()];
649
650 // Add operand contributions
651 for (const MachineOperand &MO : MI.operands())
652 InstructionEmbedding += Vocab.getOperandEmbedding(MO, MF.getRegInfo());
653
654 return InstructionEmbedding;
655}
656
657//===----------------------------------------------------------------------===//
658// Printer Passes
659//===----------------------------------------------------------------------===//
660
663 "MIR2Vec Vocabulary Printer Pass", false, true)
667 "MIR2Vec Vocabulary Printer Pass", false, true)
668
669static void printVocabulary(const mir2vec::MIRVocabulary &MIR2VecVocab,
670 raw_ostream &OS) {
671 unsigned Pos = 0;
672 for (const auto &Entry : MIR2VecVocab) {
673 // Skip zero embeddings to avoid printing entries not in the vocabulary.
674 // This makes the output stable across changes to the opcode list.
675 if (PrintAllVocabEntries || !Entry.isZero()) {
676 OS << "Key: " << MIR2VecVocab.getStringKey(Pos) << ": ";
677 Entry.print(OS);
678 }
679 ++Pos;
680 }
681}
682
686
689 auto MIR2VecVocabOrErr = Analysis.getMIR2VecVocabulary(M);
690
691 if (!MIR2VecVocabOrErr) {
692 OS << "MIR2Vec Vocabulary Printer: Failed to get vocabulary - "
693 << toString(MIR2VecVocabOrErr.takeError()) << "\n";
694 return false;
695 }
696
697 printVocabulary(*MIR2VecVocabOrErr, OS);
698 return false;
699}
700
705
711
712static void printEmbeddings(const MachineFunction &MF,
713 const mir2vec::MIRVocabulary &MIRVocab,
714 raw_ostream &OS) {
715 auto Emb = mir2vec::MIREmbedder::create(MIR2VecEmbeddingKind, MF, MIRVocab);
716 if (!Emb) {
717 OS << "Error creating MIR2Vec embeddings for function " << MF.getName()
718 << "\n";
719 return;
720 }
721
722 OS << "MIR2Vec embeddings for machine function " << MF.getName() << ":\n";
723 OS << "Machine Function vector: ";
724 Emb->getMFunctionVector().print(OS);
725
726 OS << "Machine basic block vectors:\n";
727 for (const MachineBasicBlock &MBB : MF) {
728 OS << "Machine basic block: " << MBB.getFullName() << ":\n";
729 Emb->getMBBVector(MBB).print(OS);
730 }
731
732 OS << "Machine instruction vectors:\n";
733 for (const MachineBasicBlock &MBB : MF) {
734 for (const MachineInstr &MI : MBB) {
735 // Skip debug instructions as they are not
736 // embedded
737 if (MI.isDebugInstr())
738 continue;
739
740 OS << "Machine instruction: ";
741 MI.print(OS);
742 Emb->getMInstVector(MI).print(OS);
743 }
744 }
745}
746
749 "MIR2Vec Embedder Printer Pass", false, true)
753 "MIR2Vec Embedder Printer Pass", false, true)
754
757 auto VocabOrErr =
758 Analysis.getMIR2VecVocabulary(*MF.getFunction().getParent());
759 if (!VocabOrErr)
760 reportFatalUsageError(VocabOrErr.takeError());
761 printEmbeddings(MF, *VocabOrErr, OS);
762 return false;
763}
764
768
772 const auto *Vocab =
774 .getCachedResult<MIR2VecVocabAnalysis>(*MF.getFunction().getParent());
775 if (!Vocab)
776 reportFatalUsageError("print<mir2vec> requires mir2vec-vocab");
777 printEmbeddings(MF, *Vocab, OS);
778 return PreservedAnalyses::all();
779}
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
block Block Frequency Analysis
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define RegName(no)
#define I(x, y, z)
Definition MD5.cpp:57
static void printEmbeddings(const MachineFunction &MF, const mir2vec::MIRVocabulary &MIRVocab, raw_ostream &OS)
Definition MIR2Vec.cpp:712
static Error readVocabulary(VocabMap &OpcodeVocab, VocabMap &CommonOperandVocab, VocabMap &PhyRegVocabMap, VocabMap &VirtRegVocabMap)
Definition MIR2Vec.cpp:475
std::map< std::string, Embedding > VocabMap
Definition MIR2Vec.cpp:473
print mir2vec MIR2Vec Vocabulary Printer static true void printVocabulary(const mir2vec::MIRVocabulary &MIR2VecVocab, raw_ostream &OS)
Definition MIR2Vec.cpp:669
static Expected< mir2vec::MIRVocabulary > buildVocabulary(const TargetSubtargetInfo &ST)
Definition MIR2Vec.cpp:527
This file defines the MIR2Vec framework for generating Machine IR embeddings.
Register Reg
Register const TargetRegisterInfo * TRI
ModuleAnalysisManager MAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SmallVector< MachineBasicBlock *, 4 > MBBVector
MachineRegisterInfo & MRI
const char * Msg
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const unsigned InvalidIndex
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
Module * getParent()
Get the module that this global value is contained inside of...
unsigned getID() const
getID() - Return the register class ID number.
This pass prints the MIR2Vec embeddings for machine functions, basic blocks, and instructions.
Definition MIR2Vec.h:462
MIR2VecPrinterLegacyPass(raw_ostream &OS)
Definition MIR2Vec.h:467
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Definition MIR2Vec.cpp:755
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Definition MIR2Vec.cpp:770
New pass manager analysis that provides the MIR2Vec vocabulary for a module.
Definition MIR2Vec.h:486
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &MAM)
Definition MIR2Vec.cpp:568
const mir2vec::MIRVocabulary Result
Definition MIR2Vec.h:491
Pass to analyze and populate MIR2Vec vocabulary from a module.
Definition MIR2Vec.h:407
This pass prints the embeddings in the MIR2Vec vocabulary.
Definition MIR2Vec.h:439
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Definition MIR2Vec.cpp:683
bool doFinalization(Module &M) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Definition MIR2Vec.cpp:687
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Definition MIR2Vec.cpp:706
MIR2Vec vocabulary provider used by pass managers and standalone tools.
Definition MIR2Vec.h:396
LLVM_ABI Expected< mir2vec::MIRVocabulary > getVocabulary(const Module &M)
Definition MIR2Vec.cpp:541
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
An analysis that produces MachineModuleInfo for a module.
MachineOperand class - Representation of each machine instruction operand.
@ MO_Register
Register operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
LLVM_ABI bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
Definition Regex.cpp:84
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
char back() const
Get the last character in the string.
Definition StringRef.h:153
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition StringRef.h:634
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Generic storage class for section-based vocabularies.
Definition IR2Vec.h:155
static LLVM_ABI Error parseVocabSection(StringRef Key, const json::Value &ParsedVocabValue, VocabMap &TargetVocab, unsigned &Dim)
Parse a vocabulary section from JSON and populate the target vocabulary map.
Definition IR2Vec.cpp:304
unsigned getDimension() const
Get vocabulary dimension.
Definition IR2Vec.h:194
bool isValid() const
Check if vocabulary is valid (has data)
Definition IR2Vec.h:197
const unsigned Dimension
Dimension of the embeddings; Captured from the vocabulary.
Definition MIR2Vec.h:331
const MIRVocabulary & Vocab
Definition MIR2Vec.h:328
const float RegOperandWeight
Definition MIR2Vec.h:334
const float CommonOperandWeight
Definition MIR2Vec.h:334
LLVM_ABI Embedding computeEmbeddings() const
Function to compute embeddings.
Definition MIR2Vec.cpp:620
const float OpcWeight
Weight for opcode embeddings.
Definition MIR2Vec.h:334
const MachineFunction & MF
Definition MIR2Vec.h:327
static LLVM_ABI std::unique_ptr< MIREmbedder > create(MIR2VecKind Mode, const MachineFunction &MF, const MIRVocabulary &Vocab)
Factory method to create an Embedder object of the specified kind Returns nullptr if the requested ki...
Definition MIR2Vec.cpp:581
LLVM_ABI MIREmbedder(const MachineFunction &MF, const MIRVocabulary &Vocab)
Definition MIR2Vec.cpp:591
Class for storing and accessing the MIR2Vec vocabulary.
Definition MIR2Vec.h:85
const Embedding & getOperandEmbedding(const MachineOperand &Operand, const MachineRegisterInfo &MRI) const
Definition MIR2Vec.h:283
LLVM_ABI unsigned getCanonicalIndexForOperandName(StringRef OperandName) const
Definition MIR2Vec.cpp:169
LLVM_ABI unsigned getCanonicalIndexForRegisterClass(StringRef RegName, bool IsPhysical=true) const
Definition MIR2Vec.cpp:180
static LLVM_ABI std::string extractBaseOpcodeName(StringRef InstrName)
Static method for extracting base opcode names (public for testing)
Definition MIR2Vec.cpp:125
static LLVM_ABI Expected< MIRVocabulary > createDummyVocabForTest(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, unsigned Dim=1)
Create a dummy vocabulary for testing purposes.
Definition MIR2Vec.cpp:426
static LLVM_ABI Expected< MIRVocabulary > create(VocabMap &&OpcMap, VocabMap &&CommonOperandsMap, VocabMap &&PhyRegMap, VocabMap &&VirtRegMap, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI)
Factory method to create MIRVocabulary from vocabulary map.
Definition MIR2Vec.cpp:103
LLVM_ABI std::string getStringKey(unsigned Pos) const
Get the string key for a vocabulary entry at the given position.
Definition MIR2Vec.cpp:190
LLVM_ABI bool invalidate(Module &M, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &Inv) const
The vocabulary stays valid unless explicitly invalidated.
Definition MIR2Vec.cpp:562
LLVM_ABI unsigned getCanonicalIndexForBaseName(StringRef BaseName) const
Get indices from opcode or operand names.
Definition MIR2Vec.cpp:155
static std::unique_ptr< SymbolicMIREmbedder > create(const MachineFunction &MF, const MIRVocabulary &Vocab)
Definition MIR2Vec.cpp:637
SymbolicMIREmbedder(const MachineFunction &F, const MIRVocabulary &Vocab)
Definition MIR2Vec.cpp:632
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ Entry
Definition COFF.h:862
OperandType
Operands are tagged with one of the values of this enum.
Definition MCInstrDesc.h:59
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LLVM_ABI llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition JSON.cpp:681
LLVM_ABI llvm::cl::OptionCategory MIR2VecCategory
static cl::opt< float > OpcWeight("mir2vec-opc-weight", cl::init(1.0), cl::desc("Weight for machine opcode embeddings"), cl::cat(MIR2VecCategory))
static cl::opt< float > RegOperandWeight("mir2vec-reg-operand-weight", cl::init(1.0), cl::desc("Weight for register operand embeddings"), cl::cat(MIR2VecCategory))
static cl::opt< bool > PrintAllVocabEntries("mir2vec-print-all-vocab-entries", cl::init(false), cl::desc("Print all vocabulary entries including zero embeddings"), cl::cat(MIR2VecCategory))
ir2vec::Embedding Embedding
Definition MIR2Vec.h:78
cl::opt< MIR2VecKind > MIR2VecEmbeddingKind("mir2vec-kind", cl::values(clEnumValN(MIR2VecKind::Symbolic, "symbolic", "Generate symbolic embeddings for MIR")), cl::init(MIR2VecKind::Symbolic), cl::desc("MIR2Vec embedding kind"), cl::cat(MIR2VecCategory))
static cl::opt< std::string > VocabFile("mir2vec-vocab-path", cl::desc("Path to the vocabulary file for MIR2Vec"), cl::init(""), cl::cat(MIR2VecCategory))
static cl::opt< float > CommonOperandWeight("mir2vec-common-operand-weight", cl::init(1.0), cl::desc("Weight for common operand embeddings"), cl::cat(MIR2VecCategory))
This is an optimization pass for GlobalISel generic memory operations.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
@ illegal_byte_sequence
Definition Errc.h:52
@ invalid_argument
Definition Errc.h:56
LLVM_ABI MachineFunctionPass * createMIR2VecPrinterLegacyPass(raw_ostream &OS)
Create a machine pass that prints MIR2Vec embeddings.
Definition MIR2Vec.cpp:765
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
LLVM_ABI MachineFunctionPass * createMIR2VecVocabPrinterLegacyPass(raw_ostream &OS)
MIR2VecVocabPrinter pass - This pass prints out the MIR2Vec vocabulary contents to the given stream a...
Definition MIR2Vec.cpp:702
MIR2VecKind
Definition MIR2Vec.h:68
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29