[llvm-exegesis] Provide a way to handle memory instructions.
[llvm-core.git] / tools / llvm-exegesis / lib / Assembler.cpp
blob3b8b1d6bf38f0b9aac3c0f4d24cfa49242822536
1 //===-- Assembler.cpp -------------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
10 #include "Assembler.h"
12 #include "Target.h"
13 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
14 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
15 #include "llvm/CodeGen/MachineInstrBuilder.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetInstrInfo.h"
19 #include "llvm/CodeGen/TargetPassConfig.h"
20 #include "llvm/CodeGen/TargetSubtargetInfo.h"
21 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/Support/MemoryBuffer.h"
26 namespace exegesis {
28 static constexpr const char ModuleID[] = "ExegesisInfoTest";
29 static constexpr const char FunctionID[] = "foo";
31 static std::vector<llvm::MCInst>
32 generateSnippetSetupCode(const llvm::ArrayRef<unsigned> RegsToDef,
33 const ExegesisTarget &ET,
34 const llvm::LLVMTargetMachine &TM, bool &IsComplete) {
35 IsComplete = true;
36 std::vector<llvm::MCInst> Result;
37 for (const unsigned Reg : RegsToDef) {
38 // Load a constant in the register.
39 const auto Code = ET.setRegToConstant(*TM.getMCSubtargetInfo(), Reg);
40 if (Code.empty())
41 IsComplete = false;
42 Result.insert(Result.end(), Code.begin(), Code.end());
44 return Result;
47 // Small utility function to add named passes.
48 static bool addPass(llvm::PassManagerBase &PM, llvm::StringRef PassName,
49 llvm::TargetPassConfig &TPC) {
50 const llvm::PassRegistry *PR = llvm::PassRegistry::getPassRegistry();
51 const llvm::PassInfo *PI = PR->getPassInfo(PassName);
52 if (!PI) {
53 llvm::errs() << " run-pass " << PassName << " is not registered.\n";
54 return true;
57 if (!PI->getNormalCtor()) {
58 llvm::errs() << " cannot create pass: " << PI->getPassName() << "\n";
59 return true;
61 llvm::Pass *P = PI->getNormalCtor()();
62 std::string Banner = std::string("After ") + std::string(P->getPassName());
63 PM.add(P);
64 TPC.printAndVerify(Banner);
66 return false;
69 // Creates a void(int8*) MachineFunction.
70 static llvm::MachineFunction &
71 createVoidVoidPtrMachineFunction(llvm::StringRef FunctionID,
72 llvm::Module *Module,
73 llvm::MachineModuleInfo *MMI) {
74 llvm::Type *const ReturnType = llvm::Type::getInt32Ty(Module->getContext());
75 llvm::Type *const MemParamType = llvm::PointerType::get(
76 llvm::Type::getInt8Ty(Module->getContext()), 0 /*default address space*/);
77 llvm::FunctionType *FunctionType =
78 llvm::FunctionType::get(ReturnType, {MemParamType}, false);
79 llvm::Function *const F = llvm::Function::Create(
80 FunctionType, llvm::GlobalValue::InternalLinkage, FunctionID, Module);
81 // Making sure we can create a MachineFunction out of this Function even if it
82 // contains no IR.
83 F->setIsMaterializable(true);
84 return MMI->getOrCreateMachineFunction(*F);
87 static void fillMachineFunction(llvm::MachineFunction &MF,
88 llvm::ArrayRef<unsigned> LiveIns,
89 llvm::ArrayRef<llvm::MCInst> Instructions) {
90 llvm::MachineBasicBlock *MBB = MF.CreateMachineBasicBlock();
91 MF.push_back(MBB);
92 for (const unsigned Reg : LiveIns)
93 MBB->addLiveIn(Reg);
94 const llvm::MCInstrInfo *MCII = MF.getTarget().getMCInstrInfo();
95 llvm::DebugLoc DL;
96 for (const llvm::MCInst &Inst : Instructions) {
97 const unsigned Opcode = Inst.getOpcode();
98 const llvm::MCInstrDesc &MCID = MCII->get(Opcode);
99 llvm::MachineInstrBuilder Builder = llvm::BuildMI(MBB, DL, MCID);
100 for (unsigned OpIndex = 0, E = Inst.getNumOperands(); OpIndex < E;
101 ++OpIndex) {
102 const llvm::MCOperand &Op = Inst.getOperand(OpIndex);
103 if (Op.isReg()) {
104 const bool IsDef = OpIndex < MCID.getNumDefs();
105 unsigned Flags = 0;
106 const llvm::MCOperandInfo &OpInfo = MCID.operands().begin()[OpIndex];
107 if (IsDef && !OpInfo.isOptionalDef())
108 Flags |= llvm::RegState::Define;
109 Builder.addReg(Op.getReg(), Flags);
110 } else if (Op.isImm()) {
111 Builder.addImm(Op.getImm());
112 } else {
113 llvm_unreachable("Not yet implemented");
117 // Insert the return code.
118 const llvm::TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
119 if (TII->getReturnOpcode() < TII->getNumOpcodes()) {
120 llvm::BuildMI(MBB, DL, TII->get(TII->getReturnOpcode()));
121 } else {
122 llvm::MachineIRBuilder MIB(MF);
123 MIB.setMBB(*MBB);
124 MF.getSubtarget().getCallLowering()->lowerReturn(MIB, nullptr, 0);
128 static std::unique_ptr<llvm::Module>
129 createModule(const std::unique_ptr<llvm::LLVMContext> &Context,
130 const llvm::DataLayout DL) {
131 auto Module = llvm::make_unique<llvm::Module>(ModuleID, *Context);
132 Module->setDataLayout(DL);
133 return Module;
136 llvm::BitVector getFunctionReservedRegs(const llvm::TargetMachine &TM) {
137 std::unique_ptr<llvm::LLVMContext> Context =
138 llvm::make_unique<llvm::LLVMContext>();
139 std::unique_ptr<llvm::Module> Module =
140 createModule(Context, TM.createDataLayout());
141 std::unique_ptr<llvm::MachineModuleInfo> MMI =
142 llvm::make_unique<llvm::MachineModuleInfo>(&TM);
143 llvm::MachineFunction &MF =
144 createVoidVoidPtrMachineFunction(FunctionID, Module.get(), MMI.get());
145 // Saving reserved registers for client.
146 return MF.getSubtarget().getRegisterInfo()->getReservedRegs(MF);
149 void assembleToStream(const ExegesisTarget &ET,
150 std::unique_ptr<llvm::LLVMTargetMachine> TM,
151 llvm::ArrayRef<unsigned> LiveIns,
152 llvm::ArrayRef<unsigned> RegsToDef,
153 llvm::ArrayRef<llvm::MCInst> Instructions,
154 llvm::raw_pwrite_stream &AsmStream) {
155 std::unique_ptr<llvm::LLVMContext> Context =
156 llvm::make_unique<llvm::LLVMContext>();
157 std::unique_ptr<llvm::Module> Module =
158 createModule(Context, TM->createDataLayout());
159 std::unique_ptr<llvm::MachineModuleInfo> MMI =
160 llvm::make_unique<llvm::MachineModuleInfo>(TM.get());
161 llvm::MachineFunction &MF =
162 createVoidVoidPtrMachineFunction(FunctionID, Module.get(), MMI.get());
164 // We need to instruct the passes that we're done with SSA and virtual
165 // registers.
166 auto &Properties = MF.getProperties();
167 Properties.set(llvm::MachineFunctionProperties::Property::NoVRegs);
168 Properties.reset(llvm::MachineFunctionProperties::Property::IsSSA);
170 for (const unsigned Reg : LiveIns)
171 MF.getRegInfo().addLiveIn(Reg);
173 bool IsSnippetSetupComplete = false;
174 std::vector<llvm::MCInst> SnippetWithSetup =
175 generateSnippetSetupCode(RegsToDef, ET, *TM, IsSnippetSetupComplete);
176 if (!SnippetWithSetup.empty()) {
177 SnippetWithSetup.insert(SnippetWithSetup.end(), Instructions.begin(),
178 Instructions.end());
179 Instructions = SnippetWithSetup;
181 // If the snippet setup is not complete, we disable liveliness tracking. This
182 // means that we won't know what values are in the registers.
183 if (!IsSnippetSetupComplete)
184 Properties.reset(llvm::MachineFunctionProperties::Property::TracksLiveness);
186 // prologue/epilogue pass needs the reserved registers to be frozen, this
187 // is usually done by the SelectionDAGISel pass.
188 MF.getRegInfo().freezeReservedRegs(MF);
190 // Fill the MachineFunction from the instructions.
191 fillMachineFunction(MF, LiveIns, Instructions);
193 // We create the pass manager, run the passes to populate AsmBuffer.
194 llvm::MCContext &MCContext = MMI->getContext();
195 llvm::legacy::PassManager PM;
197 llvm::TargetLibraryInfoImpl TLII(llvm::Triple(Module->getTargetTriple()));
198 PM.add(new llvm::TargetLibraryInfoWrapperPass(TLII));
200 llvm::TargetPassConfig *TPC = TM->createPassConfig(PM);
201 PM.add(TPC);
202 PM.add(MMI.release());
203 TPC->printAndVerify("MachineFunctionGenerator::assemble");
204 // Add target-specific passes.
205 ET.addTargetSpecificPasses(PM);
206 TPC->printAndVerify("After ExegesisTarget::addTargetSpecificPasses");
207 // Adding the following passes:
208 // - machineverifier: checks that the MachineFunction is well formed.
209 // - prologepilog: saves and restore callee saved registers.
210 for (const char *PassName : {"machineverifier", "prologepilog"})
211 if (addPass(PM, PassName, *TPC))
212 llvm::report_fatal_error("Unable to add a mandatory pass");
213 TPC->setInitialized();
215 // AsmPrinter is responsible for generating the assembly into AsmBuffer.
216 if (TM->addAsmPrinter(PM, AsmStream, nullptr,
217 llvm::TargetMachine::CGFT_ObjectFile, MCContext))
218 llvm::report_fatal_error("Cannot add AsmPrinter passes");
220 PM.run(*Module); // Run all the passes
223 llvm::object::OwningBinary<llvm::object::ObjectFile>
224 getObjectFromBuffer(llvm::StringRef InputData) {
225 // Storing the generated assembly into a MemoryBuffer that owns the memory.
226 std::unique_ptr<llvm::MemoryBuffer> Buffer =
227 llvm::MemoryBuffer::getMemBufferCopy(InputData);
228 // Create the ObjectFile from the MemoryBuffer.
229 std::unique_ptr<llvm::object::ObjectFile> Obj = llvm::cantFail(
230 llvm::object::ObjectFile::createObjectFile(Buffer->getMemBufferRef()));
231 // Returning both the MemoryBuffer and the ObjectFile.
232 return llvm::object::OwningBinary<llvm::object::ObjectFile>(
233 std::move(Obj), std::move(Buffer));
236 llvm::object::OwningBinary<llvm::object::ObjectFile>
237 getObjectFromFile(llvm::StringRef Filename) {
238 return llvm::cantFail(llvm::object::ObjectFile::createObjectFile(Filename));
241 namespace {
243 // Implementation of this class relies on the fact that a single object with a
244 // single function will be loaded into memory.
245 class TrackingSectionMemoryManager : public llvm::SectionMemoryManager {
246 public:
247 explicit TrackingSectionMemoryManager(uintptr_t *CodeSize)
248 : CodeSize(CodeSize) {}
250 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
251 unsigned SectionID,
252 llvm::StringRef SectionName) override {
253 *CodeSize = Size;
254 return llvm::SectionMemoryManager::allocateCodeSection(
255 Size, Alignment, SectionID, SectionName);
258 private:
259 uintptr_t *const CodeSize = nullptr;
262 } // namespace
264 ExecutableFunction::ExecutableFunction(
265 std::unique_ptr<llvm::LLVMTargetMachine> TM,
266 llvm::object::OwningBinary<llvm::object::ObjectFile> &&ObjectFileHolder)
267 : Context(llvm::make_unique<llvm::LLVMContext>()) {
268 assert(ObjectFileHolder.getBinary() && "cannot create object file");
269 // Initializing the execution engine.
270 // We need to use the JIT EngineKind to be able to add an object file.
271 LLVMLinkInMCJIT();
272 uintptr_t CodeSize = 0;
273 std::string Error;
274 ExecEngine.reset(
275 llvm::EngineBuilder(createModule(Context, TM->createDataLayout()))
276 .setErrorStr(&Error)
277 .setMCPU(TM->getTargetCPU())
278 .setEngineKind(llvm::EngineKind::JIT)
279 .setMCJITMemoryManager(
280 llvm::make_unique<TrackingSectionMemoryManager>(&CodeSize))
281 .create(TM.release()));
282 if (!ExecEngine)
283 llvm::report_fatal_error(Error);
284 // Adding the generated object file containing the assembled function.
285 // The ExecutionEngine makes sure the object file is copied into an
286 // executable page.
287 ExecEngine->addObjectFile(std::move(ObjectFileHolder));
288 // Fetching function bytes.
289 FunctionBytes =
290 llvm::StringRef(reinterpret_cast<const char *>(
291 ExecEngine->getFunctionAddress(FunctionID)),
292 CodeSize);
295 } // namespace exegesis