15a440378SAlex Zinenko //===- ExecutionEngine.cpp - MLIR Execution engine and utils --------------===// 25a440378SAlex Zinenko // 35a440378SAlex Zinenko // Copyright 2019 The MLIR Authors. 45a440378SAlex Zinenko // 55a440378SAlex Zinenko // Licensed under the Apache License, Version 2.0 (the "License"); 65a440378SAlex Zinenko // you may not use this file except in compliance with the License. 75a440378SAlex Zinenko // You may obtain a copy of the License at 85a440378SAlex Zinenko // 95a440378SAlex Zinenko // http://www.apache.org/licenses/LICENSE-2.0 105a440378SAlex Zinenko // 115a440378SAlex Zinenko // Unless required by applicable law or agreed to in writing, software 125a440378SAlex Zinenko // distributed under the License is distributed on an "AS IS" BASIS, 135a440378SAlex Zinenko // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 145a440378SAlex Zinenko // See the License for the specific language governing permissions and 155a440378SAlex Zinenko // limitations under the License. 165a440378SAlex Zinenko // ============================================================================= 175a440378SAlex Zinenko // 185a440378SAlex Zinenko // This file implements the execution engine for MLIR modules based on LLVM Orc 195a440378SAlex Zinenko // JIT engine. 205a440378SAlex Zinenko // 215a440378SAlex Zinenko //===----------------------------------------------------------------------===// 225a440378SAlex Zinenko #include "mlir/ExecutionEngine/ExecutionEngine.h" 235a440378SAlex Zinenko #include "mlir/IR/Function.h" 245a440378SAlex Zinenko #include "mlir/IR/Module.h" 255a440378SAlex Zinenko #include "mlir/Pass.h" 265a440378SAlex Zinenko #include "mlir/Target/LLVMIR.h" 275a440378SAlex Zinenko #include "mlir/Transforms/Passes.h" 285a440378SAlex Zinenko 295a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/CompileUtils.h" 305a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" 315a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" 325a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" 335a440378SAlex Zinenko #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 345a440378SAlex Zinenko #include "llvm/ExecutionEngine/SectionMemoryManager.h" 355a440378SAlex Zinenko #include "llvm/IR/IRBuilder.h" 365a440378SAlex Zinenko #include "llvm/Support/Error.h" 375a440378SAlex Zinenko #include "llvm/Support/TargetRegistry.h" 385a440378SAlex Zinenko 395a440378SAlex Zinenko using namespace mlir; 405a440378SAlex Zinenko using llvm::Error; 415a440378SAlex Zinenko using llvm::Expected; 425a440378SAlex Zinenko 435a440378SAlex Zinenko namespace { 445a440378SAlex Zinenko // Memory manager for the JIT's objectLayer. Its main goal is to fallback to 455a440378SAlex Zinenko // resolving functions in the current process if they cannot be resolved in the 465a440378SAlex Zinenko // JIT-compiled modules. 475a440378SAlex Zinenko class MemoryManager : public llvm::SectionMemoryManager { 485a440378SAlex Zinenko public: 495a440378SAlex Zinenko MemoryManager(llvm::orc::ExecutionSession &execSession) 505a440378SAlex Zinenko : session(execSession) {} 515a440378SAlex Zinenko 525a440378SAlex Zinenko // Resolve the named symbol. First, try looking it up in the main library of 535a440378SAlex Zinenko // the execution session. If there is no such symbol, try looking it up in 545a440378SAlex Zinenko // the current process (for example, if it is a standard library function). 555a440378SAlex Zinenko // Return `nullptr` if lookup fails. 565a440378SAlex Zinenko llvm::JITSymbol findSymbol(const std::string &name) override { 575a440378SAlex Zinenko auto mainLibSymbol = session.lookup({&session.getMainJITDylib()}, name); 585a440378SAlex Zinenko if (mainLibSymbol) 595a440378SAlex Zinenko return mainLibSymbol.get(); 605a440378SAlex Zinenko auto address = llvm::RTDyldMemoryManager::getSymbolAddressInProcess(name); 615a440378SAlex Zinenko if (!address) { 625a440378SAlex Zinenko llvm::errs() << "Could not look up: " << name << '\n'; 635a440378SAlex Zinenko return nullptr; 645a440378SAlex Zinenko } 655a440378SAlex Zinenko return llvm::JITSymbol(address, llvm::JITSymbolFlags::Exported); 665a440378SAlex Zinenko } 675a440378SAlex Zinenko 685a440378SAlex Zinenko private: 695a440378SAlex Zinenko llvm::orc::ExecutionSession &session; 705a440378SAlex Zinenko }; 715a440378SAlex Zinenko } // end anonymous namespace 725a440378SAlex Zinenko 735a440378SAlex Zinenko namespace mlir { 745a440378SAlex Zinenko namespace impl { 755a440378SAlex Zinenko // Simple layered Orc JIT compilation engine. 765a440378SAlex Zinenko class OrcJIT { 775a440378SAlex Zinenko public: 785a440378SAlex Zinenko // Construct a JIT engine for the target host defined by `machineBuilder`, 795a440378SAlex Zinenko // using the data layout provided as `dataLayout`. 805a440378SAlex Zinenko // Setup the object layer to use our custom memory manager in order to resolve 815a440378SAlex Zinenko // calls to library functions present in the process. 825a440378SAlex Zinenko OrcJIT(llvm::orc::JITTargetMachineBuilder machineBuilder, 835a440378SAlex Zinenko llvm::DataLayout layout) 845a440378SAlex Zinenko : objectLayer( 855a440378SAlex Zinenko session, 865a440378SAlex Zinenko [this]() { return llvm::make_unique<MemoryManager>(session); }), 875a440378SAlex Zinenko compileLayer( 885a440378SAlex Zinenko session, objectLayer, 895a440378SAlex Zinenko llvm::orc::ConcurrentIRCompiler(std::move(machineBuilder))), 905a440378SAlex Zinenko dataLayout(layout), mangler(session, this->dataLayout), 915a440378SAlex Zinenko threadSafeCtx(llvm::make_unique<llvm::LLVMContext>()) { 925a440378SAlex Zinenko session.getMainJITDylib().setGenerator( 935a440378SAlex Zinenko cantFail(llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess( 945a440378SAlex Zinenko layout))); 955a440378SAlex Zinenko } 965a440378SAlex Zinenko 975a440378SAlex Zinenko // Create a JIT engine for the current host. 985a440378SAlex Zinenko static Expected<std::unique_ptr<OrcJIT>> createDefault() { 995a440378SAlex Zinenko auto machineBuilder = llvm::orc::JITTargetMachineBuilder::detectHost(); 1005a440378SAlex Zinenko if (!machineBuilder) 1015a440378SAlex Zinenko return machineBuilder.takeError(); 1025a440378SAlex Zinenko 1035a440378SAlex Zinenko auto dataLayout = machineBuilder->getDefaultDataLayoutForTarget(); 1045a440378SAlex Zinenko if (!dataLayout) 1055a440378SAlex Zinenko return dataLayout.takeError(); 1065a440378SAlex Zinenko 1075a440378SAlex Zinenko return llvm::make_unique<OrcJIT>(std::move(*machineBuilder), 1085a440378SAlex Zinenko std::move(*dataLayout)); 1095a440378SAlex Zinenko } 1105a440378SAlex Zinenko 1115a440378SAlex Zinenko // Add an LLVM module to the main library managed by the JIT engine. 1125a440378SAlex Zinenko Error addModule(std::unique_ptr<llvm::Module> M) { 1135a440378SAlex Zinenko return compileLayer.add( 1145a440378SAlex Zinenko session.getMainJITDylib(), 1155a440378SAlex Zinenko llvm::orc::ThreadSafeModule(std::move(M), threadSafeCtx)); 1165a440378SAlex Zinenko } 1175a440378SAlex Zinenko 1185a440378SAlex Zinenko // Lookup a symbol in the main library managed by the JIT engine. 1195a440378SAlex Zinenko Expected<llvm::JITEvaluatedSymbol> lookup(StringRef Name) { 1205a440378SAlex Zinenko return session.lookup({&session.getMainJITDylib()}, mangler(Name.str())); 1215a440378SAlex Zinenko } 1225a440378SAlex Zinenko 1235a440378SAlex Zinenko private: 1245a440378SAlex Zinenko llvm::orc::ExecutionSession session; 1255a440378SAlex Zinenko llvm::orc::RTDyldObjectLinkingLayer objectLayer; 1265a440378SAlex Zinenko llvm::orc::IRCompileLayer compileLayer; 1275a440378SAlex Zinenko llvm::DataLayout dataLayout; 1285a440378SAlex Zinenko llvm::orc::MangleAndInterner mangler; 1295a440378SAlex Zinenko llvm::orc::ThreadSafeContext threadSafeCtx; 1305a440378SAlex Zinenko }; 1315a440378SAlex Zinenko } // end namespace impl 1325a440378SAlex Zinenko } // namespace mlir 1335a440378SAlex Zinenko 1345a440378SAlex Zinenko // Wrap a string into an llvm::StringError. 1355a440378SAlex Zinenko static inline Error make_string_error(const llvm::Twine &message) { 1365a440378SAlex Zinenko return llvm::make_error<llvm::StringError>(message.str(), 1375a440378SAlex Zinenko llvm::inconvertibleErrorCode()); 1385a440378SAlex Zinenko } 1395a440378SAlex Zinenko 1405a440378SAlex Zinenko // Given a list of PassInfo coming from a higher level, creates the passes to 1415a440378SAlex Zinenko // run as an owning vector and appends the extra required passes to lower to 1425a440378SAlex Zinenko // LLVMIR. Currently, these extra passes are: 1435a440378SAlex Zinenko // - constant folding 1445a440378SAlex Zinenko // - CSE 1455a440378SAlex Zinenko // - canonicalization 1465a440378SAlex Zinenko // - affine lowering 1475a440378SAlex Zinenko static std::vector<std::unique_ptr<mlir::Pass>> 1485a440378SAlex Zinenko getDefaultPasses(const std::vector<const mlir::PassInfo *> &mlirPassInfoList) { 1495a440378SAlex Zinenko std::vector<std::unique_ptr<mlir::Pass>> passList; 1505a440378SAlex Zinenko passList.reserve(mlirPassInfoList.size() + 4); 1515a440378SAlex Zinenko // Run each of the passes that were selected. 1525a440378SAlex Zinenko for (const auto *passInfo : mlirPassInfoList) { 1535a440378SAlex Zinenko passList.emplace_back(passInfo->createPass()); 1545a440378SAlex Zinenko } 1555a440378SAlex Zinenko // Append the extra passes for lowering to MLIR. 1565a440378SAlex Zinenko passList.emplace_back(mlir::createConstantFoldPass()); 1575a440378SAlex Zinenko passList.emplace_back(mlir::createCSEPass()); 1585a440378SAlex Zinenko passList.emplace_back(mlir::createCanonicalizerPass()); 1595a440378SAlex Zinenko passList.emplace_back(mlir::createLowerAffinePass()); 1605a440378SAlex Zinenko return passList; 1615a440378SAlex Zinenko } 1625a440378SAlex Zinenko 1635a440378SAlex Zinenko // Run the passes sequentially on the given module. 1645a440378SAlex Zinenko // Return `nullptr` immediately if any of the passes fails. 1655a440378SAlex Zinenko static bool runPasses(const std::vector<std::unique_ptr<mlir::Pass>> &passes, 1665a440378SAlex Zinenko Module *module) { 1675a440378SAlex Zinenko for (const auto &pass : passes) { 1685a440378SAlex Zinenko mlir::PassResult result = pass->runOnModule(module); 1695a440378SAlex Zinenko if (result == mlir::PassResult::Failure || module->verify()) { 1705a440378SAlex Zinenko llvm::errs() << "Pass failed\n"; 1715a440378SAlex Zinenko return true; 1725a440378SAlex Zinenko } 1735a440378SAlex Zinenko } 1745a440378SAlex Zinenko return false; 1755a440378SAlex Zinenko } 1765a440378SAlex Zinenko 1775a440378SAlex Zinenko // Setup LLVM target triple from the current machine. 1785a440378SAlex Zinenko static bool setupTargetTriple(llvm::Module *llvmModule) { 1795a440378SAlex Zinenko // Setup the machine properties from the current architecture. 1805a440378SAlex Zinenko auto targetTriple = llvm::sys::getDefaultTargetTriple(); 1815a440378SAlex Zinenko std::string errorMessage; 1825a440378SAlex Zinenko auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); 1835a440378SAlex Zinenko if (!target) { 1845a440378SAlex Zinenko llvm::errs() << "NO target: " << errorMessage << "\n"; 1855a440378SAlex Zinenko return true; 1865a440378SAlex Zinenko } 1875a440378SAlex Zinenko auto machine = 1885a440378SAlex Zinenko target->createTargetMachine(targetTriple, "generic", "", {}, {}); 1895a440378SAlex Zinenko llvmModule->setDataLayout(machine->createDataLayout()); 1905a440378SAlex Zinenko llvmModule->setTargetTriple(targetTriple); 1915a440378SAlex Zinenko return false; 1925a440378SAlex Zinenko } 1935a440378SAlex Zinenko 1945a440378SAlex Zinenko static std::string makePackedFunctionName(StringRef name) { 1955a440378SAlex Zinenko return "_mlir_" + name.str(); 1965a440378SAlex Zinenko } 1975a440378SAlex Zinenko 1985a440378SAlex Zinenko // For each function in the LLVM module, define an interface function that wraps 1995a440378SAlex Zinenko // all the arguments of the original function and all its results into an i8** 2005a440378SAlex Zinenko // pointer to provide a unified invocation interface. 2015a440378SAlex Zinenko void packFunctionArguments(llvm::Module *module) { 2025a440378SAlex Zinenko auto &ctx = module->getContext(); 2035a440378SAlex Zinenko llvm::IRBuilder<> builder(ctx); 2045a440378SAlex Zinenko llvm::DenseSet<llvm::Function *> interfaceFunctions; 2055a440378SAlex Zinenko for (auto &func : module->getFunctionList()) { 2065a440378SAlex Zinenko if (func.isDeclaration()) { 2075a440378SAlex Zinenko continue; 2085a440378SAlex Zinenko } 2095a440378SAlex Zinenko if (interfaceFunctions.count(&func)) { 2105a440378SAlex Zinenko continue; 2115a440378SAlex Zinenko } 2125a440378SAlex Zinenko 2135a440378SAlex Zinenko // Given a function `foo(<...>)`, define the interface function 2145a440378SAlex Zinenko // `mlir_foo(i8**)`. 2155a440378SAlex Zinenko auto newType = llvm::FunctionType::get( 2165a440378SAlex Zinenko builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), 2175a440378SAlex Zinenko /*isVarArg=*/false); 2185a440378SAlex Zinenko auto newName = makePackedFunctionName(func.getName()); 2195a440378SAlex Zinenko llvm::Constant *funcCst = module->getOrInsertFunction(newName, newType); 2205a440378SAlex Zinenko llvm::Function *interfaceFunc = llvm::cast<llvm::Function>(funcCst); 2215a440378SAlex Zinenko interfaceFunctions.insert(interfaceFunc); 2225a440378SAlex Zinenko 2235a440378SAlex Zinenko // Extract the arguments from the type-erased argument list and cast them to 2245a440378SAlex Zinenko // the proper types. 2255a440378SAlex Zinenko auto bb = llvm::BasicBlock::Create(ctx); 2265a440378SAlex Zinenko bb->insertInto(interfaceFunc); 2275a440378SAlex Zinenko builder.SetInsertPoint(bb); 2285a440378SAlex Zinenko llvm::Value *argList = interfaceFunc->arg_begin(); 2295a440378SAlex Zinenko llvm::SmallVector<llvm::Value *, 8> args; 2305a440378SAlex Zinenko args.reserve(llvm::size(func.args())); 2315a440378SAlex Zinenko for (auto &indexedArg : llvm::enumerate(func.args())) { 2325a440378SAlex Zinenko llvm::Value *argIndex = llvm::Constant::getIntegerValue( 2335a440378SAlex Zinenko builder.getInt64Ty(), llvm::APInt(64, indexedArg.index())); 2345a440378SAlex Zinenko llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); 2355a440378SAlex Zinenko llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); 2365a440378SAlex Zinenko argPtr = builder.CreateBitCast( 2375a440378SAlex Zinenko argPtr, indexedArg.value().getType()->getPointerTo()); 2385a440378SAlex Zinenko llvm::Value *arg = builder.CreateLoad(argPtr); 2395a440378SAlex Zinenko args.push_back(arg); 2405a440378SAlex Zinenko } 2415a440378SAlex Zinenko 2425a440378SAlex Zinenko // Call the implementation function with the extracted arguments. 2435a440378SAlex Zinenko llvm::Value *result = builder.CreateCall(&func, args); 2445a440378SAlex Zinenko 2455a440378SAlex Zinenko // Assuming the result is one value, potentially of type `void`. 2465a440378SAlex Zinenko if (!result->getType()->isVoidTy()) { 2475a440378SAlex Zinenko llvm::Value *retIndex = llvm::Constant::getIntegerValue( 2485a440378SAlex Zinenko builder.getInt64Ty(), llvm::APInt(64, llvm::size(func.args()))); 2495a440378SAlex Zinenko llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); 2505a440378SAlex Zinenko llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); 2515a440378SAlex Zinenko retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); 2525a440378SAlex Zinenko builder.CreateStore(result, retPtr); 2535a440378SAlex Zinenko } 2545a440378SAlex Zinenko 2555a440378SAlex Zinenko // The interface function returns void. 2565a440378SAlex Zinenko builder.CreateRetVoid(); 2575a440378SAlex Zinenko } 2585a440378SAlex Zinenko } 2595a440378SAlex Zinenko 260d9ce382fSMehdi Amini // Out of line for PIMPL unique_ptr. 261d9ce382fSMehdi Amini ExecutionEngine::~ExecutionEngine() = default; 2625a440378SAlex Zinenko 2635a440378SAlex Zinenko Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create(Module *m) { 2645a440378SAlex Zinenko auto engine = llvm::make_unique<ExecutionEngine>(); 2655a440378SAlex Zinenko auto expectedJIT = impl::OrcJIT::createDefault(); 2665a440378SAlex Zinenko if (!expectedJIT) 2675a440378SAlex Zinenko return expectedJIT.takeError(); 2685a440378SAlex Zinenko 2695a440378SAlex Zinenko if (runPasses(getDefaultPasses({}), m)) 2705a440378SAlex Zinenko return make_string_error("passes failed"); 2715a440378SAlex Zinenko 2725a440378SAlex Zinenko auto llvmModule = convertModuleToLLVMIR(*m, engine->llvmContext); 2735a440378SAlex Zinenko if (!llvmModule) 2745a440378SAlex Zinenko return make_string_error("could not convert to LLVM IR"); 2755a440378SAlex Zinenko // FIXME: the triple should be passed to the translation or dialect conversion 2765a440378SAlex Zinenko // instead of this. Currently, the LLVM module created above has no triple 2775a440378SAlex Zinenko // associated with it. 2785a440378SAlex Zinenko setupTargetTriple(llvmModule.get()); 2795a440378SAlex Zinenko packFunctionArguments(llvmModule.get()); 2805a440378SAlex Zinenko 281*cacf0589SNicolas Vasilache if (auto err = (*expectedJIT)->addModule(std::move(llvmModule))) 2825a440378SAlex Zinenko return std::move(err); 283*cacf0589SNicolas Vasilache engine->jit = std::move(*expectedJIT); 2845a440378SAlex Zinenko 2855a440378SAlex Zinenko return engine; 2865a440378SAlex Zinenko } 2875a440378SAlex Zinenko 2885a440378SAlex Zinenko Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { 2895a440378SAlex Zinenko auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); 2905a440378SAlex Zinenko if (!expectedSymbol) 2915a440378SAlex Zinenko return expectedSymbol.takeError(); 2925a440378SAlex Zinenko auto rawFPtr = expectedSymbol->getAddress(); 2935a440378SAlex Zinenko auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); 2945a440378SAlex Zinenko if (!fptr) 2955a440378SAlex Zinenko return make_string_error("looked up function is null"); 2965a440378SAlex Zinenko return fptr; 2975a440378SAlex Zinenko } 298629f5b7fSNicolas Vasilache 299629f5b7fSNicolas Vasilache llvm::Error ExecutionEngine::invoke(StringRef name, 300629f5b7fSNicolas Vasilache MutableArrayRef<void *> args) { 301629f5b7fSNicolas Vasilache auto expectedFPtr = lookup(name); 302629f5b7fSNicolas Vasilache if (!expectedFPtr) 303629f5b7fSNicolas Vasilache return expectedFPtr.takeError(); 304629f5b7fSNicolas Vasilache auto fptr = *expectedFPtr; 305629f5b7fSNicolas Vasilache 306629f5b7fSNicolas Vasilache (*fptr)(args.data()); 307629f5b7fSNicolas Vasilache 308629f5b7fSNicolas Vasilache return llvm::Error::success(); 309629f5b7fSNicolas Vasilache } 310