Advertisement
Guest User

Parallel lli (llvm interpreter)

a guest
Mar 20th, 2013
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 12.35 KB | None | 0 0
  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.  
  16. #include "llvm/LLVMContext.h"
  17. #include "llvm/Module.h"
  18. #include "llvm/Type.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/Bitcode/ReaderWriter.h"
  21. #include "llvm/CodeGen/LinkAllCodegenComponents.h"
  22. #include "llvm/ExecutionEngine/GenericValue.h"
  23. #include "llvm/ExecutionEngine/Interpreter.h"
  24. #include "llvm/ExecutionEngine/JIT.h"
  25. #include "llvm/ExecutionEngine/JITEventListener.h"
  26. #include "llvm/ExecutionEngine/JITMemoryManager.h"
  27. #include "llvm/ExecutionEngine/MCJIT.h"
  28. #include "llvm/Support/CommandLine.h"
  29. #include "llvm/Support/IRReader.h"
  30. #include "llvm/Support/ManagedStatic.h"
  31. #include "llvm/Support/MemoryBuffer.h"
  32. #include "llvm/Support/PluginLoader.h"
  33. #include "llvm/Support/PrettyStackTrace.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Support/Process.h"
  36. #include "llvm/Support/Signals.h"
  37. #include "llvm/Support/TargetSelect.h"
  38. #include <cerrno>
  39.  
  40. #ifdef __CYGWIN__
  41. #include <cygwin/version.h>
  42. #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
  43. #define DO_NOTHING_ATEXIT 1
  44. #endif
  45. #endif
  46.  
  47. using namespace llvm;
  48.  
  49. namespace {
  50.   cl::opt<std::string>
  51.   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
  52.  
  53.   cl::list<std::string>
  54.   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
  55.  
  56.   cl::opt<bool> ForceInterpreter("force-interpreter",
  57.                                  cl::desc("Force interpretation: disable JIT"),
  58.                                  cl::init(false));
  59.  
  60.   cl::opt<bool> UseMCJIT(
  61.     "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
  62.     cl::init(false));
  63.  
  64.   // Determine optimization level.
  65.   cl::opt<char>
  66.   OptLevel("O",
  67.            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  68.                     "(default = '-O2')"),
  69.            cl::Prefix,
  70.            cl::ZeroOrMore,
  71.            cl::init(' '));
  72.  
  73.   cl::opt<std::string>
  74.   TargetTriple("mtriple", cl::desc("Override target triple for module"));
  75.  
  76.   cl::opt<std::string>
  77.   MArch("march",
  78.         cl::desc("Architecture to generate assembly for (see --version)"));
  79.  
  80.   cl::opt<std::string>
  81.   MCPU("mcpu",
  82.        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  83.        cl::value_desc("cpu-name"),
  84.        cl::init(""));
  85.  
  86.   cl::list<std::string>
  87.   MAttrs("mattr",
  88.          cl::CommaSeparated,
  89.          cl::desc("Target specific attributes (-mattr=help for details)"),
  90.          cl::value_desc("a1,+a2,-a3,..."));
  91.  
  92.   cl::opt<std::string>
  93.   EntryFunc("entry-function",
  94.             cl::desc("Specify the entry function (default = 'main') "
  95.                      "of the executable"),
  96.             cl::value_desc("function"),
  97.             cl::init("main"));
  98.  
  99.   cl::opt<std::string>
  100.   FakeArgv0("fake-argv0",
  101.             cl::desc("Override the 'argv[0]' value passed into the executing"
  102.                      " program"), cl::value_desc("executable"));
  103.  
  104.   cl::opt<bool>
  105.   DisableCoreFiles("disable-core-files", cl::Hidden,
  106.                    cl::desc("Disable emission of core files if possible"));
  107.  
  108.   cl::opt<bool>
  109.   NoLazyCompilation("disable-lazy-compilation",
  110.                   cl::desc("Disable JIT lazy compilation"),
  111.                   cl::init(false));
  112.  
  113.   cl::opt<Reloc::Model>
  114.   RelocModel("relocation-model",
  115.              cl::desc("Choose relocation model"),
  116.              cl::init(Reloc::Default),
  117.              cl::values(
  118.             clEnumValN(Reloc::Default, "default",
  119.                        "Target default relocation model"),
  120.             clEnumValN(Reloc::Static, "static",
  121.                        "Non-relocatable code"),
  122.             clEnumValN(Reloc::PIC_, "pic",
  123.                        "Fully relocatable, position independent code"),
  124.             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
  125.                        "Relocatable external references, non-relocatable code"),
  126.             clEnumValEnd));
  127.  
  128.   cl::opt<llvm::CodeModel::Model>
  129.   CMModel("code-model",
  130.           cl::desc("Choose code model"),
  131.           cl::init(CodeModel::JITDefault),
  132.           cl::values(clEnumValN(CodeModel::JITDefault, "default",
  133.                                 "Target default JIT code model"),
  134.                      clEnumValN(CodeModel::Small, "small",
  135.                                 "Small code model"),
  136.                      clEnumValN(CodeModel::Kernel, "kernel",
  137.                                 "Kernel code model"),
  138.                      clEnumValN(CodeModel::Medium, "medium",
  139.                                 "Medium code model"),
  140.                      clEnumValN(CodeModel::Large, "large",
  141.                                 "Large code model"),
  142.                      clEnumValEnd));
  143.  
  144.   cl::opt<bool>
  145.   EnableJITExceptionHandling("jit-enable-eh",
  146.     cl::desc("Emit exception handling information"),
  147.     cl::init(false));
  148.  
  149.   cl::opt<bool>
  150. // In debug builds, make this default to true.
  151. #ifdef NDEBUG
  152. #define EMIT_DEBUG false
  153. #else
  154. #define EMIT_DEBUG true
  155. #endif
  156.   EmitJitDebugInfo("jit-emit-debug",
  157.     cl::desc("Emit debug information to debugger"),
  158.     cl::init(EMIT_DEBUG));
  159. #undef EMIT_DEBUG
  160.  
  161.   static cl::opt<bool>
  162.   EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
  163.     cl::Hidden,
  164.     cl::desc("Emit debug info objfiles to disk"),
  165.     cl::init(false));
  166. }
  167.  
  168. static ExecutionEngine *EE = 0;
  169.  
  170. static void do_shutdown() {
  171.   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
  172. #ifndef DO_NOTHING_ATEXIT
  173.   delete EE;
  174.   llvm_shutdown();
  175. #endif
  176. }
  177.  
  178. typedef struct {
  179.     int argc;
  180.     char **argv;
  181.     char *const *envp;
  182. } arg_t;
  183.  
  184. void *run(void *arg) {
  185.   int argc = ((arg_t *) arg)->argc;
  186.   char **argv = ((arg_t *) arg)->argv;
  187.   char *const *envp = ((arg_t *) arg)->envp;
  188.   LLVMContext Context;
  189.   // Load the bitcode...
  190.   SMDiagnostic Err;
  191.   Module *Mod = ParseIRFile(InputFile, Err, Context);
  192.   if (!Mod) {
  193.     Err.print(argv[0], errs());
  194.     return (void *)1;
  195.   }
  196.  
  197.   // If not jitting lazily, load the whole bitcode file eagerly too.
  198.   std::string ErrorMsg;
  199.   if (NoLazyCompilation) {
  200.     if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
  201.       errs() << argv[0] << ": bitcode didn't read correctly.\n";
  202.       errs() << "Reason: " << ErrorMsg << "\n";
  203.       exit(1);
  204.     }
  205.   }
  206.  
  207.   EngineBuilder builder(Mod);
  208.   builder.setMArch(MArch);
  209.   builder.setMCPU(MCPU);
  210.   builder.setMAttrs(MAttrs);
  211.   builder.setRelocationModel(RelocModel);
  212.   builder.setCodeModel(CMModel);
  213.   builder.setErrorStr(&ErrorMsg);
  214.   builder.setJITMemoryManager(ForceInterpreter ? 0 :
  215.                               JITMemoryManager::CreateDefaultMemManager());
  216.   builder.setEngineKind(ForceInterpreter
  217.                         ? EngineKind::Interpreter
  218.                         : EngineKind::JIT);
  219.  
  220.   // If we are supposed to override the target triple, do so now.
  221.   if (!TargetTriple.empty())
  222.     Mod->setTargetTriple(Triple::normalize(TargetTriple));
  223.  
  224.   // Enable MCJIT if desired.
  225.   if (UseMCJIT && !ForceInterpreter) {
  226.     builder.setUseMCJIT(true);
  227.     builder.setJITMemoryManager(JITMemoryManager::CreateDefaultMemManager());
  228.   }
  229.  
  230.   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  231.   switch (OptLevel) {
  232.   default:
  233.     errs() << argv[0] << ": invalid optimization level.\n";
  234.     return (void *)1;
  235.   case ' ': break;
  236.   case '0': OLvl = CodeGenOpt::None; break;
  237.   case '1': OLvl = CodeGenOpt::Less; break;
  238.   case '2': OLvl = CodeGenOpt::Default; break;
  239.   case '3': OLvl = CodeGenOpt::Aggressive; break;
  240.   }
  241.   builder.setOptLevel(OLvl);
  242.  
  243.   TargetOptions Options;
  244.   Options.JITExceptionHandling = EnableJITExceptionHandling;
  245.   Options.JITEmitDebugInfo = EmitJitDebugInfo;
  246.   Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
  247.   builder.setTargetOptions(Options);
  248.  
  249.   EE = builder.create();
  250.   if (!EE) {
  251.     if (!ErrorMsg.empty())
  252.       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
  253.     else
  254.       errs() << argv[0] << ": unknown error creating EE!\n";
  255.     exit(1);
  256.   }
  257.  
  258.   // The following functions have no effect if their respective profiling
  259.   // support wasn't enabled in the build configuration.
  260.   EE->RegisterJITEventListener(
  261.                 JITEventListener::createOProfileJITEventListener());
  262.   EE->RegisterJITEventListener(
  263.                 JITEventListener::createIntelJITEventListener());
  264.  
  265.   EE->DisableLazyCompilation(NoLazyCompilation);
  266.  
  267.   // If the user specifically requested an argv[0] to pass into the program,
  268.   // do it now.
  269.   if (!FakeArgv0.empty()) {
  270.     InputFile = FakeArgv0;
  271.   } else {
  272.     // Otherwise, if there is a .bc suffix on the executable strip it off, it
  273.     // might confuse the program.
  274.     if (StringRef(InputFile).endswith(".bc"))
  275.       InputFile.erase(InputFile.length() - 3);
  276.   }
  277.  
  278.   // Add the module's name to the start of the vector of arguments to main().
  279.   InputArgv.insert(InputArgv.begin(), InputFile);
  280.  
  281.   // Call the main function from M as if its signature were:
  282.   //   int main (int argc, char **argv, const char **envp)
  283.   // using the contents of Args to determine argc & argv, and the contents of
  284.   // EnvVars to determine envp.
  285.   //
  286.   Function *EntryFn = Mod->getFunction(EntryFunc);
  287.   if (!EntryFn) {
  288.     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
  289.     return (void *)-1;
  290.   }
  291.  
  292.   // If the program doesn't explicitly call exit, we will need the Exit
  293.   // function later on to make an explicit call, so get the function now.
  294.   Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
  295.                                                     Type::getInt32Ty(Context),
  296.                                                     NULL);
  297.  
  298.   // Reset errno to zero on entry to main.
  299.   errno = 0;
  300.  
  301.   // Run static constructors.
  302.   EE->runStaticConstructorsDestructors(false);
  303.  
  304.   if (NoLazyCompilation) {
  305.     for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
  306.       Function *Fn = &*I;
  307.       if (Fn != EntryFn && !Fn->isDeclaration())
  308.         EE->getPointerToFunction(Fn);
  309.     }
  310.   }
  311.  
  312.   // Run main.
  313.   int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
  314.  
  315.   // Run static destructors.
  316.   EE->runStaticConstructorsDestructors(true);
  317.  
  318.   // If the program didn't call exit explicitly, we should call it now.
  319.   // This ensures that any atexit handlers get called correctly.
  320.   if (Function *ExitF = dyn_cast<Function>(Exit)) {
  321.     std::vector<GenericValue> Args;
  322.     GenericValue ResultGV;
  323.     ResultGV.IntVal = APInt(32, Result);
  324.     Args.push_back(ResultGV);
  325.     EE->runFunction(ExitF, Args);
  326.     errs() << "ERROR: exit(" << Result << ") returned!\n";
  327.     abort();
  328.   } else {
  329.     errs() << "ERROR: exit defined with wrong prototype!\n";
  330.     abort();
  331.   }
  332. }
  333.  
  334.  
  335. //===----------------------------------------------------------------------===//
  336. // main Driver function
  337. //
  338. int main(int argc, char **argv, char * const *envp) {
  339.   sys::PrintStackTraceOnErrorSignal();
  340.   PrettyStackTraceProgram X(argc, argv);
  341.  
  342.   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
  343.  
  344.   // If we have a native target, initialize it to ensure it is linked in and
  345.   // usable by the JIT.
  346.   InitializeNativeTarget();
  347.   InitializeNativeTargetAsmPrinter();
  348.  
  349.   cl::ParseCommandLineOptions(argc, argv,
  350.                               "llvm interpreter & dynamic compiler\n");
  351.  
  352.   // If the user doesn't want core files, disable them.
  353.   if (DisableCoreFiles)
  354.     sys::Process::PreventCoreFiles();
  355.  
  356.   arg_t *aa = new arg_t();
  357.   aa->argc = argc;
  358.   aa->argv = argv;
  359.   aa->envp = envp;
  360.   pthread_t t1, t2;
  361.   void *r1, *r2;
  362.  
  363.  
  364.   if(0 != pthread_create(&t1, NULL, &run, aa)) {
  365.       errs() << "Failed to create thread " << strerror(errno) << "\n";
  366.       return 66;
  367.   }
  368.  
  369.   if(0 != pthread_create(&t2, NULL, &run, aa)) {
  370.       errs() << "Failed to create thread " << strerror(errno) << "\n";
  371.       return 67;
  372.   }
  373.  
  374.   pthread_join(t1, &r1);
  375.   pthread_join(t2, &r2);
  376.   return (long) r1 | (long) r2;
  377. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement