blob: 4004b6c4d408cabf04725356a108f9d9d848955a [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
341void *LLIMCJITMemoryManager::getPointerToNamedFunction(const std::string &Name,
342 bool AbortOnFailure) {
343#if defined(__linux__)
344 //===--------------------------------------------------------------------===//
345 // Function stubs that are invoked instead of certain library calls
346 //
347 // Force the following functions to be linked in to anything that uses the
348 // JIT. This is a hack designed to work around the all-too-clever Glibc
349 // strategy of making these functions work differently when inlined vs. when
350 // not inlined, and hiding their real definitions in a separate archive file
351 // that the dynamic linker can't see. For more info, search for
352 // 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
353 if (Name == "stat") return (void*)(intptr_t)&stat;
354 if (Name == "fstat") return (void*)(intptr_t)&fstat;
355 if (Name == "lstat") return (void*)(intptr_t)&lstat;
356 if (Name == "stat64") return (void*)(intptr_t)&stat64;
357 if (Name == "fstat64") return (void*)(intptr_t)&fstat64;
358 if (Name == "lstat64") return (void*)(intptr_t)&lstat64;
359 if (Name == "atexit") return (void*)(intptr_t)&atexit;
360 if (Name == "mknod") return (void*)(intptr_t)&mknod;
361#endif // __linux__
362
363 const char *NameStr = Name.c_str();
364 void *Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
365 if (Ptr) return Ptr;
366
367 // If it wasn't found and if it starts with an underscore ('_') character,
368 // try again without the underscore.
369 if (NameStr[0] == '_') {
370 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
371 if (Ptr) return Ptr;
372 }
373
374 if (AbortOnFailure)
375 report_fatal_error("Program used external function '" + Name +
376 "' which could not be resolved!");
377 return 0;
378}
379
380LLIMCJITMemoryManager::~LLIMCJITMemoryManager() {
381 for (unsigned i = 0, e = AllocatedCodeMem.size(); i != e; ++i)
382 sys::Memory::ReleaseRWX(AllocatedCodeMem[i]);
383 for (unsigned i = 0, e = AllocatedDataMem.size(); i != e; ++i)
384 free(AllocatedDataMem[i].base());
385}
386
Jim Grosbach706f03a2012-09-05 16:50:34 +0000387
388void layoutRemoteTargetMemory(RemoteTarget *T, RecordingMemoryManager *JMM) {
389 // Lay out our sections in order, with all the code sections first, then
390 // all the data sections.
391 uint64_t CurOffset = 0;
392 unsigned MaxAlign = T->getPageAlignment();
393 SmallVector<std::pair<const void*, uint64_t>, 16> Offsets;
394 SmallVector<unsigned, 16> Sizes;
395 for (RecordingMemoryManager::const_code_iterator I = JMM->code_begin(),
396 E = JMM->code_end();
397 I != E; ++I) {
398 DEBUG(dbgs() << "code region: size " << I->first.size()
399 << ", alignment " << I->second << "\n");
400 // Align the current offset up to whatever is needed for the next
401 // section.
402 unsigned Align = I->second;
403 CurOffset = (CurOffset + Align - 1) / Align * Align;
404 // Save off the address of the new section and allocate its space.
405 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
406 Sizes.push_back(I->first.size());
407 CurOffset += I->first.size();
408 }
409 // Adjust to keep code and data aligned on seperate pages.
410 CurOffset = (CurOffset + MaxAlign - 1) / MaxAlign * MaxAlign;
411 unsigned FirstDataIndex = Offsets.size();
412 for (RecordingMemoryManager::const_data_iterator I = JMM->data_begin(),
413 E = JMM->data_end();
414 I != E; ++I) {
415 DEBUG(dbgs() << "data region: size " << I->first.size()
416 << ", alignment " << I->second << "\n");
417 // Align the current offset up to whatever is needed for the next
418 // section.
419 unsigned Align = I->second;
420 CurOffset = (CurOffset + Align - 1) / Align * Align;
421 // Save off the address of the new section and allocate its space.
422 Offsets.push_back(std::pair<const void*,uint64_t>(I->first.base(), CurOffset));
423 Sizes.push_back(I->first.size());
424 CurOffset += I->first.size();
425 }
426
427 // Allocate space in the remote target.
428 uint64_t RemoteAddr;
429 if (T->allocateSpace(CurOffset, MaxAlign, RemoteAddr))
430 report_fatal_error(T->getErrorMsg());
431 // Map the section addresses so relocations will get updated in the local
432 // copies of the sections.
433 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
434 uint64_t Addr = RemoteAddr + Offsets[i].second;
435 EE->mapSectionAddress(const_cast<void*>(Offsets[i].first), Addr);
436
437 DEBUG(dbgs() << " Mapping local: " << Offsets[i].first
438 << " to remote: " << format("%#018x", Addr) << "\n");
439
440 }
441 // Now load it all to the target.
442 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
443 uint64_t Addr = RemoteAddr + Offsets[i].second;
444
445 if (i < FirstDataIndex) {
446 T->loadCode(Addr, Offsets[i].first, Sizes[i]);
447
448 DEBUG(dbgs() << " loading code: " << Offsets[i].first
449 << " to remote: " << format("%#018x", Addr) << "\n");
450 } else {
451 T->loadData(Addr, Offsets[i].first, Sizes[i]);
452
453 DEBUG(dbgs() << " loading data: " << Offsets[i].first
454 << " to remote: " << format("%#018x", Addr) << "\n");
455 }
456
457 }
458}
459
Chris Lattner92101ac2001-08-23 17:05:04 +0000460//===----------------------------------------------------------------------===//
Chris Lattner92101ac2001-08-23 17:05:04 +0000461// main Driver function
462//
Misha Brukmanc4fb6fd2003-10-14 21:39:53 +0000463int main(int argc, char **argv, char * const *envp) {
Chris Lattnercc14d252009-03-06 05:34:10 +0000464 sys::PrintStackTraceOnErrorSignal();
465 PrettyStackTraceProgram X(argc, argv);
Eli Benderskya66a1852012-01-16 08:56:09 +0000466
Owen Anderson0d7c6952009-07-15 22:16:10 +0000467 LLVMContext &Context = getGlobalContext();
Reid Spencerf70d6772007-03-03 18:21:44 +0000468 atexit(do_shutdown); // Call llvm_shutdown() on exit.
Daniel Dunbar494d6632009-07-16 02:04:54 +0000469
470 // If we have a native target, initialize it to ensure it is linked in and
471 // usable by the JIT.
472 InitializeNativeTarget();
Jim Grosbach31649e62011-03-18 22:48:41 +0000473 InitializeNativeTargetAsmPrinter();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000474
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000475 cl::ParseCommandLineOptions(argc, argv,
Dan Gohman82a13c92007-10-08 15:45:12 +0000476 "llvm interpreter & dynamic compiler\n");
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000477
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000478 // If the user doesn't want core files, disable them.
479 if (DisableCoreFiles)
480 sys::Process::PreventCoreFiles();
Eli Benderskya66a1852012-01-16 08:56:09 +0000481
Gabor Greifa99be512007-07-05 17:07:56 +0000482 // Load the bitcode...
Daniel Dunbar46a27162010-11-13 00:28:01 +0000483 SMDiagnostic Err;
484 Module *Mod = ParseIRFile(InputFile, Err, Context);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000485 if (!Mod) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000486 Err.print(argv[0], errs());
Daniel Dunbar46a27162010-11-13 00:28:01 +0000487 return 1;
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000488 }
489
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000490 // If not jitting lazily, load the whole bitcode file eagerly too.
Daniel Dunbar46a27162010-11-13 00:28:01 +0000491 std::string ErrorMsg;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000492 if (NoLazyCompilation) {
493 if (Mod->MaterializeAllPermanently(&ErrorMsg)) {
494 errs() << argv[0] << ": bitcode didn't read correctly.\n";
495 errs() << "Reason: " << ErrorMsg << "\n";
496 exit(1);
497 }
Evan Chengc290a5b2008-04-22 06:51:41 +0000498 }
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000499
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000500 EngineBuilder builder(Mod);
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000501 builder.setMArch(MArch);
502 builder.setMCPU(MCPU);
503 builder.setMAttrs(MAttrs);
Evan Cheng43966132011-07-19 06:37:02 +0000504 builder.setRelocationModel(RelocModel);
Evan Cheng34ad6db2011-07-20 07:51:56 +0000505 builder.setCodeModel(CMModel);
Daniel Dunbar4dc31362009-07-18 08:07:13 +0000506 builder.setErrorStr(&ErrorMsg);
507 builder.setEngineKind(ForceInterpreter
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000508 ? EngineKind::Interpreter
509 : EngineKind::JIT);
510
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000511 // If we are supposed to override the target triple, do so now.
512 if (!TargetTriple.empty())
Duncan Sands75ebbce2010-08-28 01:30:02 +0000513 Mod->setTargetTriple(Triple::normalize(TargetTriple));
Evan Chengc290a5b2008-04-22 06:51:41 +0000514
Eli Benderskya66a1852012-01-16 08:56:09 +0000515 // Enable MCJIT if desired.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000516 JITMemoryManager *JMM = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000517 if (UseMCJIT && !ForceInterpreter) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000518 builder.setUseMCJIT(true);
Jim Grosbach706f03a2012-09-05 16:50:34 +0000519 if (RemoteMCJIT)
520 JMM = new RecordingMemoryManager();
521 else
522 JMM = new LLIMCJITMemoryManager();
Danil Malyshev068c65b2012-05-16 18:50:11 +0000523 builder.setJITMemoryManager(JMM);
Benjamin Kramer65145512012-05-20 17:24:08 +0000524 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000525 if (RemoteMCJIT) {
526 errs() << "error: Remote process execution requires -use-mcjit\n";
527 exit(1);
528 }
Benjamin Kramer65145512012-05-20 17:24:08 +0000529 builder.setJITMemoryManager(ForceInterpreter ? 0 :
530 JITMemoryManager::CreateDefaultMemManager());
Eli Benderskya66a1852012-01-16 08:56:09 +0000531 }
Daniel Dunbar6d135972010-11-17 16:06:37 +0000532
Evan Cheng712e80e2009-05-04 23:05:19 +0000533 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
534 switch (OptLevel) {
535 default:
Dan Gohman65f57c22009-07-15 16:35:29 +0000536 errs() << argv[0] << ": invalid optimization level.\n";
Evan Cheng712e80e2009-05-04 23:05:19 +0000537 return 1;
538 case ' ': break;
539 case '0': OLvl = CodeGenOpt::None; break;
Evan Chengbf57b522009-10-16 21:02:20 +0000540 case '1': OLvl = CodeGenOpt::Less; break;
Evan Cheng712e80e2009-05-04 23:05:19 +0000541 case '2': OLvl = CodeGenOpt::Default; break;
542 case '3': OLvl = CodeGenOpt::Aggressive; break;
543 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000544 builder.setOptLevel(OLvl);
545
Jim Grosbach706f03a2012-09-05 16:50:34 +0000546 // Remote target execution doesn't handle EH or debug registration.
547 if (!RemoteMCJIT) {
548 TargetOptions Options;
549 Options.JITExceptionHandling = EnableJITExceptionHandling;
550 Options.JITEmitDebugInfo = EmitJitDebugInfo;
551 Options.JITEmitDebugInfoToDisk = EmitJitDebugInfoToDisk;
552 builder.setTargetOptions(Options);
553 }
Nick Lewycky9a148412012-04-18 08:34:12 +0000554
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000555 EE = builder.create();
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000556 if (!EE) {
557 if (!ErrorMsg.empty())
Dan Gohman65f57c22009-07-15 16:35:29 +0000558 errs() << argv[0] << ": error creating EE: " << ErrorMsg << "\n";
Chris Lattnerfd15bee2009-07-07 18:31:09 +0000559 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000560 errs() << argv[0] << ": unknown error creating EE!\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000561 exit(1);
562 }
563
Eli Bendersky61b18512012-03-13 08:33:15 +0000564 // The following functions have no effect if their respective profiling
565 // support wasn't enabled in the build configuration.
566 EE->RegisterJITEventListener(
567 JITEventListener::createOProfileJITEventListener());
568 EE->RegisterJITEventListener(
569 JITEventListener::createIntelJITEventListener());
Jeffrey Yasskindf5a7da2009-06-25 02:04:04 +0000570
Jim Grosbach706f03a2012-09-05 16:50:34 +0000571 if (!NoLazyCompilation && RemoteMCJIT) {
572 errs() << "warning: remote mcjit does not support lazy compilation\n";
573 NoLazyCompilation = true;
574 }
Jeffrey Yasskin18fec732009-10-27 22:39:42 +0000575 EE->DisableLazyCompilation(NoLazyCompilation);
Evan Chengc290a5b2008-04-22 06:51:41 +0000576
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000577 // If the user specifically requested an argv[0] to pass into the program,
578 // do it now.
579 if (!FakeArgv0.empty()) {
580 InputFile = FakeArgv0;
581 } else {
582 // Otherwise, if there is a .bc suffix on the executable strip it off, it
583 // might confuse the program.
Benjamin Kramer3bb37e92010-04-15 11:33:14 +0000584 if (StringRef(InputFile).endswith(".bc"))
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000585 InputFile.erase(InputFile.length() - 3);
586 }
587
588 // Add the module's name to the start of the vector of arguments to main().
589 InputArgv.insert(InputArgv.begin(), InputFile);
590
591 // Call the main function from M as if its signature were:
592 // int main (int argc, char **argv, const char **envp)
593 // using the contents of Args to determine argc & argv, and the contents of
594 // EnvVars to determine envp.
595 //
Evan Chengec740e32008-11-05 23:21:52 +0000596 Function *EntryFn = Mod->getFunction(EntryFunc);
597 if (!EntryFn) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000598 errs() << '\'' << EntryFunc << "\' function not found in module.\n";
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000599 return -1;
600 }
601
Eli Benderskya66a1852012-01-16 08:56:09 +0000602 // If the program doesn't explicitly call exit, we will need the Exit
603 // function later on to make an explicit call, so get the function now.
Owen Anderson1d0be152009-08-13 21:58:54 +0000604 Constant *Exit = Mod->getOrInsertFunction("exit", Type::getVoidTy(Context),
605 Type::getInt32Ty(Context),
606 NULL);
Eli Benderskya66a1852012-01-16 08:56:09 +0000607
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000608 // Reset errno to zero on entry to main.
609 errno = 0;
Eli Benderskya66a1852012-01-16 08:56:09 +0000610
Jim Grosbach706f03a2012-09-05 16:50:34 +0000611 // Remote target MCJIT doesn't (yet) support static constructors. No reason
612 // it couldn't. This is a limitation of the LLI implemantation, not the
613 // MCJIT itself. FIXME.
614 //
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000615 // Run static constructors.
Jim Grosbach706f03a2012-09-05 16:50:34 +0000616 if (!RemoteMCJIT)
617 EE->runStaticConstructorsDestructors(false);
Evan Chengc290a5b2008-04-22 06:51:41 +0000618
619 if (NoLazyCompilation) {
620 for (Module::iterator I = Mod->begin(), E = Mod->end(); I != E; ++I) {
621 Function *Fn = &*I;
Evan Chengec740e32008-11-05 23:21:52 +0000622 if (Fn != EntryFn && !Fn->isDeclaration())
Evan Chengc290a5b2008-04-22 06:51:41 +0000623 EE->getPointerToFunction(Fn);
624 }
625 }
626
Jim Grosbach706f03a2012-09-05 16:50:34 +0000627 int Result;
628 if (RemoteMCJIT) {
629 RecordingMemoryManager *MM = static_cast<RecordingMemoryManager*>(JMM);
630 // Everything is prepared now, so lay out our program for the target
631 // address space, assign the section addresses to resolve any relocations,
632 // and send it to the target.
633 RemoteTarget Target;
634 Target.create();
Jim Grosbach5da959d2012-08-28 23:22:30 +0000635
Jim Grosbach706f03a2012-09-05 16:50:34 +0000636 // Ask for a pointer to the entry function. This triggers the actual
637 // compilation.
638 (void)EE->getPointerToFunction(EntryFn);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000639
Jim Grosbach706f03a2012-09-05 16:50:34 +0000640 // Enough has been compiled to execute the entry function now, so
641 // layout the target memory.
642 layoutRemoteTargetMemory(&Target, MM);
Eli Benderskya66a1852012-01-16 08:56:09 +0000643
Jim Grosbach706f03a2012-09-05 16:50:34 +0000644 // Since we're executing in a (at least simulated) remote address space,
645 // we can't use the ExecutionEngine::runFunctionAsMain(). We have to
646 // grab the function address directly here and tell the remote target
647 // to execute the function.
648 // FIXME: argv and envp handling.
649 uint64_t Entry = (uint64_t)EE->getPointerToFunction(EntryFn);
650
651 DEBUG(dbgs() << "Executing '" << EntryFn->getName() << "' at "
652 << format("%#18x", Entry) << "\n");
653
654 if (Target.executeCode(Entry, Result))
655 errs() << "ERROR: " << Target.getErrorMsg() << "\n";
656
657 Target.stop();
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000658 } else {
Jim Grosbach706f03a2012-09-05 16:50:34 +0000659 // Clear instruction cache before code will be executed.
660 if (JMM)
661 static_cast<LLIMCJITMemoryManager*>(JMM)->invalidateInstructionCache();
662
663 // Run main.
664 Result = EE->runFunctionAsMain(EntryFn, InputArgv, envp);
Chris Lattnerc1e6d682007-05-06 04:58:26 +0000665 }
Jim Grosbach706f03a2012-09-05 16:50:34 +0000666
667 // Like static constructors, the remote target MCJIT support doesn't handle
668 // this yet. It could. FIXME.
669 if (!RemoteMCJIT) {
670 // Run static destructors.
671 EE->runStaticConstructorsDestructors(true);
672
673 // If the program didn't call exit explicitly, we should call it now.
674 // This ensures that any atexit handlers get called correctly.
675 if (Function *ExitF = dyn_cast<Function>(Exit)) {
676 std::vector<GenericValue> Args;
677 GenericValue ResultGV;
678 ResultGV.IntVal = APInt(32, Result);
679 Args.push_back(ResultGV);
680 EE->runFunction(ExitF, Args);
681 errs() << "ERROR: exit(" << Result << ") returned!\n";
682 abort();
683 } else {
684 errs() << "ERROR: exit defined with wrong prototype!\n";
685 abort();
686 }
687 }
688 return Result;
Chris Lattner92101ac2001-08-23 17:05:04 +0000689}