blob: 57a31f21b89ddc2dda4e8342c1511fbc39d6c869 [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>
174// In debug builds, make this default to true.
175#ifdef NDEBUG
176#define EMIT_DEBUG false
177#else
178#define EMIT_DEBUG true
179#endif
180 EmitJitDebugInfo("jit-emit-debug",
181 cl::desc("Emit debug information to debugger"),
182 cl::init(EMIT_DEBUG));
183#undef EMIT_DEBUG
184
185 static cl::opt<bool>
186 EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
187 cl::Hidden,
188 cl::desc("Emit debug info objfiles to disk"),
189 cl::init(false));
Chris Lattnerfe11a972002-12-23 23:59:41 +0000190}
Chris Lattner43e3f7c2001-10-27 08:43:52 +0000191
Reid Spencerf70d6772007-03-03 18:21:44 +0000192static ExecutionEngine *EE = 0;
193
194static void do_shutdown() {
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000195 // Cygwin-1.5 invokes DLL's dtors before atexit handler.
196#ifndef DO_NOTHING_ATEXIT
Reid Spencerf70d6772007-03-03 18:21:44 +0000197 delete EE;
198 llvm_shutdown();
NAKAMURA Takumia13d14a2010-10-22 14:53:59 +0000199#endif
Reid Spencerf70d6772007-03-03 18:21:44 +0000200}
201
Danil Malyshev068c65b2012-05-16 18:50:11 +0000202// Memory manager for MCJIT
203class LLIMCJITMemoryManager : public JITMemoryManager {
204public:
205 SmallVector<sys::MemoryBlock, 16> AllocatedDataMem;
206 SmallVector<sys::MemoryBlock, 16> AllocatedCodeMem;
207 SmallVector<sys::MemoryBlock, 16> FreeCodeMem;
208
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000209 LLIMCJITMemoryManager() { }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000210 ~LLIMCJITMemoryManager();
211
212 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
213 unsigned SectionID);
214
215 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
216 unsigned SectionID);
217
218 virtual void *getPointerToNamedFunction(const std::string &Name,
219 bool AbortOnFailure = true);
220
221 // Invalidate instruction cache for code sections. Some platforms with
222 // separate data cache and instruction cache require explicit cache flush,
223 // otherwise JIT code manipulations (like resolved relocations) will get to
224 // the data cache but not to the instruction cache.
225 virtual void invalidateInstructionCache();
226
227 // The MCJITMemoryManager doesn't use the following functions, so we don't
228 // need implement them.
229 virtual void setMemoryWritable() {
230 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000231 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000232 virtual void setMemoryExecutable() {
233 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000234 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000235 virtual void setPoisonMemory(bool poison) {
236 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000237 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000238 virtual void AllocateGOT() {
239 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000240 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000241 virtual uint8_t *getGOTBase() const {
242 llvm_unreachable("Unexpected call!");
243 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000244 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000245 virtual uint8_t *startFunctionBody(const Function *F,
246 uintptr_t &ActualSize){
247 llvm_unreachable("Unexpected call!");
248 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000249 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000250 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
251 unsigned Alignment) {
252 llvm_unreachable("Unexpected call!");
253 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000254 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000255 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
256 uint8_t *FunctionEnd) {
257 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000258 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000259 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
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 *allocateGlobal(uintptr_t Size, unsigned Alignment) {
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 void deallocateFunctionBody(void *Body) {
268 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000269 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000270 virtual uint8_t* startExceptionTable(const Function* F,
271 uintptr_t &ActualSize) {
272 llvm_unreachable("Unexpected call!");
273 return 0;
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000274 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000275 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
276 uint8_t *TableEnd, uint8_t* FrameRegister) {
277 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000278 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000279 virtual void deallocateExceptionTable(void *ET) {
280 llvm_unreachable("Unexpected call!");
Benjamin Kramer223f2a72012-05-19 16:44:12 +0000281 }
Danil Malyshev068c65b2012-05-16 18:50:11 +0000282};
283
284uint8_t *LLIMCJITMemoryManager::allocateDataSection(uintptr_t Size,
285 unsigned Alignment,
286 unsigned SectionID) {
287 if (!Alignment)
288 Alignment = 16;
289 uint8_t *Addr = (uint8_t*)calloc((Size + Alignment - 1)/Alignment, Alignment);
290 AllocatedDataMem.push_back(sys::MemoryBlock(Addr, Size));
291 return Addr;
292}
293
294uint8_t *LLIMCJITMemoryManager::allocateCodeSection(uintptr_t Size,
295 unsigned Alignment,
296 unsigned SectionID) {
297 if (!Alignment)
298 Alignment = 16;
299 unsigned NeedAllocate = Alignment * ((Size + Alignment - 1)/Alignment + 1);
300 uintptr_t Addr = 0;
301 // Look in the list of free code memory regions and use a block there if one
302 // is available.
303 for (int i = 0, e = FreeCodeMem.size(); i != e; ++i) {
304 sys::MemoryBlock &MB = FreeCodeMem[i];
305 if (MB.size() >= NeedAllocate) {
306 Addr = (uintptr_t)MB.base();
307 uintptr_t EndOfBlock = Addr + MB.size();
308 // Align the address.
309 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
310 // Store cutted free memory block.
311 FreeCodeMem[i] = sys::MemoryBlock((void*)(Addr + Size),
312 EndOfBlock - Addr - Size);
313 return (uint8_t*)Addr;
314 }
315 }
316
317 // No pre-allocated free block was large enough. Allocate a new memory region.
318 sys::MemoryBlock MB = sys::Memory::AllocateRWX(NeedAllocate, 0, 0);
319
320 AllocatedCodeMem.push_back(MB);
321 Addr = (uintptr_t)MB.base();
322 uintptr_t EndOfBlock = Addr + MB.size();
323 // Align the address.
324 Addr = (Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1);
325 // The AllocateRWX may allocate much more memory than we need. In this case,
326 // we store the unused memory as a free memory block.
327 unsigned FreeSize = EndOfBlock-Addr-Size;
328 if (FreeSize > 16)
329 FreeCodeMem.push_back(sys::MemoryBlock((void*)(Addr + Size), FreeSize));
330
331 // Return aligned address
332 return (uint8_t*)Addr;
333}
334
335void LLIMCJITMemoryManager::invalidateInstructionCache() {
336 for (int i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
337 sys::Memory::InvalidateInstructionCache(AllocatedCodeMem[i].base(),
338 AllocatedCodeMem[i].size());
339}
340
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000341static int jit_noop() {
342 return 0;
343}
344
Danil Malyshev068c65b2012-05-16 18:50:11 +0000345void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
346 bool AbortOnFailure) {
347#if defined(__linux__)
348 //===--------------------------------------------------------------------===//
349 // Function stubs that are invoked instead of certain library calls
350 //
351 // Force the following functions to be linked in to anything that uses the
352 // JIT. This is a hack designed to work around the all-too-clever Glibc
353 // strategy of making these functions work differently when inlined vs. when
354 // not inlined, and hiding their real definitions in a separate archive file
355 // that the dynamic linker can't see. For more info, search for
356 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
357 if (Name == "stat") return (void*)(intptr_t)&stat;
358 if (Name == "fstat") return (void*)(intptr_t)&fstat;
359 if (Name == "lstat") return (void*)(intptr_t)&lstat;
360 if (Name == "stat64") return (void*)(intptr_t)&stat64;
361 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
362 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
363 if (Name == "atexit") return (void*)(intptr_t)&atexit;
364 if (Name == "mknod") return (void*)(intptr_t)&mknod;
365#endif // __linux__
366
NAKAMURA Takumi55587cf2012-10-05 14:10:23 +0000367 // We should not invoke parent's ctors/dtors from generated main()!
368 // On Mingw and Cygwin, the symbol __main is resolved to
369 // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
370 // (and register wrong callee's dtors with atexit(3)).
371 // We expect ExecutionEngine::runStaticConstructorsDestructors()
372 // is called before ExecutionEngine::runFunctionAsMain() is called.
373 if (Name == "__main") return (void*)(intptr_t)&jit_noop;
374
Danil Malyshev068c65b2012-05-16 18:50:11 +0000375 const char *NameStr = Name.c_str();
376 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
377 if (Ptr) return Ptr;
378
379 // If it wasn't found and if it starts with an underscore ('_') character,
380 // try again without the underscore.
381 if (NameStr[0] == '_') {
382 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
383 if (Ptr) return Ptr;
384 }
385
386 if (AbortOnFailure)
387 report_fatal_error("Program used external function '" + Name +
388 "' which could not be resolved!");
389 return 0;
390}
391
392LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
393 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
394 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
395 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
396 free(AllocatedDataMem[i].base());
397}
398
Jim Grosbach706f03a2012-09-05 16:50:34 +0000399
400void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
401 // Lay out our sections in order, with all the code sections first, then
402 // all the data sections.
403 uint64_t CurOffset = 0;
404 unsigned MaxAlign = T->getPageAlignment();
405 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
406 SmallVector<unsigned, 16> Sizes;
407 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
408 E = JMM->code_end();
409 I != E; ++I) {
410 DEBUG(dbgs() << "code region: size " << I->first.size()
411 << ", alignment " << I->second << "\n");
412 // Align the current offset up to whatever is needed for the next
413 // section.
414 unsigned Align = I->second;
415 CurOffset = (CurOffset + Align - 1) / Align * Align;
416 // Save off the address of the new section and allocate its space.
417 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
418 Sizes.push_back(I->first.size());
419 CurOffset += I->first.size();
420 }
421 // Adjust to keep code and data aligned on seperate pages.
422 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
423 unsigned FirstDataIndex = Offsets.size();
424 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
425 E = JMM->data_end();
426 I != E; ++I) {
427 DEBUG(dbgs() << "data 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
439 // Allocate space in the remote target.
440 uint64_t RemoteAddr;
441 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
442 report_fatal_error(T->getErrorMsg());
443 // Map the section addresses so relocations will get updated in the local
444 // copies of the sections.
445 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
446 uint64_t Addr = RemoteAddr + Offsets[i].second;
447 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
448
449 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
450 << " to remote: " << format("%#018x", Addr) << "\n");
451
452 }
453 // Now load it all to the target.
454 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
455 uint64_t Addr = RemoteAddr + Offsets[i].second;
456
457 if (i < FirstDataIndex) {
458 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
459
460 DEBUG(dbgs() << " loading code: " << Offsets[i].first
461 << " to remote: " << format("%#018x", Addr) << "\n");
462 } else {
463 T->loadData(Addr, Offsets[i].first, Sizes[i]);
464
465 DEBUG(dbgs() << " loading data: " << Offsets[i].first
466 << " to remote: " << format("%#018x", Addr) << "\n");
467 }
468
469 }
470}
471
Chris Lattner92101ac2001-08-23 17:05:04 +0000472//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000473// main Driver function
474//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000475int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000476 sys::PrintStackTraceOnErrorSignal();
477 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000478
Owen Anderson0d7c6952009-07-15 22:16:10 +0000479 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000480 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000481
482 // If we have a native target, initialize it to ensure it is linked in and
483 // usable by the JIT.
484 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000485 InitializeNativeTargetAsmPrinter();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000486
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000487 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000488 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000489
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000490 // If the user doesn't want core files, disable them.
491 if (DisableCoreFiles)
492 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000493
Gabor Greifa99be512007-07-05 17:07:56 +0000494 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000495 SMDiagnostic Err;
496 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000497 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000498 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000499 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000500 }
501
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000502 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000503 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000504 if (NoLazyCompilation) {
505 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
506 errs() << argv[0] << ": bitcode didn't read correctly.\n";
507 errs() << "Reason: " << ErrorMsg << "\n";
508 exit(1);
509 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000510 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000511
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000512 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000513 builder.setMArch(MArch);
514 builder.setMCPU(MCPU);
515 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000516 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000517 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000518 builder.setErrorStr(&ErrorMsg);
519 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000520 ? EngineKind::Interpreter
521 : EngineKind::JIT);
522
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000523 // If we are supposed to override the target triple, do so now.
524 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000525 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000526
Eli Benderskya66a1852012-01-16 08:56:09 +0000527 // Enable MCJIT if desired.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000528 JITMemoryManager *JMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000529 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000530 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000531 if (RemoteMCJIT)
532 JMM = new RecordingMemoryManager();
533 else
534 JMM = new LLIMCJITMemoryManager();
Danil Malyshev068c65b2012-05-16 18:50:11 +0000535 builder.setJITMemoryManager(JMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000536 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000537 if (RemoteMCJIT) {
538 errs() << "error: Remote process execution requires -use-mcjit\n";
539 exit(1);
540 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000541 builder.setJITMemoryManager(ForceInterpreter ? 0 :
542 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000543 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000544
Evan Cheng712e80e2009-05-04 23:05:19 +0000545 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
546 switch (OptLevel) {
547 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000548 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000549 return 1;
550 case ' ': break;
551 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000552 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000553 case '2': OLvl = CodeGenOpt::Default; break;
554 case '3': OLvl = CodeGenOpt::Aggressive; break;
555 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000556 builder.setOptLevel(OLvl);
557
Jim Grosbach706f03a2012-09-05 16:50:34 +0000558 // Remote target execution doesn't handle EH or debug registration.
559 if (!RemoteMCJIT) {
560 TargetOptions Options;
561 Options.JITExceptionHandling = EnableJITExceptionHandling;
562 Options.JITEmitDebugInfo = EmitJitDebugInfo;
563 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
564 builder.setTargetOptions(Options);
565 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000566
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000567 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000568 if (!EE) {
569 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000570 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000571 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000572 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000573 exit(1);
574 }
575
Eli Bendersky61b18512012-03-13 08:33:15 +0000576 // The following functions have no effect if their respective profiling
577 // support wasn't enabled in the build configuration.
578 EE->RegisterJITEventListener(
579 JITEventListener::createOProfileJITEventListener());
580 EE->RegisterJITEventListener(
581 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000582
Jim Grosbach706f03a2012-09-05 16:50:34 +0000583 if (!NoLazyCompilation && RemoteMCJIT) {
584 errs() << "warning: remote mcjit does not support lazy compilation\n";
585 NoLazyCompilation = true;
586 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000587 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000588
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000589 // If the user specifically requested an argv[0] to pass into the program,
590 // do it now.
591 if (!FakeArgv0.empty()) {
592 InputFile = FakeArgv0;
593 } else {
594 // Otherwise, if there is a .bc suffix on the executable strip it off, it
595 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000596 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000597 InputFile.erase(InputFile.length() - 3);
598 }
599
600 // Add the module's name to the start of the vector of arguments to main().
601 InputArgv.insert(InputArgv.begin(), InputFile);
602
603 // Call the main function from M as if its signature were:
604 // int main (int argc, char **argv, const char **envp)
605 // using the contents of Args to determine argc & argv, and the contents of
606 // EnvVars to determine envp.
607 //
Evan Chengec740e32008-11-05 23:21:52 +0000608 Function *EntryFn = Mod->getFunction(EntryFunc);
609 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000610 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000611 return -1;
612 }
613
Eli Benderskya66a1852012-01-16 08:56:09 +0000614 // If the program doesn't explicitly call exit, we will need the Exit
615 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000616 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
617 Type::getInt32Ty(Context),
618 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000619
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000620 // Reset errno to zero on entry to main.
621 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000622
Jim Grosbach706f03a2012-09-05 16:50:34 +0000623 // Remote target MCJIT doesn't (yet) support static constructors. No reason
624 // it couldn't. This is a limitation of the LLI implemantation, not the
625 // MCJIT itself. FIXME.
626 //
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000627 // Run static constructors.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000628 if (!RemoteMCJIT)
629 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000630
631 if (NoLazyCompilation) {
632 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
633 Function *Fn = &*I;
Evan Chengec740e32008-11-05 23:21:52 +0000634 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengc290a5b2008-04-22 06:51:41 +0000635 EE->getPointerToFunction(Fn);
636 }
637 }
638
Jim Grosbach706f03a2012-09-05 16:50:34 +0000639 int Result;
640 if (RemoteMCJIT) {
641 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
642 // Everything is prepared now, so lay out our program for the target
643 // address space, assign the section addresses to resolve any relocations,
644 // and send it to the target.
645 RemoteTarget Target;
646 Target.create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000647
Jim Grosbach706f03a2012-09-05 16:50:34 +0000648 // Ask for a pointer to the entry function. This triggers the actual
649 // compilation.
650 (void)EE->getPointerToFunction(EntryFn);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000651
Jim Grosbach706f03a2012-09-05 16:50:34 +0000652 // Enough has been compiled to execute the entry function now, so
653 // layout the target memory.
654 layoutRemoteTargetMemory(&Target, MM);
Eli Benderskya66a1852012-01-16 08:56:09 +0000655
Jim Grosbach706f03a2012-09-05 16:50:34 +0000656 // Since we're executing in a (at least simulated) remote address space,
657 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
658 // grab the function address directly here and tell the remote target
659 // to execute the function.
660 // FIXME: argv and envp handling.
661 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
662
663 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
664 << format("%#18x", Entry) << "\n");
665
666 if (Target.executeCode(Entry, Result))
667 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
668
669 Target.stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000670 } else {
Tim Northovera668b462012-09-20 08:46:30 +0000671 // Trigger compilation separately so code regions that need to be
672 // invalidated will be known.
673 (void)EE->getPointerToFunction(EntryFn);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000674 // Clear instruction cache before code will be executed.
675 if (JMM)
676 static_cast<LLIMCJITMemoryManager*>(JMM)->invalidateInstructionCache();
677
678 // Run main.
679 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000680 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000681
682 // Like static constructors, the remote target MCJIT support doesn't handle
683 // this yet. It could. FIXME.
684 if (!RemoteMCJIT) {
685 // Run static destructors.
686 EE->runStaticConstructorsDestructors(true);
687
688 // If the program didn't call exit explicitly, we should call it now.
689 // This ensures that any atexit handlers get called correctly.
690 if (Function *ExitF = dyn_cast<Function>(Exit)) {
691 std::vector<GenericValue> Args;
692 GenericValue ResultGV;
693 ResultGV.IntVal = APInt(32, Result);
694 Args.push_back(ResultGV);
695 EE->runFunction(ExitF, Args);
696 errs() << "ERROR: exit(" << Result << ") returned!\n";
697 abort();
698 } else {
699 errs() << "ERROR: exit defined with wrong prototype!\n";
700 abort();
701 }
702 }
703 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000704}