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 #define DEBUG_TYPE "lli" 17 #include "llvm/IR/LLVMContext.h" 18 #include "RecordingMemoryManager.h" 19 #include "RemoteTarget.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/Bitcode/ReaderWriter.h" 22 #include "llvm/CodeGen/LinkAllCodegenComponents.h" 23 #include "llvm/ExecutionEngine/GenericValue.h" 24 #include "llvm/ExecutionEngine/Interpreter.h" 25 #include "llvm/ExecutionEngine/JIT.h" 26 #include "llvm/ExecutionEngine/JITEventListener.h" 27 #include "llvm/ExecutionEngine/JITMemoryManager.h" 28 #include "llvm/ExecutionEngine/MCJIT.h" 29 #include "llvm/ExecutionEngine/SectionMemoryManager.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/IR/Type.h" 32 #include "llvm/IRReader/IRReader.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/DynamicLibrary.h" 36 #include "llvm/Support/Format.h" 37 #include "llvm/Support/ManagedStatic.h" 38 #include "llvm/Support/MathExtras.h" 39 #include "llvm/Support/Memory.h" 40 #include "llvm/Support/MemoryBuffer.h" 41 #include "llvm/Support/PluginLoader.h" 42 #include "llvm/Support/PrettyStackTrace.h" 43 #include "llvm/Support/Process.h" 44 #include "llvm/Support/Signals.h" 45 #include "llvm/Support/SourceMgr.h" 46 #include "llvm/Support/TargetSelect.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include "llvm/Transforms/Instrumentation.h" 49 #include <cerrno> 50 51 #ifdef __CYGWIN__ 52 #include <cygwin/version.h> 53 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007 54 #define DO_NOTHING_ATEXIT 1 55 #endif 56 #endif 57 58 using namespace llvm; 59 60 namespace { 61 cl::opt<std::string> 62 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-")); 63 64 cl::list<std::string> 65 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); 66 67 cl::opt<bool> ForceInterpreter("force-interpreter", 68 cl::desc("Force interpretation: disable JIT"), 69 cl::init(false)); 70 71 cl::opt<bool> UseMCJIT( 72 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"), 73 cl::init(false)); 74 75 cl::opt<bool> DebugIR( 76 "debug-ir", cl::desc("Generate debug information to allow debugging IR."), 77 cl::init(false)); 78 79 // The MCJIT supports building for a target address space separate from 80 // the JIT compilation process. Use a forked process and a copying 81 // memory manager with IPC to execute using this functionality. 82 cl::opt<bool> RemoteMCJIT("remote-mcjit", 83 cl::desc("Execute MCJIT'ed code in a separate process."), 84 cl::init(false)); 85 86 // Determine optimization level. 87 cl::opt<char> 88 OptLevel("O", 89 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 90 "(default = '-O2')"), 91 cl::Prefix, 92 cl::ZeroOrMore, 93 cl::init(' ')); 94 95 cl::opt<std::string> 96 TargetTriple("mtriple", cl::desc("Override target triple for module")); 97 98 cl::opt<std::string> 99 MArch("march", 100 cl::desc("Architecture to generate assembly for (see --version)")); 101 102 cl::opt<std::string> 103 MCPU("mcpu", 104 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 105 cl::value_desc("cpu-name"), 106 cl::init("")); 107 108 cl::list<std::string> 109 MAttrs("mattr", 110 cl::CommaSeparated, 111 cl::desc("Target specific attributes (-mattr=help for details)"), 112 cl::value_desc("a1,+a2,-a3,...")); 113 114 cl::opt<std::string> 115 EntryFunc("entry-function", 116 cl::desc("Specify the entry function (default = 'main') " 117 "of the executable"), 118 cl::value_desc("function"), 119 cl::init("main")); 120 121 cl::opt<std::string> 122 FakeArgv0("fake-argv0", 123 cl::desc("Override the 'argv[0]' value passed into the executing" 124 " program"), cl::value_desc("executable")); 125 126 cl::opt<bool> 127 DisableCoreFiles("disable-core-files", cl::Hidden, 128 cl::desc("Disable emission of core files if possible")); 129 130 cl::opt<bool> 131 NoLazyCompilation("disable-lazy-compilation", 132 cl::desc("Disable JIT lazy compilation"), 133 cl::init(false)); 134 135 cl::opt<Reloc::Model> 136 RelocModel("relocation-model", 137 cl::desc("Choose relocation model"), 138 cl::init(Reloc::Default), 139 cl::values( 140 clEnumValN(Reloc::Default, "default", 141 "Target default relocation model"), 142 clEnumValN(Reloc::Static, "static", 143 "Non-relocatable code"), 144 clEnumValN(Reloc::PIC_, "pic", 145 "Fully relocatable, position independent code"), 146 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", 147 "Relocatable external references, non-relocatable code"), 148 clEnumValEnd)); 149 150 cl::opt<llvm::CodeModel::Model> 151 CMModel("code-model", 152 cl::desc("Choose code model"), 153 cl::init(CodeModel::JITDefault), 154 cl::values(clEnumValN(CodeModel::JITDefault, "default", 155 "Target default JIT code model"), 156 clEnumValN(CodeModel::Small, "small", 157 "Small code model"), 158 clEnumValN(CodeModel::Kernel, "kernel", 159 "Kernel code model"), 160 clEnumValN(CodeModel::Medium, "medium", 161 "Medium code model"), 162 clEnumValN(CodeModel::Large, "large", 163 "Large code model"), 164 clEnumValEnd)); 165 166 cl::opt<bool> 167 GenerateSoftFloatCalls("soft-float", 168 cl::desc("Generate software floating point library calls"), 169 cl::init(false)); 170 171 cl::opt<llvm::FloatABI::ABIType> 172 FloatABIForCalls("float-abi", 173 cl::desc("Choose float ABI type"), 174 cl::init(FloatABI::Default), 175 cl::values( 176 clEnumValN(FloatABI::Default, "default", 177 "Target default float ABI type"), 178 clEnumValN(FloatABI::Soft, "soft", 179 "Soft float ABI (implied by -soft-float)"), 180 clEnumValN(FloatABI::Hard, "hard", 181 "Hard float ABI (uses FP registers)"), 182 clEnumValEnd)); 183 cl::opt<bool> 184 // In debug builds, make this default to true. 185 #ifdef NDEBUG 186 #define EMIT_DEBUG false 187 #else 188 #define EMIT_DEBUG true 189 #endif 190 EmitJitDebugInfo("jit-emit-debug", 191 cl::desc("Emit debug information to debugger"), 192 cl::init(EMIT_DEBUG)); 193 #undef EMIT_DEBUG 194 195 static cl::opt<bool> 196 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk", 197 cl::Hidden, 198 cl::desc("Emit debug info objfiles to disk"), 199 cl::init(false)); 200 } 201 202 static ExecutionEngine *EE = 0; 203 204 static void do_shutdown() { 205 // Cygwin-1.5 invokes DLL's dtors before atexit handler. 206 #ifndef DO_NOTHING_ATEXIT 207 delete EE; 208 llvm_shutdown(); 209 #endif 210 } 211 212 void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) { 213 // Lay out our sections in order, with all the code sections first, then 214 // all the data sections. 215 uint64_t CurOffset = 0; 216 unsigned MaxAlign = T->getPageAlignment(); 217 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets; 218 SmallVector<unsigned, 16> Sizes; 219 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(), 220 E = JMM->code_end(); 221 I != E; ++I) { 222 DEBUG(dbgs() << "code region: size " << I->first.size() 223 << ", alignment " << I->second << "\n"); 224 // Align the current offset up to whatever is needed for the next 225 // section. 226 unsigned Align = I->second; 227 CurOffset = (CurOffset + Align - 1) / Align * Align; 228 // Save off the address of the new section and allocate its space. 229 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset)); 230 Sizes.push_back(I->first.size()); 231 CurOffset += I->first.size(); 232 } 233 // Adjust to keep code and data aligned on seperate pages. 234 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign; 235 unsigned FirstDataIndex = Offsets.size(); 236 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(), 237 E = JMM->data_end(); 238 I != E; ++I) { 239 DEBUG(dbgs() << "data region: size " << I->first.size() 240 << ", alignment " << I->second << "\n"); 241 // Align the current offset up to whatever is needed for the next 242 // section. 243 unsigned Align = I->second; 244 CurOffset = (CurOffset + Align - 1) / Align * Align; 245 // Save off the address of the new section and allocate its space. 246 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset)); 247 Sizes.push_back(I->first.size()); 248 CurOffset += I->first.size(); 249 } 250 251 // Allocate space in the remote target. 252 uint64_t RemoteAddr; 253 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr)) 254 report_fatal_error(T->getErrorMsg()); 255 // Map the section addresses so relocations will get updated in the local 256 // copies of the sections. 257 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { 258 uint64_t Addr = RemoteAddr + Offsets[i].second; 259 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr); 260 261 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first 262 << " to remote: 0x" << format("%llx", Addr) << "\n"); 263 264 } 265 266 // Trigger application of relocations 267 EE->finalizeObject(); 268 269 // Now load it all to the target. 270 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) { 271 uint64_t Addr = RemoteAddr + Offsets[i].second; 272 273 if (i < FirstDataIndex) { 274 T->loadCode(Addr, Offsets[i].first, Sizes[i]); 275 276 DEBUG(dbgs() << " loading code: " << Offsets[i].first 277 << " to remote: 0x" << format("%llx", Addr) << "\n"); 278 } else { 279 T->loadData(Addr, Offsets[i].first, Sizes[i]); 280 281 DEBUG(dbgs() << " loading data: " << Offsets[i].first 282 << " to remote: 0x" << format("%llx", Addr) << "\n"); 283 } 284 285 } 286 } 287 288 //===----------------------------------------------------------------------===// 289 // main Driver function 290 // 291 int main(int argc, char **argv, char * const *envp) { 292 sys::PrintStackTraceOnErrorSignal(); 293 PrettyStackTraceProgram X(argc, argv); 294 295 LLVMContext &Context = getGlobalContext(); 296 atexit(do_shutdown); // Call llvm_shutdown() on exit. 297 298 // If we have a native target, initialize it to ensure it is linked in and 299 // usable by the JIT. 300 InitializeNativeTarget(); 301 InitializeNativeTargetAsmPrinter(); 302 InitializeNativeTargetAsmParser(); 303 304 cl::ParseCommandLineOptions(argc, argv, 305 "llvm interpreter & dynamic compiler\n"); 306 307 // If the user doesn't want core files, disable them. 308 if (DisableCoreFiles) 309 sys::Process::PreventCoreFiles(); 310 311 // Load the bitcode... 312 SMDiagnostic Err; 313 Module *Mod = ParseIRFile(InputFile, Err, Context); 314 if (!Mod) { 315 Err.print(argv[0], errs()); 316 return 1; 317 } 318 319 // If not jitting lazily, load the whole bitcode file eagerly too. 320 std::string ErrorMsg; 321 if (NoLazyCompilation) { 322 if (Mod->MaterializeAllPermanently(&ErrorMsg)) { 323 errs() << argv[0] << ": bitcode didn't read correctly.\n"; 324 errs() << "Reason: " << ErrorMsg << "\n"; 325 exit(1); 326 } 327 } 328 329 if (DebugIR) { 330 if (!UseMCJIT) { 331 errs() << "warning: -debug-ir used without -use-mcjit. Only partial debug" 332 << " information will be emitted by the non-MC JIT engine. To see full" 333 << " source debug information, enable the flag '-use-mcjit'.\n"; 334 335 } 336 ModulePass *DebugIRPass = createDebugIRPass(); 337 DebugIRPass->runOnModule(*Mod); 338 } 339 340 EngineBuilder builder(Mod); 341 builder.setMArch(MArch); 342 builder.setMCPU(MCPU); 343 builder.setMAttrs(MAttrs); 344 builder.setRelocationModel(RelocModel); 345 builder.setCodeModel(CMModel); 346 builder.setErrorStr(&ErrorMsg); 347 builder.setEngineKind(ForceInterpreter 348 ? EngineKind::Interpreter 349 : EngineKind::JIT); 350 351 // If we are supposed to override the target triple, do so now. 352 if (!TargetTriple.empty()) 353 Mod->setTargetTriple(Triple::normalize(TargetTriple)); 354 355 // Enable MCJIT if desired. 356 RTDyldMemoryManager *RTDyldMM = 0; 357 if (UseMCJIT && !ForceInterpreter) { 358 builder.setUseMCJIT(true); 359 if (RemoteMCJIT) 360 RTDyldMM = new RecordingMemoryManager(); 361 else 362 RTDyldMM = new SectionMemoryManager(); 363 builder.setMCJITMemoryManager(RTDyldMM); 364 } else { 365 if (RemoteMCJIT) { 366 errs() << "error: Remote process execution requires -use-mcjit\n"; 367 exit(1); 368 } 369 builder.setJITMemoryManager(ForceInterpreter ? 0 : 370 JITMemoryManager::CreateDefaultMemManager()); 371 } 372 373 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 374 switch (OptLevel) { 375 default: 376 errs() << argv[0] << ": invalid optimization level.\n"; 377 return 1; 378 case ' ': break; 379 case '0': OLvl = CodeGenOpt::None; break; 380 case '1': OLvl = CodeGenOpt::Less; break; 381 case '2': OLvl = CodeGenOpt::Default; break; 382 case '3': OLvl = CodeGenOpt::Aggressive; break; 383 } 384 builder.setOptLevel(OLvl); 385 386 TargetOptions Options; 387 Options.UseSoftFloat = GenerateSoftFloatCalls; 388 if (FloatABIForCalls != FloatABI::Default) 389 Options.FloatABIType = FloatABIForCalls; 390 if (GenerateSoftFloatCalls) 391 FloatABIForCalls = FloatABI::Soft; 392 393 // Remote target execution doesn't handle EH or debug registration. 394 if (!RemoteMCJIT) { 395 Options.JITEmitDebugInfo = EmitJitDebugInfo; 396 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk; 397 } 398 399 builder.setTargetOptions(Options); 400 401 EE = builder.create(); 402 if (!EE) { 403 if (!ErrorMsg.empty()) 404 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n"; 405 else 406 errs() << argv[0] << ": unknown error creating EE!\n"; 407 exit(1); 408 } 409 410 // The following functions have no effect if their respective profiling 411 // support wasn't enabled in the build configuration. 412 EE->RegisterJITEventListener( 413 JITEventListener::createOProfileJITEventListener()); 414 EE->RegisterJITEventListener( 415 JITEventListener::createIntelJITEventListener()); 416 417 if (!NoLazyCompilation && RemoteMCJIT) { 418 errs() << "warning: remote mcjit does not support lazy compilation\n"; 419 NoLazyCompilation = true; 420 } 421 EE->DisableLazyCompilation(NoLazyCompilation); 422 423 // If the user specifically requested an argv[0] to pass into the program, 424 // do it now. 425 if (!FakeArgv0.empty()) { 426 InputFile = FakeArgv0; 427 } else { 428 // Otherwise, if there is a .bc suffix on the executable strip it off, it 429 // might confuse the program. 430 if (StringRef(InputFile).endswith(".bc")) 431 InputFile.erase(InputFile.length() - 3); 432 } 433 434 // Add the module's name to the start of the vector of arguments to main(). 435 InputArgv.insert(InputArgv.begin(), InputFile); 436 437 // Call the main function from M as if its signature were: 438 // int main (int argc, char **argv, const char **envp) 439 // using the contents of Args to determine argc & argv, and the contents of 440 // EnvVars to determine envp. 441 // 442 Function *EntryFn = Mod->getFunction(EntryFunc); 443 if (!EntryFn) { 444 errs() << '\'' << EntryFunc << "\' function not found in module.\n"; 445 return -1; 446 } 447 448 // If the program doesn't explicitly call exit, we will need the Exit 449 // function later on to make an explicit call, so get the function now. 450 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context), 451 Type::getInt32Ty(Context), 452 NULL); 453 454 // Reset errno to zero on entry to main. 455 errno = 0; 456 457 // Remote target MCJIT doesn't (yet) support static constructors. No reason 458 // it couldn't. This is a limitation of the LLI implemantation, not the 459 // MCJIT itself. FIXME. 460 // 461 // Run static constructors. 462 if (!RemoteMCJIT) { 463 if (UseMCJIT && !ForceInterpreter) { 464 // Give MCJIT a chance to apply relocations and set page permissions. 465 EE->finalizeObject(); 466 } 467 EE->runStaticConstructorsDestructors(false); 468 } 469 470 if (NoLazyCompilation) { 471 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) { 472 Function *Fn = &*I; 473 if (Fn != EntryFn && !Fn->isDeclaration()) 474 EE->getPointerToFunction(Fn); 475 } 476 } 477 478 int Result; 479 if (RemoteMCJIT) { 480 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(RTDyldMM); 481 // Everything is prepared now, so lay out our program for the target 482 // address space, assign the section addresses to resolve any relocations, 483 // and send it to the target. 484 RemoteTarget Target; 485 Target.create(); 486 487 // Ask for a pointer to the entry function. This triggers the actual 488 // compilation. 489 (void)EE->getPointerToFunction(EntryFn); 490 491 // Enough has been compiled to execute the entry function now, so 492 // layout the target memory. 493 layoutRemoteTargetMemory(&Target, MM); 494 495 // Since we're executing in a (at least simulated) remote address space, 496 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to 497 // grab the function address directly here and tell the remote target 498 // to execute the function. 499 // FIXME: argv and envp handling. 500 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn); 501 502 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at 0x" 503 << format("%llx", Entry) << "\n"); 504 505 if (Target.executeCode(Entry, Result)) 506 errs() << "ERROR: " << Target.getErrorMsg() << "\n"; 507 508 Target.stop(); 509 } else { 510 // Trigger compilation separately so code regions that need to be 511 // invalidated will be known. 512 (void)EE->getPointerToFunction(EntryFn); 513 // Clear instruction cache before code will be executed. 514 if (RTDyldMM) 515 static_cast<SectionMemoryManager*>(RTDyldMM)->invalidateInstructionCache(); 516 517 // Run main. 518 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp); 519 } 520 521 // Like static constructors, the remote target MCJIT support doesn't handle 522 // this yet. It could. FIXME. 523 if (!RemoteMCJIT) { 524 // Run static destructors. 525 EE->runStaticConstructorsDestructors(true); 526 527 // If the program didn't call exit explicitly, we should call it now. 528 // This ensures that any atexit handlers get called correctly. 529 if (Function *ExitF = dyn_cast<Function>(Exit)) { 530 std::vector<GenericValue> Args; 531 GenericValue ResultGV; 532 ResultGV.IntVal = APInt(32, Result); 533 Args.push_back(ResultGV); 534 EE->runFunction(ExitF, Args); 535 errs() << "ERROR: exit(" << Result << ") returned!\n"; 536 abort(); 537 } else { 538 errs() << "ERROR: exit defined with wrong prototype!\n"; 539 abort(); 540 } 541 } 542 return Result; 543 } 544