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/Export.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/MC/TargetRegistry.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/Error.h" 33 #include "llvm/Support/Host.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 if (!machine) { 134 errs() << "Unable to create target machine\n"; 135 return true; 136 } 137 llvmModule->setDataLayout(machine->createDataLayout()); 138 llvmModule->setTargetTriple(targetTriple); 139 return false; 140 } 141 142 static std::string makePackedFunctionName(StringRef name) { 143 return "_mlir_" + name.str(); 144 } 145 146 // For each function in the LLVM module, define an interface function that wraps 147 // all the arguments of the original function and all its results into an i8** 148 // pointer to provide a unified invocation interface. 149 static void packFunctionArguments(Module *module) { 150 auto &ctx = module->getContext(); 151 llvm::IRBuilder<> builder(ctx); 152 DenseSet<llvm::Function *> interfaceFunctions; 153 for (auto &func : module->getFunctionList()) { 154 if (func.isDeclaration()) { 155 continue; 156 } 157 if (interfaceFunctions.count(&func)) { 158 continue; 159 } 160 161 // Given a function `foo(<...>)`, define the interface function 162 // `mlir_foo(i8**)`. 163 auto newType = llvm::FunctionType::get( 164 builder.getVoidTy(), builder.getInt8PtrTy()->getPointerTo(), 165 /*isVarArg=*/false); 166 auto newName = makePackedFunctionName(func.getName()); 167 auto funcCst = module->getOrInsertFunction(newName, newType); 168 llvm::Function *interfaceFunc = cast<llvm::Function>(funcCst.getCallee()); 169 interfaceFunctions.insert(interfaceFunc); 170 171 // Extract the arguments from the type-erased argument list and cast them to 172 // the proper types. 173 auto bb = llvm::BasicBlock::Create(ctx); 174 bb->insertInto(interfaceFunc); 175 builder.SetInsertPoint(bb); 176 llvm::Value *argList = interfaceFunc->arg_begin(); 177 SmallVector<llvm::Value *, 8> args; 178 args.reserve(llvm::size(func.args())); 179 for (auto &indexedArg : llvm::enumerate(func.args())) { 180 llvm::Value *argIndex = llvm::Constant::getIntegerValue( 181 builder.getInt64Ty(), APInt(64, indexedArg.index())); 182 llvm::Value *argPtrPtr = builder.CreateGEP( 183 builder.getInt8PtrTy(), argList, argIndex); 184 llvm::Value *argPtr = builder.CreateLoad(builder.getInt8PtrTy(), 185 argPtrPtr); 186 llvm::Type *argTy = indexedArg.value().getType(); 187 argPtr = builder.CreateBitCast(argPtr, argTy->getPointerTo()); 188 llvm::Value *arg = builder.CreateLoad(argTy, argPtr); 189 args.push_back(arg); 190 } 191 192 // Call the implementation function with the extracted arguments. 193 llvm::Value *result = builder.CreateCall(&func, args); 194 195 // Assuming the result is one value, potentially of type `void`. 196 if (!result->getType()->isVoidTy()) { 197 llvm::Value *retIndex = llvm::Constant::getIntegerValue( 198 builder.getInt64Ty(), APInt(64, llvm::size(func.args()))); 199 llvm::Value *retPtrPtr = 200 builder.CreateGEP(builder.getInt8PtrTy(), argList, retIndex); 201 llvm::Value *retPtr = builder.CreateLoad(builder.getInt8PtrTy(), 202 retPtrPtr); 203 retPtr = builder.CreateBitCast(retPtr, result->getType()->getPointerTo()); 204 builder.CreateStore(result, retPtr); 205 } 206 207 // The interface function returns void. 208 builder.CreateRetVoid(); 209 } 210 } 211 212 ExecutionEngine::ExecutionEngine(bool enableObjectCache, 213 bool enableGDBNotificationListener, 214 bool enablePerfNotificationListener) 215 : cache(enableObjectCache ? new SimpleObjectCache() : nullptr), 216 gdbListener(enableGDBNotificationListener 217 ? llvm::JITEventListener::createGDBRegistrationListener() 218 : nullptr), 219 perfListener(enablePerfNotificationListener 220 ? llvm::JITEventListener::createPerfJITEventListener() 221 : nullptr) {} 222 223 Expected<std::unique_ptr<ExecutionEngine>> ExecutionEngine::create( 224 ModuleOp m, 225 llvm::function_ref<std::unique_ptr<llvm::Module>(ModuleOp, 226 llvm::LLVMContext &)> 227 llvmModuleBuilder, 228 llvm::function_ref<Error(llvm::Module *)> transformer, 229 Optional<llvm::CodeGenOpt::Level> jitCodeGenOptLevel, 230 ArrayRef<StringRef> sharedLibPaths, bool enableObjectCache, 231 bool enableGDBNotificationListener, bool enablePerfNotificationListener) { 232 auto engine = std::make_unique<ExecutionEngine>( 233 enableObjectCache, enableGDBNotificationListener, 234 enablePerfNotificationListener); 235 236 std::unique_ptr<llvm::LLVMContext> ctx(new llvm::LLVMContext); 237 auto llvmModule = llvmModuleBuilder ? llvmModuleBuilder(m, *ctx) 238 : translateModuleToLLVMIR(m, *ctx); 239 if (!llvmModule) 240 return make_string_error("could not convert to LLVM IR"); 241 // FIXME: the triple should be passed to the translation or dialect conversion 242 // instead of this. Currently, the LLVM module created above has no triple 243 // associated with it. 244 setupTargetTriple(llvmModule.get()); 245 packFunctionArguments(llvmModule.get()); 246 247 auto dataLayout = llvmModule->getDataLayout(); 248 249 // Callback to create the object layer with symbol resolution to current 250 // process and dynamically linked libraries. 251 auto objectLinkingLayerCreator = [&](ExecutionSession &session, 252 const Triple &TT) { 253 auto objectLayer = std::make_unique<RTDyldObjectLinkingLayer>( 254 session, []() { return std::make_unique<SectionMemoryManager>(); }); 255 256 // Register JIT event listeners if they are enabled. 257 if (engine->gdbListener) 258 objectLayer->registerJITEventListener(*engine->gdbListener); 259 if (engine->perfListener) 260 objectLayer->registerJITEventListener(*engine->perfListener); 261 262 // COFF format binaries (Windows) need special handling to deal with 263 // exported symbol visibility. 264 // cf llvm/lib/ExecutionEngine/Orc/LLJIT.cpp LLJIT::createObjectLinkingLayer 265 llvm::Triple targetTriple(llvm::Twine(llvmModule->getTargetTriple())); 266 if (targetTriple.isOSBinFormatCOFF()) { 267 objectLayer->setOverrideObjectFlagsWithResponsibilityFlags(true); 268 objectLayer->setAutoClaimResponsibilityForObjectSymbols(true); 269 } 270 271 // Resolve symbols from shared libraries. 272 for (auto libPath : sharedLibPaths) { 273 auto mb = llvm::MemoryBuffer::getFile(libPath); 274 if (!mb) { 275 errs() << "Failed to create MemoryBuffer for: " << libPath 276 << "\nError: " << mb.getError().message() << "\n"; 277 continue; 278 } 279 auto &JD = session.createBareJITDylib(std::string(libPath)); 280 auto loaded = DynamicLibrarySearchGenerator::Load( 281 libPath.data(), dataLayout.getGlobalPrefix()); 282 if (!loaded) { 283 errs() << "Could not load " << libPath << ":\n " << loaded.takeError() 284 << "\n"; 285 continue; 286 } 287 JD.addGenerator(std::move(*loaded)); 288 cantFail(objectLayer->add(JD, std::move(mb.get()))); 289 } 290 291 return objectLayer; 292 }; 293 294 // Callback to inspect the cache and recompile on demand. This follows Lang's 295 // LLJITWithObjectCache example. 296 auto compileFunctionCreator = [&](JITTargetMachineBuilder JTMB) 297 -> Expected<std::unique_ptr<IRCompileLayer::IRCompiler>> { 298 if (jitCodeGenOptLevel) 299 JTMB.setCodeGenOptLevel(jitCodeGenOptLevel.getValue()); 300 auto TM = JTMB.createTargetMachine(); 301 if (!TM) 302 return TM.takeError(); 303 return std::make_unique<TMOwningSimpleCompiler>(std::move(*TM), 304 engine->cache.get()); 305 }; 306 307 // Create the LLJIT by calling the LLJITBuilder with 2 callbacks. 308 auto jit = 309 cantFail(llvm::orc::LLJITBuilder() 310 .setCompileFunctionCreator(compileFunctionCreator) 311 .setObjectLinkingLayerCreator(objectLinkingLayerCreator) 312 .create()); 313 314 // Add a ThreadSafemodule to the engine and return. 315 ThreadSafeModule tsm(std::move(llvmModule), std::move(ctx)); 316 if (transformer) 317 cantFail(tsm.withModuleDo( 318 [&](llvm::Module &module) { return transformer(&module); })); 319 cantFail(jit->addIRModule(std::move(tsm))); 320 engine->jit = std::move(jit); 321 322 // Resolve symbols that are statically linked in the current process. 323 llvm::orc::JITDylib &mainJD = engine->jit->getMainJITDylib(); 324 mainJD.addGenerator( 325 cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( 326 dataLayout.getGlobalPrefix()))); 327 328 return std::move(engine); 329 } 330 331 Expected<void (*)(void **)> ExecutionEngine::lookup(StringRef name) const { 332 auto expectedSymbol = jit->lookup(makePackedFunctionName(name)); 333 334 // JIT lookup may return an Error referring to strings stored internally by 335 // the JIT. If the Error outlives the ExecutionEngine, it would want have a 336 // dangling reference, which is currently caught by an assertion inside JIT 337 // thanks to hand-rolled reference counting. Rewrap the error message into a 338 // string before returning. Alternatively, ORC JIT should consider copying 339 // the string into the error message. 340 if (!expectedSymbol) { 341 std::string errorMessage; 342 llvm::raw_string_ostream os(errorMessage); 343 llvm::handleAllErrors(expectedSymbol.takeError(), 344 [&os](llvm::ErrorInfoBase &ei) { ei.log(os); }); 345 return make_string_error(os.str()); 346 } 347 348 auto rawFPtr = expectedSymbol->getAddress(); 349 auto fptr = reinterpret_cast<void (*)(void **)>(rawFPtr); 350 if (!fptr) 351 return make_string_error("looked up function is null"); 352 return fptr; 353 } 354 355 Error ExecutionEngine::invokePacked(StringRef name, 356 MutableArrayRef<void *> args) { 357 auto expectedFPtr = lookup(name); 358 if (!expectedFPtr) 359 return expectedFPtr.takeError(); 360 auto fptr = *expectedFPtr; 361 362 (*fptr)(args.data()); 363 364 return Error::success(); 365 } 366