LLI: move instruction cache tweaks.
[oota-llvm.git] / 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 #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/JITMemoryManager.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/PluginLoader.h"
33 #include "llvm/Support/PrettyStackTrace.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Support/Process.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/DynamicLibrary.h"
39 #include "llvm/Support/Memory.h"
40 #include <cerrno>
41
42 #ifdef __linux__
43 // These includes used by LLIMCJITMemoryManager::getPointerToNamedFunction()
44 // for Glibc trickery. Look comments in this function for more information.
45 #ifdef HAVE_SYS_STAT_H
46 #include <sys/stat.h>
47 #endif
48 #include <fcntl.h>
49 #include <unistd.h>
50 #endif
51
52 #ifdef __CYGWIN__
53 #include <cygwin/version.h>
54 #if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
55 #define DO_NOTHING_ATEXIT 1
56 #endif
57 #endif
58
59 using namespace llvm;
60
61 namespace {
62   cl::opt<std::string>
63   InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
64
65   cl::list<std::string>
66   InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
67
68   cl::opt<bool> ForceInterpreter("force-interpreter",
69                                  cl::desc("Force interpretation: disable JIT"),
70                                  cl::init(false));
71
72   cl::opt<bool> UseMCJIT(
73     "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
74     cl::init(false));
75
76   // Determine optimization level.
77   cl::opt<char>
78   OptLevel("O",
79            cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
80                     "(default = '-O2')"),
81            cl::Prefix,
82            cl::ZeroOrMore,
83            cl::init(' '));
84
85   cl::opt<std::string>
86   TargetTriple("mtriple", cl::desc("Override target triple for module"));
87
88   cl::opt<std::string>
89   MArch("march",
90         cl::desc("Architecture to generate assembly for (see --version)"));
91
92   cl::opt<std::string>
93   MCPU("mcpu",
94        cl::desc("Target a specific cpu type (-mcpu=help for details)"),
95        cl::value_desc("cpu-name"),
96        cl::init(""));
97
98   cl::list<std::string>
99   MAttrs("mattr",
100          cl::CommaSeparated,
101          cl::desc("Target specific attributes (-mattr=help for details)"),
102          cl::value_desc("a1,+a2,-a3,..."));
103
104   cl::opt<std::string>
105   EntryFunc("entry-function",
106             cl::desc("Specify the entry function (default = 'main') "
107                      "of the executable"),
108             cl::value_desc("function"),
109             cl::init("main"));
110
111   cl::opt<std::string>
112   FakeArgv0("fake-argv0",
113             cl::desc("Override the 'argv[0]' value passed into the executing"
114                      " program"), cl::value_desc("executable"));
115
116   cl::opt<bool>
117   DisableCoreFiles("disable-core-files", cl::Hidden,
118                    cl::desc("Disable emission of core files if possible"));
119
120   cl::opt<bool>
121   NoLazyCompilation("disable-lazy-compilation",
122                   cl::desc("Disable JIT lazy compilation"),
123                   cl::init(false));
124
125   cl::opt<Reloc::Model>
126   RelocModel("relocation-model",
127              cl::desc("Choose relocation model"),
128              cl::init(Reloc::Default),
129              cl::values(
130             clEnumValN(Reloc::Default, "default",
131                        "Target default relocation model"),
132             clEnumValN(Reloc::Static, "static",
133                        "Non-relocatable code"),
134             clEnumValN(Reloc::PIC_, "pic",
135                        "Fully relocatable, position independent code"),
136             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
137                        "Relocatable external references, non-relocatable code"),
138             clEnumValEnd));
139
140   cl::opt<llvm::CodeModel::Model>
141   CMModel("code-model",
142           cl::desc("Choose code model"),
143           cl::init(CodeModel::JITDefault),
144           cl::values(clEnumValN(CodeModel::JITDefault, "default",
145                                 "Target default JIT code model"),
146                      clEnumValN(CodeModel::Small, "small",
147                                 "Small code model"),
148                      clEnumValN(CodeModel::Kernel, "kernel",
149                                 "Kernel code model"),
150                      clEnumValN(CodeModel::Medium, "medium",
151                                 "Medium code model"),
152                      clEnumValN(CodeModel::Large, "large",
153                                 "Large code model"),
154                      clEnumValEnd));
155
156   cl::opt<bool>
157   EnableJITExceptionHandling("jit-enable-eh",
158     cl::desc("Emit exception handling information"),
159     cl::init(false));
160
161   cl::opt<bool>
162 // In debug builds, make this default to true.
163 #ifdef NDEBUG
164 #define EMIT_DEBUG false
165 #else
166 #define EMIT_DEBUG true
167 #endif
168   EmitJitDebugInfo("jit-emit-debug",
169     cl::desc("Emit debug information to debugger"),
170     cl::init(EMIT_DEBUG));
171 #undef EMIT_DEBUG
172
173   static cl::opt<bool>
174   EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
175     cl::Hidden,
176     cl::desc("Emit debug info objfiles to disk"),
177     cl::init(false));
178 }
179
180 static ExecutionEngine *EE = 0;
181
182 static void do_shutdown() {
183   // Cygwin-1.5 invokes DLL's dtors before atexit handler.
184 #ifndef DO_NOTHING_ATEXIT
185   delete EE;
186   llvm_shutdown();
187 #endif
188 }
189
190 // Memory manager for MCJIT
191 class LLIMCJITMemoryManager : public JITMemoryManager {
192 public:
193   SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
194   SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
195   SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
196
197   LLIMCJITMemoryManager() { }
198   ~LLIMCJITMemoryManager();
199
200   virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
201                                        unsigned SectionID);
202
203   virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
204                                        unsigned SectionID);
205
206   virtual void *getPointerToNamedFunction(const std::string &Name,
207                                           bool AbortOnFailure = true);
208
209   // Invalidate instruction cache for code sections. Some platforms with
210   // separate data cache and instruction cache require explicit cache flush,
211   // otherwise JIT code manipulations (like resolved relocations) will get to
212   // the data cache but not to the instruction cache.
213   virtual void invalidateInstructionCache();
214
215   // The MCJITMemoryManager doesn't use the following functions, so we don't
216   // need implement them.
217   virtual void setMemoryWritable() {
218     llvm_unreachable("Unexpected call!");
219   }
220   virtual void setMemoryExecutable() {
221     llvm_unreachable("Unexpected call!");
222   }
223   virtual void setPoisonMemory(bool poison) {
224     llvm_unreachable("Unexpected call!");
225   }
226   virtual void AllocateGOT() {
227     llvm_unreachable("Unexpected call!");
228   }
229   virtual uint8_t *getGOTBase() const {
230     llvm_unreachable("Unexpected call!");
231     return 0;
232   }
233   virtual uint8_t *startFunctionBody(const Function *F,
234                                      uintptr_t &ActualSize){
235     llvm_unreachable("Unexpected call!");
236     return 0;
237   }
238   virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
239                                 unsigned Alignment) {
240     llvm_unreachable("Unexpected call!");
241     return 0;
242   }
243   virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
244                                uint8_t *FunctionEnd) {
245     llvm_unreachable("Unexpected call!");
246   }
247   virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
248     llvm_unreachable("Unexpected call!");
249     return 0;
250   }
251   virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
252     llvm_unreachable("Unexpected call!");
253     return 0;
254   }
255   virtual void deallocateFunctionBody(void *Body) {
256     llvm_unreachable("Unexpected call!");
257   }
258   virtual uint8_t* startExceptionTable(const Function* F,
259                                        uintptr_t &ActualSize) {
260     llvm_unreachable("Unexpected call!");
261     return 0;
262   }
263   virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
264                                  uint8_t *TableEnd, uint8_t* FrameRegister) {
265     llvm_unreachable("Unexpected call!");
266   }
267   virtual void deallocateExceptionTable(void *ET) {
268     llvm_unreachable("Unexpected call!");
269   }
270 };
271
272 uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
273                                                     unsigned Alignment,
274                                                     unsigned SectionID) {
275   if (!Alignment)
276     Alignment = 16;
277   uint8_t *Addr = (uint8_t*)calloc((Size + Alignment - 1)/Alignment, Alignment);
278   AllocatedDataMem.push_back(sys::MemoryBlock(Addr, Size));
279   return Addr;
280 }
281
282 uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
283                                                     unsigned Alignment,
284                                                     unsigned SectionID) {
285   if (!Alignment)
286     Alignment = 16;
287   unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
288   uintptr_t Addr = 0;
289   // Look in the list of free code memory regions and use a block there if one
290   // is available.
291   for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
292     sys::MemoryBlock &MB = FreeCodeMem[i];
293     if (MB.size() >= NeedAllocate) {
294       Addr = (uintptr_t)MB.base();
295       uintptr_t EndOfBlock = Addr + MB.size();
296       // Align the address.
297       Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
298       // Store cutted free memory block.
299       FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
300                                         EndOfBlock - Addr - Size);
301       return (uint8_t*)Addr;
302     }
303   }
304
305   // No pre-allocated free block was large enough. Allocate a new memory region.
306   sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
307
308   AllocatedCodeMem.push_back(MB);
309   Addr = (uintptr_t)MB.base();
310   uintptr_t EndOfBlock = Addr + MB.size();
311   // Align the address.
312   Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
313   // The AllocateRWX may allocate much more memory than we need. In this case,
314   // we store the unused memory as a free memory block.
315   unsigned FreeSize = EndOfBlock-Addr-Size;
316   if (FreeSize > 16)
317     FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
318
319   // Return aligned address
320   return (uint8_t*)Addr;
321 }
322
323 void LLIMCJITMemoryManager::invalidateInstructionCache() {
324   for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
325     sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
326                                             AllocatedCodeMem[i].size());
327 }
328
329 void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
330                                                        bool AbortOnFailure) {
331 #if defined(__linux__)
332   //===--------------------------------------------------------------------===//
333   // Function stubs that are invoked instead of certain library calls
334   //
335   // Force the following functions to be linked in to anything that uses the
336   // JIT. This is a hack designed to work around the all-too-clever Glibc
337   // strategy of making these functions work differently when inlined vs. when
338   // not inlined, and hiding their real definitions in a separate archive file
339   // that the dynamic linker can't see. For more info, search for
340   // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
341   if (Name == "stat") return (void*)(intptr_t)&stat;
342   if (Name == "fstat") return (void*)(intptr_t)&fstat;
343   if (Name == "lstat") return (void*)(intptr_t)&lstat;
344   if (Name == "stat64") return (void*)(intptr_t)&stat64;
345   if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
346   if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
347   if (Name == "atexit") return (void*)(intptr_t)&atexit;
348   if (Name == "mknod") return (void*)(intptr_t)&mknod;
349 #endif // __linux__
350
351   const char *NameStr = Name.c_str();
352   void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
353   if (Ptr) return Ptr;
354
355   // If it wasn't found and if it starts with an underscore ('_') character,
356   // try again without the underscore.
357   if (NameStr[0] == '_') {
358     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
359     if (Ptr) return Ptr;
360   }
361
362   if (AbortOnFailure)
363     report_fatal_error("Program used external function '" + Name +
364                       "' which could not be resolved!");
365   return 0;
366 }
367
368 LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
369   for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
370     sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
371   for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
372     free(AllocatedDataMem[i].base());
373 }
374
375 //===----------------------------------------------------------------------===//
376 // main Driver function
377 //
378 int main(int argc, char **argv, char * const *envp) {
379   sys::PrintStackTraceOnErrorSignal();
380   PrettyStackTraceProgram X(argc, argv);
381
382   LLVMContext &Context = getGlobalContext();
383   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
384
385   // If we have a native target, initialize it to ensure it is linked in and
386   // usable by the JIT.
387   InitializeNativeTarget();
388   InitializeNativeTargetAsmPrinter();
389
390   cl::ParseCommandLineOptions(argc, argv,
391                               "llvm interpreter & dynamic compiler\n");
392
393   // If the user doesn't want core files, disable them.
394   if (DisableCoreFiles)
395     sys::Process::PreventCoreFiles();
396
397   // Load the bitcode...
398   SMDiagnostic Err;
399   Module *Mod = ParseIRFile(InputFile, Err, Context);
400   if (!Mod) {
401     Err.print(argv[0], errs());
402     return 1;
403   }
404
405   // If not jitting lazily, load the whole bitcode file eagerly too.
406   std::string ErrorMsg;
407   if (NoLazyCompilation) {
408     if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
409       errs() << argv[0] << ": bitcode didn't read correctly.\n";
410       errs() << "Reason: " << ErrorMsg << "\n";
411       exit(1);
412     }
413   }
414
415   EngineBuilder builder(Mod);
416   builder.setMArch(MArch);
417   builder.setMCPU(MCPU);
418   builder.setMAttrs(MAttrs);
419   builder.setRelocationModel(RelocModel);
420   builder.setCodeModel(CMModel);
421   builder.setErrorStr(&ErrorMsg);
422   builder.setEngineKind(ForceInterpreter
423                         ? EngineKind::Interpreter
424                         : EngineKind::JIT);
425
426   // If we are supposed to override the target triple, do so now.
427   if (!TargetTriple.empty())
428     Mod->setTargetTriple(Triple::normalize(TargetTriple));
429
430   // Enable MCJIT if desired.
431   LLIMCJITMemoryManager *JMM = 0;
432   if (UseMCJIT && !ForceInterpreter) {
433     builder.setUseMCJIT(true);
434     JMM = new LLIMCJITMemoryManager();
435     builder.setJITMemoryManager(JMM);
436   } else {
437     builder.setJITMemoryManager(ForceInterpreter ? 0 :
438                                 JITMemoryManager::CreateDefaultMemManager());
439   }
440
441   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
442   switch (OptLevel) {
443   default:
444     errs() << argv[0] << ": invalid optimization level.\n";
445     return 1;
446   case ' ': break;
447   case '0': OLvl = CodeGenOpt::None; break;
448   case '1': OLvl = CodeGenOpt::Less; break;
449   case '2': OLvl = CodeGenOpt::Default; break;
450   case '3': OLvl = CodeGenOpt::Aggressive; break;
451   }
452   builder.setOptLevel(OLvl);
453
454   TargetOptions Options;
455   Options.JITExceptionHandling = EnableJITExceptionHandling;
456   Options.JITEmitDebugInfo = EmitJitDebugInfo;
457   Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
458   builder.setTargetOptions(Options);
459
460   EE = builder.create();
461   if (!EE) {
462     if (!ErrorMsg.empty())
463       errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
464     else
465       errs() << argv[0] << ": unknown error creating EE!\n";
466     exit(1);
467   }
468
469   // The following functions have no effect if their respective profiling
470   // support wasn't enabled in the build configuration.
471   EE->RegisterJITEventListener(
472                 JITEventListener::createOProfileJITEventListener());
473   EE->RegisterJITEventListener(
474                 JITEventListener::createIntelJITEventListener());
475
476   EE->DisableLazyCompilation(NoLazyCompilation);
477
478   // If the user specifically requested an argv[0] to pass into the program,
479   // do it now.
480   if (!FakeArgv0.empty()) {
481     InputFile = FakeArgv0;
482   } else {
483     // Otherwise, if there is a .bc suffix on the executable strip it off, it
484     // might confuse the program.
485     if (StringRef(InputFile).endswith(".bc"))
486       InputFile.erase(InputFile.length() - 3);
487   }
488
489   // Add the module's name to the start of the vector of arguments to main().
490   InputArgv.insert(InputArgv.begin(), InputFile);
491
492   // Call the main function from M as if its signature were:
493   //   int main (int argc, char **argv, const char **envp)
494   // using the contents of Args to determine argc & argv, and the contents of
495   // EnvVars to determine envp.
496   //
497   Function *EntryFn = Mod->getFunction(EntryFunc);
498   if (!EntryFn) {
499     errs() << '\'' << EntryFunc << "\' function not found in module.\n";
500     return -1;
501   }
502
503   // If the program doesn't explicitly call exit, we will need the Exit
504   // function later on to make an explicit call, so get the function now.
505   Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
506                                                     Type::getInt32Ty(Context),
507                                                     NULL);
508
509   // Reset errno to zero on entry to main.
510   errno = 0;
511
512   // Run static constructors.
513   EE->runStaticConstructorsDestructors(false);
514
515   if (NoLazyCompilation) {
516     for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
517       Function *Fn = &*I;
518       if (Fn != EntryFn && !Fn->isDeclaration())
519         EE->getPointerToFunction(Fn);
520     }
521   }
522
523   // Clear instruction cache before code will be executed.
524   if (JMM)
525     JMM->invalidateInstructionCache();
526
527   // Run main.
528   int Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
529
530   // Run static destructors.
531   EE->runStaticConstructorsDestructors(true);
532
533   // If the program didn't call exit explicitly, we should call it now.
534   // This ensures that any atexit handlers get called correctly.
535   if (Function *ExitF = dyn_cast<Function>(Exit)) {
536     std::vector<GenericValue> Args;
537     GenericValue ResultGV;
538     ResultGV.IntVal = APInt(32, Result);
539     Args.push_back(ResultGV);
540     EE->runFunction(ExitF, Args);
541     errs() << "ERROR: exit(" << Result << ") returned!\n";
542     abort();
543   } else {
544     errs() << "ERROR: exit defined with wrong prototype!\n";
545     abort();
546   }
547 }