Merge branch 'master' into msp430
[llvm/msp430.git] / tools / lli / lli.cpp
blob6d3cbbc1f5fc4a3ba2de01802a7ad1138a15e588
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.
14 //===----------------------------------------------------------------------===//
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"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/System/Process.h"
30 #include "llvm/System/Signals.h"
31 #include <iostream>
32 #include <cerrno>
33 using namespace llvm;
35 namespace {
36 cl::opt<std::string>
37 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
39 cl::list<std::string>
40 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
42 cl::opt<bool> ForceInterpreter("force-interpreter",
43 cl::desc("Force interpretation: disable JIT"),
44 cl::init(false));
46 // 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(' '));
55 cl::opt<std::string>
56 TargetTriple("mtriple", cl::desc("Override target triple for module"));
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"));
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"));
70 cl::opt<bool>
71 DisableCoreFiles("disable-core-files", cl::Hidden,
72 cl::desc("Disable emission of core files if possible"));
74 cl::opt<bool>
75 NoLazyCompilation("disable-lazy-compilation",
76 cl::desc("Disable JIT lazy compilation"),
77 cl::init(false));
80 static ExecutionEngine *EE = 0;
82 static void do_shutdown() {
83 delete EE;
84 llvm_shutdown();
87 //===----------------------------------------------------------------------===//
88 // main Driver function
90 int main(int argc, char **argv, char * const *envp) {
91 sys::PrintStackTraceOnErrorSignal();
92 PrettyStackTraceProgram X(argc, argv);
94 atexit(do_shutdown); // Call llvm_shutdown() on exit.
95 cl::ParseCommandLineOptions(argc, argv,
96 "llvm interpreter & dynamic compiler\n");
98 // If the user doesn't want core files, disable them.
99 if (DisableCoreFiles)
100 sys::Process::PreventCoreFiles();
102 // Load the bitcode...
103 std::string ErrorMsg;
104 ModuleProvider *MP = NULL;
105 if (MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFile,&ErrorMsg)) {
106 MP = getBitcodeModuleProvider(Buffer, &ErrorMsg);
107 if (!MP) delete Buffer;
110 if (!MP) {
111 std::cerr << argv[0] << ": error loading program '" << InputFile << "': "
112 << ErrorMsg << "\n";
113 exit(1);
116 // Get the module as the MP could go away once EE takes over.
117 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);
125 // If we are supposed to override the target triple, do so now.
126 if (!TargetTriple.empty())
127 Mod->setTargetTriple(TargetTriple);
129 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;
141 EE = ExecutionEngine::create(MP, ForceInterpreter, &ErrorMsg, OLvl);
142 if (!EE && !ErrorMsg.empty()) {
143 std::cerr << argv[0] << ":error creating EE: " << ErrorMsg << "\n";
144 exit(1);
147 if (NoLazyCompilation)
148 EE->DisableLazyCompilation();
150 // 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);
161 // Add the module's name to the start of the vector of arguments to main().
162 InputArgv.insert(InputArgv.begin(), InputFile);
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.
169 Function *EntryFn = Mod->getFunction(EntryFunc);
170 if (!EntryFn) {
171 std::cerr << '\'' << EntryFunc << "\' function not found in module.\n";
172 return -1;
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);
180 // Reset errno to zero on entry to main.
181 errno = 0;
183 // Run static constructors.
184 EE->runStaticConstructorsDestructors(false);
186 if (NoLazyCompilation) {
187 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
188 Function *Fn = &*I;
189 if (Fn != EntryFn && !Fn->isDeclaration())
190 EE->getPointerToFunction(Fn);
194 // Run main.
195 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
197 // Run static destructors.
198 EE->runStaticConstructorsDestructors(true);
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();