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