blob: 9a27a4c94110a5d938194020447d1984c84b5881 [file] [log] [blame]
Chris Lattnerfe11a972002-12-23 23:59:41 +00001//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +00009//
Chris Lattner7efea1d2003-12-26 05:07:35 +000010// 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
Torok Edwindb9c0282009-07-03 12:11:32 +000012// compiler, or through an interpreter if no JIT is available for this platform.
Chris Lattner92101ac2001-08-23 17:05:04 +000013//
14//===----------------------------------------------------------------------===//
15
Jim Grosbach706f03a2012-09-05 16:50:34 +000016#define DEBUG_TYPE "lli"
17#include "RecordingMemoryManager.h"
18#include "RemoteTarget.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +000019#include "llvm/LLVMContext.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000020#include "llvm/Module.h"
Chris Lattner269a4282003-12-26 06:49:53 +000021#include "llvm/Type.h"
Duncan Sands75ebbce2010-08-28 01:30:02 +000022#include "llvm/ADT/Triple.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000023#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnerd3a680a2006-08-01 22:34:35 +000024#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Brian Gaeked1cab3e2003-09-05 19:42:34 +000025#include "llvm/ExecutionEngine/GenericValue.h"
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +000026#include "llvm/ExecutionEngine/Interpreter.h"
27#include "llvm/ExecutionEngine/JIT.h"
28#include "llvm/ExecutionEngine/JITEventListener.h"
Jim Grosbachbf9ab932012-01-11 21:12:51 +000029#include "llvm/ExecutionEngine/JITMemoryManager.h"
Daniel Dunbar6aec2982010-11-17 16:06:43 +000030#include "llvm/ExecutionEngine/MCJIT.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
Daniel Dunbar46a27162010-11-13 00:28:01 +000032#include "llvm/Support/IRReader.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000033#include "llvm/Support/ManagedStatic.h"
Chris Lattnerc1e6d682007-05-06 04:58:26 +000034#include "llvm/Support/MemoryBuffer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/PluginLoader.h"
Chris Lattnercc14d252009-03-06 05:34:10 +000036#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner74382b72009-08-23 22:45:37 +000037#include "llvm/Support/raw_ostream.h"
Jim Grosbach706f03a2012-09-05 16:50:34 +000038#include "llvm/Support/Format.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000039#include "llvm/Support/Process.h"
40#include "llvm/Support/Signals.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000041#include "llvm/Support/TargetSelect.h"
Jim Grosbach706f03a2012-09-05 16:50:34 +000042#include "llvm/Support/Debug.h"
Danil Malyshev068c65b2012-05-16 18:50:11 +000043#include "llvm/Support/DynamicLibrary.h"
44#include "llvm/Support/Memory.h"
Tim Northoverb210e6f2012-10-29 10:47:07 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner02040322007-04-27 17:02:33 +000046#include <cerrno>
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000047
Danil Malyshev068c65b2012-05-16 18:50:11 +000048#ifdef __linux__
49// These includes used by LLIMCJITMemoryManager::getPointerToNamedFunction()
50// for Glibc trickery. Look comments in this function for more information.
51#ifdef HAVE_SYS_STAT_H
52#include <sys/stat.h>
53#endif
54#include <fcntl.h>
55#include <unistd.h>
56#endif
57
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000058#ifdef __CYGWIN__
59#include <cygwin/version.h>
60#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
61#define DO_NOTHING_ATEXIT 1
62#endif
63#endif
64
Brian Gaeked0fde302003-11-11 22:41:34 +000065using namespace llvm;
66
Chris Lattnerfe11a972002-12-23 23:59:41 +000067namespace {
68 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000069 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000070
Chris Lattnerfe11a972002-12-23 23:59:41 +000071 cl::list<std::string>
72 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000073
Chris Lattnerfe11a972002-12-23 23:59:41 +000074 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000075 cl::desc("Force interpretation: disable JIT"),
76 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000077
Daniel Dunbar6d135972010-11-17 16:06:37 +000078 cl::opt<bool> UseMCJIT(
79 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
80 cl::init(false));
81
Jim Grosbach706f03a2012-09-05 16:50:34 +000082 // The MCJIT supports building for a target address space separate from
83 // the JIT compilation process. Use a forked process and a copying
84 // memory manager with IPC to execute using this functionality.
85 cl::opt<bool> RemoteMCJIT("remote-mcjit",
86 cl::desc("Execute MCJIT'ed code in a separate process."),
87 cl::init(false));
88
Evan Cheng712e80e2009-05-04 23:05:19 +000089 // Determine optimization level.
90 cl::opt<char>
91 OptLevel("O",
92 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
93 "(default = '-O2')"),
94 cl::Prefix,
95 cl::ZeroOrMore,
96 cl::init(' '));
Evan Chenge1a4eda2008-08-08 08:12:06 +000097
Chris Lattner3015e602005-12-16 05:00:21 +000098 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +000099 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +0000100
101 cl::opt<std::string>
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000102 MArch("march",
103 cl::desc("Architecture to generate assembly for (see --version)"));
104
105 cl::opt<std::string>
106 MCPU("mcpu",
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
109 cl::init(""));
110
111 cl::list<std::string>
112 MAttrs("mattr",
113 cl::CommaSeparated,
114 cl::desc("Target specific attributes (-mattr=help for details)"),
115 cl::value_desc("a1,+a2,-a3,..."));
116
117 cl::opt<std::string>
Evan Chengec740e32008-11-05 23:21:52 +0000118 EntryFunc("entry-function",
119 cl::desc("Specify the entry function (default = 'main') "
120 "of the executable"),
121 cl::value_desc("function"),
122 cl::init("main"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000123
Chris Lattnere69671d2003-10-28 22:51:44 +0000124 cl::opt<std::string>
125 FakeArgv0("fake-argv0",
126 cl::desc("Override the 'argv[0]' value passed into the executing"
127 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000128
Chris Lattner43f249a2006-09-14 06:17:09 +0000129 cl::opt<bool>
130 DisableCoreFiles("disable-core-files", cl::Hidden,
131 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000132
133 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000134 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000135 cl::desc("Disable JIT lazy compilation"),
136 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000137
138 cl::opt<Reloc::Model>
139 RelocModel("relocation-model",
140 cl::desc("Choose relocation model"),
141 cl::init(Reloc::Default),
142 cl::values(
143 clEnumValN(Reloc::Default, "default",
144 "Target default relocation model"),
145 clEnumValN(Reloc::Static, "static",
146 "Non-relocatable code"),
147 clEnumValN(Reloc::PIC_, "pic",
148 "Fully relocatable, position independent code"),
149 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
150 "Relocatable external references, non-relocatable code"),
151 clEnumValEnd));
Evan Cheng34ad6db2011-07-20 07:51:56 +0000152
153 cl::opt<llvm::CodeModel::Model>
154 CMModel("code-model",
155 cl::desc("Choose code model"),
156 cl::init(CodeModel::JITDefault),
157 cl::values(clEnumValN(CodeModel::JITDefault, "default",
158 "Target default JIT code model"),
159 clEnumValN(CodeModel::Small, "small",
160 "Small code model"),
161 clEnumValN(CodeModel::Kernel, "kernel",
162 "Kernel code model"),
163 clEnumValN(CodeModel::Medium, "medium",
164 "Medium code model"),
165 clEnumValN(CodeModel::Large, "large",
166 "Large code model"),
167 clEnumValEnd));
168
Nick Lewycky9a148412012-04-18 08:34:12 +0000169 cl::opt<bool>
170 EnableJITExceptionHandling("jit-enable-eh",
171 cl::desc("Emit exception handling information"),
172 cl::init(false));
173
174 cl::opt<bool>
Tim Northover77b4c692012-10-12 09:55:13 +0000175 GenerateSoftFloatCalls("soft-float",
176 cl::desc("Generate software floating point library calls"),
177 cl::init(false));
178
179 cl::opt<llvm::FloatABI::ABIType>
180 FloatABIForCalls("float-abi",
181 cl::desc("Choose float ABI type"),
182 cl::init(FloatABI::Default),
183 cl::values(
184 clEnumValN(FloatABI::Default, "default",
185 "Target default float ABI type"),
186 clEnumValN(FloatABI::Soft, "soft",
187 "Soft float ABI (implied by -soft-float)"),
188 clEnumValN(FloatABI::Hard, "hard",
189 "Hard float ABI (uses FP registers)"),
190 clEnumValEnd));
191 cl::opt<bool>
Nick Lewycky9a148412012-04-18 08:34:12 +0000192// In debug builds, make this default to true.
193#ifdef NDEBUG
194#define EMIT_DEBUG false
195#else
196#define EMIT_DEBUG true
197#endif
198 EmitJitDebugInfo("jit-emit-debug",
199 cl::desc("Emit debug information to debugger"),
200 cl::init(EMIT_DEBUG));
201#undef EMIT_DEBUG
202
203 static cl::opt<bool>
204 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
205 cl::Hidden,
206 cl::desc("Emit debug info objfiles to disk"),
207 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000208}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000209
Reid Spencerf70d6772007-03-03 18:21:44 +0000210static ExecutionEngine *EE = 0;
211
212static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000213 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
214#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000215 delete EE;
216 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000217#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000218}
219
Danil Malyshev068c65b2012-05-16 18:50:11 +0000220// Memory manager for MCJIT
221class LLIMCJITMemoryManager : public JITMemoryManager {
222public:
223 SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
224 SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
225 SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
226
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000227 LLIMCJITMemoryManager() { }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000228 ~LLIMCJITMemoryManager();
229
230 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
231 unsigned SectionID);
232
233 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
234 unsigned SectionID);
235
236 virtual void *getPointerToNamedFunction(const std::string &Name,
237 bool AbortOnFailure = true);
238
239 // Invalidate instruction cache for code sections. Some platforms with
240 // separate data cache and instruction cache require explicit cache flush,
241 // otherwise JIT code manipulations (like resolved relocations) will get to
242 // the data cache but not to the instruction cache.
243 virtual void invalidateInstructionCache();
244
Andrew Kaylor647d6d72012-11-01 00:46:04 +0000245 // The RTDyldMemoryManager doesn't use the following functions, so we don't
Danil Malyshev068c65b2012-05-16 18:50:11 +0000246 // need implement them.
247 virtual void setMemoryWritable() {
248 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000249 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000250 virtual void setMemoryExecutable() {
251 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000252 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000253 virtual void setPoisonMemory(bool poison) {
254 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000255 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000256 virtual void AllocateGOT() {
257 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000258 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000259 virtual uint8_t *getGOTBase() const {
260 llvm_unreachable("Unexpected call!");
261 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000262 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000263 virtual uint8_t *startFunctionBody(const Function *F,
264 uintptr_t &ActualSize){
265 llvm_unreachable("Unexpected call!");
266 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000267 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000268 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
269 unsigned Alignment) {
270 llvm_unreachable("Unexpected call!");
271 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000272 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000273 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
274 uint8_t *FunctionEnd) {
275 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000276 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000277 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
278 llvm_unreachable("Unexpected call!");
279 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000280 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000281 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
282 llvm_unreachable("Unexpected call!");
283 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000284 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000285 virtual void deallocateFunctionBody(void *Body) {
286 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000287 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000288 virtual uint8_t* startExceptionTable(const Function* F,
289 uintptr_t &ActualSize) {
290 llvm_unreachable("Unexpected call!");
291 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000292 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000293 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
294 uint8_t *TableEnd, uint8_t* FrameRegister) {
295 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000296 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000297 virtual void deallocateExceptionTable(void *ET) {
298 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000299 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000300};
301
302uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
303 unsigned Alignment,
304 unsigned SectionID) {
305 if (!Alignment)
306 Alignment = 16;
Tim Northoverb210e6f2012-10-29 10:47:07 +0000307 // Ensure that enough memory is requested to allow aligning.
308 size_t NumElementsAligned = 1 + (Size + Alignment - 1)/Alignment;
309 uint8_t *Addr = (uint8_t*)calloc(NumElementsAligned, Alignment);
310
311 // Honour the alignment requirement.
312 uint8_t *AlignedAddr = (uint8_t*)RoundUpToAlignment((uint64_t)Addr, Alignment);
313
314 // Store the original address from calloc so we can free it later.
315 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, NumElementsAligned*Alignment));
316 return AlignedAddr;
Danil Malyshev068c65b2012-05-16 18:50:11 +0000317}
318
319uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
320 unsigned Alignment,
321 unsigned SectionID) {
322 if (!Alignment)
323 Alignment = 16;
324 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
325 uintptr_t Addr = 0;
326 // Look in the list of free code memory regions and use a block there if one
327 // is available.
328 for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
329 sys::MemoryBlock &MB = FreeCodeMem[i];
330 if (MB.size() >= NeedAllocate) {
331 Addr = (uintptr_t)MB.base();
332 uintptr_t EndOfBlock = Addr + MB.size();
333 // Align the address.
334 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
335 // Store cutted free memory block.
336 FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
337 EndOfBlock - Addr - Size);
338 return (uint8_t*)Addr;
339 }
340 }
341
342 // No pre-allocated free block was large enough. Allocate a new memory region.
343 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
344
345 AllocatedCodeMem.push_back(MB);
346 Addr = (uintptr_t)MB.base();
347 uintptr_t EndOfBlock = Addr + MB.size();
348 // Align the address.
349 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
350 // The AllocateRWX may allocate much more memory than we need. In this case,
351 // we store the unused memory as a free memory block.
352 unsigned FreeSize = EndOfBlock-Addr-Size;
353 if (FreeSize > 16)
354 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
355
356 // Return aligned address
357 return (uint8_t*)Addr;
358}
359
360void LLIMCJITMemoryManager::invalidateInstructionCache() {
361 for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
362 sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
363 AllocatedCodeMem[i].size());
364}
365
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000366static int jit_noop() {
367 return 0;
368}
369
Danil Malyshev068c65b2012-05-16 18:50:11 +0000370void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
371 bool AbortOnFailure) {
372#if defined(__linux__)
373 //===--------------------------------------------------------------------===//
374 // Function stubs that are invoked instead of certain library calls
375 //
376 // Force the following functions to be linked in to anything that uses the
377 // JIT. This is a hack designed to work around the all-too-clever Glibc
378 // strategy of making these functions work differently when inlined vs. when
379 // not inlined, and hiding their real definitions in a separate archive file
380 // that the dynamic linker can't see. For more info, search for
381 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
382 if (Name == "stat") return (void*)(intptr_t)&stat;
383 if (Name == "fstat") return (void*)(intptr_t)&fstat;
384 if (Name == "lstat") return (void*)(intptr_t)&lstat;
385 if (Name == "stat64") return (void*)(intptr_t)&stat64;
386 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
387 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
388 if (Name == "atexit") return (void*)(intptr_t)&atexit;
389 if (Name == "mknod") return (void*)(intptr_t)&mknod;
390#endif // __linux__
391
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000392 // We should not invoke parent's ctors/dtors from generated main()!
393 // On Mingw and Cygwin, the symbol __main is resolved to
394 // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
395 // (and register wrong callee's dtors with atexit(3)).
396 // We expect ExecutionEngine::runStaticConstructorsDestructors()
397 // is called before ExecutionEngine::runFunctionAsMain() is called.
398 if (Name == "__main") return (void*)(intptr_t)&jit_noop;
399
Danil Malyshev068c65b2012-05-16 18:50:11 +0000400 const char *NameStr = Name.c_str();
401 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
402 if (Ptr) return Ptr;
403
404 // If it wasn't found and if it starts with an underscore ('_') character,
405 // try again without the underscore.
406 if (NameStr[0] == '_') {
407 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
408 if (Ptr) return Ptr;
409 }
410
411 if (AbortOnFailure)
412 report_fatal_error("Program used external function '" + Name +
413 "' which could not be resolved!");
414 return 0;
415}
416
417LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
418 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
419 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
420 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
421 free(AllocatedDataMem[i].base());
422}
423
Jim Grosbach706f03a2012-09-05 16:50:34 +0000424
425void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
426 // Lay out our sections in order, with all the code sections first, then
427 // all the data sections.
428 uint64_t CurOffset = 0;
429 unsigned MaxAlign = T->getPageAlignment();
430 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
431 SmallVector<unsigned, 16> Sizes;
432 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
433 E = JMM->code_end();
434 I != E; ++I) {
435 DEBUG(dbgs() << "code region: size " << I->first.size()
436 << ", alignment " << I->second << "\n");
437 // Align the current offset up to whatever is needed for the next
438 // section.
439 unsigned Align = I->second;
440 CurOffset = (CurOffset + Align - 1) / Align * Align;
441 // Save off the address of the new section and allocate its space.
442 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
443 Sizes.push_back(I->first.size());
444 CurOffset += I->first.size();
445 }
446 // Adjust to keep code and data aligned on seperate pages.
447 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
448 unsigned FirstDataIndex = Offsets.size();
449 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
450 E = JMM->data_end();
451 I != E; ++I) {
452 DEBUG(dbgs() << "data region: size " << I->first.size()
453 << ", alignment " << I->second << "\n");
454 // Align the current offset up to whatever is needed for the next
455 // section.
456 unsigned Align = I->second;
457 CurOffset = (CurOffset + Align - 1) / Align * Align;
458 // Save off the address of the new section and allocate its space.
459 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
460 Sizes.push_back(I->first.size());
461 CurOffset += I->first.size();
462 }
463
464 // Allocate space in the remote target.
465 uint64_t RemoteAddr;
466 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
467 report_fatal_error(T->getErrorMsg());
468 // Map the section addresses so relocations will get updated in the local
469 // copies of the sections.
470 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
471 uint64_t Addr = RemoteAddr + Offsets[i].second;
472 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
473
474 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
Andrew Kaylor3037a582012-11-01 00:17:11 +0000475 << " to remote: " << format("%p", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000476
477 }
478 // Now load it all to the target.
479 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
480 uint64_t Addr = RemoteAddr + Offsets[i].second;
481
482 if (i < FirstDataIndex) {
483 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
484
485 DEBUG(dbgs() << " loading code: " << Offsets[i].first
Andrew Kaylor3037a582012-11-01 00:17:11 +0000486 << " to remote: " << format("%p", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000487 } else {
488 T->loadData(Addr, Offsets[i].first, Sizes[i]);
489
490 DEBUG(dbgs() << " loading data: " << Offsets[i].first
Andrew Kaylor3037a582012-11-01 00:17:11 +0000491 << " to remote: " << format("%p", Addr) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000492 }
493
494 }
495}
496
Chris Lattner92101ac2001-08-23 17:05:04 +0000497//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000498// main Driver function
499//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000500int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000501 sys::PrintStackTraceOnErrorSignal();
502 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000503
Owen Anderson0d7c6952009-07-15 22:16:10 +0000504 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000505 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000506
507 // If we have a native target, initialize it to ensure it is linked in and
508 // usable by the JIT.
509 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000510 InitializeNativeTargetAsmPrinter();
Jim Grosbach68372322012-11-05 19:06:05 +0000511 InitializeNativeTargetAsmParser();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000512
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000513 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000514 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000515
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000516 // If the user doesn't want core files, disable them.
517 if (DisableCoreFiles)
518 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000519
Gabor Greifa99be512007-07-05 17:07:56 +0000520 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000521 SMDiagnostic Err;
522 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000523 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000524 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000525 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000526 }
527
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000528 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000529 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000530 if (NoLazyCompilation) {
531 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
532 errs() << argv[0] << ": bitcode didn't read correctly.\n";
533 errs() << "Reason: " << ErrorMsg << "\n";
534 exit(1);
535 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000536 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000537
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000538 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000539 builder.setMArch(MArch);
540 builder.setMCPU(MCPU);
541 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000542 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000543 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000544 builder.setErrorStr(&ErrorMsg);
545 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000546 ? EngineKind::Interpreter
547 : EngineKind::JIT);
548
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000549 // If we are supposed to override the target triple, do so now.
550 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000551 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000552
Eli Benderskya66a1852012-01-16 08:56:09 +0000553 // Enable MCJIT if desired.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000554 JITMemoryManager *JMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000555 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000556 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000557 if (RemoteMCJIT)
558 JMM = new RecordingMemoryManager();
559 else
560 JMM = new LLIMCJITMemoryManager();
Danil Malyshev068c65b2012-05-16 18:50:11 +0000561 builder.setJITMemoryManager(JMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000562 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000563 if (RemoteMCJIT) {
564 errs() << "error: Remote process execution requires -use-mcjit\n";
565 exit(1);
566 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000567 builder.setJITMemoryManager(ForceInterpreter ? 0 :
568 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000569 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000570
Evan Cheng712e80e2009-05-04 23:05:19 +0000571 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
572 switch (OptLevel) {
573 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000574 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000575 return 1;
576 case ' ': break;
577 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000578 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000579 case '2': OLvl = CodeGenOpt::Default; break;
580 case '3': OLvl = CodeGenOpt::Aggressive; break;
581 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000582 builder.setOptLevel(OLvl);
583
Tim Northover77b4c692012-10-12 09:55:13 +0000584 TargetOptions Options;
585 Options.UseSoftFloat = GenerateSoftFloatCalls;
586 if (FloatABIForCalls != FloatABI::Default)
587 Options.FloatABIType = FloatABIForCalls;
588 if (GenerateSoftFloatCalls)
589 FloatABIForCalls = FloatABI::Soft;
590
Jim Grosbach706f03a2012-09-05 16:50:34 +0000591 // Remote target execution doesn't handle EH or debug registration.
592 if (!RemoteMCJIT) {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000593 Options.JITExceptionHandling = EnableJITExceptionHandling;
594 Options.JITEmitDebugInfo = EmitJitDebugInfo;
595 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach706f03a2012-09-05 16:50:34 +0000596 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000597
Tim Northover77b4c692012-10-12 09:55:13 +0000598 builder.setTargetOptions(Options);
599
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000600 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000601 if (!EE) {
602 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000603 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000604 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000605 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000606 exit(1);
607 }
608
Eli Bendersky61b18512012-03-13 08:33:15 +0000609 // The following functions have no effect if their respective profiling
610 // support wasn't enabled in the build configuration.
611 EE->RegisterJITEventListener(
612 JITEventListener::createOProfileJITEventListener());
613 EE->RegisterJITEventListener(
614 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000615
Jim Grosbach706f03a2012-09-05 16:50:34 +0000616 if (!NoLazyCompilation && RemoteMCJIT) {
617 errs() << "warning: remote mcjit does not support lazy compilation\n";
618 NoLazyCompilation = true;
619 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000620 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000621
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000622 // If the user specifically requested an argv[0] to pass into the program,
623 // do it now.
624 if (!FakeArgv0.empty()) {
625 InputFile = FakeArgv0;
626 } else {
627 // Otherwise, if there is a .bc suffix on the executable strip it off, it
628 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000629 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000630 InputFile.erase(InputFile.length() - 3);
631 }
632
633 // Add the module's name to the start of the vector of arguments to main().
634 InputArgv.insert(InputArgv.begin(), InputFile);
635
636 // Call the main function from M as if its signature were:
637 // int main (int argc, char **argv, const char **envp)
638 // using the contents of Args to determine argc & argv, and the contents of
639 // EnvVars to determine envp.
640 //
Evan Chengec740e32008-11-05 23:21:52 +0000641 Function *EntryFn = Mod->getFunction(EntryFunc);
642 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000643 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000644 return -1;
645 }
646
Eli Benderskya66a1852012-01-16 08:56:09 +0000647 // If the program doesn't explicitly call exit, we will need the Exit
648 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000649 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
650 Type::getInt32Ty(Context),
651 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000652
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000653 // Reset errno to zero on entry to main.
654 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000655
Jim Grosbach706f03a2012-09-05 16:50:34 +0000656 // Remote target MCJIT doesn't (yet) support static constructors. No reason
657 // it couldn't. This is a limitation of the LLI implemantation, not the
658 // MCJIT itself. FIXME.
659 //
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000660 // Run static constructors.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000661 if (!RemoteMCJIT)
662 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000663
664 if (NoLazyCompilation) {
665 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
666 Function *Fn = &*I;
Evan Chengec740e32008-11-05 23:21:52 +0000667 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengc290a5b2008-04-22 06:51:41 +0000668 EE->getPointerToFunction(Fn);
669 }
670 }
671
Jim Grosbach706f03a2012-09-05 16:50:34 +0000672 int Result;
673 if (RemoteMCJIT) {
674 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
675 // Everything is prepared now, so lay out our program for the target
676 // address space, assign the section addresses to resolve any relocations,
677 // and send it to the target.
678 RemoteTarget Target;
679 Target.create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000680
Jim Grosbach706f03a2012-09-05 16:50:34 +0000681 // Ask for a pointer to the entry function. This triggers the actual
682 // compilation.
683 (void)EE->getPointerToFunction(EntryFn);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000684
Jim Grosbach706f03a2012-09-05 16:50:34 +0000685 // Enough has been compiled to execute the entry function now, so
686 // layout the target memory.
687 layoutRemoteTargetMemory(&Target, MM);
Eli Benderskya66a1852012-01-16 08:56:09 +0000688
Jim Grosbach706f03a2012-09-05 16:50:34 +0000689 // Since we're executing in a (at least simulated) remote address space,
690 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
691 // grab the function address directly here and tell the remote target
692 // to execute the function.
693 // FIXME: argv and envp handling.
694 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
695
696 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
Andrew Kaylor3037a582012-11-01 00:17:11 +0000697 << format("%p", Entry) << "\n");
Jim Grosbach706f03a2012-09-05 16:50:34 +0000698
699 if (Target.executeCode(Entry, Result))
700 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
701
702 Target.stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000703 } else {
Tim Northovera668b462012-09-20 08:46:30 +0000704 // Trigger compilation separately so code regions that need to be
705 // invalidated will be known.
706 (void)EE->getPointerToFunction(EntryFn);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000707 // Clear instruction cache before code will be executed.
708 if (JMM)
709 static_cast<LLIMCJITMemoryManager*>(JMM)->invalidateInstructionCache();
710
711 // Run main.
712 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000713 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000714
715 // Like static constructors, the remote target MCJIT support doesn't handle
716 // this yet. It could. FIXME.
717 if (!RemoteMCJIT) {
718 // Run static destructors.
719 EE->runStaticConstructorsDestructors(true);
720
721 // If the program didn't call exit explicitly, we should call it now.
722 // This ensures that any atexit handlers get called correctly.
723 if (Function *ExitF = dyn_cast<Function>(Exit)) {
724 std::vector<GenericValue> Args;
725 GenericValue ResultGV;
726 ResultGV.IntVal = APInt(32, Result);
727 Args.push_back(ResultGV);
728 EE->runFunction(ExitF, Args);
729 errs() << "ERROR: exit(" << Result << ") returned!\n";
730 abort();
731 } else {
732 errs() << "ERROR: exit defined with wrong prototype!\n";
733 abort();
734 }
735 }
736 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000737}