blob: afd3c5a71fa4d0dae6f833ffbb260460220f0091 [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 Lattner41788082009-06-17 16:42:19 +000031#include "llvm/Target/TargetSelect.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
88//===----------------------------------------------------------------------===//
89// main Driver function
90//
91int main(int argc, char **argv, char * const *envp) {
Chris Lattnere6012df2009-03-06 05:34:10 +000092 sys::PrintStackTraceOnErrorSignal();
93 PrettyStackTraceProgram X(argc, argv);
94
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 atexit(do_shutdown); // Call llvm_shutdown() on exit.
96 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman6099df82007-10-08 15:45:12 +000097 "llvm interpreter & dynamic compiler\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098
99 // If the user doesn't want core files, disable them.
100 if (DisableCoreFiles)
101 sys::Process::PreventCoreFiles();
102
103 // Load the bitcode...
104 std::string ErrorMsg;
Evan Chengdb7d42d2008-04-22 06:51:41 +0000105 ModuleProvider *MP = NULL;
106 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 MP = getBitcodeModuleProvider(Buffer, &ErrorMsg);
108 if (!MP) delete Buffer;
109 }
110
111 if (!MP) {
112 std::cerr << argv[0] << ": error loading program '" << InputFile << "': "
113 << ErrorMsg << "\n";
114 exit(1);
115 }
116
117 // Get the module as the MP could go away once EE takes over.
Evan Chengdb7d42d2008-04-22 06:51:41 +0000118 Module *Mod = NoLazyCompilation
119 ? MP->materializeModule(&ErrorMsg) : MP->getModule();
120 if (!Mod) {
121 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
122 std::cerr << "Reason: " << ErrorMsg << "\n";
123 exit(1);
124 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125
126 // If we are supposed to override the target triple, do so now.
127 if (!TargetTriple.empty())
128 Mod->setTargetTriple(TargetTriple);
Evan Chengdb7d42d2008-04-22 06:51:41 +0000129
Evan Chengb244f3f2009-05-04 23:05:19 +0000130 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
131 switch (OptLevel) {
132 default:
133 std::cerr << argv[0] << ": invalid optimization level.\n";
134 return 1;
135 case ' ': break;
136 case '0': OLvl = CodeGenOpt::None; break;
137 case '1':
138 case '2': OLvl = CodeGenOpt::Default; break;
139 case '3': OLvl = CodeGenOpt::Aggressive; break;
140 }
Chris Lattner519028c2009-06-17 02:15:40 +0000141
Chris Lattner41788082009-06-17 16:42:19 +0000142 // If we have a native target, initialize it to ensure it is linked in and
143 // usable by the JIT.
144 InitializeNativeTarget();
Evan Chengb244f3f2009-05-04 23:05:19 +0000145
146 EE = ExecutionEngine::create(MP, ForceInterpreter, &ErrorMsg, OLvl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 if (!EE && !ErrorMsg.empty()) {
148 std::cerr << argv[0] << ":error creating EE: " << ErrorMsg << "\n";
149 exit(1);
150 }
151
Evan Chengdb7d42d2008-04-22 06:51:41 +0000152 if (NoLazyCompilation)
153 EE->DisableLazyCompilation();
154
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 // If the user specifically requested an argv[0] to pass into the program,
156 // do it now.
157 if (!FakeArgv0.empty()) {
158 InputFile = FakeArgv0;
159 } else {
160 // Otherwise, if there is a .bc suffix on the executable strip it off, it
161 // might confuse the program.
162 if (InputFile.rfind(".bc") == InputFile.length() - 3)
163 InputFile.erase(InputFile.length() - 3);
164 }
165
166 // Add the module's name to the start of the vector of arguments to main().
167 InputArgv.insert(InputArgv.begin(), InputFile);
168
169 // Call the main function from M as if its signature were:
170 // int main (int argc, char **argv, const char **envp)
171 // using the contents of Args to determine argc & argv, and the contents of
172 // EnvVars to determine envp.
173 //
Evan Chengd2294242008-11-05 23:21:52 +0000174 Function *EntryFn = Mod->getFunction(EntryFunc);
175 if (!EntryFn) {
176 std::cerr << '\'' << EntryFunc << "\' function not found in module.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 return -1;
178 }
179
180 // If the program doesn't explicitly call exit, we will need the Exit
181 // function later on to make an explicit call, so get the function now.
182 Constant *Exit = Mod->getOrInsertFunction("exit", Type::VoidTy,
183 Type::Int32Ty, NULL);
184
185 // Reset errno to zero on entry to main.
186 errno = 0;
187
188 // Run static constructors.
189 EE->runStaticConstructorsDestructors(false);
Evan Chengdb7d42d2008-04-22 06:51:41 +0000190
191 if (NoLazyCompilation) {
192 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
193 Function *Fn = &*I;
Evan Chengd2294242008-11-05 23:21:52 +0000194 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengdb7d42d2008-04-22 06:51:41 +0000195 EE->getPointerToFunction(Fn);
196 }
197 }
198
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 // Run main.
Evan Chengd2294242008-11-05 23:21:52 +0000200 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201
202 // Run static destructors.
203 EE->runStaticConstructorsDestructors(true);
204
205 // If the program didn't call exit explicitly, we should call it now.
206 // This ensures that any atexit handlers get called correctly.
207 if (Function *ExitF = dyn_cast<Function>(Exit)) {
208 std::vector<GenericValue> Args;
209 GenericValue ResultGV;
210 ResultGV.IntVal = APInt(32, Result);
211 Args.push_back(ResultGV);
212 EE->runFunction(ExitF, Args);
213 std::cerr << "ERROR: exit(" << Result << ") returned!\n";
214 abort();
215 } else {
216 std::cerr << "ERROR: exit defined with wrong prototype!\n";
217 abort();
218 }
219}