blob: 618692db70fc0fb3dff4f329044932b4bdf21dfb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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/Module.h"
17#include "llvm/ModuleProvider.h"
18#include "llvm/Type.h"
19#include "llvm/Bitcode/ReaderWriter.h"
20#include "llvm/CodeGen/LinkAllCodegenComponents.h"
21#include "llvm/ExecutionEngine/JIT.h"
22#include "llvm/ExecutionEngine/Interpreter.h"
23#include "llvm/ExecutionEngine/GenericValue.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/ManagedStatic.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/PluginLoader.h"
Chris Lattnere6012df2009-03-06 05:34:10 +000028#include "llvm/Support/PrettyStackTrace.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/System/Process.h"
30#include "llvm/System/Signals.h"
Chris Lattner519028c2009-06-17 02:15:40 +000031#include "llvm/Config/config.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include <iostream>
33#include <cerrno>
34using namespace llvm;
35
36namespace {
37 cl::opt<std::string>
38 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
39
40 cl::list<std::string>
41 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
42
43 cl::opt<bool> ForceInterpreter("force-interpreter",
44 cl::desc("Force interpretation: disable JIT"),
45 cl::init(false));
Evan Cheng209e6d22008-08-08 08:12:06 +000046
Evan Chengb244f3f2009-05-04 23:05:19 +000047 // Determine optimization level.
48 cl::opt<char>
49 OptLevel("O",
50 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
51 "(default = '-O2')"),
52 cl::Prefix,
53 cl::ZeroOrMore,
54 cl::init(' '));
Evan Cheng209e6d22008-08-08 08:12:06 +000055
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 cl::opt<std::string>
57 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengd2294242008-11-05 23:21:52 +000058
59 cl::opt<std::string>
60 EntryFunc("entry-function",
61 cl::desc("Specify the entry function (default = 'main') "
62 "of the executable"),
63 cl::value_desc("function"),
64 cl::init("main"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065
66 cl::opt<std::string>
67 FakeArgv0("fake-argv0",
68 cl::desc("Override the 'argv[0]' value passed into the executing"
69 " program"), cl::value_desc("executable"));
70
71 cl::opt<bool>
72 DisableCoreFiles("disable-core-files", cl::Hidden,
73 cl::desc("Disable emission of core files if possible"));
Evan Chengdb7d42d2008-04-22 06:51:41 +000074
75 cl::opt<bool>
Evan Cheng15e26e42008-05-21 18:20:21 +000076 NoLazyCompilation("disable-lazy-compilation",
Evan Chengdb7d42d2008-04-22 06:51:41 +000077 cl::desc("Disable JIT lazy compilation"),
78 cl::init(false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079}
80
81static ExecutionEngine *EE = 0;
82
83static void do_shutdown() {
84 delete EE;
85 llvm_shutdown();
86}
87
Chris Lattner519028c2009-06-17 02:15:40 +000088#ifdef LLVM_NATIVE_ARCH
89namespace llvm {
90#define Declare2(TARG, MOD) void Initialize ## TARG ## MOD()
91#define Declare(T, M) Declare2(T, M)
92 Declare(LLVM_NATIVE_ARCH, Target);
93#undef Declare
94#undef Declare2
95}
96#endif
97
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098//===----------------------------------------------------------------------===//
99// main Driver function
100//
101int main(int argc, char **argv, char * const *envp) {
Chris Lattnere6012df2009-03-06 05:34:10 +0000102 sys::PrintStackTraceOnErrorSignal();
103 PrettyStackTraceProgram X(argc, argv);
104
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105 atexit(do_shutdown); // Call llvm_shutdown() on exit.
106 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman6099df82007-10-08 15:45:12 +0000107 "llvm interpreter & dynamic compiler\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108
109 // If the user doesn't want core files, disable them.
110 if (DisableCoreFiles)
111 sys::Process::PreventCoreFiles();
112
113 // Load the bitcode...
114 std::string ErrorMsg;
Evan Chengdb7d42d2008-04-22 06:51:41 +0000115 ModuleProvider *MP = NULL;
116 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 MP = getBitcodeModuleProvider(Buffer, &ErrorMsg);
118 if (!MP) delete Buffer;
119 }
120
121 if (!MP) {
122 std::cerr << argv[0] << ": error loading program '" << InputFile << "': "
123 << ErrorMsg << "\n";
124 exit(1);
125 }
126
127 // Get the module as the MP could go away once EE takes over.
Evan Chengdb7d42d2008-04-22 06:51:41 +0000128 Module *Mod = NoLazyCompilation
129 ? MP->materializeModule(&ErrorMsg) : MP->getModule();
130 if (!Mod) {
131 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
132 std::cerr << "Reason: " << ErrorMsg << "\n";
133 exit(1);
134 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135
136 // If we are supposed to override the target triple, do so now.
137 if (!TargetTriple.empty())
138 Mod->setTargetTriple(TargetTriple);
Evan Chengdb7d42d2008-04-22 06:51:41 +0000139
Evan Chengb244f3f2009-05-04 23:05:19 +0000140 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
141 switch (OptLevel) {
142 default:
143 std::cerr << argv[0] << ": invalid optimization level.\n";
144 return 1;
145 case ' ': break;
146 case '0': OLvl = CodeGenOpt::None; break;
147 case '1':
148 case '2': OLvl = CodeGenOpt::Default; break;
149 case '3': OLvl = CodeGenOpt::Aggressive; break;
150 }
Chris Lattner519028c2009-06-17 02:15:40 +0000151
152 // If we have a native target, initialize it to ensure it is linked in.
153#ifdef LLVM_NATIVE_ARCH
154#define DoInit2(TARG, MOD) llvm::Initialize ## TARG ## MOD()
155#define DoInit(T, M) DoInit2(T, M)
156 DoInit(LLVM_NATIVE_ARCH, Target);
157#undef DoInit
158#undef DoInit2
159#endif
160
Evan Chengb244f3f2009-05-04 23:05:19 +0000161
162 EE = ExecutionEngine::create(MP, ForceInterpreter, &ErrorMsg, OLvl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 if (!EE && !ErrorMsg.empty()) {
164 std::cerr << argv[0] << ":error creating EE: " << ErrorMsg << "\n";
165 exit(1);
166 }
167
Evan Chengdb7d42d2008-04-22 06:51:41 +0000168 if (NoLazyCompilation)
169 EE->DisableLazyCompilation();
170
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 // If the user specifically requested an argv[0] to pass into the program,
172 // do it now.
173 if (!FakeArgv0.empty()) {
174 InputFile = FakeArgv0;
175 } else {
176 // Otherwise, if there is a .bc suffix on the executable strip it off, it
177 // might confuse the program.
178 if (InputFile.rfind(".bc") == InputFile.length() - 3)
179 InputFile.erase(InputFile.length() - 3);
180 }
181
182 // Add the module's name to the start of the vector of arguments to main().
183 InputArgv.insert(InputArgv.begin(), InputFile);
184
185 // Call the main function from M as if its signature were:
186 // int main (int argc, char **argv, const char **envp)
187 // using the contents of Args to determine argc & argv, and the contents of
188 // EnvVars to determine envp.
189 //
Evan Chengd2294242008-11-05 23:21:52 +0000190 Function *EntryFn = Mod->getFunction(EntryFunc);
191 if (!EntryFn) {
192 std::cerr << '\'' << EntryFunc << "\' function not found in module.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 return -1;
194 }
195
196 // If the program doesn't explicitly call exit, we will need the Exit
197 // function later on to make an explicit call, so get the function now.
198 Constant *Exit = Mod->getOrInsertFunction("exit", Type::VoidTy,
199 Type::Int32Ty, NULL);
200
201 // Reset errno to zero on entry to main.
202 errno = 0;
203
204 // Run static constructors.
205 EE->runStaticConstructorsDestructors(false);
Evan Chengdb7d42d2008-04-22 06:51:41 +0000206
207 if (NoLazyCompilation) {
208 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
209 Function *Fn = &*I;
Evan Chengd2294242008-11-05 23:21:52 +0000210 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengdb7d42d2008-04-22 06:51:41 +0000211 EE->getPointerToFunction(Fn);
212 }
213 }
214
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 // Run main.
Evan Chengd2294242008-11-05 23:21:52 +0000216 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217
218 // Run static destructors.
219 EE->runStaticConstructorsDestructors(true);
220
221 // If the program didn't call exit explicitly, we should call it now.
222 // This ensures that any atexit handlers get called correctly.
223 if (Function *ExitF = dyn_cast<Function>(Exit)) {
224 std::vector<GenericValue> Args;
225 GenericValue ResultGV;
226 ResultGV.IntVal = APInt(32, Result);
227 Args.push_back(ResultGV);
228 EE->runFunction(ExitF, Args);
229 std::cerr << "ERROR: exit(" << Result << ") returned!\n";
230 abort();
231 } else {
232 std::cerr << "ERROR: exit defined with wrong prototype!\n";
233 abort();
234 }
235}