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/Dialect/LLVMIR/LLVMDialect.h" 15 #include "mlir/IR/BuiltinOps.h" 16 #include "mlir/Support/FileUtilities.h" 17 #include "mlir/Target/LLVMIR.h" 18 19 #include "llvm/ExecutionEngine/JITEventListener.h" 20 #include "llvm/ExecutionEngine/ObjectCache.h" 21 #include "llvm/ExecutionEngine/Orc/CompileUtils.h" 22 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" 23 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" 24 #include "llvm/ExecutionEngine/Orc/IRTransformLayer.h" 25 #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" 26 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 27 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/MC/SubtargetFeature.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/Error.h" 32 #include "llvm/Support/Host.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::MangleAndInterner; 55 using llvm::orc::RTDyldObjectLinkingLayer; 56 using llvm::orc::SymbolMap; 57 using llvm::orc::ThreadSafeModule; 58 using llvm::orc::TMOwningSimpleCompiler; 59 60 /// Wrap a string into an llvm::StringError. 61 static Error make_string_error(const Twine &message) { 62 return llvm::make_error<StringError>(message.str(), 63 llvm::inconvertibleErrorCode()); 64 } 65 66 void SimpleObjectCache::notifyObjectCompiled(const Module *M, 67 MemoryBufferRef ObjBuffer) { 68 cachedObjects[M->getModuleIdentifier()] = MemoryBuffer::getMemBufferCopy( 69 ObjBuffer.getBuffer(), ObjBuffer.getBufferIdentifier()); 70 } 71 72 std::unique_ptr<MemoryBuffer> SimpleObjectCache::getObject(const Module *M) { 73 auto I = cachedObjects.find(M->getModuleIdentifier()); 74 if (I == cachedObjects.end()) { 75 LLVM_DEBUG(dbgs() << "No object for " << M->getModuleIdentifier() 76 << " in cache. Compiling.\n"); 77 return nullptr; 78 } 79 LLVM_DEBUG(dbgs() << "Object for " << M->getModuleIdentifier() 80 << " loaded from cache.\n"); 81 return MemoryBuffer::getMemBuffer(I->second->getMemBufferRef()); 82 } 83 84 void SimpleObjectCache::dumpToObjectFile(StringRef outputFilename) { 85 // Set up the output file. 86 std::string errorMessage; 87 auto file = openOutputFile(outputFilename, &errorMessage); 88 if (!file) { 89 llvm::errs() << errorMessage << "\n"; 90 return; 91 } 92 93 // Dump the object generated for a single module to the output file. 94 assert(cachedObjects.size() == 1 && "Expected only one object entry."); 95 auto &cachedObject = cachedObjects.begin()->second; 96 file->os() << cachedObject->getBuffer(); 97 file->keep(); 98 } 99 100 void ExecutionEngine::dumpToObjectFile(StringRef filename) { 101 cache->dumpToObjectFile(filename); 102 } 103 104 void ExecutionEngine::registerSymbols( 105 llvm::function_ref<SymbolMap(MangleAndInterner)> symbolMap) { 106 auto &mainJitDylib = jit->getMainJITDylib(); 107 cantFail(mainJitDylib.define( 108 absoluteSymbols(symbolMap(llvm::orc::MangleAndInterner( 109 mainJitDylib.getExecutionSession(), jit->getDataLayout()))))); 110 } 111 112 // Setup LLVM target triple from the current machine. 113 bool ExecutionEngine::setupTargetTriple(Module *llvmModule) { 114 // Setup the machine properties from the current architecture. 115 auto targetTriple = llvm::sys::getDefaultTargetTriple(); 116 std::string errorMessage; 117 auto target = llvm::TargetRegistry::lookupTarget(targetTriple, errorMessage); 118 if (!target) { 119 errs() << "NO target: " << errorMessage << "\n"; 120 return true; 121 } 122 123 std::string cpu(llvm::sys::getHostCPUName()); 124 llvm::SubtargetFeatures features; 125 llvm::StringMap<bool> hostFeatures; 126 127 if (llvm::sys::getHostCPUFeatures(hostFeatures)) 128 for (auto &f : hostFeatures) 129 features.AddFeature(f.first(), f.second); 130 131 std::unique_ptr<llvm::TargetMachine> machine(target->createTargetMachine( 132 targetTriple, cpu, features.getString(), {}, {})); 133 llvmModule->setDataLayout(machine->createDataLayout()); 134 llvmModule->setTargetTriple(targetTriple); 135 return false; 136 } 137 138 static std::string makePackedFunctionName(StringRef name) { 139 return "_mlir_" + name.str(); 140 } 141 142 // For each function in the LLVM module, define an interface function that wraps 143 // all the arguments of the original function and all its results into an i8** 144 // pointer to provide a unified invocation interface. 145 static void packFunctionArguments(Module *module) { 146 auto &ctx = module->getContext(); 147 llvm::IRBuilder<> builder(ctx); 148 DenseSet<llvm::Function *> interfaceFunctions; 149 for (auto &func : module->getFunctionList()) { 150 if (func.isDeclaration()) { 151 continue; 152 } 153 if (interfaceFunctions.count(&func)) { 154 continue; 155 } 156 157 // Given a function `foo(<...>)`, define the interface function 158 // `mlir_foo(i8**)`. 159 auto newType = llvm::FunctionType::get( 160 builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), 161 /*isVarArg=*/false); 162 auto newName = makePackedFunctionName(func.getName()); 163 auto funcCst = module->getOrInsertFunction(newName, newType); 164 llvm::Function *interfaceFunc = cast<llvm::Function>(funcCst.getCallee()); 165 interfaceFunctions.insert(interfaceFunc); 166 167 // Extract the arguments from the type-erased argument list and cast them to 168 // the proper types. 169 auto bb = llvm::BasicBlock::Create(ctx); 170 bb->insertInto(interfaceFunc); 171 builder.SetInsertPoint(bb); 172 llvm::Value *argList = interfaceFunc->arg_begin(); 173 SmallVector<llvm::Value *, 8> args; 174 args.reserve(llvm::size(func.args())); 175 for (auto &indexedArg : llvm::enumerate(func.args())) { 176 llvm::Value *argIndex = llvm::Constant::getIntegerValue( 177 builder.getInt64Ty(), APInt(64, indexedArg.index())); 178 llvm::Value *argPtrPtr = builder.CreateGEP(argList, argIndex); 179 llvm::Value *argPtr = builder.CreateLoad(argPtrPtr); 180 argPtr = builder.CreateBitCast( 181 argPtr, indexedArg.value().getType()->getPointerTo()); 182 llvm::Value *arg = builder.CreateLoad(argPtr); 183 args.push_back(arg); 184 } 185 186 // Call the implementation function with the extracted arguments. 187 llvm::Value *result = builder.CreateCall(&func, args); 188 189 // Assuming the result is one value, potentially of type `void`. 190 if (!result->getType()->isVoidTy()) { 191 llvm::Value *retIndex = llvm::Constant::getIntegerValue( 192 builder.getInt64Ty(), APInt(64, llvm::size(func.args()))); 193 llvm::Value *retPtrPtr = builder.CreateGEP(argList, retIndex); 194 llvm::Value *retPtr = builder.CreateLoad(retPtrPtr); 195 retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); 196 builder.CreateStore(result, retPtr); 197 } 198 199 // The interface function returns void. 200 builder.CreateRetVoid(); 201 } 202 } 203 204 ExecutionEngine::ExecutionEngine(bool enableObjectCache, 205 bool enableGDBNotificationListener, 206 bool enablePerfNotificationListener) 207 : cache(enableObjectCache ? new SimpleObjectCache() : nullptr), 208 gdbListener(enableGDBNotificationListener 209 ? llvm::JITEventListener::createGDBRegistrationListener() 210 : nullptr), 211 perfListener(enablePerfNotificationListener 212 ? llvm::JITEventListener::createPerfJITEventListener() 213 : nullptr) {} 214 215 Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( 216 ModuleOp m, 217 llvm::function_ref<std::unique_ptr<llvm::Module>(ModuleOp, 218 llvm::LLVMContext &)> 219 llvmModuleBuilder, 220 llvm::function_ref<Error(llvm::Module *)> transformer, 221 Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel, 222 ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache, 223 bool enableGDBNotificationListener, bool enablePerfNotificationListener) { 224 auto engine = std::make_unique<ExecutionEngine>( 225 enableObjectCache, enableGDBNotificationListener, 226 enablePerfNotificationListener); 227 228 std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext); 229 auto llvmModule = llvmModuleBuilder ? llvmModuleBuilder(m, *ctx) 230 : translateModuleToLLVMIR(m, *ctx); 231 if (!llvmModule) 232 return make_string_error("could not convert to LLVM IR"); 233 // FIXME: the triple should be passed to the translation or dialect conversion 234 // instead of this. Currently, the LLVM module created above has no triple 235 // associated with it. 236 setupTargetTriple(llvmModule.get()); 237 packFunctionArguments(llvmModule.get()); 238 239 auto dataLayout = llvmModule->getDataLayout(); 240 241 // Callback to create the object layer with symbol resolution to current 242 // process and dynamically linked libraries. 243 auto objectLinkingLayerCreator = [&](ExecutionSession &session, 244 const Triple &TT) { 245 auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>( 246 session, []() { return std::make_unique<SectionMemoryManager>(); }); 247 248 // Register JIT event listeners if they are enabled. 249 if (engine->gdbListener) 250 objectLayer->registerJITEventListener(*engine->gdbListener); 251 if (engine->perfListener) 252 objectLayer->registerJITEventListener(*engine->perfListener); 253 254 // Resolve symbols from shared libraries. 255 for (auto libPath : sharedLibPaths) { 256 auto mb = llvm::MemoryBuffer::getFile(libPath); 257 if (!mb) { 258 errs() << "Failed to create MemoryBuffer for: " << libPath 259 << "\nError: " << mb.getError().message() << "\n"; 260 continue; 261 } 262 auto &JD = session.createBareJITDylib(std::string(libPath)); 263 auto loaded = DynamicLibrarySearchGenerator::Load( 264 libPath.data(), dataLayout.getGlobalPrefix()); 265 if (!loaded) { 266 errs() << "Could not load " << libPath << ":\n " << loaded.takeError() 267 << "\n"; 268 continue; 269 } 270 JD.addGenerator(std::move(*loaded)); 271 cantFail(objectLayer->add(JD, std::move(mb.get()))); 272 } 273 274 return objectLayer; 275 }; 276 277 // Callback to inspect the cache and recompile on demand. This follows Lang's 278 // LLJITWithObjectCache example. 279 auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB) 280 -> Expected<std::unique_ptr<IRCompileLayer::IRCompiler>> { 281 if (jitCodeGenOptLevel) 282 JTMB.setCodeGenOptLevel(jitCodeGenOptLevel.getValue()); 283 auto TM = JTMB.createTargetMachine(); 284 if (!TM) 285 return TM.takeError(); 286 return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM), 287 engine->cache.get()); 288 }; 289 290 // Create the LLJIT by calling the LLJITBuilder with 2 callbacks. 291 auto jit = 292 cantFail(llvm::orc::LLJITBuilder() 293 .setCompileFunctionCreator(compileFunctionCreator) 294 .setObjectLinkingLayerCreator(objectLinkingLayerCreator) 295 .create()); 296 297 // Add a ThreadSafemodule to the engine and return. 298 ThreadSafeModule tsm(std::move(llvmModule), std::move(ctx)); 299 if (transformer) 300 cantFail(tsm.withModuleDo( 301 [&](llvm::Module &module) { return transformer(&module); })); 302 cantFail(jit->addIRModule(std::move(tsm))); 303 engine->jit = std::move(jit); 304 305 // Resolve symbols that are statically linked in the current process. 306 llvm::orc::JITDylib &mainJD = engine->jit->getMainJITDylib(); 307 mainJD.addGenerator( 308 cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( 309 dataLayout.getGlobalPrefix()))); 310 311 return std::move(engine); 312 } 313 314 Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { 315 auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); 316 317 // JIT lookup may return an Error referring to strings stored internally by 318 // the JIT. If the Error outlives the ExecutionEngine, it would want have a 319 // dangling reference, which is currently caught by an assertion inside JIT 320 // thanks to hand-rolled reference counting. Rewrap the error message into a 321 // string before returning. Alternatively, ORC JIT should consider copying 322 // the string into the error message. 323 if (!expectedSymbol) { 324 std::string errorMessage; 325 llvm::raw_string_ostream os(errorMessage); 326 llvm::handleAllErrors(expectedSymbol.takeError(), 327 [&os](llvm::ErrorInfoBase &ei) { ei.log(os); }); 328 return make_string_error(os.str()); 329 } 330 331 auto rawFPtr = expectedSymbol->getAddress(); 332 auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); 333 if (!fptr) 334 return make_string_error("looked up function is null"); 335 return fptr; 336 } 337 338 Error ExecutionEngine::invoke(StringRef name, MutableArrayRef<void *> args) { 339 auto expectedFPtr = lookup(name); 340 if (!expectedFPtr) 341 return expectedFPtr.takeError(); 342 auto fptr = *expectedFPtr; 343 344 (*fptr)(args.data()); 345 346 return Error::success(); 347 } 348