For PR411:
[oota-llvm.git] / tools / lli / lli.cpp
1 //===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/Type.h"
19 #include "llvm/Bytecode/Reader.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/PluginLoader.h"
27 #include "llvm/System/Process.h"
28 #include "llvm/System/Signals.h"
29 #include <iostream>
30
31 using namespace llvm;
32
33 namespace {
34   cl::opt<std::string>
35   InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-"));
36
37   cl::list<std::string>
38   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
39
40   cl::opt<bool> ForceInterpreter("force-interpreter",
41                                  cl::desc("Force interpretation: disable JIT"),
42                                  cl::init(false));
43   cl::opt<std::string>
44   TargetTriple("mtriple", cl::desc("Override target triple for module"));
45   
46   cl::opt<std::string>
47   FakeArgv0("fake-argv0",
48             cl::desc("Override the 'argv[0]' value passed into the executing"
49                      " program"), cl::value_desc("executable"));
50   
51   cl::opt<bool>
52   DisableCoreFiles("disable-core-files", cl::Hidden,
53                    cl::desc("Disable emission of core files if possible"));
54 }
55
56 //===----------------------------------------------------------------------===//
57 // main Driver function
58 //
59 int main(int argc, char **argv, char * const *envp) {
60   atexit(llvm_shutdown);  // Call llvm_shutdown() on exit.
61   try {
62     cl::ParseCommandLineOptions(argc, argv,
63                                 " llvm interpreter & dynamic compiler\n");
64     sys::PrintStackTraceOnErrorSignal();
65
66     // If the user doesn't want core files, disable them.
67     if (DisableCoreFiles)
68       sys::Process::PreventCoreFiles();
69     
70     // Load the bytecode...
71     std::string ErrorMsg;
72     ModuleProvider *MP = 0;
73     MP = getBytecodeModuleProvider(InputFile, &ErrorMsg);
74     if (!MP) {
75       std::cerr << "Error loading program '" << InputFile << "': "
76                 << ErrorMsg << "\n";
77       exit(1);
78     }
79
80     // If we are supposed to override the target triple, do so now.
81     if (!TargetTriple.empty())
82       MP->getModule()->setTargetTriple(TargetTriple);
83     
84     ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter);
85     assert(EE &&"Couldn't create an ExecutionEngine, not even an interpreter?");
86
87     // If the user specifically requested an argv[0] to pass into the program,
88     // do it now.
89     if (!FakeArgv0.empty()) {
90       InputFile = FakeArgv0;
91     } else {
92       // Otherwise, if there is a .bc suffix on the executable strip it off, it
93       // might confuse the program.
94       if (InputFile.rfind(".bc") == InputFile.length() - 3)
95         InputFile.erase(InputFile.length() - 3);
96     }
97
98     // Add the module's name to the start of the vector of arguments to main().
99     InputArgv.insert(InputArgv.begin(), InputFile);
100
101     // Call the main function from M as if its signature were:
102     //   int main (int argc, char **argv, const char **envp)
103     // using the contents of Args to determine argc & argv, and the contents of
104     // EnvVars to determine envp.
105     //
106     Function *Fn = MP->getModule()->getFunction("main");
107     if (!Fn) {
108       std::cerr << "'main' function not found in module.\n";
109       return -1;
110     }
111
112     // Run static constructors.
113     EE->runStaticConstructorsDestructors(false);
114     
115     // Run main.
116     int Result = EE->runFunctionAsMain(Fn, InputArgv, envp);
117
118     // Run static destructors.
119     EE->runStaticConstructorsDestructors(true);
120     
121     // If the program didn't explicitly call exit, call exit now, for the
122     // program. This ensures that any atexit handlers get called correctly.
123     Constant *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy,
124                                                           Type::Int32Ty, NULL);
125     if (Function *ExitF = dyn_cast<Function>(Exit)) {
126       std::vector<GenericValue> Args;
127       GenericValue ResultGV;
128       ResultGV.Int32Val = Result;
129       Args.push_back(ResultGV);
130       EE->runFunction(ExitF, Args);
131       std::cerr << "ERROR: exit(" << Result << ") returned!\n";
132       abort();
133     } else {
134       std::cerr << "ERROR: exit defined with wrong prototype!\n";
135       abort();
136     }
137   } catch (const std::string& msg) {
138     std::cerr << argv[0] << ": " << msg << "\n";
139   } catch (...) {
140     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
141   }
142   abort();
143 }