Hold the LLVMContext by reference rather than by pointer.
[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 intepreter if no JIT is available for this platform.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/ModuleProvider.h"
19 #include "llvm/Type.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/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/PluginLoader.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/System/Process.h"
32 #include "llvm/System/Signals.h"
33 #include "llvm/Target/TargetSelect.h"
34 #include <iostream>
35 #include <cerrno>
36 using namespace llvm;
37
38 namespace {
39   cl::opt<std::string>
40   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
41
42   cl::list<std::string>
43   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
44
45   cl::opt<bool> ForceInterpreter("force-interpreter",
46                                  cl::desc("Force interpretation: disable JIT"),
47                                  cl::init(false));
48
49   // Determine optimization level.
50   cl::opt<char>
51   OptLevel("O",
52            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
53                     "(default = '-O2')"),
54            cl::Prefix,
55            cl::ZeroOrMore,
56            cl::init(' '));
57
58   cl::opt<std::string>
59   TargetTriple("mtriple", cl::desc("Override target triple for module"));
60
61   cl::opt<std::string>
62   EntryFunc("entry-function",
63             cl::desc("Specify the entry function (default = 'main') "
64                      "of the executable"),
65             cl::value_desc("function"),
66             cl::init("main"));
67   
68   cl::opt<std::string>
69   FakeArgv0("fake-argv0",
70             cl::desc("Override the 'argv[0]' value passed into the executing"
71                      " program"), cl::value_desc("executable"));
72   
73   cl::opt<bool>
74   DisableCoreFiles("disable-core-files", cl::Hidden,
75                    cl::desc("Disable emission of core files if possible"));
76
77   cl::opt<bool>
78   NoLazyCompilation("disable-lazy-compilation",
79                   cl::desc("Disable JIT lazy compilation"),
80                   cl::init(false));
81 }
82
83 static ExecutionEngine *EE = 0;
84
85 static void do_shutdown() {
86   delete EE;
87   llvm_shutdown();
88 }
89
90 //===----------------------------------------------------------------------===//
91 // main Driver function
92 //
93 int main(int argc, char **argv, char * const *envp) {
94   sys::PrintStackTraceOnErrorSignal();
95   PrettyStackTraceProgram X(argc, argv);
96   
97   LLVMContext Context;
98   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
99   cl::ParseCommandLineOptions(argc, argv,
100                               "llvm interpreter & dynamic compiler\n");
101
102   // If the user doesn't want core files, disable them.
103   if (DisableCoreFiles)
104     sys::Process::PreventCoreFiles();
105   
106   // Load the bitcode...
107   std::string ErrorMsg;
108   ModuleProvider *MP = NULL;
109   if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)){
110     MP = getBitcodeModuleProvider(Buffer, Context, &ErrorMsg);
111     if (!MP) delete Buffer;
112   }
113   
114   if (!MP) {
115     std::cerr << argv[0] << ": error loading program '" << InputFile << "': "
116               << ErrorMsg << "\n";
117     exit(1);
118   }
119
120   // Get the module as the MP could go away once EE takes over.
121   Module *Mod = NoLazyCompilation
122     ? MP->materializeModule(&ErrorMsg) : MP->getModule();
123   if (!Mod) {
124     std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
125     std::cerr << "Reason: " << ErrorMsg << "\n";
126     exit(1);
127   }
128
129   // If we are supposed to override the target triple, do so now.
130   if (!TargetTriple.empty())
131     Mod->setTargetTriple(TargetTriple);
132
133   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
134   switch (OptLevel) {
135   default:
136     std::cerr << argv[0] << ": invalid optimization level.\n";
137     return 1;
138   case ' ': break;
139   case '0': OLvl = CodeGenOpt::None; break;
140   case '1':
141   case '2': OLvl = CodeGenOpt::Default; break;
142   case '3': OLvl = CodeGenOpt::Aggressive; break;
143   }
144   
145   // If we have a native target, initialize it to ensure it is linked in and
146   // usable by the JIT.
147   InitializeNativeTarget();
148
149   EE = ExecutionEngine::create(MP, ForceInterpreter, &ErrorMsg, OLvl);
150   if (!EE && !ErrorMsg.empty()) {
151     std::cerr << argv[0] << ":error creating EE: " << ErrorMsg << "\n";
152     exit(1);
153   }
154
155   EE->RegisterJITEventListener(createMacOSJITEventListener());
156
157   if (NoLazyCompilation)
158     EE->DisableLazyCompilation();
159
160   // If the user specifically requested an argv[0] to pass into the program,
161   // do it now.
162   if (!FakeArgv0.empty()) {
163     InputFile = FakeArgv0;
164   } else {
165     // Otherwise, if there is a .bc suffix on the executable strip it off, it
166     // might confuse the program.
167     if (InputFile.rfind(".bc") == InputFile.length() - 3)
168       InputFile.erase(InputFile.length() - 3);
169   }
170
171   // Add the module's name to the start of the vector of arguments to main().
172   InputArgv.insert(InputArgv.begin(), InputFile);
173
174   // Call the main function from M as if its signature were:
175   //   int main (int argc, char **argv, const char **envp)
176   // using the contents of Args to determine argc & argv, and the contents of
177   // EnvVars to determine envp.
178   //
179   Function *EntryFn = Mod->getFunction(EntryFunc);
180   if (!EntryFn) {
181     std::cerr << '\'' << EntryFunc << "\' function not found in module.\n";
182     return -1;
183   }
184
185   // If the program doesn't explicitly call exit, we will need the Exit 
186   // function later on to make an explicit call, so get the function now. 
187   Constant *Exit = Mod->getOrInsertFunction("exit", Type::VoidTy,
188                                                         Type::Int32Ty, NULL);
189   
190   // Reset errno to zero on entry to main.
191   errno = 0;
192  
193   // Run static constructors.
194   EE->runStaticConstructorsDestructors(false);
195
196   if (NoLazyCompilation) {
197     for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
198       Function *Fn = &*I;
199       if (Fn != EntryFn && !Fn->isDeclaration())
200         EE->getPointerToFunction(Fn);
201     }
202   }
203
204   // Run main.
205   int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
206
207   // Run static destructors.
208   EE->runStaticConstructorsDestructors(true);
209   
210   // If the program didn't call exit explicitly, we should call it now. 
211   // This ensures that any atexit handlers get called correctly.
212   if (Function *ExitF = dyn_cast<Function>(Exit)) {
213     std::vector<GenericValue> Args;
214     GenericValue ResultGV;
215     ResultGV.IntVal = APInt(32, Result);
216     Args.push_back(ResultGV);
217     EE->runFunction(ExitF, Args);
218     std::cerr << "ERROR: exit(" << Result << ") returned!\n";
219     abort();
220   } else {
221     std::cerr << "ERROR: exit defined with wrong prototype!\n";
222     abort();
223   }
224 }