87fe461ce0d744a4fea39729595868f5102149ce
[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> ForceInterpreter("force-interpreter",
43                                  cl::desc("Force interpretation: disable JIT"),
44                                  cl::init(false));
45
46   cl::opt<std::string>
47   FakeArgv0("fake-argv0",
48             cl::desc("Override the 'argv[0]' value passed into the executing"
49                      " program"), cl::value_desc("executable"));
50 }
51
52 static std::vector<std::string> makeStringVector(char * const *envp) {
53   std::vector<std::string> rv;
54   for (unsigned i = 0; envp[i]; ++i)
55     rv.push_back(envp[i]);
56   return rv;
57 }
58
59 static void *CreateArgv(ExecutionEngine *EE,
60                         const std::vector<std::string> &InputArgv) {
61   if (EE->getTargetData().getPointerSize() == 8) {   // 64 bit target?
62     PointerTy *Result = new PointerTy[InputArgv.size()+1];
63     DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
64
65     for (unsigned i = 0; i < InputArgv.size(); ++i) {
66       unsigned Size = InputArgv[i].size()+1;
67       char *Dest = new char[Size];
68       DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
69       
70       std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
71       Dest[Size-1] = 0;
72       
73       // Endian safe: Result[i] = (PointerTy)Dest;
74       EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i),
75                              Type::LongTy);
76     }
77     Result[InputArgv.size()] = 0;
78     return Result;
79   } else {                                      // 32 bit target?
80     int *Result = new int[InputArgv.size()+1];
81     DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
82
83     for (unsigned i = 0; i < InputArgv.size(); ++i) {
84       unsigned Size = InputArgv[i].size()+1;
85       char *Dest = new char[Size];
86       DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
87       
88       std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
89       Dest[Size-1] = 0;
90       
91       // Endian safe: Result[i] = (PointerTy)Dest;
92       EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i),
93                              Type::IntTy);
94     }
95     Result[InputArgv.size()] = 0;  // null terminate it
96     return Result;
97   }
98 }
99
100 /// callAsMain - Call the function named FnName from M as if its
101 /// signature were int main (int argc, char **argv, const char
102 /// **envp), using the contents of Args to determine argc & argv, and
103 /// the contents of EnvVars to determine envp.  Returns the result
104 /// from calling FnName, or -1 and prints an error msg. if the named
105 /// function cannot be found.
106 ///
107 int callAsMain(ExecutionEngine *EE, ModuleProvider *MP,
108                const std::string &FnName,
109                const std::vector<std::string> &Args,
110                const std::vector<std::string> &EnvVars) {
111   Function *Fn = MP->getModule()->getNamedFunction(FnName);
112   if (!Fn) {
113     std::cerr << "Function '" << FnName << "' not found in module.\n";
114     return -1;
115   }
116   std::vector<GenericValue> GVArgs;
117   GenericValue GVArgc;
118   GVArgc.IntVal = Args.size();
119   GVArgs.push_back(GVArgc); // Arg #0 = argc.
120   GVArgs.push_back(PTOGV(CreateArgv(EE, Args))); // Arg #1 = argv.
121   GVArgs.push_back(PTOGV(CreateArgv(EE, EnvVars))); // Arg #2 = envp.
122   return EE->run(Fn, GVArgs).IntVal;
123 }
124
125 //===----------------------------------------------------------------------===//
126 // main Driver function
127 //
128 int main(int argc, char **argv, char * const *envp) {
129   cl::ParseCommandLineOptions(argc, argv,
130                               " llvm interpreter & dynamic compiler\n");
131
132   // Load the bytecode...
133   std::string ErrorMsg;
134   ModuleProvider *MP = 0;
135   try {
136     MP = getBytecodeModuleProvider(InputFile);
137   } catch (std::string &err) {
138     std::cerr << "Error parsing '" << InputFile << "': " << err << "\n";
139     exit(1);
140   }
141
142   ExecutionEngine *EE =
143     ExecutionEngine::create(MP, ForceInterpreter);
144   assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
145
146   // If the user specifically requested an argv[0] to pass into the program, do
147   // it now.
148   if (!FakeArgv0.empty()) {
149     InputFile = FakeArgv0;
150   } else {
151     // Otherwise, if there is a .bc suffix on the executable strip it off, it
152     // might confuse the program.
153     if (InputFile.rfind(".bc") == InputFile.length() - 3)
154       InputFile.erase(InputFile.length() - 3);
155   }
156
157   // Add the module's name to the start of the vector of arguments to main().
158   InputArgv.insert(InputArgv.begin(), InputFile);
159
160   // Run the main function!
161   int ExitCode = callAsMain(EE, MP, MainFunction, InputArgv,
162                             makeStringVector(envp)); 
163
164   // Now that we are done executing the program, shut down the execution engine
165   delete EE;
166   return ExitCode;
167 }