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