LLVM 24.0.0git
MIR2Vec.h
Go to the documentation of this file.
1//===- MIR2Vec.h - Implementation of MIR2Vec ------------------*- C++ -*-===//
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 defines the MIR2Vec framework for generating Machine IR
11/// embeddings.
12///
13/// Design Overview:
14/// ----------------------
15/// 1. MIR2VecVocabProvider - Core vocabulary loading logic (no PM dependency)
16/// - Can be used standalone or wrapped by the pass manager
17/// - Requires MachineModuleInfo and a module with a function definition
18///
19/// 2. MIR2VecVocabLegacyAnalysis - Pass manager wrapper (ImmutablePass)
20/// - Integrated and used by llc -print-mir2vec
21///
22/// 3. MIREmbedder - Generates embeddings from vocabulary
23/// - SymbolicMIREmbedder: MIR2Vec embedding implementation
24///
25/// MIR2Vec extends IR2Vec to support Machine IR embeddings. It represents the
26/// LLVM Machine IR as embeddings which can be used as input to machine learning
27/// algorithms.
28///
29/// The original idea of MIR2Vec is described in the following paper:
30///
31/// RL4ReAl: Reinforcement Learning for Register Allocation. S. VenkataKeerthy,
32/// Siddharth Jain, Anilava Kundu, Rohit Aggarwal, Albert Cohen, and Ramakrishna
33/// Upadrasta. 2023. RL4ReAl: Reinforcement Learning for Register Allocation.
34/// Proceedings of the 32nd ACM SIGPLAN International Conference on Compiler
35/// Construction (CC 2023). https://doi.org/10.1145/3578360.3580273.
36/// https://arxiv.org/abs/2204.02013
37///
38//===----------------------------------------------------------------------===//
39
40#ifndef LLVM_CODEGEN_MIR2VEC_H
41#define LLVM_CODEGEN_MIR2VEC_H
42
51#include "llvm/IR/PassManager.h"
52#include "llvm/Pass.h"
54#include "llvm/Support/Error.h"
56#include <map>
57#include <memory>
58#include <optional>
59#include <string>
60
61namespace llvm {
62
63class Module;
64class raw_ostream;
66class TargetInstrInfo;
67
68enum class MIR2VecKind { Symbolic };
69
70namespace mir2vec {
71
72// Forward declarations
73class MIREmbedder;
75
77
82
83/// Class for storing and accessing the MIR2Vec vocabulary.
84/// The MIRVocabulary class manages seed embeddings for LLVM Machine IR
87 using VocabMap = std::map<std::string, ir2vec::Embedding>;
88
89 // MIRVocabulary Layout:
90 // +-------------------+-----------------------------------------------------+
91 // | Entity Type | Description |
92 // +-------------------+-----------------------------------------------------+
93 // | 1. Opcodes | Target specific opcodes derived from TII, grouped |
94 // | | by instruction semantics. |
95 // | 2. Common Operands| All common operand types, except register operands, |
96 // | | defined by MachineOperand::MachineOperandType enum. |
97 // | 3. Physical | Register classes defined by the target, specialized |
98 // | Reg classes | by physical registers. |
99 // | 4. Virtual | Register classes defined by the target, specialized |
100 // | Reg classes | by virtual and physical registers. |
101 // +-------------------+-----------------------------------------------------+
102 // Both register sections end with a NoRegClass entry for classless registers.
103
104 /// Layout information for the MIR vocabulary. Defines the starting index
105 /// and size of each section in the vocabulary.
106 struct {
107 size_t OpcodeBase = 0;
109 size_t PhyRegBase = 0;
110 size_t VirtRegBase = 0;
111 size_t TotalEntries = 0;
112 } Layout;
113
114 // TODO: See if we can have only one reg classes section instead of physical
115 // and virtual separate sections in the vocabulary. This would reduce the
116 // number of vocabulary entities significantly.
117 // We can potentially distinguish physical and virtual registers by
118 // considering them as a separate feature.
119 enum class Section : unsigned {
120 Opcodes = 0,
121 CommonOperands = 1,
122 PhyRegisters = 2,
123 VirtRegisters = 3,
124 MaxSections
125 };
126
127 ir2vec::VocabStorage Storage;
128 /// Sorted unique base opcode names. The position is the canonical index.
129 SmallVector<std::string, 0> UniqueBaseOpcodeNames;
130 SmallVector<unsigned, 0> OpcodeToCanonicalIndex;
131 SmallVector<std::string, 24> RegisterOperandNames;
132 static constexpr StringLiteral NoRegClassName = "NoRegClass";
133
134 // Some instructions have optional register operands that may be NoRegister.
135 // We return a zero vector in such cases.
136 Embedding ZeroEmbedding;
137
138 // Operand types without a CommonOperands entry. MO_Register is handled by the
139 // register sections; the others get a zero embedding.
140 static constexpr MachineOperand::MachineOperandType ExcludedOperandTypes[] = {
142
143 struct CommonOperandEntry {
145 StringLiteral Name;
146 };
147 static constexpr CommonOperandEntry CommonOperands[] = {
148 {MachineOperand::MO_Immediate, "Immediate"},
149 {MachineOperand::MO_CImmediate, "CImmediate"},
150 {MachineOperand::MO_FPImmediate, "FPImmediate"},
152 {MachineOperand::MO_FrameIndex, "FrameIndex"},
153 {MachineOperand::MO_ConstantPoolIndex, "ConstantPoolIndex"},
154 {MachineOperand::MO_TargetIndex, "TargetIndex"},
155 {MachineOperand::MO_JumpTableIndex, "JumpTableIndex"},
156 {MachineOperand::MO_ExternalSymbol, "ExternalSymbol"},
157 {MachineOperand::MO_GlobalAddress, "GlobalAddress"},
158 {MachineOperand::MO_BlockAddress, "BlockAddress"},
159 {MachineOperand::MO_RegisterMask, "RegisterMask"},
160 {MachineOperand::MO_RegisterLiveOut, "RegisterLiveOut"},
161 {MachineOperand::MO_Metadata, "Metadata"},
162 {MachineOperand::MO_MCSymbol, "MCSymbol"},
163 {MachineOperand::MO_CFIIndex, "CFIIndex"},
164 {MachineOperand::MO_IntrinsicID, "IntrinsicID"},
165 {MachineOperand::MO_Predicate, "Predicate"},
166 {MachineOperand::MO_ShuffleMask, "ShuffleMask"},
167 {MachineOperand::MO_LaneMask, "LaneMask"}};
168 static_assert(std::size(CommonOperands) + std::size(ExcludedOperandTypes) ==
170 "Every MachineOperandType must be in CommonOperands or "
171 "ExcludedOperandTypes");
172
173 const TargetInstrInfo &TII;
174 const TargetRegisterInfo &TRI;
175
176 void generateStorage(const VocabMap &OpcodeMap,
177 const VocabMap &CommonOperandMap,
178 const VocabMap &PhyRegMap, const VocabMap &VirtRegMap);
179 void buildCanonicalOpcodeMapping();
180 void buildRegisterOperandMapping();
181
182 /// Get canonical index for a machine opcode
183 LLVM_ABI unsigned getCanonicalOpcodeIndex(unsigned Opcode) const;
184
185 /// Get index for a common (non-register) machine operand. Returns
186 /// std::nullopt if OperandType has no vocabulary entry.
187 LLVM_ABI std::optional<unsigned>
188 getCommonOperandIndex(MachineOperand::MachineOperandType OperandType) const;
189
190 /// Get index for a register machine operand. Registers without a register
191 /// class map to the NoRegClass entry.
192 LLVM_ABI unsigned
193 getRegisterOperandIndex(Register Reg, const MachineRegisterInfo &MRI) const;
194
195 // Accessors for operand types
196 const Embedding &
197 operator[](MachineOperand::MachineOperandType OperandType) const {
198 std::optional<unsigned> LocalIndex = getCommonOperandIndex(OperandType);
199 if (!LocalIndex)
200 return ZeroEmbedding;
201 return Storage[static_cast<unsigned>(Section::CommonOperands)][*LocalIndex];
202 }
203
204 const Embedding &getRegisterEmbedding(Register Reg,
205 const MachineRegisterInfo &MRI) const {
206 // Reg is sometimes NoRegister (0) for optional operands. We return a zero
207 // vector in this case.
208 if (!Reg.isValid())
209 return ZeroEmbedding;
210 // TODO: Implement proper stack slot handling for MIR2Vec embeddings.
211 // Stack slots represent frame indices and should have their own
212 // embedding strategy rather than defaulting to register class 0.
213 // Consider: 1) Separate vocabulary section for stack slots
214 // 2) Stack slot size/alignment based embeddings
215 // 3) Frame index based categorization
216 if (Reg.isStack())
217 return ZeroEmbedding;
218
219 auto SectionID =
220 Reg.isPhysical() ? Section::PhyRegisters : Section::VirtRegisters;
221 return Storage[static_cast<unsigned>(SectionID)]
222 [getRegisterOperandIndex(Reg, MRI)];
223 }
224
225 /// Get entity ID (flat index) for a common operand type
226 /// This is used for triplet generation
227 unsigned getEntityIDForCommonOperand(
228 MachineOperand::MachineOperandType OperandType) const {
229 std::optional<unsigned> LocalIndex = getCommonOperandIndex(OperandType);
230 assert(LocalIndex && "Operand type has no vocabulary entry");
231 return Layout.CommonOperandBase + *LocalIndex;
232 }
233
234 /// Get entity ID (flat index) for a register
235 /// This is used for triplet generation. Reg must be a physical or virtual
236 /// register.
237 unsigned getEntityIDForRegister(Register Reg,
238 const MachineRegisterInfo &MRI) const {
239 size_t BaseOffset =
240 Reg.isPhysical() ? Layout.PhyRegBase : Layout.VirtRegBase;
241 return BaseOffset + getRegisterOperandIndex(Reg, MRI);
242 }
243
244public:
245 /// Static method for extracting base opcode names (public for testing)
246 LLVM_ABI static std::string extractBaseOpcodeName(StringRef InstrName);
247
248 /// Get indices from opcode or operand names. These are public for testing.
249 /// String based lookups are inefficient and should be avoided in general.
250 LLVM_ABI unsigned getCanonicalIndexForBaseName(StringRef BaseName) const;
251 LLVM_ABI unsigned
252 getCanonicalIndexForOperandName(StringRef OperandName) const;
253 LLVM_ABI unsigned
255 bool IsPhysical = true) const;
256
257 /// Get the string key for a vocabulary entry at the given position
258 LLVM_ABI std::string getStringKey(unsigned Pos) const;
259
260 unsigned getDimension() const { return Storage.getDimension(); }
261
262 /// Get entity ID (flat index) for an opcode
263 /// This is used for triplet generation
264 unsigned getEntityIDForOpcode(unsigned Opcode) const {
265 return Layout.OpcodeBase + getCanonicalOpcodeIndex(Opcode);
266 }
267
268 /// Get entity ID (flat index) for a machine operand
269 /// This is used for triplet generation
271 const MachineRegisterInfo &MRI) const {
273 return getEntityIDForRegister(MO.getReg(), MRI);
274 return getEntityIDForCommonOperand(MO.getType());
275 }
276
277 // Accessor methods
278 const Embedding &operator[](unsigned Opcode) const {
279 unsigned LocalIndex = getCanonicalOpcodeIndex(Opcode);
280 return Storage[static_cast<unsigned>(Section::Opcodes)][LocalIndex];
281 }
282
284 const MachineRegisterInfo &MRI) const {
285 auto OperandType = Operand.getType();
286 if (OperandType == MachineOperand::MO_Register)
287 return getRegisterEmbedding(Operand.getReg(), MRI);
288 else
289 return operator[](OperandType);
290 }
291
292 // Iterator access
294 const_iterator begin() const { return Storage.begin(); }
295
296 const_iterator end() const { return Storage.end(); }
297
298 /// The vocabulary stays valid unless explicitly invalidated.
299 LLVM_ABI bool invalidate(Module &M, const PreservedAnalyses &PA,
300 ModuleAnalysisManager::Invalidator &Inv) const;
301
302 MIRVocabulary() = delete;
303
304 /// Factory method to create MIRVocabulary from vocabulary map
306 create(VocabMap &&OpcMap, VocabMap &&CommonOperandsMap, VocabMap &&PhyRegMap,
307 VocabMap &&VirtRegMap, const TargetInstrInfo &TII,
308 const TargetRegisterInfo &TRI);
309
310 /// Create a dummy vocabulary for testing purposes.
313 const TargetRegisterInfo &TRI, unsigned Dim = 1);
314
315 /// Total number of entries in the vocabulary
316 size_t getCanonicalSize() const { return Storage.size(); }
317
318private:
319 MIRVocabulary(VocabMap &&OpcMap, VocabMap &&CommonOperandsMap,
320 VocabMap &&PhyRegMap, VocabMap &&VirtRegMap,
322};
323
324/// Base class for MIR embedders
326protected:
329
330 /// Dimension of the embeddings; Captured from the vocabulary
331 const unsigned Dimension;
332
333 /// Weight for opcode embeddings
335
337
338 /// Function to compute embeddings.
340
341 /// Function to compute the embedding for a given machine basic block.
343
344 /// Function to compute the embedding for a given machine instruction.
345 /// Specific to the kind of embeddings being computed.
346 virtual Embedding computeEmbeddings(const MachineInstr &MI) const = 0;
347
348public:
349 virtual ~MIREmbedder() = default;
350
351 /// Factory method to create an Embedder object of the specified kind
352 /// Returns nullptr if the requested kind is not supported.
353 LLVM_ABI static std::unique_ptr<MIREmbedder>
355 const MIRVocabulary &Vocab);
356
357 /// Computes and returns the embedding for a given machine instruction MI in
358 /// the machine function MF.
360 return computeEmbeddings(MI);
361 }
362
363 /// Computes and returns the embedding for a given machine basic block in the
364 /// machine function MF.
368
369 /// Computes and returns the embedding for the current machine function.
371 // Currently, we always (re)compute the embeddings for the function. This is
372 // cheaper than caching the vector.
373 return computeEmbeddings();
374 }
375};
376
377/// Class for computing Symbolic embeddings
378/// Symbolic embeddings are constructed based on the entity-level
379/// representations obtained from the MIR Vocabulary.
381private:
382 Embedding computeEmbeddings(const MachineInstr &MI) const override;
383
384public:
386 static std::unique_ptr<SymbolicMIREmbedder>
388};
389
390} // namespace mir2vec
391
392/// MIR2Vec vocabulary provider used by pass managers and standalone tools.
393/// This class encapsulates the core vocabulary loading logic and can be used
394/// independently of the pass manager infrastructure. For pass-based usage,
395/// see MIR2VecVocabLegacyAnalysis and MIR2VecVocabAnalysis.
397public:
398 MIR2VecVocabProvider(const MachineModuleInfo &MMI) : MMI(MMI) {}
399
401
402private:
403 const MachineModuleInfo &MMI;
404};
405
406/// Pass to analyze and populate MIR2Vec vocabulary from a module
408 using VocabMap = std::map<std::string, mir2vec::Embedding>;
409
410 StringRef getPassName() const override;
411
412protected:
413 void getAnalysisUsage(AnalysisUsage &AU) const override {
415 AU.setPreservesAll();
416 }
417 std::optional<mir2vec::MIRVocabulary> Vocab;
418
419public:
420 static char ID;
422
423 /// Build the vocabulary on the first call and return the cached one after.
426 if (!Vocab) {
427 MIR2VecVocabProvider Provider(
429 auto VocabOrErr = Provider.getVocabulary(M);
430 if (!VocabOrErr)
431 return VocabOrErr.takeError();
432 Vocab.emplace(std::move(*VocabOrErr));
433 }
434 return *Vocab;
435 }
436};
437
438/// This pass prints the embeddings in the MIR2Vec vocabulary
440 raw_ostream &OS;
441
442public:
443 static char ID;
446
447 bool runOnMachineFunction(MachineFunction &MF) override;
448 bool doFinalization(Module &M) override;
454
455 StringRef getPassName() const override {
456 return "MIR2Vec Vocabulary Printer Pass";
457 }
458};
459
460/// This pass prints the MIR2Vec embeddings for machine functions, basic blocks,
461/// and instructions
463 raw_ostream &OS;
464
465public:
466 static char ID;
469
470 bool runOnMachineFunction(MachineFunction &MF) override;
476
477 StringRef getPassName() const override {
478 return "MIR2Vec Embedder Printer Pass";
479 }
480};
481
482/// Create a machine pass that prints MIR2Vec embeddings
483LLVM_ABI MachineFunctionPass *createMIR2VecPrinterLegacyPass(raw_ostream &OS);
484
485/// New pass manager analysis that provides the MIR2Vec vocabulary for a module.
486class MIR2VecVocabAnalysis : public AnalysisInfoMixin<MIR2VecVocabAnalysis> {
488 LLVM_ABI static AnalysisKey Key;
489
490public:
493};
494
495/// New pass manager pass that prints the MIR2Vec vocabulary once per module.
497 : public RequiredPassInfoMixin<MIR2VecVocabPrinterPass> {
498 raw_ostream &OS;
499
500public:
501 explicit MIR2VecVocabPrinterPass(raw_ostream &OS) : OS(OS) {}
503};
504
505/// New pass manager pass that prints the MIR2Vec embeddings for machine
506/// functions, basic blocks, and instructions.
507class MIR2VecPrinterPass : public RequiredPassInfoMixin<MIR2VecPrinterPass> {
508 raw_ostream &OS;
509
510public:
511 explicit MIR2VecPrinterPass(raw_ostream &OS) : OS(OS) {}
514};
515
516} // namespace llvm
517
518#endif // LLVM_CODEGEN_MIR2VEC_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
#define LLVM_ABI
Definition Compiler.h:211
Provides ErrorOr<T> smart pointer.
This file defines the IR2Vec vocabulary analysis(IR2VecVocabAnalysis), the core ir2vec::Embedder inte...
IRTranslator LLVM IR MI
This header defines various interfaces for pass management in LLVM.
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
std::map< std::string, Embedding > VocabMap
Definition MIR2Vec.cpp:473
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
ModuleAnalysisManager MAM
MachineRegisterInfo & MRI
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Tagged union holding either a T or a Error.
Definition Error.h:485
ImmutablePass(char &pid)
Definition Pass.h:285
MIR2VecPrinterLegacyPass(raw_ostream &OS)
Definition MIR2Vec.h:467
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition MIR2Vec.h:471
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
Definition MIR2Vec.h:477
MIR2VecPrinterPass(raw_ostream &OS)
Definition MIR2Vec.h:511
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
std::optional< mir2vec::MIRVocabulary > Vocab
Definition MIR2Vec.h:417
Expected< const mir2vec::MIRVocabulary & > getMIR2VecVocabulary(const Module &M)
Build the vocabulary on the first call and return the cached one after.
Definition MIR2Vec.h:425
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition MIR2Vec.h:413
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
Definition MIR2Vec.h:455
MIR2VecVocabPrinterLegacyPass(raw_ostream &OS)
Definition MIR2Vec.h:444
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition MIR2Vec.h:449
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Definition MIR2Vec.cpp:706
MIR2VecVocabPrinterPass(raw_ostream &OS)
Definition MIR2Vec.h:501
MIR2Vec vocabulary provider used by pass managers and standalone tools.
Definition MIR2Vec.h:396
MIR2VecVocabProvider(const MachineModuleInfo &MMI)
Definition MIR2Vec.h:398
LLVM_ABI Expected< mir2vec::MIRVocabulary > getVocabulary(const Module &M)
Definition MIR2Vec.cpp:541
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Representation of each machine instruction.
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
Register getReg() const
getReg - Returns the register number.
@ MO_CFIIndex
MCCFIInstruction index.
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_Predicate
Generic predicate for ISel.
@ MO_GlobalAddress
Address of a global value.
@ MO_RegisterMask
Mask of preserved registers.
@ MO_ShuffleMask
Other IR Constant for ISel (shuffle masks)
@ MO_CImmediate
Immediate >64bit operand.
@ MO_BlockAddress
Address of a basic block.
@ MO_DbgInstrRef
Integer indices referring to an instruction+operand.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_LaneMask
Mask to represent active parts of registers.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_IntrinsicID
Intrinsic ID for ISel.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_TargetIndex
Target-dependent index+offset operand.
@ MO_Metadata
Metadata reference (for debug info)
@ MO_FPImmediate
Floating-point immediate operand.
@ MO_RegisterLiveOut
Mask of live-out registers.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:880
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Iterator support for section-based access.
Definition IR2Vec.h:200
Generic storage class for section-based vocabularies.
Definition IR2Vec.h:155
Base class for MIR embedders.
Definition MIR2Vec.h:325
const unsigned Dimension
Dimension of the embeddings; Captured from the vocabulary.
Definition MIR2Vec.h:331
Embedding getMFunctionVector() const
Computes and returns the embedding for the current machine function.
Definition MIR2Vec.h:370
const MIRVocabulary & Vocab
Definition MIR2Vec.h:328
Embedding getMInstVector(const MachineInstr &MI) const
Computes and returns the embedding for a given machine instruction MI in the machine function MF.
Definition MIR2Vec.h:359
virtual Embedding computeEmbeddings(const MachineInstr &MI) const =0
Function to compute the embedding for a given machine instruction.
Embedding getMBBVector(const MachineBasicBlock &MBB) const
Computes and returns the embedding for a given machine basic block in the machine function MF.
Definition MIR2Vec.h:365
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
virtual ~MIREmbedder()=default
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
unsigned getDimension() const
Definition MIR2Vec.h:260
unsigned getEntityIDForOpcode(unsigned Opcode) const
Get entity ID (flat index) for an opcode This is used for triplet generation.
Definition MIR2Vec.h:264
const_iterator end() const
Definition MIR2Vec.h:296
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
ir2vec::VocabStorage::const_iterator const_iterator
Definition MIR2Vec.h:293
const_iterator begin() const
Definition MIR2Vec.h:294
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
const Embedding & operator[](unsigned Opcode) const
Definition MIR2Vec.h:278
unsigned getEntityIDForMachineOperand(const MachineOperand &MO, const MachineRegisterInfo &MRI) const
Get entity ID (flat index) for a machine operand This is used for triplet generation.
Definition MIR2Vec.h:270
size_t getCanonicalSize() const
Total number of entries in the vocabulary.
Definition MIR2Vec.h:316
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
Class for computing Symbolic embeddings Symbolic embeddings are constructed based on the entity-level...
Definition MIR2Vec.h:380
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
DenseMap< const MachineInstr *, Embedding > MachineInstEmbeddingsMap
Definition MIR2Vec.h:79
LLVM_ABI llvm::cl::OptionCategory MIR2VecCategory
ir2vec::Embedding Embedding
Definition MIR2Vec.h:78
DenseMap< const MachineBasicBlock *, Embedding > MachineBlockEmbeddingsMap
Definition MIR2Vec.h:80
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI MachineFunctionPass * createMIR2VecPrinterLegacyPass(raw_ostream &OS)
Create a machine pass that prints MIR2Vec embeddings.
Definition MIR2Vec.cpp:765
MIR2VecKind
Definition MIR2Vec.h:68
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
A CRTP mix-in for passes that should not be skipped.
Embedding is a datatype that wraps std::vector<double>.
Definition IR2Vec.h:86