1 //===- jit-runner.cpp - MLIR CPU Execution Driver Library -----------------===//
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 is a library that provides a shared implementation for command line
10 // utilities that execute an MLIR file on the CPU by translating MLIR to LLVM
11 // IR before JIT-compiling and executing the latter.
12 //
13 // The translation can be customized by providing an MLIR to MLIR
14 // transformation.
15 //===----------------------------------------------------------------------===//
16 
17 #include "mlir/ExecutionEngine/JitRunner.h"
18 
19 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
20 #include "mlir/ExecutionEngine/ExecutionEngine.h"
21 #include "mlir/ExecutionEngine/OptUtils.h"
22 #include "mlir/IR/BuiltinTypes.h"
23 #include "mlir/IR/MLIRContext.h"
24 #include "mlir/Parser.h"
25 #include "mlir/Support/FileUtilities.h"
26 
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/LegacyPassNameParser.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/StringSaver.h"
36 #include "llvm/Support/ToolOutputFile.h"
37 #include <cstdint>
38 #include <numeric>
39 
40 using namespace mlir;
41 using llvm::Error;
42 
43 namespace {
44 /// This options struct prevents the need for global static initializers, and
45 /// is only initialized if the JITRunner is invoked.
46 struct Options {
47   llvm::cl::opt<std::string> inputFilename{llvm::cl::Positional,
48                                            llvm::cl::desc("<input file>"),
49                                            llvm::cl::init("-")};
50   llvm::cl::opt<std::string> mainFuncName{
51       "e", llvm::cl::desc("The function to be called"),
52       llvm::cl::value_desc("<function name>"), llvm::cl::init("main")};
53   llvm::cl::opt<std::string> mainFuncType{
54       "entry-point-result",
55       llvm::cl::desc("Textual description of the function type to be called"),
56       llvm::cl::value_desc("f32 | i32 | i64 | void"), llvm::cl::init("f32")};
57 
58   llvm::cl::OptionCategory optFlags{"opt-like flags"};
59 
60   // CLI list of pass information
61   llvm::cl::list<const llvm::PassInfo *, bool, llvm::PassNameParser> llvmPasses{
62       llvm::cl::desc("LLVM optimizing passes to run"), llvm::cl::cat(optFlags)};
63 
64   // CLI variables for -On options.
65   llvm::cl::opt<bool> optO0{"O0",
66                             llvm::cl::desc("Run opt passes and codegen at O0"),
67                             llvm::cl::cat(optFlags)};
68   llvm::cl::opt<bool> optO1{"O1",
69                             llvm::cl::desc("Run opt passes and codegen at O1"),
70                             llvm::cl::cat(optFlags)};
71   llvm::cl::opt<bool> optO2{"O2",
72                             llvm::cl::desc("Run opt passes and codegen at O2"),
73                             llvm::cl::cat(optFlags)};
74   llvm::cl::opt<bool> optO3{"O3",
75                             llvm::cl::desc("Run opt passes and codegen at O3"),
76                             llvm::cl::cat(optFlags)};
77 
78   llvm::cl::OptionCategory clOptionsCategory{"linking options"};
79   llvm::cl::list<std::string> clSharedLibs{
80       "shared-libs", llvm::cl::desc("Libraries to link dynamically"),
81       llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated,
82       llvm::cl::cat(clOptionsCategory)};
83 
84   /// CLI variables for debugging.
85   llvm::cl::opt<bool> dumpObjectFile{
86       "dump-object-file",
87       llvm::cl::desc("Dump JITted-compiled object to file specified with "
88                      "-object-filename (<input file>.o by default).")};
89 
90   llvm::cl::opt<std::string> objectFilename{
91       "object-filename",
92       llvm::cl::desc("Dump JITted-compiled object to file <input file>.o")};
93 };
94 
95 struct CompileAndExecuteConfig {
96   /// LLVM module transformer that is passed to ExecutionEngine.
97   llvm::function_ref<llvm::Error(llvm::Module *)> transformer;
98 
99   /// A custom function that is passed to ExecutionEngine. It processes MLIR
100   /// module and creates LLVM IR module.
101   llvm::function_ref<std::unique_ptr<llvm::Module>(ModuleOp,
102                                                    llvm::LLVMContext &)>
103       llvmModuleBuilder;
104 
105   /// A custom function that is passed to ExecutinEngine to register symbols at
106   /// runtime.
107   llvm::function_ref<llvm::orc::SymbolMap(llvm::orc::MangleAndInterner)>
108       runtimeSymbolMap;
109 };
110 
111 } // end anonymous namespace
112 
113 static OwningModuleRef parseMLIRInput(StringRef inputFilename,
114                                       MLIRContext *context) {
115   // Set up the input file.
116   std::string errorMessage;
117   auto file = openInputFile(inputFilename, &errorMessage);
118   if (!file) {
119     llvm::errs() << errorMessage << "\n";
120     return nullptr;
121   }
122 
123   llvm::SourceMgr sourceMgr;
124   sourceMgr.AddNewSourceBuffer(std::move(file), llvm::SMLoc());
125   return OwningModuleRef(parseSourceFile(sourceMgr, context));
126 }
127 
128 static inline Error make_string_error(const Twine &message) {
129   return llvm::make_error<llvm::StringError>(message.str(),
130                                              llvm::inconvertibleErrorCode());
131 }
132 
133 static Optional<unsigned> getCommandLineOptLevel(Options &options) {
134   Optional<unsigned> optLevel;
135   SmallVector<std::reference_wrapper<llvm::cl::opt<bool>>, 4> optFlags{
136       options.optO0, options.optO1, options.optO2, options.optO3};
137 
138   // Determine if there is an optimization flag present.
139   for (unsigned j = 0; j < 4; ++j) {
140     auto &flag = optFlags[j].get();
141     if (flag) {
142       optLevel = j;
143       break;
144     }
145   }
146   return optLevel;
147 }
148 
149 // JIT-compile the given module and run "entryPoint" with "args" as arguments.
150 static Error compileAndExecute(Options &options, ModuleOp module,
151                                StringRef entryPoint,
152                                CompileAndExecuteConfig config, void **args) {
153   Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel;
154   if (auto clOptLevel = getCommandLineOptLevel(options))
155     jitCodeGenOptLevel =
156         static_cast<llvm::CodeGenOpt::Level>(clOptLevel.getValue());
157 
158   // If shared library implements custom mlir-runner library init and destroy
159   // functions, we'll use them to register the library with the execution
160   // engine. Otherwise we'll pass library directly to the execution engine.
161   SmallVector<SmallString<256>, 4> libPaths;
162 
163   // Use absolute library path so that gdb can find the symbol table.
164   transform(
165       options.clSharedLibs, std::back_inserter(libPaths),
166       [](std::string libPath) {
167         SmallString<256> absPath(libPath.begin(), libPath.end());
168         cantFail(llvm::errorCodeToError(llvm::sys::fs::make_absolute(absPath)));
169         return absPath;
170       });
171 
172   // Libraries that we'll pass to the ExecutionEngine for loading.
173   SmallVector<StringRef, 4> executionEngineLibs;
174 
175   using MlirRunnerInitFn = void (*)(llvm::StringMap<void *> &);
176   using MlirRunnerDestroyFn = void (*)();
177 
178   llvm::StringMap<void *> exportSymbols;
179   SmallVector<MlirRunnerDestroyFn> destroyFns;
180 
181   // Handle libraries that do support mlir-runner init/destroy callbacks.
182   for (auto &libPath : libPaths) {
183     auto lib = llvm::sys::DynamicLibrary::getPermanentLibrary(libPath.c_str());
184     void *initSym = lib.getAddressOfSymbol("__mlir_runner_init");
185     void *destroySim = lib.getAddressOfSymbol("__mlir_runner_destroy");
186 
187     // Library does not support mlir runner, load it with ExecutionEngine.
188     if (!initSym || !destroySim) {
189       executionEngineLibs.push_back(libPath);
190       continue;
191     }
192 
193     auto initFn = reinterpret_cast<MlirRunnerInitFn>(initSym);
194     initFn(exportSymbols);
195 
196     auto destroyFn = reinterpret_cast<MlirRunnerDestroyFn>(destroySim);
197     destroyFns.push_back(destroyFn);
198   }
199 
200   // Build a runtime symbol map from the config and exported symbols.
201   auto runtimeSymbolMap = [&](llvm::orc::MangleAndInterner interner) {
202     auto symbolMap = config.runtimeSymbolMap ? config.runtimeSymbolMap(interner)
203                                              : llvm::orc::SymbolMap();
204     for (auto &exportSymbol : exportSymbols)
205       symbolMap[interner(exportSymbol.getKey())] =
206           llvm::JITEvaluatedSymbol::fromPointer(exportSymbol.getValue());
207     return symbolMap;
208   };
209 
210   auto expectedEngine = mlir::ExecutionEngine::create(
211       module, config.llvmModuleBuilder, config.transformer, jitCodeGenOptLevel,
212       executionEngineLibs);
213   if (!expectedEngine)
214     return expectedEngine.takeError();
215 
216   auto engine = std::move(*expectedEngine);
217   engine->registerSymbols(runtimeSymbolMap);
218 
219   auto expectedFPtr = engine->lookup(entryPoint);
220   if (!expectedFPtr)
221     return expectedFPtr.takeError();
222 
223   if (options.dumpObjectFile)
224     engine->dumpToObjectFile(options.objectFilename.empty()
225                                  ? options.inputFilename + ".o"
226                                  : options.objectFilename);
227 
228   void (*fptr)(void **) = *expectedFPtr;
229   (*fptr)(args);
230 
231   // Run all dynamic library destroy callbacks to prepare for the shutdown.
232   llvm::for_each(destroyFns, [](MlirRunnerDestroyFn destroy) { destroy(); });
233 
234   return Error::success();
235 }
236 
237 static Error compileAndExecuteVoidFunction(Options &options, ModuleOp module,
238                                            StringRef entryPoint,
239                                            CompileAndExecuteConfig config) {
240   auto mainFunction = module.lookupSymbol<LLVM::LLVMFuncOp>(entryPoint);
241   if (!mainFunction || mainFunction.empty())
242     return make_string_error("entry point not found");
243   void *empty = nullptr;
244   return compileAndExecute(options, module, entryPoint, config, &empty);
245 }
246 
247 template <typename Type>
248 Error checkCompatibleReturnType(LLVM::LLVMFuncOp mainFunction);
249 template <>
250 Error checkCompatibleReturnType<int32_t>(LLVM::LLVMFuncOp mainFunction) {
251   auto resultType = mainFunction.getType()
252                         .cast<LLVM::LLVMFunctionType>()
253                         .getReturnType()
254                         .dyn_cast<IntegerType>();
255   if (!resultType || resultType.getWidth() != 32)
256     return make_string_error("only single i32 function result supported");
257   return Error::success();
258 }
259 template <>
260 Error checkCompatibleReturnType<int64_t>(LLVM::LLVMFuncOp mainFunction) {
261   auto resultType = mainFunction.getType()
262                         .cast<LLVM::LLVMFunctionType>()
263                         .getReturnType()
264                         .dyn_cast<IntegerType>();
265   if (!resultType || resultType.getWidth() != 64)
266     return make_string_error("only single i64 function result supported");
267   return Error::success();
268 }
269 template <>
270 Error checkCompatibleReturnType<float>(LLVM::LLVMFuncOp mainFunction) {
271   if (!mainFunction.getType()
272            .cast<LLVM::LLVMFunctionType>()
273            .getReturnType()
274            .isa<Float32Type>())
275     return make_string_error("only single f32 function result supported");
276   return Error::success();
277 }
278 template <typename Type>
279 Error compileAndExecuteSingleReturnFunction(Options &options, ModuleOp module,
280                                             StringRef entryPoint,
281                                             CompileAndExecuteConfig config) {
282   auto mainFunction = module.lookupSymbol<LLVM::LLVMFuncOp>(entryPoint);
283   if (!mainFunction || mainFunction.isExternal())
284     return make_string_error("entry point not found");
285 
286   if (mainFunction.getType().cast<LLVM::LLVMFunctionType>().getNumParams() != 0)
287     return make_string_error("function inputs not supported");
288 
289   if (Error error = checkCompatibleReturnType<Type>(mainFunction))
290     return error;
291 
292   Type res;
293   struct {
294     void *data;
295   } data;
296   data.data = &res;
297   if (auto error = compileAndExecute(options, module, entryPoint, config,
298                                      (void **)&data))
299     return error;
300 
301   // Intentional printing of the output so we can test.
302   llvm::outs() << res << '\n';
303 
304   return Error::success();
305 }
306 
307 /// Entry point for all CPU runners. Expects the common argc/argv arguments for
308 /// standard C++ main functions.
309 int mlir::JitRunnerMain(int argc, char **argv, const DialectRegistry &registry,
310                         JitRunnerConfig config) {
311   // Create the options struct containing the command line options for the
312   // runner. This must come before the command line options are parsed.
313   Options options;
314   llvm::cl::ParseCommandLineOptions(argc, argv, "MLIR CPU execution driver\n");
315 
316   Optional<unsigned> optLevel = getCommandLineOptLevel(options);
317   SmallVector<std::reference_wrapper<llvm::cl::opt<bool>>, 4> optFlags{
318       options.optO0, options.optO1, options.optO2, options.optO3};
319   unsigned optCLIPosition = 0;
320   // Determine if there is an optimization flag present, and its CLI position
321   // (optCLIPosition).
322   for (unsigned j = 0; j < 4; ++j) {
323     auto &flag = optFlags[j].get();
324     if (flag) {
325       optCLIPosition = flag.getPosition();
326       break;
327     }
328   }
329   // Generate vector of pass information, plus the index at which we should
330   // insert any optimization passes in that vector (optPosition).
331   SmallVector<const llvm::PassInfo *, 4> passes;
332   unsigned optPosition = 0;
333   for (unsigned i = 0, e = options.llvmPasses.size(); i < e; ++i) {
334     passes.push_back(options.llvmPasses[i]);
335     if (optCLIPosition < options.llvmPasses.getPosition(i)) {
336       optPosition = i;
337       optCLIPosition = UINT_MAX; // To ensure we never insert again
338     }
339   }
340 
341   MLIRContext context(registry);
342 
343   auto m = parseMLIRInput(options.inputFilename, &context);
344   if (!m) {
345     llvm::errs() << "could not parse the input IR\n";
346     return 1;
347   }
348 
349   if (config.mlirTransformer)
350     if (failed(config.mlirTransformer(m.get())))
351       return EXIT_FAILURE;
352 
353   auto tmBuilderOrError = llvm::orc::JITTargetMachineBuilder::detectHost();
354   if (!tmBuilderOrError) {
355     llvm::errs() << "Failed to create a JITTargetMachineBuilder for the host\n";
356     return EXIT_FAILURE;
357   }
358   auto tmOrError = tmBuilderOrError->createTargetMachine();
359   if (!tmOrError) {
360     llvm::errs() << "Failed to create a TargetMachine for the host\n";
361     return EXIT_FAILURE;
362   }
363 
364   auto transformer = mlir::makeLLVMPassesTransformer(
365       passes, optLevel, /*targetMachine=*/tmOrError->get(), optPosition);
366 
367   CompileAndExecuteConfig compileAndExecuteConfig;
368   compileAndExecuteConfig.transformer = transformer;
369   compileAndExecuteConfig.llvmModuleBuilder = config.llvmModuleBuilder;
370   compileAndExecuteConfig.runtimeSymbolMap = config.runtimesymbolMap;
371 
372   // Get the function used to compile and execute the module.
373   using CompileAndExecuteFnT =
374       Error (*)(Options &, ModuleOp, StringRef, CompileAndExecuteConfig);
375   auto compileAndExecuteFn =
376       StringSwitch<CompileAndExecuteFnT>(options.mainFuncType.getValue())
377           .Case("i32", compileAndExecuteSingleReturnFunction<int32_t>)
378           .Case("i64", compileAndExecuteSingleReturnFunction<int64_t>)
379           .Case("f32", compileAndExecuteSingleReturnFunction<float>)
380           .Case("void", compileAndExecuteVoidFunction)
381           .Default(nullptr);
382 
383   Error error = compileAndExecuteFn
384                     ? compileAndExecuteFn(options, m.get(),
385                                           options.mainFuncName.getValue(),
386                                           compileAndExecuteConfig)
387                     : make_string_error("unsupported function type");
388 
389   int exitCode = EXIT_SUCCESS;
390   llvm::handleAllErrors(std::move(error),
391                         [&exitCode](const llvm::ErrorInfoBase &info) {
392                           llvm::errs() << "Error: ";
393                           info.log(llvm::errs());
394                           llvm::errs() << '\n';
395                           exitCode = EXIT_FAILURE;
396                         });
397 
398   return exitCode;
399 }
400