blob: 6d3cbbc1f5fc4a3ba2de01802a7ad1138a15e588 [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"
31#include <iostream>
32#include <cerrno>
33using namespace llvm;
34
35namespace {
36 cl::opt<std::string>
37 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
38
39 cl::list<std::string>
40 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
41
42 cl::opt<bool> ForceInterpreter("force-interpreter",
43 cl::desc("Force interpretation: disable JIT"),
44 cl::init(false));
Evan Cheng209e6d22008-08-08 08:12:06 +000045
Evan Chengb244f3f2009-05-04 23:05:19 +000046 // Determine optimization level.
47 cl::opt<char>
48 OptLevel("O",
49 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
50 "(default = '-O2')"),
51 cl::Prefix,
52 cl::ZeroOrMore,
53 cl::init(' '));
Evan Cheng209e6d22008-08-08 08:12:06 +000054
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 cl::opt<std::string>
56 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengd2294242008-11-05 23:21:52 +000057
58 cl::opt<std::string>
59 EntryFunc("entry-function",
60 cl::desc("Specify the entry function (default = 'main') "
61 "of the executable"),
62 cl::value_desc("function"),
63 cl::init("main"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064
65 cl::opt<std::string>
66 FakeArgv0("fake-argv0",
67 cl::desc("Override the 'argv[0]' value passed into the executing"
68 " program"), cl::value_desc("executable"));
69
70 cl::opt<bool>
71 DisableCoreFiles("disable-core-files", cl::Hidden,
72 cl::desc("Disable emission of core files if possible"));
Evan Chengdb7d42d2008-04-22 06:51:41 +000073
74 cl::opt<bool>
Evan Cheng15e26e42008-05-21 18:20:21 +000075 NoLazyCompilation("disable-lazy-compilation",
Evan Chengdb7d42d2008-04-22 06:51:41 +000076 cl::desc("Disable JIT lazy compilation"),
77 cl::init(false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078}
79
80static ExecutionEngine *EE = 0;
81
82static void do_shutdown() {
83 delete EE;
84 llvm_shutdown();
85}
86
87//===----------------------------------------------------------------------===//
88// main Driver function
89//
90int main(int argc, char **argv, char * const *envp) {
Chris Lattnere6012df2009-03-06 05:34:10 +000091 sys::PrintStackTraceOnErrorSignal();
92 PrettyStackTraceProgram X(argc, argv);
93
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 atexit(do_shutdown); // Call llvm_shutdown() on exit.
95 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman6099df82007-10-08 15:45:12 +000096 "llvm interpreter & dynamic compiler\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097
98 // If the user doesn't want core files, disable them.
99 if (DisableCoreFiles)
100 sys::Process::PreventCoreFiles();
101
102 // Load the bitcode...
103 std::string ErrorMsg;
Evan Chengdb7d42d2008-04-22 06:51:41 +0000104 ModuleProvider *MP = NULL;
105 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 MP = getBitcodeModuleProvider(Buffer, &ErrorMsg);
107 if (!MP) delete Buffer;
108 }
109
110 if (!MP) {
111 std::cerr << argv[0] << ": error loading program '" << InputFile << "': "
112 << ErrorMsg << "\n";
113 exit(1);
114 }
115
116 // Get the module as the MP could go away once EE takes over.
Evan Chengdb7d42d2008-04-22 06:51:41 +0000117 Module *Mod = NoLazyCompilation
118 ? MP->materializeModule(&ErrorMsg) : MP->getModule();
119 if (!Mod) {
120 std::cerr << argv[0] << ": bitcode didn't read correctly.\n";
121 std::cerr << "Reason: " << ErrorMsg << "\n";
122 exit(1);
123 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124
125 // If we are supposed to override the target triple, do so now.
126 if (!TargetTriple.empty())
127 Mod->setTargetTriple(TargetTriple);
Evan Chengdb7d42d2008-04-22 06:51:41 +0000128
Evan Chengb244f3f2009-05-04 23:05:19 +0000129 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
130 switch (OptLevel) {
131 default:
132 std::cerr << argv[0] << ": invalid optimization level.\n";
133 return 1;
134 case ' ': break;
135 case '0': OLvl = CodeGenOpt::None; break;
136 case '1':
137 case '2': OLvl = CodeGenOpt::Default; break;
138 case '3': OLvl = CodeGenOpt::Aggressive; break;
139 }
140
141 EE = ExecutionEngine::create(MP, ForceInterpreter, &ErrorMsg, OLvl);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142 if (!EE && !ErrorMsg.empty()) {
143 std::cerr << argv[0] << ":error creating EE: " << ErrorMsg << "\n";
144 exit(1);
145 }
146
Evan Chengdb7d42d2008-04-22 06:51:41 +0000147 if (NoLazyCompilation)
148 EE->DisableLazyCompilation();
149
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 // If the user specifically requested an argv[0] to pass into the program,
151 // do it now.
152 if (!FakeArgv0.empty()) {
153 InputFile = FakeArgv0;
154 } else {
155 // Otherwise, if there is a .bc suffix on the executable strip it off, it
156 // might confuse the program.
157 if (InputFile.rfind(".bc") == InputFile.length() - 3)
158 InputFile.erase(InputFile.length() - 3);
159 }
160
161 // Add the module's name to the start of the vector of arguments to main().
162 InputArgv.insert(InputArgv.begin(), InputFile);
163
164 // Call the main function from M as if its signature were:
165 // int main (int argc, char **argv, const char **envp)
166 // using the contents of Args to determine argc & argv, and the contents of
167 // EnvVars to determine envp.
168 //
Evan Chengd2294242008-11-05 23:21:52 +0000169 Function *EntryFn = Mod->getFunction(EntryFunc);
170 if (!EntryFn) {
171 std::cerr << '\'' << EntryFunc << "\' function not found in module.\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172 return -1;
173 }
174
175 // If the program doesn't explicitly call exit, we will need the Exit
176 // function later on to make an explicit call, so get the function now.
177 Constant *Exit = Mod->getOrInsertFunction("exit", Type::VoidTy,
178 Type::Int32Ty, NULL);
179
180 // Reset errno to zero on entry to main.
181 errno = 0;
182
183 // Run static constructors.
184 EE->runStaticConstructorsDestructors(false);
Evan Chengdb7d42d2008-04-22 06:51:41 +0000185
186 if (NoLazyCompilation) {
187 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
188 Function *Fn = &*I;
Evan Chengd2294242008-11-05 23:21:52 +0000189 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengdb7d42d2008-04-22 06:51:41 +0000190 EE->getPointerToFunction(Fn);
191 }
192 }
193
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 // Run main.
Evan Chengd2294242008-11-05 23:21:52 +0000195 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196
197 // Run static destructors.
198 EE->runStaticConstructorsDestructors(true);
199
200 // If the program didn't call exit explicitly, we should call it now.
201 // This ensures that any atexit handlers get called correctly.
202 if (Function *ExitF = dyn_cast<Function>(Exit)) {
203 std::vector<GenericValue> Args;
204 GenericValue ResultGV;
205 ResultGV.IntVal = APInt(32, Result);
206 Args.push_back(ResultGV);
207 EE->runFunction(ExitF, Args);
208 std::cerr << "ERROR: exit(" << Result << ") returned!\n";
209 abort();
210 } else {
211 std::cerr << "ERROR: exit defined with wrong prototype!\n";
212 abort();
213 }
214}