]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/lli/lli.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / lli / lli.cpp
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 <cerrno>
49
50 #ifdef __CYGWIN__
51 #include <cygwin/version.h>
52 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
53 #define DO_NOTHING_ATEXIT 1
54 #endif
55 #endif
56
57 using namespace llvm;
58
59 namespace {
60   cl::opt<std::string>
61   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
62
63   cl::list<std::string>
64   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
65
66   cl::opt<bool> ForceInterpreter("force-interpreter",
67                                  cl::desc("Force interpretation: disable JIT"),
68                                  cl::init(false));
69
70   cl::opt<bool> UseMCJIT(
71     "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
72     cl::init(false));
73
74   // The MCJIT supports building for a target address space separate from
75   // the JIT compilation process. Use a forked process and a copying
76   // memory manager with IPC to execute using this functionality.
77   cl::opt<bool> RemoteMCJIT("remote-mcjit",
78     cl::desc("Execute MCJIT'ed code in a separate process."),
79     cl::init(false));
80
81   // Determine optimization level.
82   cl::opt<char>
83   OptLevel("O",
84            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
85                     "(default = '-O2')"),
86            cl::Prefix,
87            cl::ZeroOrMore,
88            cl::init(' '));
89
90   cl::opt<std::string>
91   TargetTriple("mtriple", cl::desc("Override target triple for module"));
92
93   cl::opt<std::string>
94   MArch("march",
95         cl::desc("Architecture to generate assembly for (see --version)"));
96
97   cl::opt<std::string>
98   MCPU("mcpu",
99        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
100        cl::value_desc("cpu-name"),
101        cl::init(""));
102
103   cl::list<std::string>
104   MAttrs("mattr",
105          cl::CommaSeparated,
106          cl::desc("Target specific attributes (-mattr=help for details)"),
107          cl::value_desc("a1,+a2,-a3,..."));
108
109   cl::opt<std::string>
110   EntryFunc("entry-function",
111             cl::desc("Specify the entry function (default = 'main') "
112                      "of the executable"),
113             cl::value_desc("function"),
114             cl::init("main"));
115
116   cl::opt<std::string>
117   FakeArgv0("fake-argv0",
118             cl::desc("Override the 'argv[0]' value passed into the executing"
119                      " program"), cl::value_desc("executable"));
120
121   cl::opt<bool>
122   DisableCoreFiles("disable-core-files", cl::Hidden,
123                    cl::desc("Disable emission of core files if possible"));
124
125   cl::opt<bool>
126   NoLazyCompilation("disable-lazy-compilation",
127                   cl::desc("Disable JIT lazy compilation"),
128                   cl::init(false));
129
130   cl::opt<Reloc::Model>
131   RelocModel("relocation-model",
132              cl::desc("Choose relocation model"),
133              cl::init(Reloc::Default),
134              cl::values(
135             clEnumValN(Reloc::Default, "default",
136                        "Target default relocation model"),
137             clEnumValN(Reloc::Static, "static",
138                        "Non-relocatable code"),
139             clEnumValN(Reloc::PIC_, "pic",
140                        "Fully relocatable, position independent code"),
141             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
142                        "Relocatable external references, non-relocatable code"),
143             clEnumValEnd));
144
145   cl::opt<llvm::CodeModel::Model>
146   CMModel("code-model",
147           cl::desc("Choose code model"),
148           cl::init(CodeModel::JITDefault),
149           cl::values(clEnumValN(CodeModel::JITDefault, "default",
150                                 "Target default JIT code model"),
151                      clEnumValN(CodeModel::Small, "small",
152                                 "Small code model"),
153                      clEnumValN(CodeModel::Kernel, "kernel",
154                                 "Kernel code model"),
155                      clEnumValN(CodeModel::Medium, "medium",
156                                 "Medium code model"),
157                      clEnumValN(CodeModel::Large, "large",
158                                 "Large code model"),
159                      clEnumValEnd));
160
161   cl::opt<bool>
162   EnableJITExceptionHandling("jit-enable-eh",
163     cl::desc("Emit exception handling information"),
164     cl::init(false));
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: " << format("%p", 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: " << format("%p", 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: " << format("%p", 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   EngineBuilder builder(Mod);
330   builder.setMArch(MArch);
331   builder.setMCPU(MCPU);
332   builder.setMAttrs(MAttrs);
333   builder.setRelocationModel(RelocModel);
334   builder.setCodeModel(CMModel);
335   builder.setErrorStr(&ErrorMsg);
336   builder.setEngineKind(ForceInterpreter
337                         ? EngineKind::Interpreter
338                         : EngineKind::JIT);
339
340   // If we are supposed to override the target triple, do so now.
341   if (!TargetTriple.empty())
342     Mod->setTargetTriple(Triple::normalize(TargetTriple));
343
344   // Enable MCJIT if desired.
345   JITMemoryManager *JMM = 0;
346   if (UseMCJIT && !ForceInterpreter) {
347     builder.setUseMCJIT(true);
348     if (RemoteMCJIT)
349       JMM = new RecordingMemoryManager();
350     else
351       JMM = new SectionMemoryManager();
352     builder.setJITMemoryManager(JMM);
353   } else {
354     if (RemoteMCJIT) {
355       errs() << "error: Remote process execution requires -use-mcjit\n";
356       exit(1);
357     }
358     builder.setJITMemoryManager(ForceInterpreter ? 0 :
359                                 JITMemoryManager::CreateDefaultMemManager());
360   }
361
362   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
363   switch (OptLevel) {
364   default:
365     errs() << argv[0] << ": invalid optimization level.\n";
366     return 1;
367   case ' ': break;
368   case '0': OLvl = CodeGenOpt::None; break;
369   case '1': OLvl = CodeGenOpt::Less; break;
370   case '2': OLvl = CodeGenOpt::Default; break;
371   case '3': OLvl = CodeGenOpt::Aggressive; break;
372   }
373   builder.setOptLevel(OLvl);
374
375   TargetOptions Options;
376   Options.UseSoftFloat = GenerateSoftFloatCalls;
377   if (FloatABIForCalls != FloatABI::Default)
378     Options.FloatABIType = FloatABIForCalls;
379   if (GenerateSoftFloatCalls)
380     FloatABIForCalls = FloatABI::Soft;
381
382   // Remote target execution doesn't handle EH or debug registration.
383   if (!RemoteMCJIT) {
384     Options.JITExceptionHandling = EnableJITExceptionHandling;
385     Options.JITEmitDebugInfo = EmitJitDebugInfo;
386     Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
387   }
388
389   builder.setTargetOptions(Options);
390
391   EE = builder.create();
392   if (!EE) {
393     if (!ErrorMsg.empty())
394       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
395     else
396       errs() << argv[0] << ": unknown error creating EE!\n";
397     exit(1);
398   }
399
400   // The following functions have no effect if their respective profiling
401   // support wasn't enabled in the build configuration.
402   EE->RegisterJITEventListener(
403                 JITEventListener::createOProfileJITEventListener());
404   EE->RegisterJITEventListener(
405                 JITEventListener::createIntelJITEventListener());
406
407   if (!NoLazyCompilation && RemoteMCJIT) {
408     errs() << "warning: remote mcjit does not support lazy compilation\n";
409     NoLazyCompilation = true;
410   }
411   EE->DisableLazyCompilation(NoLazyCompilation);
412
413   // If the user specifically requested an argv[0] to pass into the program,
414   // do it now.
415   if (!FakeArgv0.empty()) {
416     InputFile = FakeArgv0;
417   } else {
418     // Otherwise, if there is a .bc suffix on the executable strip it off, it
419     // might confuse the program.
420     if (StringRef(InputFile).endswith(".bc"))
421       InputFile.erase(InputFile.length() - 3);
422   }
423
424   // Add the module's name to the start of the vector of arguments to main().
425   InputArgv.insert(InputArgv.begin(), InputFile);
426
427   // Call the main function from M as if its signature were:
428   //   int main (int argc, char **argv, const char **envp)
429   // using the contents of Args to determine argc & argv, and the contents of
430   // EnvVars to determine envp.
431   //
432   Function *EntryFn = Mod->getFunction(EntryFunc);
433   if (!EntryFn) {
434     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
435     return -1;
436   }
437
438   // If the program doesn't explicitly call exit, we will need the Exit
439   // function later on to make an explicit call, so get the function now.
440   Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
441                                                     Type::getInt32Ty(Context),
442                                                     NULL);
443
444   // Reset errno to zero on entry to main.
445   errno = 0;
446
447   // Remote target MCJIT doesn't (yet) support static constructors. No reason
448   // it couldn't. This is a limitation of the LLI implemantation, not the
449   // MCJIT itself. FIXME.
450   //
451   // Run static constructors.
452   if (!RemoteMCJIT) {
453       if (UseMCJIT && !ForceInterpreter) {
454         // Give MCJIT a chance to apply relocations and set page permissions.
455         EE->finalizeObject();
456       }
457       EE->runStaticConstructorsDestructors(false);
458   }
459
460   if (NoLazyCompilation) {
461     for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
462       Function *Fn = &*I;
463       if (Fn != EntryFn && !Fn->isDeclaration())
464         EE->getPointerToFunction(Fn);
465     }
466   }
467
468   int Result;
469   if (RemoteMCJIT) {
470     RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
471     // Everything is prepared now, so lay out our program for the target
472     // address space, assign the section addresses to resolve any relocations,
473     // and send it to the target.
474     RemoteTarget Target;
475     Target.create();
476
477     // Ask for a pointer to the entry function. This triggers the actual
478     // compilation.
479     (void)EE->getPointerToFunction(EntryFn);
480
481     // Enough has been compiled to execute the entry function now, so
482     // layout the target memory.
483     layoutRemoteTargetMemory(&Target, MM);
484
485     // Since we're executing in a (at least simulated) remote address space,
486     // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
487     // grab the function address directly here and tell the remote target
488     // to execute the function.
489     // FIXME: argv and envp handling.
490     uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
491
492     DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
493                  << format("%p", Entry) << "\n");
494
495     if (Target.executeCode(Entry, Result))
496       errs() << "ERROR: " << Target.getErrorMsg() << "\n";
497
498     Target.stop();
499   } else {
500     // Trigger compilation separately so code regions that need to be 
501     // invalidated will be known.
502     (void)EE->getPointerToFunction(EntryFn);
503     // Clear instruction cache before code will be executed.
504     if (JMM)
505       static_cast<SectionMemoryManager*>(JMM)->invalidateInstructionCache();
506
507     // Run main.
508     Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
509   }
510
511   // Like static constructors, the remote target MCJIT support doesn't handle
512   // this yet. It could. FIXME.
513   if (!RemoteMCJIT) {
514     // Run static destructors.
515     EE->runStaticConstructorsDestructors(true);
516
517     // If the program didn't call exit explicitly, we should call it now.
518     // This ensures that any atexit handlers get called correctly.
519     if (Function *ExitF = dyn_cast<Function>(Exit)) {
520       std::vector<GenericValue> Args;
521       GenericValue ResultGV;
522       ResultGV.IntVal = APInt(32, Result);
523       Args.push_back(ResultGV);
524       EE->runFunction(ExitF, Args);
525       errs() << "ERROR: exit(" << Result << ") returned!\n";
526       abort();
527     } else {
528       errs() << "ERROR: exit defined with wrong prototype!\n";
529       abort();
530     }
531   }
532   return Result;
533 }