#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/ExecutionEngine/JitRunner.h"
#include "mlir/ExecutionEngine/OptUtils.h"
#include "mlir/IR/Dialect.h"
#include "mlir/Target/LLVMIR/Dialect/All.h"
#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
#include "mlir/Target/LLVMIR/Export.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/TargetSelect.h"
using namespace mlir;
static llvm::cl::opt<bool> linkNestedModules(
"link-nested-modules",
llvm::cl::desc("Link two nested MLIR modules into a single LLVM IR module. "
"Useful if both the host and device code can be run on the "
"same CPU, as in SPIR-V CPU Runner tests."));
static std::unique_ptr<llvm::Module>
convertMLIRModule(Operation *op, llvm::LLVMContext &context) {
auto module = dyn_cast<ModuleOp>(op);
if (!module)
return op->emitError("op must be a 'builtin.module"), nullptr;
std::unique_ptr<llvm::Module> kernelModule;
if (linkNestedModules) {
auto modules = module.getOps<ModuleOp>();
if (!llvm::hasSingleElement(modules)) {
module.emitError("The module must contain exactly one nested module");
return nullptr;
}
ModuleOp nested = *modules.begin();
kernelModule = translateModuleToLLVMIR(nested, context);
nested.erase();
}
std::unique_ptr<llvm::Module> mainModule =
translateModuleToLLVMIR(module, context);
if (linkNestedModules)
llvm::Linker::linkModules(*mainModule, std::move(kernelModule));
return mainModule;
}
int main(int argc, char **argv) {
llvm::InitLLVM y(argc, argv);
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
mlir::DialectRegistry registry;
mlir::registerAllToLLVMIRTranslations(registry);
mlir::JitRunnerConfig jitRunnerConfig;
jitRunnerConfig.llvmModuleBuilder = convertMLIRModule;
return mlir::JitRunnerMain(argc, argv, registry, jitRunnerConfig);
}