lli: Add stub -use-mcjit option, which doesn't currently do anything.
[oota-llvm.git] / tools / lli / lli.cpp
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/Support/CommandLine.h"
27 #include "llvm/Support/IRReader.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/PluginLoader.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Process.h"
34 #include "llvm/System/Signals.h"
35 #include "llvm/Target/TargetSelect.h"
36 #include <cerrno>
37
38 #ifdef __CYGWIN__
39 #include <cygwin/version.h>
40 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
41 #define DO_NOTHING_ATEXIT 1
42 #endif
43 #endif
44
45 using namespace llvm;
46
47 namespace {
48   cl::opt<std::string>
49   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
50
51   cl::list<std::string>
52   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
53
54   cl::opt<bool> ForceInterpreter("force-interpreter",
55                                  cl::desc("Force interpretation: disable JIT"),
56                                  cl::init(false));
57
58   cl::opt<bool> UseMCJIT(
59     "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
60     cl::init(false));
61
62   // Determine optimization level.
63   cl::opt<char>
64   OptLevel("O",
65            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
66                     "(default = '-O2')"),
67            cl::Prefix,
68            cl::ZeroOrMore,
69            cl::init(' '));
70
71   cl::opt<std::string>
72   TargetTriple("mtriple", cl::desc("Override target triple for module"));
73
74   cl::opt<std::string>
75   MArch("march",
76         cl::desc("Architecture to generate assembly for (see --version)"));
77
78   cl::opt<std::string>
79   MCPU("mcpu",
80        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
81        cl::value_desc("cpu-name"),
82        cl::init(""));
83
84   cl::list<std::string>
85   MAttrs("mattr",
86          cl::CommaSeparated,
87          cl::desc("Target specific attributes (-mattr=help for details)"),
88          cl::value_desc("a1,+a2,-a3,..."));
89
90   cl::opt<std::string>
91   EntryFunc("entry-function",
92             cl::desc("Specify the entry function (default = 'main') "
93                      "of the executable"),
94             cl::value_desc("function"),
95             cl::init("main"));
96   
97   cl::opt<std::string>
98   FakeArgv0("fake-argv0",
99             cl::desc("Override the 'argv[0]' value passed into the executing"
100                      " program"), cl::value_desc("executable"));
101   
102   cl::opt<bool>
103   DisableCoreFiles("disable-core-files", cl::Hidden,
104                    cl::desc("Disable emission of core files if possible"));
105
106   cl::opt<bool>
107   NoLazyCompilation("disable-lazy-compilation",
108                   cl::desc("Disable JIT lazy compilation"),
109                   cl::init(false));
110 }
111
112 static ExecutionEngine *EE = 0;
113
114 static void do_shutdown() {
115   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
116 #ifndef DO_NOTHING_ATEXIT
117   delete EE;
118   llvm_shutdown();
119 #endif
120 }
121
122 //===----------------------------------------------------------------------===//
123 // main Driver function
124 //
125 int main(int argc, char **argv, char * const *envp) {
126   sys::PrintStackTraceOnErrorSignal();
127   PrettyStackTraceProgram X(argc, argv);
128   
129   LLVMContext &Context = getGlobalContext();
130   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
131
132   // If we have a native target, initialize it to ensure it is linked in and
133   // usable by the JIT.
134   InitializeNativeTarget();
135
136   cl::ParseCommandLineOptions(argc, argv,
137                               "llvm interpreter & dynamic compiler\n");
138
139   // If the user doesn't want core files, disable them.
140   if (DisableCoreFiles)
141     sys::Process::PreventCoreFiles();
142   
143   // Load the bitcode...
144   SMDiagnostic Err;
145   Module *Mod = ParseIRFile(InputFile, Err, Context);
146   if (!Mod) {
147     Err.Print(argv[0], errs());
148     return 1;
149   }
150
151   // If not jitting lazily, load the whole bitcode file eagerly too.
152   std::string ErrorMsg;
153   if (NoLazyCompilation) {
154     if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
155       errs() << argv[0] << ": bitcode didn't read correctly.\n";
156       errs() << "Reason: " << ErrorMsg << "\n";
157       exit(1);
158     }
159   }
160
161   EngineBuilder builder(Mod);
162   builder.setMArch(MArch);
163   builder.setMCPU(MCPU);
164   builder.setMAttrs(MAttrs);
165   builder.setErrorStr(&ErrorMsg);
166   builder.setEngineKind(ForceInterpreter
167                         ? EngineKind::Interpreter
168                         : EngineKind::JIT);
169
170   // If we are supposed to override the target triple, do so now.
171   if (!TargetTriple.empty())
172     Mod->setTargetTriple(Triple::normalize(TargetTriple));
173
174   // Enable MCJIT, if desired.
175   if (UseMCJIT)
176     builder.setUseMCJIT(true);
177
178   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
179   switch (OptLevel) {
180   default:
181     errs() << argv[0] << ": invalid optimization level.\n";
182     return 1;
183   case ' ': break;
184   case '0': OLvl = CodeGenOpt::None; break;
185   case '1': OLvl = CodeGenOpt::Less; break;
186   case '2': OLvl = CodeGenOpt::Default; break;
187   case '3': OLvl = CodeGenOpt::Aggressive; break;
188   }
189   builder.setOptLevel(OLvl);
190
191   EE = builder.create();
192   if (!EE) {
193     if (!ErrorMsg.empty())
194       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
195     else
196       errs() << argv[0] << ": unknown error creating EE!\n";
197     exit(1);
198   }
199
200   EE->RegisterJITEventListener(createOProfileJITEventListener());
201
202   EE->DisableLazyCompilation(NoLazyCompilation);
203
204   // If the user specifically requested an argv[0] to pass into the program,
205   // do it now.
206   if (!FakeArgv0.empty()) {
207     InputFile = FakeArgv0;
208   } else {
209     // Otherwise, if there is a .bc suffix on the executable strip it off, it
210     // might confuse the program.
211     if (StringRef(InputFile).endswith(".bc"))
212       InputFile.erase(InputFile.length() - 3);
213   }
214
215   // Add the module's name to the start of the vector of arguments to main().
216   InputArgv.insert(InputArgv.begin(), InputFile);
217
218   // Call the main function from M as if its signature were:
219   //   int main (int argc, char **argv, const char **envp)
220   // using the contents of Args to determine argc & argv, and the contents of
221   // EnvVars to determine envp.
222   //
223   Function *EntryFn = Mod->getFunction(EntryFunc);
224   if (!EntryFn) {
225     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
226     return -1;
227   }
228
229   // If the program doesn't explicitly call exit, we will need the Exit 
230   // function later on to make an explicit call, so get the function now. 
231   Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
232                                                     Type::getInt32Ty(Context),
233                                                     NULL);
234   
235   // Reset errno to zero on entry to main.
236   errno = 0;
237  
238   // Run static constructors.
239   EE->runStaticConstructorsDestructors(false);
240
241   if (NoLazyCompilation) {
242     for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
243       Function *Fn = &*I;
244       if (Fn != EntryFn && !Fn->isDeclaration())
245         EE->getPointerToFunction(Fn);
246     }
247   }
248
249   // Run main.
250   int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
251
252   // Run static destructors.
253   EE->runStaticConstructorsDestructors(true);
254   
255   // If the program didn't call exit explicitly, we should call it now. 
256   // This ensures that any atexit handlers get called correctly.
257   if (Function *ExitF = dyn_cast<Function>(Exit)) {
258     std::vector<GenericValue> Args;
259     GenericValue ResultGV;
260     ResultGV.IntVal = APInt(32, Result);
261     Args.push_back(ResultGV);
262     EE->runFunction(ExitF, Args);
263     errs() << "ERROR: exit(" << Result << ") returned!\n";
264     abort();
265   } else {
266     errs() << "ERROR: exit defined with wrong prototype!\n";
267     abort();
268   }
269 }