1 //===--------- LLJIT.cpp - An ORC-based JIT for compiling LLVM IR ---------===// 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 #include "llvm/ExecutionEngine/Orc/LLJIT.h" 10 #include "llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h" 11 #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h" 12 #include "llvm/ExecutionEngine/Orc/OrcError.h" 13 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" 14 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 15 #include "llvm/IR/Mangler.h" 16 17 namespace llvm { 18 namespace orc { 19 20 Error LLJITBuilderState::prepareForConstruction() { 21 22 if (!JTMB) { 23 if (auto JTMBOrErr = JITTargetMachineBuilder::detectHost()) 24 JTMB = std::move(*JTMBOrErr); 25 else 26 return JTMBOrErr.takeError(); 27 } 28 29 // If the client didn't configure any linker options then auto-configure the 30 // JIT linker. 31 if (!CreateObjectLinkingLayer && JTMB->getCodeModel() == None && 32 JTMB->getRelocationModel() == None) { 33 34 auto &TT = JTMB->getTargetTriple(); 35 if (TT.isOSBinFormatMachO() && 36 (TT.getArch() == Triple::aarch64 || TT.getArch() == Triple::x86_64)) { 37 38 JTMB->setRelocationModel(Reloc::PIC_); 39 JTMB->setCodeModel(CodeModel::Small); 40 CreateObjectLinkingLayer = 41 [](ExecutionSession &ES, 42 const Triple &) -> std::unique_ptr<ObjectLayer> { 43 return std::make_unique<ObjectLinkingLayer>( 44 ES, std::make_unique<jitlink::InProcessMemoryManager>()); 45 }; 46 } 47 } 48 49 return Error::success(); 50 } 51 52 LLJIT::~LLJIT() { 53 if (CompileThreads) 54 CompileThreads->wait(); 55 } 56 57 Error LLJIT::defineAbsolute(StringRef Name, JITEvaluatedSymbol Sym) { 58 auto InternedName = ES->intern(Name); 59 SymbolMap Symbols({{InternedName, Sym}}); 60 return Main.define(absoluteSymbols(std::move(Symbols))); 61 } 62 63 Error LLJIT::addIRModule(JITDylib &JD, ThreadSafeModule TSM) { 64 assert(TSM && "Can not add null module"); 65 66 if (auto Err = 67 TSM.withModuleDo([&](Module &M) { return applyDataLayout(M); })) 68 return Err; 69 70 return CompileLayer->add(JD, std::move(TSM), ES->allocateVModule()); 71 } 72 73 Error LLJIT::addObjectFile(JITDylib &JD, std::unique_ptr<MemoryBuffer> Obj) { 74 assert(Obj && "Can not add null object"); 75 76 return ObjTransformLayer.add(JD, std::move(Obj), ES->allocateVModule()); 77 } 78 79 Expected<JITEvaluatedSymbol> LLJIT::lookupLinkerMangled(JITDylib &JD, 80 StringRef Name) { 81 return ES->lookup( 82 makeJITDylibSearchOrder(&JD, JITDylibLookupFlags::MatchAllSymbols), 83 ES->intern(Name)); 84 } 85 86 std::unique_ptr<ObjectLayer> 87 LLJIT::createObjectLinkingLayer(LLJITBuilderState &S, ExecutionSession &ES) { 88 89 // If the config state provided an ObjectLinkingLayer factory then use it. 90 if (S.CreateObjectLinkingLayer) 91 return S.CreateObjectLinkingLayer(ES, S.JTMB->getTargetTriple()); 92 93 // Otherwise default to creating an RTDyldObjectLinkingLayer that constructs 94 // a new SectionMemoryManager for each object. 95 auto GetMemMgr = []() { return std::make_unique<SectionMemoryManager>(); }; 96 auto ObjLinkingLayer = 97 std::make_unique<RTDyldObjectLinkingLayer>(ES, std::move(GetMemMgr)); 98 99 if (S.JTMB->getTargetTriple().isOSBinFormatCOFF()) 100 ObjLinkingLayer->setOverrideObjectFlagsWithResponsibilityFlags(true); 101 102 // FIXME: Explicit conversion to std::unique_ptr<ObjectLayer> added to silence 103 // errors from some GCC / libstdc++ bots. Remove this conversion (i.e. 104 // just return ObjLinkingLayer) once those bots are upgraded. 105 return std::unique_ptr<ObjectLayer>(std::move(ObjLinkingLayer)); 106 } 107 108 Expected<IRCompileLayer::CompileFunction> 109 LLJIT::createCompileFunction(LLJITBuilderState &S, 110 JITTargetMachineBuilder JTMB) { 111 112 /// If there is a custom compile function creator set then use it. 113 if (S.CreateCompileFunction) 114 return S.CreateCompileFunction(std::move(JTMB)); 115 116 // Otherwise default to creating a SimpleCompiler, or ConcurrentIRCompiler, 117 // depending on the number of threads requested. 118 if (S.NumCompileThreads > 0) 119 return ConcurrentIRCompiler(std::move(JTMB)); 120 121 auto TM = JTMB.createTargetMachine(); 122 if (!TM) 123 return TM.takeError(); 124 125 return TMOwningSimpleCompiler(std::move(*TM)); 126 } 127 128 LLJIT::LLJIT(LLJITBuilderState &S, Error &Err) 129 : ES(S.ES ? std::move(S.ES) : std::make_unique<ExecutionSession>()), 130 Main(this->ES->createJITDylib("<main>")), DL(""), 131 ObjLinkingLayer(createObjectLinkingLayer(S, *ES)), 132 ObjTransformLayer(*this->ES, *ObjLinkingLayer), CtorRunner(Main), 133 DtorRunner(Main) { 134 135 ErrorAsOutParameter _(&Err); 136 137 if (auto DLOrErr = S.JTMB->getDefaultDataLayoutForTarget()) 138 DL = std::move(*DLOrErr); 139 else { 140 Err = DLOrErr.takeError(); 141 return; 142 } 143 144 { 145 auto CompileFunction = createCompileFunction(S, std::move(*S.JTMB)); 146 if (!CompileFunction) { 147 Err = CompileFunction.takeError(); 148 return; 149 } 150 CompileLayer = std::make_unique<IRCompileLayer>( 151 *ES, ObjTransformLayer, std::move(*CompileFunction)); 152 } 153 154 if (S.NumCompileThreads > 0) { 155 CompileLayer->setCloneToNewContextOnEmit(true); 156 CompileThreads = std::make_unique<ThreadPool>(S.NumCompileThreads); 157 ES->setDispatchMaterialization( 158 [this](JITDylib &JD, std::unique_ptr<MaterializationUnit> MU) { 159 // FIXME: Switch to move capture once we have c++14. 160 auto SharedMU = std::shared_ptr<MaterializationUnit>(std::move(MU)); 161 auto Work = [SharedMU, &JD]() { SharedMU->doMaterialize(JD); }; 162 CompileThreads->async(std::move(Work)); 163 }); 164 } 165 } 166 167 std::string LLJIT::mangle(StringRef UnmangledName) { 168 std::string MangledName; 169 { 170 raw_string_ostream MangledNameStream(MangledName); 171 Mangler::getNameWithPrefix(MangledNameStream, UnmangledName, DL); 172 } 173 return MangledName; 174 } 175 176 Error LLJIT::applyDataLayout(Module &M) { 177 if (M.getDataLayout().isDefault()) 178 M.setDataLayout(DL); 179 180 if (M.getDataLayout() != DL) 181 return make_error<StringError>( 182 "Added modules have incompatible data layouts", 183 inconvertibleErrorCode()); 184 185 return Error::success(); 186 } 187 188 void LLJIT::recordCtorDtors(Module &M) { 189 CtorRunner.add(getConstructors(M)); 190 DtorRunner.add(getDestructors(M)); 191 } 192 193 Error LLLazyJITBuilderState::prepareForConstruction() { 194 if (auto Err = LLJITBuilderState::prepareForConstruction()) 195 return Err; 196 TT = JTMB->getTargetTriple(); 197 return Error::success(); 198 } 199 200 Error LLLazyJIT::addLazyIRModule(JITDylib &JD, ThreadSafeModule TSM) { 201 assert(TSM && "Can not add null module"); 202 203 if (auto Err = TSM.withModuleDo([&](Module &M) -> Error { 204 if (auto Err = applyDataLayout(M)) 205 return Err; 206 207 recordCtorDtors(M); 208 return Error::success(); 209 })) 210 return Err; 211 212 return CODLayer->add(JD, std::move(TSM), ES->allocateVModule()); 213 } 214 215 LLLazyJIT::LLLazyJIT(LLLazyJITBuilderState &S, Error &Err) : LLJIT(S, Err) { 216 217 // If LLJIT construction failed then bail out. 218 if (Err) 219 return; 220 221 ErrorAsOutParameter _(&Err); 222 223 /// Take/Create the lazy-compile callthrough manager. 224 if (S.LCTMgr) 225 LCTMgr = std::move(S.LCTMgr); 226 else { 227 if (auto LCTMgrOrErr = createLocalLazyCallThroughManager( 228 S.TT, *ES, S.LazyCompileFailureAddr)) 229 LCTMgr = std::move(*LCTMgrOrErr); 230 else { 231 Err = LCTMgrOrErr.takeError(); 232 return; 233 } 234 } 235 236 // Take/Create the indirect stubs manager builder. 237 auto ISMBuilder = std::move(S.ISMBuilder); 238 239 // If none was provided, try to build one. 240 if (!ISMBuilder) 241 ISMBuilder = createLocalIndirectStubsManagerBuilder(S.TT); 242 243 // No luck. Bail out. 244 if (!ISMBuilder) { 245 Err = make_error<StringError>("Could not construct " 246 "IndirectStubsManagerBuilder for target " + 247 S.TT.str(), 248 inconvertibleErrorCode()); 249 return; 250 } 251 252 // Create the transform layer. 253 TransformLayer = std::make_unique<IRTransformLayer>(*ES, *CompileLayer); 254 255 // Create the COD layer. 256 CODLayer = std::make_unique<CompileOnDemandLayer>( 257 *ES, *TransformLayer, *LCTMgr, std::move(ISMBuilder)); 258 259 if (S.NumCompileThreads > 0) 260 CODLayer->setCloneToNewContextOnEmit(true); 261 } 262 263 } // End namespace orc. 264 } // End namespace llvm. 265