blob: 0ee72387b8111f3de4698a2d64f45af72c99baca [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"
Chris Lattner02040322007-04-27 17:02:33 +000045#include <cerrno>
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000046
Danil Malyshev068c65b2012-05-16 18:50:11 +000047#ifdef __linux__
48// These includes used by LLIMCJITMemoryManager::getPointerToNamedFunction()
49// for Glibc trickery. Look comments in this function for more information.
50#ifdef HAVE_SYS_STAT_H
51#include <sys/stat.h>
52#endif
53#include <fcntl.h>
54#include <unistd.h>
55#endif
56
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +000057#ifdef __CYGWIN__
58#include <cygwin/version.h>
59#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
60#define DO_NOTHING_ATEXIT 1
61#endif
62#endif
63
Brian Gaeked0fde302003-11-11 22:41:34 +000064using namespace llvm;
65
Chris Lattnerfe11a972002-12-23 23:59:41 +000066namespace {
67 cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000068 InputFile(cl::desc("<input bitcode>"), cl::Positional, cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000069
Chris Lattnerfe11a972002-12-23 23:59:41 +000070 cl::list<std::string>
71 InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>..."));
Chris Lattner5ff62e92002-07-22 02:10:13 +000072
Chris Lattnerfe11a972002-12-23 23:59:41 +000073 cl::opt<bool> ForceInterpreter("force-interpreter",
Misha Brukman3d8a54d2003-09-25 18:10:34 +000074 cl::desc("Force interpretation: disable JIT"),
75 cl::init(false));
Evan Chenge1a4eda2008-08-08 08:12:06 +000076
Daniel Dunbar6d135972010-11-17 16:06:37 +000077 cl::opt<bool> UseMCJIT(
78 "use-mcjit", cl::desc("Enable use of the MC-based JIT (if available)"),
79 cl::init(false));
80
Jim Grosbach706f03a2012-09-05 16:50:34 +000081 // The MCJIT supports building for a target address space separate from
82 // the JIT compilation process. Use a forked process and a copying
83 // memory manager with IPC to execute using this functionality.
84 cl::opt<bool> RemoteMCJIT("remote-mcjit",
85 cl::desc("Execute MCJIT'ed code in a separate process."),
86 cl::init(false));
87
Evan Cheng712e80e2009-05-04 23:05:19 +000088 // Determine optimization level.
89 cl::opt<char>
90 OptLevel("O",
91 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
92 "(default = '-O2')"),
93 cl::Prefix,
94 cl::ZeroOrMore,
95 cl::init(' '));
Evan Chenge1a4eda2008-08-08 08:12:06 +000096
Chris Lattner3015e602005-12-16 05:00:21 +000097 cl::opt<std::string>
Chris Lattner60844d42005-12-16 05:19:18 +000098 TargetTriple("mtriple", cl::desc("Override target triple for module"));
Evan Chengec740e32008-11-05 23:21:52 +000099
100 cl::opt<std::string>
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000101 MArch("march",
102 cl::desc("Architecture to generate assembly for (see --version)"));
103
104 cl::opt<std::string>
105 MCPU("mcpu",
106 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
107 cl::value_desc("cpu-name"),
108 cl::init(""));
109
110 cl::list<std::string>
111 MAttrs("mattr",
112 cl::CommaSeparated,
113 cl::desc("Target specific attributes (-mattr=help for details)"),
114 cl::value_desc("a1,+a2,-a3,..."));
115
116 cl::opt<std::string>
Evan Chengec740e32008-11-05 23:21:52 +0000117 EntryFunc("entry-function",
118 cl::desc("Specify the entry function (default = 'main') "
119 "of the executable"),
120 cl::value_desc("function"),
121 cl::init("main"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000122
Chris Lattnere69671d2003-10-28 22:51:44 +0000123 cl::opt<std::string>
124 FakeArgv0("fake-argv0",
125 cl::desc("Override the 'argv[0]' value passed into the executing"
126 " program"), cl::value_desc("executable"));
Eli Benderskya66a1852012-01-16 08:56:09 +0000127
Chris Lattner43f249a2006-09-14 06:17:09 +0000128 cl::opt<bool>
129 DisableCoreFiles("disable-core-files", cl::Hidden,
130 cl::desc("Disable emission of core files if possible"));
Evan Chengc290a5b2008-04-22 06:51:41 +0000131
132 cl::opt<bool>
Evan Cheng03dace82008-05-21 18:20:21 +0000133 NoLazyCompilation("disable-lazy-compilation",
Evan Chengc290a5b2008-04-22 06:51:41 +0000134 cl::desc("Disable JIT lazy compilation"),
135 cl::init(false));
Evan Cheng43966132011-07-19 06:37:02 +0000136
137 cl::opt<Reloc::Model>
138 RelocModel("relocation-model",
139 cl::desc("Choose relocation model"),
140 cl::init(Reloc::Default),
141 cl::values(
142 clEnumValN(Reloc::Default, "default",
143 "Target default relocation model"),
144 clEnumValN(Reloc::Static, "static",
145 "Non-relocatable code"),
146 clEnumValN(Reloc::PIC_, "pic",
147 "Fully relocatable, position independent code"),
148 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
149 "Relocatable external references, non-relocatable code"),
150 clEnumValEnd));
Evan Cheng34ad6db2011-07-20 07:51:56 +0000151
152 cl::opt<llvm::CodeModel::Model>
153 CMModel("code-model",
154 cl::desc("Choose code model"),
155 cl::init(CodeModel::JITDefault),
156 cl::values(clEnumValN(CodeModel::JITDefault, "default",
157 "Target default JIT code model"),
158 clEnumValN(CodeModel::Small, "small",
159 "Small code model"),
160 clEnumValN(CodeModel::Kernel, "kernel",
161 "Kernel code model"),
162 clEnumValN(CodeModel::Medium, "medium",
163 "Medium code model"),
164 clEnumValN(CodeModel::Large, "large",
165 "Large code model"),
166 clEnumValEnd));
167
Nick Lewycky9a148412012-04-18 08:34:12 +0000168 cl::opt<bool>
169 EnableJITExceptionHandling("jit-enable-eh",
170 cl::desc("Emit exception handling information"),
171 cl::init(false));
172
173 cl::opt<bool>
Tim Northover77b4c692012-10-12 09:55:13 +0000174 GenerateSoftFloatCalls("soft-float",
175 cl::desc("Generate software floating point library calls"),
176 cl::init(false));
177
178 cl::opt<llvm::FloatABI::ABIType>
179 FloatABIForCalls("float-abi",
180 cl::desc("Choose float ABI type"),
181 cl::init(FloatABI::Default),
182 cl::values(
183 clEnumValN(FloatABI::Default, "default",
184 "Target default float ABI type"),
185 clEnumValN(FloatABI::Soft, "soft",
186 "Soft float ABI (implied by -soft-float)"),
187 clEnumValN(FloatABI::Hard, "hard",
188 "Hard float ABI (uses FP registers)"),
189 clEnumValEnd));
190 cl::opt<bool>
Nick Lewycky9a148412012-04-18 08:34:12 +0000191// In debug builds, make this default to true.
192#ifdef NDEBUG
193#define EMIT_DEBUG false
194#else
195#define EMIT_DEBUG true
196#endif
197 EmitJitDebugInfo("jit-emit-debug",
198 cl::desc("Emit debug information to debugger"),
199 cl::init(EMIT_DEBUG));
200#undef EMIT_DEBUG
201
202 static cl::opt<bool>
203 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
204 cl::Hidden,
205 cl::desc("Emit debug info objfiles to disk"),
206 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000207}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000208
Reid Spencerf70d6772007-03-03 18:21:44 +0000209static ExecutionEngine *EE = 0;
210
211static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000212 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
213#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000214 delete EE;
215 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000216#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000217}
218
Danil Malyshev068c65b2012-05-16 18:50:11 +0000219// Memory manager for MCJIT
220class LLIMCJITMemoryManager : public JITMemoryManager {
221public:
222 SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
223 SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
224 SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
225
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000226 LLIMCJITMemoryManager() { }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000227 ~LLIMCJITMemoryManager();
228
229 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
230 unsigned SectionID);
231
232 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
233 unsigned SectionID);
234
235 virtual void *getPointerToNamedFunction(const std::string &Name,
236 bool AbortOnFailure = true);
237
238 // Invalidate instruction cache for code sections. Some platforms with
239 // separate data cache and instruction cache require explicit cache flush,
240 // otherwise JIT code manipulations (like resolved relocations) will get to
241 // the data cache but not to the instruction cache.
242 virtual void invalidateInstructionCache();
243
244 // The MCJITMemoryManager doesn't use the following functions, so we don't
245 // need implement them.
246 virtual void setMemoryWritable() {
247 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000248 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000249 virtual void setMemoryExecutable() {
250 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000251 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000252 virtual void setPoisonMemory(bool poison) {
253 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000254 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000255 virtual void AllocateGOT() {
256 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000257 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000258 virtual uint8_t *getGOTBase() const {
259 llvm_unreachable("Unexpected call!");
260 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000261 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000262 virtual uint8_t *startFunctionBody(const Function *F,
263 uintptr_t &ActualSize){
264 llvm_unreachable("Unexpected call!");
265 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000266 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000267 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
268 unsigned Alignment) {
269 llvm_unreachable("Unexpected call!");
270 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000271 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000272 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
273 uint8_t *FunctionEnd) {
274 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000275 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000276 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
277 llvm_unreachable("Unexpected call!");
278 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000279 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000280 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
281 llvm_unreachable("Unexpected call!");
282 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000283 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000284 virtual void deallocateFunctionBody(void *Body) {
285 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000286 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000287 virtual uint8_t* startExceptionTable(const Function* F,
288 uintptr_t &ActualSize) {
289 llvm_unreachable("Unexpected call!");
290 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000291 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000292 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
293 uint8_t *TableEnd, uint8_t* FrameRegister) {
294 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000295 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000296 virtual void deallocateExceptionTable(void *ET) {
297 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000298 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000299};
300
301uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
302 unsigned Alignment,
303 unsigned SectionID) {
304 if (!Alignment)
305 Alignment = 16;
306 uint8_t *Addr = (uint8_t*)calloc((Size + Alignment - 1)/Alignment, Alignment);
307 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, Size));
308 return Addr;
309}
310
311uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
312 unsigned Alignment,
313 unsigned SectionID) {
314 if (!Alignment)
315 Alignment = 16;
316 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
317 uintptr_t Addr = 0;
318 // Look in the list of free code memory regions and use a block there if one
319 // is available.
320 for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
321 sys::MemoryBlock &MB = FreeCodeMem[i];
322 if (MB.size() >= NeedAllocate) {
323 Addr = (uintptr_t)MB.base();
324 uintptr_t EndOfBlock = Addr + MB.size();
325 // Align the address.
326 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
327 // Store cutted free memory block.
328 FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
329 EndOfBlock - Addr - Size);
330 return (uint8_t*)Addr;
331 }
332 }
333
334 // No pre-allocated free block was large enough. Allocate a new memory region.
335 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
336
337 AllocatedCodeMem.push_back(MB);
338 Addr = (uintptr_t)MB.base();
339 uintptr_t EndOfBlock = Addr + MB.size();
340 // Align the address.
341 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
342 // The AllocateRWX may allocate much more memory than we need. In this case,
343 // we store the unused memory as a free memory block.
344 unsigned FreeSize = EndOfBlock-Addr-Size;
345 if (FreeSize > 16)
346 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
347
348 // Return aligned address
349 return (uint8_t*)Addr;
350}
351
352void LLIMCJITMemoryManager::invalidateInstructionCache() {
353 for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
354 sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
355 AllocatedCodeMem[i].size());
356}
357
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000358static int jit_noop() {
359 return 0;
360}
361
Danil Malyshev068c65b2012-05-16 18:50:11 +0000362void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
363 bool AbortOnFailure) {
364#if defined(__linux__)
365 //===--------------------------------------------------------------------===//
366 // Function stubs that are invoked instead of certain library calls
367 //
368 // Force the following functions to be linked in to anything that uses the
369 // JIT. This is a hack designed to work around the all-too-clever Glibc
370 // strategy of making these functions work differently when inlined vs. when
371 // not inlined, and hiding their real definitions in a separate archive file
372 // that the dynamic linker can't see. For more info, search for
373 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
374 if (Name == "stat") return (void*)(intptr_t)&stat;
375 if (Name == "fstat") return (void*)(intptr_t)&fstat;
376 if (Name == "lstat") return (void*)(intptr_t)&lstat;
377 if (Name == "stat64") return (void*)(intptr_t)&stat64;
378 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
379 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
380 if (Name == "atexit") return (void*)(intptr_t)&atexit;
381 if (Name == "mknod") return (void*)(intptr_t)&mknod;
382#endif // __linux__
383
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000384 // We should not invoke parent's ctors/dtors from generated main()!
385 // On Mingw and Cygwin, the symbol __main is resolved to
386 // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
387 // (and register wrong callee's dtors with atexit(3)).
388 // We expect ExecutionEngine::runStaticConstructorsDestructors()
389 // is called before ExecutionEngine::runFunctionAsMain() is called.
390 if (Name == "__main") return (void*)(intptr_t)&jit_noop;
391
Danil Malyshev068c65b2012-05-16 18:50:11 +0000392 const char *NameStr = Name.c_str();
393 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
394 if (Ptr) return Ptr;
395
396 // If it wasn't found and if it starts with an underscore ('_') character,
397 // try again without the underscore.
398 if (NameStr[0] == '_') {
399 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
400 if (Ptr) return Ptr;
401 }
402
403 if (AbortOnFailure)
404 report_fatal_error("Program used external function '" + Name +
405 "' which could not be resolved!");
406 return 0;
407}
408
409LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
410 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
411 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
412 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
413 free(AllocatedDataMem[i].base());
414}
415
Jim Grosbach706f03a2012-09-05 16:50:34 +0000416
417void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
418 // Lay out our sections in order, with all the code sections first, then
419 // all the data sections.
420 uint64_t CurOffset = 0;
421 unsigned MaxAlign = T->getPageAlignment();
422 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
423 SmallVector<unsigned, 16> Sizes;
424 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
425 E = JMM->code_end();
426 I != E; ++I) {
427 DEBUG(dbgs() << "code region: size " << I->first.size()
428 << ", alignment " << I->second << "\n");
429 // Align the current offset up to whatever is needed for the next
430 // section.
431 unsigned Align = I->second;
432 CurOffset = (CurOffset + Align - 1) / Align * Align;
433 // Save off the address of the new section and allocate its space.
434 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
435 Sizes.push_back(I->first.size());
436 CurOffset += I->first.size();
437 }
438 // Adjust to keep code and data aligned on seperate pages.
439 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
440 unsigned FirstDataIndex = Offsets.size();
441 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
442 E = JMM->data_end();
443 I != E; ++I) {
444 DEBUG(dbgs() << "data region: size " << I->first.size()
445 << ", alignment " << I->second << "\n");
446 // Align the current offset up to whatever is needed for the next
447 // section.
448 unsigned Align = I->second;
449 CurOffset = (CurOffset + Align - 1) / Align * Align;
450 // Save off the address of the new section and allocate its space.
451 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
452 Sizes.push_back(I->first.size());
453 CurOffset += I->first.size();
454 }
455
456 // Allocate space in the remote target.
457 uint64_t RemoteAddr;
458 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
459 report_fatal_error(T->getErrorMsg());
460 // Map the section addresses so relocations will get updated in the local
461 // copies of the sections.
462 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
463 uint64_t Addr = RemoteAddr + Offsets[i].second;
464 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
465
466 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
467 << " to remote: " << format("%#018x", Addr) << "\n");
468
469 }
470 // Now load it all to the target.
471 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
472 uint64_t Addr = RemoteAddr + Offsets[i].second;
473
474 if (i < FirstDataIndex) {
475 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
476
477 DEBUG(dbgs() << " loading code: " << Offsets[i].first
478 << " to remote: " << format("%#018x", Addr) << "\n");
479 } else {
480 T->loadData(Addr, Offsets[i].first, Sizes[i]);
481
482 DEBUG(dbgs() << " loading data: " << Offsets[i].first
483 << " to remote: " << format("%#018x", Addr) << "\n");
484 }
485
486 }
487}
488
Chris Lattner92101ac2001-08-23 17:05:04 +0000489//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000490// main Driver function
491//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000492int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000493 sys::PrintStackTraceOnErrorSignal();
494 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000495
Owen Anderson0d7c6952009-07-15 22:16:10 +0000496 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000497 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000498
499 // If we have a native target, initialize it to ensure it is linked in and
500 // usable by the JIT.
501 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000502 InitializeNativeTargetAsmPrinter();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000503
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000504 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000505 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000506
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000507 // If the user doesn't want core files, disable them.
508 if (DisableCoreFiles)
509 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000510
Gabor Greifa99be512007-07-05 17:07:56 +0000511 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000512 SMDiagnostic Err;
513 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000514 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000515 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000516 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000517 }
518
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000519 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000520 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000521 if (NoLazyCompilation) {
522 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
523 errs() << argv[0] << ": bitcode didn't read correctly.\n";
524 errs() << "Reason: " << ErrorMsg << "\n";
525 exit(1);
526 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000527 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000528
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000529 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000530 builder.setMArch(MArch);
531 builder.setMCPU(MCPU);
532 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000533 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000534 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000535 builder.setErrorStr(&ErrorMsg);
536 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000537 ? EngineKind::Interpreter
538 : EngineKind::JIT);
539
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000540 // If we are supposed to override the target triple, do so now.
541 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000542 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000543
Eli Benderskya66a1852012-01-16 08:56:09 +0000544 // Enable MCJIT if desired.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000545 JITMemoryManager *JMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000546 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000547 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000548 if (RemoteMCJIT)
549 JMM = new RecordingMemoryManager();
550 else
551 JMM = new LLIMCJITMemoryManager();
Danil Malyshev068c65b2012-05-16 18:50:11 +0000552 builder.setJITMemoryManager(JMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000553 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000554 if (RemoteMCJIT) {
555 errs() << "error: Remote process execution requires -use-mcjit\n";
556 exit(1);
557 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000558 builder.setJITMemoryManager(ForceInterpreter ? 0 :
559 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000560 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000561
Evan Cheng712e80e2009-05-04 23:05:19 +0000562 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
563 switch (OptLevel) {
564 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000565 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000566 return 1;
567 case ' ': break;
568 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000569 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000570 case '2': OLvl = CodeGenOpt::Default; break;
571 case '3': OLvl = CodeGenOpt::Aggressive; break;
572 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000573 builder.setOptLevel(OLvl);
574
Tim Northover77b4c692012-10-12 09:55:13 +0000575 TargetOptions Options;
576 Options.UseSoftFloat = GenerateSoftFloatCalls;
577 if (FloatABIForCalls != FloatABI::Default)
578 Options.FloatABIType = FloatABIForCalls;
579 if (GenerateSoftFloatCalls)
580 FloatABIForCalls = FloatABI::Soft;
581
Jim Grosbach706f03a2012-09-05 16:50:34 +0000582 // Remote target execution doesn't handle EH or debug registration.
583 if (!RemoteMCJIT) {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000584 Options.JITExceptionHandling = EnableJITExceptionHandling;
585 Options.JITEmitDebugInfo = EmitJitDebugInfo;
586 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
Jim Grosbach706f03a2012-09-05 16:50:34 +0000587 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000588
Tim Northover77b4c692012-10-12 09:55:13 +0000589 builder.setTargetOptions(Options);
590
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000591 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000592 if (!EE) {
593 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000594 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000595 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000596 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000597 exit(1);
598 }
599
Eli Bendersky61b18512012-03-13 08:33:15 +0000600 // The following functions have no effect if their respective profiling
601 // support wasn't enabled in the build configuration.
602 EE->RegisterJITEventListener(
603 JITEventListener::createOProfileJITEventListener());
604 EE->RegisterJITEventListener(
605 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000606
Jim Grosbach706f03a2012-09-05 16:50:34 +0000607 if (!NoLazyCompilation && RemoteMCJIT) {
608 errs() << "warning: remote mcjit does not support lazy compilation\n";
609 NoLazyCompilation = true;
610 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000611 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000612
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000613 // If the user specifically requested an argv[0] to pass into the program,
614 // do it now.
615 if (!FakeArgv0.empty()) {
616 InputFile = FakeArgv0;
617 } else {
618 // Otherwise, if there is a .bc suffix on the executable strip it off, it
619 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000620 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000621 InputFile.erase(InputFile.length() - 3);
622 }
623
624 // Add the module's name to the start of the vector of arguments to main().
625 InputArgv.insert(InputArgv.begin(), InputFile);
626
627 // Call the main function from M as if its signature were:
628 // int main (int argc, char **argv, const char **envp)
629 // using the contents of Args to determine argc & argv, and the contents of
630 // EnvVars to determine envp.
631 //
Evan Chengec740e32008-11-05 23:21:52 +0000632 Function *EntryFn = Mod->getFunction(EntryFunc);
633 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000634 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000635 return -1;
636 }
637
Eli Benderskya66a1852012-01-16 08:56:09 +0000638 // If the program doesn't explicitly call exit, we will need the Exit
639 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000640 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
641 Type::getInt32Ty(Context),
642 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000643
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000644 // Reset errno to zero on entry to main.
645 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000646
Jim Grosbach706f03a2012-09-05 16:50:34 +0000647 // Remote target MCJIT doesn't (yet) support static constructors. No reason
648 // it couldn't. This is a limitation of the LLI implemantation, not the
649 // MCJIT itself. FIXME.
650 //
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000651 // Run static constructors.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000652 if (!RemoteMCJIT)
653 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000654
655 if (NoLazyCompilation) {
656 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
657 Function *Fn = &*I;
Evan Chengec740e32008-11-05 23:21:52 +0000658 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengc290a5b2008-04-22 06:51:41 +0000659 EE->getPointerToFunction(Fn);
660 }
661 }
662
Jim Grosbach706f03a2012-09-05 16:50:34 +0000663 int Result;
664 if (RemoteMCJIT) {
665 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
666 // Everything is prepared now, so lay out our program for the target
667 // address space, assign the section addresses to resolve any relocations,
668 // and send it to the target.
669 RemoteTarget Target;
670 Target.create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000671
Jim Grosbach706f03a2012-09-05 16:50:34 +0000672 // Ask for a pointer to the entry function. This triggers the actual
673 // compilation.
674 (void)EE->getPointerToFunction(EntryFn);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000675
Jim Grosbach706f03a2012-09-05 16:50:34 +0000676 // Enough has been compiled to execute the entry function now, so
677 // layout the target memory.
678 layoutRemoteTargetMemory(&Target, MM);
Eli Benderskya66a1852012-01-16 08:56:09 +0000679
Jim Grosbach706f03a2012-09-05 16:50:34 +0000680 // Since we're executing in a (at least simulated) remote address space,
681 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
682 // grab the function address directly here and tell the remote target
683 // to execute the function.
684 // FIXME: argv and envp handling.
685 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
686
687 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
688 << format("%#18x", Entry) << "\n");
689
690 if (Target.executeCode(Entry, Result))
691 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
692
693 Target.stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000694 } else {
Tim Northovera668b462012-09-20 08:46:30 +0000695 // Trigger compilation separately so code regions that need to be
696 // invalidated will be known.
697 (void)EE->getPointerToFunction(EntryFn);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000698 // Clear instruction cache before code will be executed.
699 if (JMM)
700 static_cast<LLIMCJITMemoryManager*>(JMM)->invalidateInstructionCache();
701
702 // Run main.
703 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000704 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000705
706 // Like static constructors, the remote target MCJIT support doesn't handle
707 // this yet. It could. FIXME.
708 if (!RemoteMCJIT) {
709 // Run static destructors.
710 EE->runStaticConstructorsDestructors(true);
711
712 // If the program didn't call exit explicitly, we should call it now.
713 // This ensures that any atexit handlers get called correctly.
714 if (Function *ExitF = dyn_cast<Function>(Exit)) {
715 std::vector<GenericValue> Args;
716 GenericValue ResultGV;
717 ResultGV.IntVal = APInt(32, Result);
718 Args.push_back(ResultGV);
719 EE->runFunction(ExitF, Args);
720 errs() << "ERROR: exit(" << Result << ") returned!\n";
721 abort();
722 } else {
723 errs() << "ERROR: exit defined with wrong prototype!\n";
724 abort();
725 }
726 }
727 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000728}