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