1 //===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the execution engine for MLIR modules based on LLVM Orc
10 // JIT engine.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "mlir/ExecutionEngine/ExecutionEngine.h"
14 #include "mlir/IR/Function.h"
15 #include "mlir/IR/Module.h"
16 #include "mlir/Support/FileUtilities.h"
17 #include "mlir/Target/LLVMIR.h"
18 
19 #include "llvm/Bitcode/BitcodeReader.h"
20 #include "llvm/Bitcode/BitcodeWriter.h"
21 #include "llvm/ExecutionEngine/JITEventListener.h"
22 #include "llvm/ExecutionEngine/ObjectCache.h"
23 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
24 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
25 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
26 #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h"
27 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
28 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
29 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 
36 #define DEBUG_TYPE "execution-engine"
37 
38 using namespace mlir;
39 using llvm::dbgs;
40 using llvm::Error;
41 using llvm::errs;
42 using llvm::Expected;
43 using llvm::LLVMContext;
44 using llvm::MemoryBuffer;
45 using llvm::MemoryBufferRef;
46 using llvm::Module;
47 using llvm::SectionMemoryManager;
48 using llvm::StringError;
49 using llvm::Triple;
50 using llvm::orc::DynamicLibrarySearchGenerator;
51 using llvm::orc::ExecutionSession;
52 using llvm::orc::IRCompileLayer;
53 using llvm::orc::JITTargetMachineBuilder;
54 using llvm::orc::RTDyldObjectLinkingLayer;
55 using llvm::orc::ThreadSafeModule;
56 using llvm::orc::TMOwningSimpleCompiler;
57 
58 /// Wrap a string into an llvm::StringError.
59 static Error make_string_error(const Twine &message) {
60   return llvm::make_error<StringError>(message.str(),
61                                        llvm::inconvertibleErrorCode());
62 }
63 
64 void SimpleObjectCache::notifyObjectCompiled(const Module *M,
65                                              MemoryBufferRef ObjBuffer) {
66   cachedObjects[M->getModuleIdentifier()] = MemoryBuffer::getMemBufferCopy(
67       ObjBuffer.getBuffer(), ObjBuffer.getBufferIdentifier());
68 }
69 
70 std::unique_ptr<MemoryBuffer> SimpleObjectCache::getObject(const Module *M) {
71   auto I = cachedObjects.find(M->getModuleIdentifier());
72   if (I == cachedObjects.end()) {
73     LLVM_DEBUG(dbgs() << "No object for " << M->getModuleIdentifier()
74                       << " in cache. Compiling.\n");
75     return nullptr;
76   }
77   LLVM_DEBUG(dbgs() << "Object for " << M->getModuleIdentifier()
78                     << " loaded from cache.\n");
79   return MemoryBuffer::getMemBuffer(I->second->getMemBufferRef());
80 }
81 
82 void SimpleObjectCache::dumpToObjectFile(StringRef outputFilename) {
83   // Set up the output file.
84   std::string errorMessage;
85   auto file = openOutputFile(outputFilename, &errorMessage);
86   if (!file) {
87     llvm::errs() << errorMessage << "\n";
88     return;
89   }
90 
91   // Dump the object generated for a single module to the output file.
92   assert(cachedObjects.size() == 1 && "Expected only one object entry.");
93   auto &cachedObject = cachedObjects.begin()->second;
94   file->os() << cachedObject->getBuffer();
95   file->keep();
96 }
97 
98 void ExecutionEngine::dumpToObjectFile(StringRef filename) {
99   cache->dumpToObjectFile(filename);
100 }
101 
102 // Setup LLVM target triple from the current machine.
103 bool ExecutionEngine::setupTargetTriple(Module *llvmModule) {
104   // Setup the machine properties from the current architecture.
105   auto targetTriple = llvm::sys::getDefaultTargetTriple();
106   std::string errorMessage;
107   auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage);
108   if (!target) {
109     errs() << "NO target: " << errorMessage << "\n";
110     return true;
111   }
112   std::unique_ptr<llvm::TargetMachine> machine(
113       target->createTargetMachine(targetTriple, "generic", "", {}, {}));
114   llvmModule->setDataLayout(machine->createDataLayout());
115   llvmModule->setTargetTriple(targetTriple);
116   return false;
117 }
118 
119 static std::string makePackedFunctionName(StringRef name) {
120   return "_mlir_" + name.str();
121 }
122 
123 // For each function in the LLVM module, define an interface function that wraps
124 // all the arguments of the original function and all its results into an i8**
125 // pointer to provide a unified invocation interface.
126 static void packFunctionArguments(Module *module) {
127   auto &ctx = module->getContext();
128   llvm::IRBuilder<> builder(ctx);
129   DenseSet<llvm::Function *> interfaceFunctions;
130   for (auto &func : module->getFunctionList()) {
131     if (func.isDeclaration()) {
132       continue;
133     }
134     if (interfaceFunctions.count(&func)) {
135       continue;
136     }
137 
138     // Given a function `foo(<...>)`, define the interface function
139     // `mlir_foo(i8**)`.
140     auto newType = llvm::FunctionType::get(
141         builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(),
142         /*isVarArg=*/false);
143     auto newName = makePackedFunctionName(func.getName());
144     auto funcCst = module->getOrInsertFunction(newName, newType);
145     llvm::Function *interfaceFunc = cast<llvm::Function>(funcCst.getCallee());
146     interfaceFunctions.insert(interfaceFunc);
147 
148     // Extract the arguments from the type-erased argument list and cast them to
149     // the proper types.
150     auto bb = llvm::BasicBlock::Create(ctx);
151     bb->insertInto(interfaceFunc);
152     builder.SetInsertPoint(bb);
153     llvm::Value *argList = interfaceFunc->arg_begin();
154     SmallVector<llvm::Value *, 8> args;
155     args.reserve(llvm::size(func.args()));
156     for (auto &indexedArg : llvm::enumerate(func.args())) {
157       llvm::Value *argIndex = llvm::Constant::getIntegerValue(
158           builder.getInt64Ty(), APInt(64, indexedArg.index()));
159       llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex);
160       llvm::Value *argPtr = builder.CreateLoad(argPtrPtr);
161       argPtr = builder.CreateBitCast(
162           argPtr, indexedArg.value().getType()->getPointerTo());
163       llvm::Value *arg = builder.CreateLoad(argPtr);
164       args.push_back(arg);
165     }
166 
167     // Call the implementation function with the extracted arguments.
168     llvm::Value *result = builder.CreateCall(&func, args);
169 
170     // Assuming the result is one value, potentially of type `void`.
171     if (!result->getType()->isVoidTy()) {
172       llvm::Value *retIndex = llvm::Constant::getIntegerValue(
173           builder.getInt64Ty(), APInt(64, llvm::size(func.args())));
174       llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex);
175       llvm::Value *retPtr = builder.CreateLoad(retPtrPtr);
176       retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo());
177       builder.CreateStore(result, retPtr);
178     }
179 
180     // The interface function returns void.
181     builder.CreateRetVoid();
182   }
183 }
184 
185 ExecutionEngine::ExecutionEngine(bool enableObjectCache)
186     : cache(enableObjectCache ? nullptr : new SimpleObjectCache()),
187       gdbListener(llvm::JITEventListener::createGDBRegistrationListener()) {}
188 
189 Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create(
190     ModuleOp m, std::function<Error(llvm::Module *)> transformer,
191     Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel,
192     ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache) {
193   auto engine = std::make_unique<ExecutionEngine>(enableObjectCache);
194 
195   std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext);
196   auto llvmModule = translateModuleToLLVMIR(m);
197   if (!llvmModule)
198     return make_string_error("could not convert to LLVM IR");
199   // FIXME: the triple should be passed to the translation or dialect conversion
200   // instead of this.  Currently, the LLVM module created above has no triple
201   // associated with it.
202   setupTargetTriple(llvmModule.get());
203   packFunctionArguments(llvmModule.get());
204 
205   // Clone module in a new LLVMContext since translateModuleToLLVMIR buries
206   // ownership too deeply.
207   // TODO(zinenko): Reevaluate model of ownership of LLVMContext in LLVMDialect.
208   SmallVector<char, 1> buffer;
209   {
210     llvm::raw_svector_ostream os(buffer);
211     WriteBitcodeToFile(*llvmModule, os);
212   }
213   llvm::MemoryBufferRef bufferRef(StringRef(buffer.data(), buffer.size()),
214                                   "cloned module buffer");
215   auto expectedModule = parseBitcodeFile(bufferRef, *ctx);
216   if (!expectedModule)
217     return expectedModule.takeError();
218   std::unique_ptr<Module> deserModule = std::move(*expectedModule);
219 
220   // Callback to create the object layer with symbol resolution to current
221   // process and dynamically linked libraries.
222   auto objectLinkingLayerCreator = [&](ExecutionSession &session,
223                                        const Triple &TT) {
224     auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>(
225         session, []() { return std::make_unique<SectionMemoryManager>(); });
226     objectLayer->setNotifyLoaded(
227         [engine = engine.get()](
228             llvm::orc::VModuleKey, const llvm::object::ObjectFile &object,
229             const llvm::RuntimeDyld::LoadedObjectInfo &objectInfo) {
230           uint64_t key = static_cast<uint64_t>(
231               reinterpret_cast<uintptr_t>(object.getData().data()));
232           engine->gdbListener->notifyObjectLoaded(key, object, objectInfo);
233         });
234     auto dataLayout = deserModule->getDataLayout();
235     llvm::orc::JITDylib *mainJD = session.getJITDylibByName("<main>");
236     if (!mainJD)
237       mainJD = &session.createJITDylib("<main>");
238 
239     // Resolve symbols that are statically linked in the current process.
240     mainJD->addGenerator(
241         cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess(
242             dataLayout.getGlobalPrefix())));
243 
244     // Resolve symbols from shared libraries.
245     for (auto libPath : sharedLibPaths) {
246       auto mb = llvm::MemoryBuffer::getFile(libPath);
247       if (!mb) {
248         errs() << "Fail to create MemoryBuffer for: " << libPath << "\n";
249         continue;
250       }
251       auto &JD = session.createJITDylib(std::string(libPath));
252       auto loaded = DynamicLibrarySearchGenerator::Load(
253           libPath.data(), dataLayout.getGlobalPrefix());
254       if (!loaded) {
255         errs() << "Could not load " << libPath << ":\n  " << loaded.takeError()
256                << "\n";
257         continue;
258       }
259       JD.addGenerator(std::move(*loaded));
260       cantFail(objectLayer->add(JD, std::move(mb.get())));
261     }
262 
263     return objectLayer;
264   };
265 
266   // Callback to inspect the cache and recompile on demand. This follows Lang's
267   // LLJITWithObjectCache example.
268   auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB)
269       -> Expected<std::unique_ptr<IRCompileLayer::IRCompiler>> {
270     if (jitCodeGenOptLevel)
271       JTMB.setCodeGenOptLevel(jitCodeGenOptLevel.getValue());
272     auto TM = JTMB.createTargetMachine();
273     if (!TM)
274       return TM.takeError();
275     return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM),
276                                                     engine->cache.get());
277   };
278 
279   // Create the LLJIT by calling the LLJITBuilder with 2 callbacks.
280   auto jit =
281       cantFail(llvm::orc::LLJITBuilder()
282                    .setCompileFunctionCreator(compileFunctionCreator)
283                    .setObjectLinkingLayerCreator(objectLinkingLayerCreator)
284                    .create());
285 
286   // Add a ThreadSafemodule to the engine and return.
287   ThreadSafeModule tsm(std::move(deserModule), std::move(ctx));
288   if (transformer)
289     cantFail(tsm.withModuleDo(
290         [&](llvm::Module &module) { return transformer(&module); }));
291   cantFail(jit->addIRModule(std::move(tsm)));
292   engine->jit = std::move(jit);
293 
294   return std::move(engine);
295 }
296 
297 Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const {
298   auto expectedSymbol = jit->lookup(makePackedFunctionName(name));
299   if (!expectedSymbol)
300     return expectedSymbol.takeError();
301   auto rawFPtr = expectedSymbol->getAddress();
302   auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr);
303   if (!fptr)
304     return make_string_error("looked up function is null");
305   return fptr;
306 }
307 
308 Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) {
309   auto expectedFPtr = lookup(name);
310   if (!expectedFPtr)
311     return expectedFPtr.takeError();
312   auto fptr = *expectedFPtr;
313 
314   (*fptr)(args.data());
315 
316   return Error::success();
317 }
318