lli.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This utility provides a simple wrapper around the LLVM Execution Engines,
  11. // which allow the direct execution of LLVM programs through a Just-In-Time
  12. // compiler, or through an interpreter if no JIT is available for this platform.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/IR/LLVMContext.h"
  16. #include "OrcLazyJIT.h"
  17. #include "RemoteMemoryManager.h"
  18. #include "RemoteTarget.h"
  19. #include "RemoteTargetExternal.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Bitcode/ReaderWriter.h"
  22. #include "llvm/CodeGen/LinkAllCodegenComponents.h"
  23. #include "llvm/ExecutionEngine/GenericValue.h"
  24. #include "llvm/ExecutionEngine/Interpreter.h"
  25. #include "llvm/ExecutionEngine/JITEventListener.h"
  26. // #include "llvm/ExecutionEngine/MCJIT.h" // HLSL Change
  27. #include "llvm/ExecutionEngine/ObjectCache.h"
  28. #include "llvm/ExecutionEngine/OrcMCJITReplacement.h"
  29. #include "llvm/ExecutionEngine/SectionMemoryManager.h"
  30. // #include "llvm/ExecutionEngine/SectionMemoryManager.h" // HLSL Change
  31. #include "llvm/IR/IRBuilder.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/IR/Type.h"
  34. #include "llvm/IR/TypeBuilder.h"
  35. #include "llvm/IRReader/IRReader.h"
  36. #include "llvm/Object/Archive.h"
  37. #include "llvm/Object/ObjectFile.h"
  38. #include "llvm/Support/CommandLine.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/DynamicLibrary.h"
  41. #include "llvm/Support/Format.h"
  42. #include "llvm/Support/ManagedStatic.h"
  43. #include "llvm/Support/MathExtras.h"
  44. #include "llvm/Support/Memory.h"
  45. #include "llvm/Support/MemoryBuffer.h"
  46. #include "llvm/Support/Path.h"
  47. #include "llvm/Support/PluginLoader.h"
  48. #include "llvm/Support/PrettyStackTrace.h"
  49. #include "llvm/Support/Process.h"
  50. #include "llvm/Support/Program.h"
  51. #include "llvm/Support/Signals.h"
  52. #include "llvm/Support/SourceMgr.h"
  53. #include "llvm/Support/TargetSelect.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Transforms/Instrumentation.h"
  56. #include <cerrno>
  57. #ifdef __CYGWIN__
  58. #include <cygwin/version.h>
  59. #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
  60. #define DO_NOTHING_ATEXIT 1
  61. #endif
  62. #endif
  63. using namespace llvm;
  64. #define DEBUG_TYPE "lli"
  65. namespace {
  66. enum class JITKind { MCJIT, OrcMCJITReplacement, OrcLazy };
  67. cl::opt<std::string>
  68. InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
  69. cl::list<std::string>
  70. InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
  71. cl::opt<bool> ForceInterpreter("force-interpreter",
  72. cl::desc("Force interpretation: disable JIT"),
  73. cl::init(false));
  74. cl::opt<JITKind> UseJITKind("jit-kind",
  75. cl::desc("Choose underlying JIT kind."),
  76. cl::init(JITKind::MCJIT),
  77. cl::values(
  78. clEnumValN(JITKind::MCJIT, "mcjit",
  79. "MCJIT"),
  80. clEnumValN(JITKind::OrcMCJITReplacement,
  81. "orc-mcjit",
  82. "Orc-based MCJIT replacement"),
  83. clEnumValN(JITKind::OrcLazy,
  84. "orc-lazy",
  85. "Orc-based lazy JIT."),
  86. clEnumValEnd));
  87. // The MCJIT supports building for a target address space separate from
  88. // the JIT compilation process. Use a forked process and a copying
  89. // memory manager with IPC to execute using this functionality.
  90. cl::opt<bool> RemoteMCJIT("remote-mcjit",
  91. cl::desc("Execute MCJIT'ed code in a separate process."),
  92. cl::init(false));
  93. // Manually specify the child process for remote execution. This overrides
  94. // the simulated remote execution that allocates address space for child
  95. // execution. The child process will be executed and will communicate with
  96. // lli via stdin/stdout pipes.
  97. cl::opt<std::string>
  98. ChildExecPath("mcjit-remote-process",
  99. cl::desc("Specify the filename of the process to launch "
  100. "for remote MCJIT execution. If none is specified,"
  101. "\n\tremote execution will be simulated in-process."),
  102. cl::value_desc("filename"), cl::init(""));
  103. // Determine optimization level.
  104. cl::opt<char>
  105. OptLevel("O",
  106. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  107. "(default = '-O2')"),
  108. cl::Prefix,
  109. cl::ZeroOrMore,
  110. cl::init(' '));
  111. cl::opt<std::string>
  112. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  113. cl::opt<std::string>
  114. MArch("march",
  115. cl::desc("Architecture to generate assembly for (see --version)"));
  116. cl::opt<std::string>
  117. MCPU("mcpu",
  118. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  119. cl::value_desc("cpu-name"),
  120. cl::init(""));
  121. cl::list<std::string>
  122. MAttrs("mattr",
  123. cl::CommaSeparated,
  124. cl::desc("Target specific attributes (-mattr=help for details)"),
  125. cl::value_desc("a1,+a2,-a3,..."));
  126. cl::opt<std::string>
  127. EntryFunc("entry-function",
  128. cl::desc("Specify the entry function (default = 'main') "
  129. "of the executable"),
  130. cl::value_desc("function"),
  131. cl::init("main"));
  132. cl::list<std::string>
  133. ExtraModules("extra-module",
  134. cl::desc("Extra modules to be loaded"),
  135. cl::value_desc("input bitcode"));
  136. cl::list<std::string>
  137. ExtraObjects("extra-object",
  138. cl::desc("Extra object files to be loaded"),
  139. cl::value_desc("input object"));
  140. cl::list<std::string>
  141. ExtraArchives("extra-archive",
  142. cl::desc("Extra archive files to be loaded"),
  143. cl::value_desc("input archive"));
  144. cl::opt<bool>
  145. EnableCacheManager("enable-cache-manager",
  146. cl::desc("Use cache manager to save/load mdoules"),
  147. cl::init(false));
  148. cl::opt<std::string>
  149. ObjectCacheDir("object-cache-dir",
  150. cl::desc("Directory to store cached object files "
  151. "(must be user writable)"),
  152. cl::init(""));
  153. cl::opt<std::string>
  154. FakeArgv0("fake-argv0",
  155. cl::desc("Override the 'argv[0]' value passed into the executing"
  156. " program"), cl::value_desc("executable"));
  157. cl::opt<bool>
  158. DisableCoreFiles("disable-core-files", cl::Hidden,
  159. cl::desc("Disable emission of core files if possible"));
  160. cl::opt<bool>
  161. NoLazyCompilation("disable-lazy-compilation",
  162. cl::desc("Disable JIT lazy compilation"),
  163. cl::init(false));
  164. cl::opt<Reloc::Model>
  165. RelocModel("relocation-model",
  166. cl::desc("Choose relocation model"),
  167. cl::init(Reloc::Default),
  168. cl::values(
  169. clEnumValN(Reloc::Default, "default",
  170. "Target default relocation model"),
  171. clEnumValN(Reloc::Static, "static",
  172. "Non-relocatable code"),
  173. clEnumValN(Reloc::PIC_, "pic",
  174. "Fully relocatable, position independent code"),
  175. clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
  176. "Relocatable external references, non-relocatable code"),
  177. clEnumValEnd));
  178. cl::opt<llvm::CodeModel::Model>
  179. CMModel("code-model",
  180. cl::desc("Choose code model"),
  181. cl::init(CodeModel::JITDefault),
  182. cl::values(clEnumValN(CodeModel::JITDefault, "default",
  183. "Target default JIT code model"),
  184. clEnumValN(CodeModel::Small, "small",
  185. "Small code model"),
  186. clEnumValN(CodeModel::Kernel, "kernel",
  187. "Kernel code model"),
  188. clEnumValN(CodeModel::Medium, "medium",
  189. "Medium code model"),
  190. clEnumValN(CodeModel::Large, "large",
  191. "Large code model"),
  192. clEnumValEnd));
  193. cl::opt<bool>
  194. GenerateSoftFloatCalls("soft-float",
  195. cl::desc("Generate software floating point library calls"),
  196. cl::init(false));
  197. cl::opt<llvm::FloatABI::ABIType>
  198. FloatABIForCalls("float-abi",
  199. cl::desc("Choose float ABI type"),
  200. cl::init(FloatABI::Default),
  201. cl::values(
  202. clEnumValN(FloatABI::Default, "default",
  203. "Target default float ABI type"),
  204. clEnumValN(FloatABI::Soft, "soft",
  205. "Soft float ABI (implied by -soft-float)"),
  206. clEnumValN(FloatABI::Hard, "hard",
  207. "Hard float ABI (uses FP registers)"),
  208. clEnumValEnd));
  209. }
  210. //===----------------------------------------------------------------------===//
  211. // Object cache
  212. //
  213. // This object cache implementation writes cached objects to disk to the
  214. // directory specified by CacheDir, using a filename provided in the module
  215. // descriptor. The cache tries to load a saved object using that path if the
  216. // file exists. CacheDir defaults to "", in which case objects are cached
  217. // alongside their originating bitcodes.
  218. //
  219. class LLIObjectCache : public ObjectCache {
  220. public:
  221. LLIObjectCache(const std::string& CacheDir) : CacheDir(CacheDir) {
  222. // Add trailing '/' to cache dir if necessary.
  223. if (!this->CacheDir.empty() &&
  224. this->CacheDir[this->CacheDir.size() - 1] != '/')
  225. this->CacheDir += '/';
  226. }
  227. ~LLIObjectCache() override {}
  228. void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override {
  229. const std::string ModuleID = M->getModuleIdentifier();
  230. std::string CacheName;
  231. if (!getCacheFilename(ModuleID, CacheName))
  232. return;
  233. if (!CacheDir.empty()) { // Create user-defined cache dir.
  234. SmallString<128> dir(CacheName);
  235. sys::path::remove_filename(dir);
  236. sys::fs::create_directories(Twine(dir));
  237. }
  238. std::error_code EC;
  239. raw_fd_ostream outfile(CacheName, EC, sys::fs::F_None);
  240. outfile.write(Obj.getBufferStart(), Obj.getBufferSize());
  241. outfile.close();
  242. }
  243. std::unique_ptr<MemoryBuffer> getObject(const Module* M) override {
  244. const std::string ModuleID = M->getModuleIdentifier();
  245. std::string CacheName;
  246. if (!getCacheFilename(ModuleID, CacheName))
  247. return nullptr;
  248. // Load the object from the cache filename
  249. ErrorOr<std::unique_ptr<MemoryBuffer>> IRObjectBuffer =
  250. MemoryBuffer::getFile(CacheName.c_str(), -1, false);
  251. // If the file isn't there, that's OK.
  252. if (!IRObjectBuffer)
  253. return nullptr;
  254. // MCJIT will want to write into this buffer, and we don't want that
  255. // because the file has probably just been mmapped. Instead we make
  256. // a copy. The filed-based buffer will be released when it goes
  257. // out of scope.
  258. return MemoryBuffer::getMemBufferCopy(IRObjectBuffer.get()->getBuffer());
  259. }
  260. private:
  261. std::string CacheDir;
  262. bool getCacheFilename(const std::string &ModID, std::string &CacheName) {
  263. std::string Prefix("file:");
  264. size_t PrefixLength = Prefix.length();
  265. if (ModID.substr(0, PrefixLength) != Prefix)
  266. return false;
  267. std::string CacheSubdir = ModID.substr(PrefixLength);
  268. #if defined(_WIN32)
  269. // Transform "X:\foo" => "/X\foo" for convenience.
  270. if (isalpha(CacheSubdir[0]) && CacheSubdir[1] == ':') {
  271. CacheSubdir[1] = CacheSubdir[0];
  272. CacheSubdir[0] = '/';
  273. }
  274. #endif
  275. CacheName = CacheDir + CacheSubdir;
  276. size_t pos = CacheName.rfind('.');
  277. CacheName.replace(pos, CacheName.length() - pos, ".o");
  278. return true;
  279. }
  280. };
  281. static ExecutionEngine *EE = nullptr;
  282. static LLIObjectCache *CacheManager = nullptr;
  283. // HLSL Change: changed calling convention to __cdecl
  284. static void __cdecl do_shutdown() {
  285. // Cygwin-1.5 invokes DLL's dtors before atexit handler.
  286. #ifndef DO_NOTHING_ATEXIT
  287. delete EE;
  288. if (CacheManager)
  289. delete CacheManager;
  290. llvm_shutdown();
  291. #endif
  292. }
  293. // On Mingw and Cygwin, an external symbol named '__main' is called from the
  294. // generated 'main' function to allow static intialization. To avoid linking
  295. // problems with remote targets (because lli's remote target support does not
  296. // currently handle external linking) we add a secondary module which defines
  297. // an empty '__main' function.
  298. static void addCygMingExtraModule(ExecutionEngine *EE,
  299. LLVMContext &Context,
  300. StringRef TargetTripleStr) {
  301. IRBuilder<> Builder(Context);
  302. Triple TargetTriple(TargetTripleStr);
  303. // Create a new module.
  304. std::unique_ptr<Module> M = make_unique<Module>("CygMingHelper", Context);
  305. M->setTargetTriple(TargetTripleStr);
  306. // Create an empty function named "__main".
  307. Function *Result;
  308. if (TargetTriple.isArch64Bit()) {
  309. Result = Function::Create(
  310. TypeBuilder<int64_t(void), false>::get(Context),
  311. GlobalValue::ExternalLinkage, "__main", M.get());
  312. } else {
  313. Result = Function::Create(
  314. TypeBuilder<int32_t(void), false>::get(Context),
  315. GlobalValue::ExternalLinkage, "__main", M.get());
  316. }
  317. BasicBlock *BB = BasicBlock::Create(Context, "__main", Result);
  318. Builder.SetInsertPoint(BB);
  319. Value *ReturnVal;
  320. if (TargetTriple.isArch64Bit())
  321. ReturnVal = ConstantInt::get(Context, APInt(64, 0));
  322. else
  323. ReturnVal = ConstantInt::get(Context, APInt(32, 0));
  324. Builder.CreateRet(ReturnVal);
  325. // Add this new module to the ExecutionEngine.
  326. EE->addModule(std::move(M));
  327. }
  328. CodeGenOpt::Level getOptLevel() {
  329. switch (OptLevel) {
  330. default:
  331. errs() << "lli: Invalid optimization level.\n";
  332. exit(1);
  333. case '0': return CodeGenOpt::None;
  334. case '1': return CodeGenOpt::Less;
  335. case ' ':
  336. case '2': return CodeGenOpt::Default;
  337. case '3': return CodeGenOpt::Aggressive;
  338. }
  339. llvm_unreachable("Unrecognized opt level.");
  340. }
  341. //===----------------------------------------------------------------------===//
  342. // main Driver function
  343. //
  344. // HLSL Change: changed calling convention to __cdecl
  345. int __cdecl main(int argc, char **argv, char * const *envp) {
  346. sys::PrintStackTraceOnErrorSignal();
  347. PrettyStackTraceProgram X(argc, argv);
  348. LLVMContext &Context = getGlobalContext();
  349. atexit(do_shutdown); // Call llvm_shutdown() on exit.
  350. // If we have a native target, initialize it to ensure it is linked in and
  351. // usable by the JIT.
  352. InitializeNativeTarget();
  353. InitializeNativeTargetAsmPrinter();
  354. InitializeNativeTargetAsmParser();
  355. cl::ParseCommandLineOptions(argc, argv,
  356. "llvm interpreter & dynamic compiler\n");
  357. // If the user doesn't want core files, disable them.
  358. if (DisableCoreFiles)
  359. sys::Process::PreventCoreFiles();
  360. // Load the bitcode...
  361. SMDiagnostic Err;
  362. std::unique_ptr<Module> Owner = parseIRFile(InputFile, Err, Context);
  363. Module *Mod = Owner.get();
  364. if (!Mod) {
  365. Err.print(argv[0], errs());
  366. return 1;
  367. }
  368. if (UseJITKind == JITKind::OrcLazy)
  369. return runOrcLazyJIT(std::move(Owner), argc, argv);
  370. if (EnableCacheManager) {
  371. std::string CacheName("file:");
  372. CacheName.append(InputFile);
  373. Mod->setModuleIdentifier(CacheName);
  374. }
  375. // If not jitting lazily, load the whole bitcode file eagerly too.
  376. if (NoLazyCompilation) {
  377. if (std::error_code EC = Mod->materializeAllPermanently()) {
  378. errs() << argv[0] << ": bitcode didn't read correctly.\n";
  379. errs() << "Reason: " << EC.message() << "\n";
  380. exit(1);
  381. }
  382. }
  383. std::string ErrorMsg;
  384. EngineBuilder builder(std::move(Owner));
  385. builder.setMArch(MArch);
  386. builder.setMCPU(MCPU);
  387. builder.setMAttrs(MAttrs);
  388. builder.setRelocationModel(RelocModel);
  389. builder.setCodeModel(CMModel);
  390. builder.setErrorStr(&ErrorMsg);
  391. builder.setEngineKind(ForceInterpreter
  392. ? EngineKind::Interpreter
  393. : EngineKind::JIT);
  394. builder.setUseOrcMCJITReplacement(UseJITKind == JITKind::OrcMCJITReplacement);
  395. // If we are supposed to override the target triple, do so now.
  396. if (!TargetTriple.empty())
  397. Mod->setTargetTriple(Triple::normalize(TargetTriple));
  398. // Enable MCJIT if desired.
  399. RTDyldMemoryManager *RTDyldMM = nullptr;
  400. #if 0 // HLSL Change Starts - disable MCJIT
  401. if (!ForceInterpreter) {
  402. if (RemoteMCJIT)
  403. RTDyldMM = new RemoteMemoryManager();
  404. else
  405. RTDyldMM = new SectionMemoryManager();
  406. // Deliberately construct a temp std::unique_ptr to pass in. Do not null out
  407. // RTDyldMM: We still use it below, even though we don't own it.
  408. builder.setMCJITMemoryManager(
  409. std::unique_ptr<RTDyldMemoryManager>(RTDyldMM));
  410. } else if (RemoteMCJIT) {
  411. errs() << "error: Remote process execution does not work with the "
  412. "interpreter.\n";
  413. exit(1);
  414. }
  415. #endif // HLSL Change Ends
  416. builder.setOptLevel(getOptLevel());
  417. TargetOptions Options;
  418. if (FloatABIForCalls != FloatABI::Default)
  419. Options.FloatABIType = FloatABIForCalls;
  420. builder.setTargetOptions(Options);
  421. EE = builder.create();
  422. if (!EE) {
  423. if (!ErrorMsg.empty())
  424. errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
  425. else
  426. errs() << argv[0] << ": unknown error creating EE!\n";
  427. exit(1);
  428. }
  429. if (EnableCacheManager) {
  430. CacheManager = new LLIObjectCache(ObjectCacheDir);
  431. EE->setObjectCache(CacheManager);
  432. }
  433. // Load any additional modules specified on the command line.
  434. for (unsigned i = 0, e = ExtraModules.size(); i != e; ++i) {
  435. std::unique_ptr<Module> XMod = parseIRFile(ExtraModules[i], Err, Context);
  436. if (!XMod) {
  437. Err.print(argv[0], errs());
  438. return 1;
  439. }
  440. if (EnableCacheManager) {
  441. std::string CacheName("file:");
  442. CacheName.append(ExtraModules[i]);
  443. XMod->setModuleIdentifier(CacheName);
  444. }
  445. EE->addModule(std::move(XMod));
  446. }
  447. for (unsigned i = 0, e = ExtraObjects.size(); i != e; ++i) {
  448. ErrorOr<object::OwningBinary<object::ObjectFile>> Obj =
  449. object::ObjectFile::createObjectFile(ExtraObjects[i]);
  450. if (!Obj) {
  451. Err.print(argv[0], errs());
  452. return 1;
  453. }
  454. object::OwningBinary<object::ObjectFile> &O = Obj.get();
  455. EE->addObjectFile(std::move(O));
  456. }
  457. for (unsigned i = 0, e = ExtraArchives.size(); i != e; ++i) {
  458. ErrorOr<std::unique_ptr<MemoryBuffer>> ArBufOrErr =
  459. MemoryBuffer::getFileOrSTDIN(ExtraArchives[i]);
  460. if (!ArBufOrErr) {
  461. Err.print(argv[0], errs());
  462. return 1;
  463. }
  464. std::unique_ptr<MemoryBuffer> &ArBuf = ArBufOrErr.get();
  465. ErrorOr<std::unique_ptr<object::Archive>> ArOrErr =
  466. object::Archive::create(ArBuf->getMemBufferRef());
  467. if (std::error_code EC = ArOrErr.getError()) {
  468. errs() << EC.message();
  469. return 1;
  470. }
  471. std::unique_ptr<object::Archive> &Ar = ArOrErr.get();
  472. object::OwningBinary<object::Archive> OB(std::move(Ar), std::move(ArBuf));
  473. EE->addArchive(std::move(OB));
  474. }
  475. // If the target is Cygwin/MingW and we are generating remote code, we
  476. // need an extra module to help out with linking.
  477. if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
  478. addCygMingExtraModule(EE, Context, Mod->getTargetTriple());
  479. }
  480. // The following functions have no effect if their respective profiling
  481. // support wasn't enabled in the build configuration.
  482. EE->RegisterJITEventListener(
  483. JITEventListener::createOProfileJITEventListener());
  484. EE->RegisterJITEventListener(
  485. JITEventListener::createIntelJITEventListener());
  486. if (!NoLazyCompilation && RemoteMCJIT) {
  487. errs() << "warning: remote mcjit does not support lazy compilation\n";
  488. NoLazyCompilation = true;
  489. }
  490. EE->DisableLazyCompilation(NoLazyCompilation);
  491. // If the user specifically requested an argv[0] to pass into the program,
  492. // do it now.
  493. if (!FakeArgv0.empty()) {
  494. InputFile = static_cast<std::string>(FakeArgv0);
  495. } else {
  496. // Otherwise, if there is a .bc suffix on the executable strip it off, it
  497. // might confuse the program.
  498. if (StringRef(InputFile).endswith(".bc"))
  499. InputFile.erase(InputFile.length() - 3);
  500. }
  501. // Add the module's name to the start of the vector of arguments to main().
  502. InputArgv.insert(InputArgv.begin(), InputFile);
  503. // Call the main function from M as if its signature were:
  504. // int main (int argc, char **argv, const char **envp)
  505. // using the contents of Args to determine argc & argv, and the contents of
  506. // EnvVars to determine envp.
  507. //
  508. Function *EntryFn = Mod->getFunction(EntryFunc);
  509. if (!EntryFn) {
  510. errs() << '\'' << EntryFunc << "\' function not found in module.\n";
  511. return -1;
  512. }
  513. // Reset errno to zero on entry to main.
  514. errno = 0;
  515. int Result;
  516. if (!RemoteMCJIT) {
  517. // If the program doesn't explicitly call exit, we will need the Exit
  518. // function later on to make an explicit call, so get the function now.
  519. Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
  520. Type::getInt32Ty(Context),
  521. nullptr);
  522. // Run static constructors.
  523. if (!ForceInterpreter) {
  524. // Give MCJIT a chance to apply relocations and set page permissions.
  525. EE->finalizeObject();
  526. }
  527. EE->runStaticConstructorsDestructors(false);
  528. // Trigger compilation separately so code regions that need to be
  529. // invalidated will be known.
  530. (void)EE->getPointerToFunction(EntryFn);
  531. // Clear instruction cache before code will be executed.
  532. #if 0 // HLSL Change Starts
  533. if (RTDyldMM)
  534. static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache();
  535. #endif // HLSL Change Ends
  536. // Run main.
  537. Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
  538. // Run static destructors.
  539. EE->runStaticConstructorsDestructors(true);
  540. // If the program didn't call exit explicitly, we should call it now.
  541. // This ensures that any atexit handlers get called correctly.
  542. if (Function *ExitF = dyn_cast<Function>(Exit)) {
  543. std::vector<GenericValue> Args;
  544. GenericValue ResultGV;
  545. ResultGV.IntVal = APInt(32, Result);
  546. Args.push_back(ResultGV);
  547. EE->runFunction(ExitF, Args);
  548. errs() << "ERROR: exit(" << Result << ") returned!\n";
  549. abort();
  550. } else {
  551. errs() << "ERROR: exit defined with wrong prototype!\n";
  552. abort();
  553. }
  554. } else {
  555. // else == "if (RemoteMCJIT)"
  556. // Remote target MCJIT doesn't (yet) support static constructors. No reason
  557. // it couldn't. This is a limitation of the LLI implemantation, not the
  558. // MCJIT itself. FIXME.
  559. //
  560. RemoteMemoryManager *MM = static_cast<RemoteMemoryManager*>(RTDyldMM);
  561. // Everything is prepared now, so lay out our program for the target
  562. // address space, assign the section addresses to resolve any relocations,
  563. // and send it to the target.
  564. std::unique_ptr<RemoteTarget> Target;
  565. if (!ChildExecPath.empty()) { // Remote execution on a child process
  566. #ifndef LLVM_ON_UNIX
  567. // FIXME: Remove this pointless fallback mode which causes tests to "pass"
  568. // on platforms where they should XFAIL.
  569. errs() << "Warning: host does not support external remote targets.\n"
  570. << " Defaulting to simulated remote execution\n";
  571. Target.reset(new RemoteTarget);
  572. #else
  573. if (!sys::fs::can_execute(ChildExecPath)) {
  574. errs() << "Unable to find usable child executable: '" << ChildExecPath
  575. << "'\n";
  576. return -1;
  577. }
  578. Target.reset(new RemoteTargetExternal(ChildExecPath));
  579. #endif
  580. } else {
  581. // No child process name provided, use simulated remote execution.
  582. Target.reset(new RemoteTarget);
  583. }
  584. // Give the memory manager a pointer to our remote target interface object.
  585. MM->setRemoteTarget(Target.get());
  586. // Create the remote target.
  587. if (!Target->create()) {
  588. errs() << "ERROR: " << Target->getErrorMsg() << "\n";
  589. return EXIT_FAILURE;
  590. }
  591. // Since we're executing in a (at least simulated) remote address space,
  592. // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
  593. // grab the function address directly here and tell the remote target
  594. // to execute the function.
  595. //
  596. // Our memory manager will map generated code into the remote address
  597. // space as it is loaded and copy the bits over during the finalizeMemory
  598. // operation.
  599. //
  600. // FIXME: argv and envp handling.
  601. uint64_t Entry = EE->getFunctionAddress(EntryFn->getName().str());
  602. DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x"
  603. << format("%llx", Entry) << "\n");
  604. if (!Target->executeCode(Entry, Result))
  605. errs() << "ERROR: " << Target->getErrorMsg() << "\n";
  606. // Like static constructors, the remote target MCJIT support doesn't handle
  607. // this yet. It could. FIXME.
  608. // Stop the remote target
  609. Target->stop();
  610. }
  611. return Result;
  612. }