lli.cpp revision 439661395fd2a2a832dba01c65bc88718528313c
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 interpreter if no JIT is available for this platform. 13// 14//===----------------------------------------------------------------------===// 15 16#include "llvm/LLVMContext.h" 17#include "llvm/Module.h" 18#include "llvm/Type.h" 19#include "llvm/ADT/Triple.h" 20#include "llvm/Bitcode/ReaderWriter.h" 21#include "llvm/CodeGen/LinkAllCodegenComponents.h" 22#include "llvm/ExecutionEngine/GenericValue.h" 23#include "llvm/ExecutionEngine/Interpreter.h" 24#include "llvm/ExecutionEngine/JIT.h" 25#include "llvm/ExecutionEngine/JITEventListener.h" 26#include "llvm/ExecutionEngine/MCJIT.h" 27#include "llvm/Support/CommandLine.h" 28#include "llvm/Support/IRReader.h" 29#include "llvm/Support/ManagedStatic.h" 30#include "llvm/Support/MemoryBuffer.h" 31#include "llvm/Support/PluginLoader.h" 32#include "llvm/Support/PrettyStackTrace.h" 33#include "llvm/Support/raw_ostream.h" 34#include "llvm/Support/Process.h" 35#include "llvm/Support/Signals.h" 36#include "llvm/Target/TargetSelect.h" 37#include <cerrno> 38 39#ifdef __CYGWIN__ 40#include <cygwin/version.h> 41#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 42#define DO_NOTHING_ATEXIT 1 43#endif 44#endif 45 46using namespace llvm; 47 48namespace { 49 cl::opt<std::string> 50 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); 51 52 cl::list<std::string> 53 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); 54 55 cl::opt<bool> ForceInterpreter("force-interpreter", 56 cl::desc("Force interpretation: disable JIT"), 57 cl::init(false)); 58 59 cl::opt<bool> UseMCJIT( 60 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"), 61 cl::init(false)); 62 63 // Determine optimization level. 64 cl::opt<char> 65 OptLevel("O", 66 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 67 "(default = '-O2')"), 68 cl::Prefix, 69 cl::ZeroOrMore, 70 cl::init(' ')); 71 72 cl::opt<std::string> 73 TargetTriple("mtriple", cl::desc("Override target triple for module")); 74 75 cl::opt<std::string> 76 MArch("march", 77 cl::desc("Architecture to generate assembly for (see --version)")); 78 79 cl::opt<std::string> 80 MCPU("mcpu", 81 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 82 cl::value_desc("cpu-name"), 83 cl::init("")); 84 85 cl::list<std::string> 86 MAttrs("mattr", 87 cl::CommaSeparated, 88 cl::desc("Target specific attributes (-mattr=help for details)"), 89 cl::value_desc("a1,+a2,-a3,...")); 90 91 cl::opt<std::string> 92 EntryFunc("entry-function", 93 cl::desc("Specify the entry function (default = 'main') " 94 "of the executable"), 95 cl::value_desc("function"), 96 cl::init("main")); 97 98 cl::opt<std::string> 99 FakeArgv0("fake-argv0", 100 cl::desc("Override the 'argv[0]' value passed into the executing" 101 " program"), cl::value_desc("executable")); 102 103 cl::opt<bool> 104 DisableCoreFiles("disable-core-files", cl::Hidden, 105 cl::desc("Disable emission of core files if possible")); 106 107 cl::opt<bool> 108 NoLazyCompilation("disable-lazy-compilation", 109 cl::desc("Disable JIT lazy compilation"), 110 cl::init(false)); 111 112 cl::opt<Reloc::Model> 113 RelocModel("relocation-model", 114 cl::desc("Choose relocation model"), 115 cl::init(Reloc::Default), 116 cl::values( 117 clEnumValN(Reloc::Default, "default", 118 "Target default relocation model"), 119 clEnumValN(Reloc::Static, "static", 120 "Non-relocatable code"), 121 clEnumValN(Reloc::PIC_, "pic", 122 "Fully relocatable, position independent code"), 123 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", 124 "Relocatable external references, non-relocatable code"), 125 clEnumValEnd)); 126} 127 128static ExecutionEngine *EE = 0; 129 130static void do_shutdown() { 131 // Cygwin-1.5 invokes DLL's dtors before atexit handler. 132#ifndef DO_NOTHING_ATEXIT 133 delete EE; 134 llvm_shutdown(); 135#endif 136} 137 138//===----------------------------------------------------------------------===// 139// main Driver function 140// 141int main(int argc, char **argv, char * const *envp) { 142 sys::PrintStackTraceOnErrorSignal(); 143 PrettyStackTraceProgram X(argc, argv); 144 145 LLVMContext &Context = getGlobalContext(); 146 atexit(do_shutdown); // Call llvm_shutdown() on exit. 147 148 // If we have a native target, initialize it to ensure it is linked in and 149 // usable by the JIT. 150 InitializeNativeTarget(); 151 InitializeNativeTargetAsmPrinter(); 152 153 cl::ParseCommandLineOptions(argc, argv, 154 "llvm interpreter & dynamic compiler\n"); 155 156 // If the user doesn't want core files, disable them. 157 if (DisableCoreFiles) 158 sys::Process::PreventCoreFiles(); 159 160 // Load the bitcode... 161 SMDiagnostic Err; 162 Module *Mod = ParseIRFile(InputFile, Err, Context); 163 if (!Mod) { 164 Err.Print(argv[0], errs()); 165 return 1; 166 } 167 168 // If not jitting lazily, load the whole bitcode file eagerly too. 169 std::string ErrorMsg; 170 if (NoLazyCompilation) { 171 if (Mod->MaterializeAllPermanently(&ErrorMsg)) { 172 errs() << argv[0] << ": bitcode didn't read correctly.\n"; 173 errs() << "Reason: " << ErrorMsg << "\n"; 174 exit(1); 175 } 176 } 177 178 EngineBuilder builder(Mod); 179 builder.setMArch(MArch); 180 builder.setMCPU(MCPU); 181 builder.setMAttrs(MAttrs); 182 builder.setRelocationModel(RelocModel); 183 builder.setErrorStr(&ErrorMsg); 184 builder.setEngineKind(ForceInterpreter 185 ? EngineKind::Interpreter 186 : EngineKind::JIT); 187 188 // If we are supposed to override the target triple, do so now. 189 if (!TargetTriple.empty()) 190 Mod->setTargetTriple(Triple::normalize(TargetTriple)); 191 192 // Enable MCJIT, if desired. 193 if (UseMCJIT) 194 builder.setUseMCJIT(true); 195 196 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 197 switch (OptLevel) { 198 default: 199 errs() << argv[0] << ": invalid optimization level.\n"; 200 return 1; 201 case ' ': break; 202 case '0': OLvl = CodeGenOpt::None; break; 203 case '1': OLvl = CodeGenOpt::Less; break; 204 case '2': OLvl = CodeGenOpt::Default; break; 205 case '3': OLvl = CodeGenOpt::Aggressive; break; 206 } 207 builder.setOptLevel(OLvl); 208 209 EE = builder.create(); 210 if (!EE) { 211 if (!ErrorMsg.empty()) 212 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; 213 else 214 errs() << argv[0] << ": unknown error creating EE!\n"; 215 exit(1); 216 } 217 218 EE->RegisterJITEventListener(createOProfileJITEventListener()); 219 220 EE->DisableLazyCompilation(NoLazyCompilation); 221 222 // If the user specifically requested an argv[0] to pass into the program, 223 // do it now. 224 if (!FakeArgv0.empty()) { 225 InputFile = FakeArgv0; 226 } else { 227 // Otherwise, if there is a .bc suffix on the executable strip it off, it 228 // might confuse the program. 229 if (StringRef(InputFile).endswith(".bc")) 230 InputFile.erase(InputFile.length() - 3); 231 } 232 233 // Add the module's name to the start of the vector of arguments to main(). 234 InputArgv.insert(InputArgv.begin(), InputFile); 235 236 // Call the main function from M as if its signature were: 237 // int main (int argc, char **argv, const char **envp) 238 // using the contents of Args to determine argc & argv, and the contents of 239 // EnvVars to determine envp. 240 // 241 Function *EntryFn = Mod->getFunction(EntryFunc); 242 if (!EntryFn) { 243 errs() << '\'' << EntryFunc << "\' function not found in module.\n"; 244 return -1; 245 } 246 247 // If the program doesn't explicitly call exit, we will need the Exit 248 // function later on to make an explicit call, so get the function now. 249 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), 250 Type::getInt32Ty(Context), 251 NULL); 252 253 // Reset errno to zero on entry to main. 254 errno = 0; 255 256 // Run static constructors. 257 EE->runStaticConstructorsDestructors(false); 258 259 if (NoLazyCompilation) { 260 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { 261 Function *Fn = &*I; 262 if (Fn != EntryFn && !Fn->isDeclaration()) 263 EE->getPointerToFunction(Fn); 264 } 265 } 266 267 // Run main. 268 int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); 269 270 // Run static destructors. 271 EE->runStaticConstructorsDestructors(true); 272 273 // If the program didn't call exit explicitly, we should call it now. 274 // This ensures that any atexit handlers get called correctly. 275 if (Function *ExitF = dyn_cast<Function>(Exit)) { 276 std::vector<GenericValue> Args; 277 GenericValue ResultGV; 278 ResultGV.IntVal = APInt(32, Result); 279 Args.push_back(ResultGV); 280 EE->runFunction(ExitF, Args); 281 errs() << "ERROR: exit(" << Result << ") returned!\n"; 282 abort(); 283 } else { 284 errs() << "ERROR: exit defined with wrong prototype!\n"; 285 abort(); 286 } 287} 288