lli.cpp revision 70975eef572b9e132bbaade16ba9edb76f15f287
1//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2//
3// This utility provides a way to execute LLVM bytecode without static
4// compilation.  This consists of a very simple and slow (but portable)
5// interpreter, along with capability for system specific dynamic compilers.  At
6// runtime, the fastest (stable) execution engine is selected to run the
7// program.  This means the JIT compiler for the current platform if it's
8// available.
9//
10//===----------------------------------------------------------------------===//
11
12#include "ExecutionEngine.h"
13#include "GenericValue.h"
14#include "Support/CommandLine.h"
15#include "Support/Debug.h"
16#include "llvm/Bytecode/Reader.h"
17#include "llvm/Module.h"
18#include "llvm/Target/TargetMachineImpls.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Target/TargetData.h"
21
22namespace {
23  cl::opt<std::string>
24  InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));
25
26  cl::list<std::string>
27  InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
28
29  cl::opt<std::string>
30  MainFunction ("f", cl::desc("Function to execute"), cl::init("main"),
31		cl::value_desc("function name"));
32
33  cl::opt<bool> TraceMode("trace", cl::desc("Enable Tracing"));
34
35  cl::opt<bool> ForceInterpreter("force-interpreter",
36				 cl::desc("Force interpretation: disable JIT"),
37				 cl::init(false));
38}
39
40static std::vector<std::string> makeStringVector (const char **envp) {
41  std::vector<std::string> rv;
42  for (unsigned i = 0; envp[i]; ++i)
43    rv.push_back (envp[i]);
44  return rv;
45}
46
47static void *CreateArgv(ExecutionEngine *EE,
48			const std::vector<std::string> &InputArgv) {
49  if (EE->getTargetData().getPointerSize() == 8) {   // 64 bit target?
50    PointerTy *Result = new PointerTy[InputArgv.size()+1];
51    DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
52
53    for (unsigned i = 0; i < InputArgv.size(); ++i) {
54      unsigned Size = InputArgv[i].size()+1;
55      char *Dest = new char[Size];
56      DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
57
58      std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
59      Dest[Size-1] = 0;
60
61      // Endian safe: Result[i] = (PointerTy)Dest;
62      EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i),
63			     Type::LongTy);
64    }
65    Result[InputArgv.size()] = 0;
66    return Result;
67  } else {                                      // 32 bit target?
68    int *Result = new int[InputArgv.size()+1];
69    DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
70
71    for (unsigned i = 0; i < InputArgv.size(); ++i) {
72      unsigned Size = InputArgv[i].size()+1;
73      char *Dest = new char[Size];
74      DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
75
76      std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
77      Dest[Size-1] = 0;
78
79      // Endian safe: Result[i] = (PointerTy)Dest;
80      EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i),
81			     Type::IntTy);
82    }
83    Result[InputArgv.size()] = 0;  // null terminate it
84    return Result;
85  }
86}
87
88/// callAsMain - Call the function named FnName from M as if its
89/// signature were int main (int argc, char **argv, const char
90/// **envp), using the contents of Args to determine argc & argv, and
91/// the contents of EnvVars to determine envp.  Returns the result
92/// from calling FnName, or -1 and prints an error msg. if the named
93/// function cannot be found.
94///
95int callAsMain (ExecutionEngine *EE, Module *M, const std::string &FnName,
96                const std::vector<std::string> &Args,
97                const std::vector<std::string> &EnvVars) {
98  Function *Fn = M->getNamedFunction (FnName);
99  if (!Fn) {
100    std::cerr << "Function '" << FnName << "' not found in module.\n";
101    return -1;
102  }
103  std::vector<GenericValue> GVArgs;
104  GenericValue GVArgc;
105  GVArgc.IntVal = Args.size ();
106  GVArgs.push_back (GVArgc); // Arg #0 = argc.
107  GVArgs.push_back (PTOGV (CreateArgv (EE, Args))); // Arg #1 = argv.
108  GVArgs.push_back (PTOGV (CreateArgv (EE, EnvVars))); // Arg #2 = envp.
109  return EE->run (Fn, GVArgs).IntVal;
110}
111
112//===----------------------------------------------------------------------===//
113// main Driver function
114//
115int main(int argc, char **argv, const char **envp) {
116  cl::ParseCommandLineOptions(argc, argv,
117			      " llvm interpreter & dynamic compiler\n");
118
119  // Load the bytecode...
120  std::string ErrorMsg;
121  Module *M = ParseBytecodeFile(InputFile, &ErrorMsg);
122  if (M == 0) {
123    std::cout << "Error parsing '" << InputFile << "': "
124              << ErrorMsg << "\n";
125    exit(1);
126  }
127
128  ExecutionEngine *EE =
129    ExecutionEngine::create (M, ForceInterpreter, TraceMode);
130  assert (EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
131
132  // Add the module's name to the start of the vector of arguments to main().
133  // But delete .bc first, since programs (and users) might not expect to
134  // see it.
135  const std::string ByteCodeFileSuffix (".bc");
136  if (InputFile.rfind (ByteCodeFileSuffix) ==
137      InputFile.length () - ByteCodeFileSuffix.length ()) {
138    InputFile.erase (InputFile.length () - ByteCodeFileSuffix.length ());
139  }
140  InputArgv.insert(InputArgv.begin(), InputFile);
141
142  // Run the main function!
143  int ExitCode = callAsMain (EE, M, MainFunction, InputArgv,
144			     makeStringVector (envp));
145
146  // Now that we are done executing the program, shut down the execution engine
147  delete EE;
148  return ExitCode;
149}
150