1 //===- JITTest.cpp - Unit tests for the JIT -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ExecutionEngine/JIT.h"
11 #include "llvm/ADT/OwningPtr.h"
12 #include "llvm/ADT/SmallPtrSet.h"
13 #include "llvm/Assembly/Parser.h"
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/ExecutionEngine/JITMemoryManager.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Constant.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/IR/TypeBuilder.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TargetSelect.h"
31 #include "gtest/gtest.h"
38 // Tests on ARM and PowerPC disabled as we're running the old jit
39 #if !defined(__arm__) && !defined(__powerpc__)
41 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
42 std::vector<Type*> params;
43 FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
45 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
46 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
47 IRBuilder<> builder(Entry);
48 Value *Load = builder.CreateLoad(G);
49 Type *GTy = G->getType()->getElementType();
50 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
51 builder.CreateStore(Add, G);
52 builder.CreateRet(Add);
56 std::string DumpFunction(const Function *F) {
58 raw_string_ostream(Result) << "" << *F;
62 class RecordingJITMemoryManager : public JITMemoryManager {
63 const OwningPtr<JITMemoryManager> Base;
65 RecordingJITMemoryManager()
66 : Base(JITMemoryManager::CreateDefaultMemManager()) {
69 virtual void *getPointerToNamedFunction(const std::string &Name,
70 bool AbortOnFailure = true) {
71 return Base->getPointerToNamedFunction(Name, AbortOnFailure);
74 virtual void setMemoryWritable() { Base->setMemoryWritable(); }
75 virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
76 virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
77 virtual void AllocateGOT() { Base->AllocateGOT(); }
78 virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
79 struct StartFunctionBodyCall {
80 StartFunctionBodyCall(uint8_t *Result, const Function *F,
81 uintptr_t ActualSize, uintptr_t ActualSizeResult)
82 : Result(Result), F(F), F_dump(DumpFunction(F)),
83 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
88 uintptr_t ActualSizeResult;
90 std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
91 virtual uint8_t *startFunctionBody(const Function *F,
92 uintptr_t &ActualSize) {
93 uintptr_t InitialActualSize = ActualSize;
94 uint8_t *Result = Base->startFunctionBody(F, ActualSize);
95 startFunctionBodyCalls.push_back(
96 StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
100 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
101 unsigned Alignment) {
103 return Base->allocateStub(F, StubSize, Alignment);
105 struct EndFunctionBodyCall {
106 EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
107 uint8_t *FunctionEnd)
108 : F(F), F_dump(DumpFunction(F)),
109 FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
112 uint8_t *FunctionStart;
113 uint8_t *FunctionEnd;
115 std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
116 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
117 uint8_t *FunctionEnd) {
118 endFunctionBodyCalls.push_back(
119 EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
120 Base->endFunctionBody(F, FunctionStart, FunctionEnd);
122 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
123 unsigned SectionID, bool IsReadOnly) {
124 return Base->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
126 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
127 unsigned SectionID) {
128 return Base->allocateCodeSection(Size, Alignment, SectionID);
130 virtual bool applyPermissions(std::string *ErrMsg) { return false; }
131 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
132 return Base->allocateSpace(Size, Alignment);
134 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
135 return Base->allocateGlobal(Size, Alignment);
137 struct DeallocateFunctionBodyCall {
138 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
141 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
142 virtual void deallocateFunctionBody(void *Body) {
143 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
144 Base->deallocateFunctionBody(Body);
146 struct DeallocateExceptionTableCall {
147 DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
150 std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
151 virtual void deallocateExceptionTable(void *ET) {
152 deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
153 Base->deallocateExceptionTable(ET);
155 struct StartExceptionTableCall {
156 StartExceptionTableCall(uint8_t *Result, const Function *F,
157 uintptr_t ActualSize, uintptr_t ActualSizeResult)
158 : Result(Result), F(F), F_dump(DumpFunction(F)),
159 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
163 uintptr_t ActualSize;
164 uintptr_t ActualSizeResult;
166 std::vector<StartExceptionTableCall> startExceptionTableCalls;
167 virtual uint8_t *startExceptionTable(const Function *F,
168 uintptr_t &ActualSize) {
169 uintptr_t InitialActualSize = ActualSize;
170 uint8_t *Result = Base->startExceptionTable(F, ActualSize);
171 startExceptionTableCalls.push_back(
172 StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
175 struct EndExceptionTableCall {
176 EndExceptionTableCall(const Function *F, uint8_t *TableStart,
177 uint8_t *TableEnd, uint8_t* FrameRegister)
178 : F(F), F_dump(DumpFunction(F)),
179 TableStart(TableStart), TableEnd(TableEnd),
180 FrameRegister(FrameRegister) {}
185 uint8_t *FrameRegister;
187 std::vector<EndExceptionTableCall> endExceptionTableCalls;
188 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
189 uint8_t *TableEnd, uint8_t* FrameRegister) {
190 endExceptionTableCalls.push_back(
191 EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
192 return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
196 bool LoadAssemblyInto(Module *M, const char *assembly) {
199 NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
201 raw_string_ostream os(errMsg);
203 EXPECT_TRUE(success) << os.str();
207 class JITTest : public testing::Test {
209 virtual RecordingJITMemoryManager *createMemoryManager() {
210 return new RecordingJITMemoryManager;
213 virtual void SetUp() {
214 M = new Module("<main>", Context);
215 RJMM = createMemoryManager();
216 RJMM->setPoisonMemory(true);
218 TargetOptions Options;
219 Options.JITExceptionHandling = true;
220 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
221 .setJITMemoryManager(RJMM)
223 .setTargetOptions(Options).create());
224 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
227 void LoadAssembly(const char *assembly) {
228 LoadAssemblyInto(M, assembly);
232 Module *M; // Owned by ExecutionEngine.
233 RecordingJITMemoryManager *RJMM;
234 OwningPtr<ExecutionEngine> TheJIT;
237 // Regression test for a bug. The JIT used to allocate globals inside the same
238 // memory block used for the function, and when the function code was freed,
239 // the global was left in the same place. This test allocates a function
240 // that uses and global, deallocates it, and then makes sure that the global
241 // stays alive after that.
242 TEST(JIT, GlobalInFunction) {
244 Module *M = new Module("<main>", context);
246 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
247 // Tell the memory manager to poison freed memory so that accessing freed
248 // memory is more easily tested.
249 MemMgr->setPoisonMemory(true);
251 OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
252 .setEngineKind(EngineKind::JIT)
254 .setJITMemoryManager(MemMgr)
255 // The next line enables the fix:
256 .setAllocateGVsWithCode(false)
258 ASSERT_EQ(Error, "");
260 // Create a global variable.
261 Type *GTy = Type::getInt32Ty(context);
262 GlobalVariable *G = new GlobalVariable(
265 false, // Not constant.
266 GlobalValue::InternalLinkage,
267 Constant::getNullValue(GTy),
270 // Make a function that points to a global.
271 Function *F1 = makeReturnGlobal("F1", G, M);
273 // Get the pointer to the native code to force it to JIT the function and
274 // allocate space for the global.
276 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
278 // Since F1 was codegen'd, a pointer to G should be available.
279 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
280 ASSERT_NE((int32_t*)NULL, GPtr);
283 // F1() should increment G.
287 // Make a second function identical to the first, referring to the same
289 Function *F2 = makeReturnGlobal("F2", G, M);
291 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
293 // F2() should increment G.
298 JIT->freeMachineCodeForFunction(F1);
300 // F2() should *still* increment G.
305 // Regression test for a bug. The JITEmitter wasn't checking to verify that
306 // it hadn't run out of space while generating the DWARF exception information
307 // for an emitted function.
309 class ExceptionMemoryManagerMock : public RecordingJITMemoryManager {
311 virtual uint8_t *startExceptionTable(const Function *F,
312 uintptr_t &ActualSize) {
313 // force an insufficient size the first time through.
314 bool ChangeActualSize = false;
316 ChangeActualSize = true;;
318 RecordingJITMemoryManager::startExceptionTable(F, ActualSize);
319 if (ChangeActualSize)
325 class JITExceptionMemoryTest : public JITTest {
327 virtual RecordingJITMemoryManager *createMemoryManager() {
328 return new ExceptionMemoryManagerMock;
332 TEST_F(JITExceptionMemoryTest, ExceptionTableOverflow) {
333 Function *F = Function::Create(TypeBuilder<void(void), false>::get(Context),
334 Function::ExternalLinkage,
336 BasicBlock *Block = BasicBlock::Create(Context, "block", F);
337 IRBuilder<> Builder(Block);
338 Builder.CreateRetVoid();
339 TheJIT->getPointerToFunction(F);
340 ASSERT_TRUE(RJMM->startExceptionTableCalls.size() == 2);
341 ASSERT_TRUE(RJMM->deallocateExceptionTableCalls.size() == 1);
342 ASSERT_TRUE(RJMM->endExceptionTableCalls.size() == 1);
345 int PlusOne(int arg) {
349 TEST_F(JITTest, FarCallToKnownFunction) {
350 // x86-64 can only make direct calls to functions within 32 bits of
351 // the current PC. To call anything farther away, we have to load
352 // the address into a register and call through the register. The
353 // current JIT does this by allocating a stub for any far call.
354 // There was a bug in which the JIT tried to emit a direct call when
355 // the target was already in the JIT's global mappings and lazy
356 // compilation was disabled.
358 Function *KnownFunction = Function::Create(
359 TypeBuilder<int(int), false>::get(Context),
360 GlobalValue::ExternalLinkage, "known", M);
361 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
363 // int test() { return known(7); }
364 Function *TestFunction = Function::Create(
365 TypeBuilder<int(), false>::get(Context),
366 GlobalValue::ExternalLinkage, "test", M);
367 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
368 IRBuilder<> Builder(Entry);
369 Value *result = Builder.CreateCall(
371 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
372 Builder.CreateRet(result);
374 TheJIT->DisableLazyCompilation(true);
375 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
376 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
377 // This used to crash in trying to call PlusOne().
378 EXPECT_EQ(8, TestFunctionPtr());
381 // Test a function C which calls A and B which call each other.
382 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
383 TheJIT->DisableLazyCompilation(true);
385 FunctionType *Func1Ty =
386 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
387 std::vector<Type*> arg_types;
388 arg_types.push_back(Type::getInt1Ty(Context));
389 FunctionType *FuncTy = FunctionType::get(
390 Type::getVoidTy(Context), arg_types, false);
391 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
393 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
395 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
397 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
398 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
399 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
400 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
401 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
402 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
403 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
405 // Make Func1 call Func2(0) and Func3(0).
406 IRBuilder<> Builder(Block1);
407 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
408 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
409 Builder.CreateRetVoid();
411 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
412 Builder.SetInsertPoint(Block2);
413 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
414 Builder.SetInsertPoint(True2);
415 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
416 Builder.CreateRetVoid();
417 Builder.SetInsertPoint(False2);
418 Builder.CreateRetVoid();
420 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
421 Builder.SetInsertPoint(Block3);
422 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
423 Builder.SetInsertPoint(True3);
424 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
425 Builder.CreateRetVoid();
426 Builder.SetInsertPoint(False3);
427 Builder.CreateRetVoid();
429 // Compile the function to native code
431 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
436 // Regression test for PR5162. This used to trigger an AssertingVH inside the
437 // JIT's Function to stub mapping.
438 TEST_F(JITTest, NonLazyLeaksNoStubs) {
439 TheJIT->DisableLazyCompilation(true);
441 // Create two functions with a single basic block each.
442 FunctionType *FuncTy =
443 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
444 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
446 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
448 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
449 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
451 // The first function calls the second and returns the result
452 IRBuilder<> Builder(Block1);
453 Value *Result = Builder.CreateCall(Func2);
454 Builder.CreateRet(Result);
456 // The second function just returns a constant
457 Builder.SetInsertPoint(Block2);
458 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
460 // Compile the function to native code
461 (void)TheJIT->getPointerToFunction(Func1);
463 // Free the JIT state for the functions
464 TheJIT->freeMachineCodeForFunction(Func1);
465 TheJIT->freeMachineCodeForFunction(Func2);
467 // Delete the first function (and show that is has no users)
468 EXPECT_EQ(Func1->getNumUses(), 0u);
469 Func1->eraseFromParent();
471 // Delete the second function (and show that it has no users - it had one,
472 // func1 but that's gone now)
473 EXPECT_EQ(Func2->getNumUses(), 0u);
474 Func2->eraseFromParent();
477 TEST_F(JITTest, ModuleDeletion) {
478 TheJIT->DisableLazyCompilation(false);
479 LoadAssembly("define void @main() { "
480 " call i32 @computeVal() "
484 "define internal i32 @computeVal() { "
487 Function *func = M->getFunction("main");
488 TheJIT->getPointerToFunction(func);
489 TheJIT->removeModule(M);
492 SmallPtrSet<const void*, 2> FunctionsDeallocated;
493 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
495 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
497 for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
498 EXPECT_TRUE(FunctionsDeallocated.count(
499 RJMM->startFunctionBodyCalls[i].Result))
500 << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
502 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
503 RJMM->deallocateFunctionBodyCalls.size());
505 SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
506 unsigned NumTablesDeallocated = 0;
507 for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
509 ExceptionTablesDeallocated.insert(
510 RJMM->deallocateExceptionTableCalls[i].ET);
511 if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
512 // If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
513 // appear in startExceptionTableCalls.
514 NumTablesDeallocated++;
517 for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
518 EXPECT_TRUE(ExceptionTablesDeallocated.count(
519 RJMM->startExceptionTableCalls[i].Result))
520 << "Function's exception table leaked: \n"
521 << RJMM->startExceptionTableCalls[i].F_dump;
523 EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
524 NumTablesDeallocated);
527 // ARM, MIPS and PPC still emit stubs for calls since the target may be
528 // too far away to call directly. This #if can probably be removed when
529 // http://llvm.org/PR5201 is fixed.
530 #if !defined(__arm__) && !defined(__mips__) && \
531 !defined(__powerpc__) && !defined(__ppc__)
532 typedef int (*FooPtr) ();
534 TEST_F(JITTest, NoStubs) {
535 LoadAssembly("define void @bar() {"
540 "define i32 @foo() {"
546 "define i32 @main() {"
548 "%0 = call i32 @foo()"
552 Function *foo = M->getFunction("foo");
553 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
554 FooPtr ptr = (FooPtr)(tmp);
558 // We should now allocate no more stubs, we have the code to foo
559 // and the existing stub for bar.
560 int stubsBefore = RJMM->stubsAllocated;
561 Function *func = M->getFunction("main");
562 TheJIT->getPointerToFunction(func);
564 Function *bar = M->getFunction("bar");
565 TheJIT->getPointerToFunction(bar);
567 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
569 #endif // !ARM && !PPC
571 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
572 TheJIT->DisableLazyCompilation(true);
573 LoadAssembly("define i8()* @get_foo_addr() { "
577 "define i8 @foo() { "
580 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
582 typedef char(*fooT)();
583 fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
584 (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
585 fooT foo_addr = get_foo_addr();
587 // Now free get_foo_addr. This should not free the machine code for foo or
588 // any call stub returned as foo's canonical address.
589 TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
591 // Check by calling the reported address of foo.
592 EXPECT_EQ(42, foo_addr());
594 // The reported address should also be the same as the result of a subsequent
595 // getPointerToFunction(foo).
597 // Fails until PR5126 is fixed:
598 Function *F_foo = M->getFunction("foo");
599 fooT foo = reinterpret_cast<fooT>(
600 (intptr_t)TheJIT->getPointerToFunction(F_foo));
601 EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
605 // ARM does not have an implementation of replaceMachineCodeForFunction(),
606 // so recompileAndRelinkFunction doesn't work.
607 #if !defined(__arm__)
608 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
609 Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
610 GlobalValue::ExternalLinkage, "test", M);
611 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
612 IRBuilder<> Builder(Entry);
613 Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
614 Builder.CreateRet(Val);
616 TheJIT->DisableLazyCompilation(true);
617 // Compile the function once, and make sure it works.
618 int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
619 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
620 EXPECT_EQ(1, OrigFPtr());
622 // Now change the function to return a different value.
623 Entry->eraseFromParent();
624 BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
625 Builder.SetInsertPoint(NewEntry);
626 Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
627 Builder.CreateRet(Val);
628 // Recompile it, which should produce a new function pointer _and_ update the
630 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
631 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
633 EXPECT_EQ(2, NewFPtr())
634 << "The new pointer should call the new version of the function";
635 EXPECT_EQ(2, OrigFPtr())
636 << "The old pointer's target should now jump to the new version";
638 #endif // !defined(__arm__)
640 } // anonymous namespace
641 // This variable is intentionally defined differently in the statically-compiled
642 // program from the IR input to the JIT to assert that the JIT doesn't use its
644 extern "C" int32_t JITTest_AvailableExternallyGlobal;
645 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
648 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
649 TheJIT->DisableLazyCompilation(true);
650 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
651 " available_externally global i32 7 "
653 "define i32 @loader() { "
654 " %result = load i32* @JITTest_AvailableExternallyGlobal "
657 Function *loaderIR = M->getFunction("loader");
659 int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
660 (intptr_t)TheJIT->getPointerToFunction(loaderIR));
661 EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
662 << " not 7 from the IR version.";
664 } // anonymous namespace
665 // This function is intentionally defined differently in the statically-compiled
666 // program from the IR input to the JIT to assert that the JIT doesn't use its
668 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
669 extern "C" int32_t JITTest_AvailableExternallyFunction() {
674 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
675 TheJIT->DisableLazyCompilation(true);
676 LoadAssembly("define available_externally i32 "
677 " @JITTest_AvailableExternallyFunction() { "
681 "define i32 @func() { "
682 " %result = tail call i32 "
683 " @JITTest_AvailableExternallyFunction() "
686 Function *funcIR = M->getFunction("func");
688 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
689 (intptr_t)TheJIT->getPointerToFunction(funcIR));
690 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
691 << " not 7 from the IR version.";
694 TEST_F(JITTest, EscapedLazyStubStillCallable) {
695 TheJIT->DisableLazyCompilation(false);
696 LoadAssembly("define internal i32 @stubbed() { "
700 "define i32()* @get_stub() { "
701 " ret i32()* @stubbed "
703 typedef int32_t(*StubTy)();
705 // Call get_stub() to get the address of @stubbed without actually JITting it.
706 Function *get_stubIR = M->getFunction("get_stub");
707 StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
708 (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
709 StubTy stubbed = get_stub();
710 // Now get_stubIR is the only reference to stubbed's stub.
711 get_stubIR->eraseFromParent();
712 // Now there are no references inside the JIT, but we've got a pointer outside
713 // it. The stub should be callable and return the right value.
714 EXPECT_EQ(42, stubbed());
717 // Converts the LLVM assembly to bitcode and returns it in a std::string. An
718 // empty string indicates an error.
719 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
720 Module TempModule("TempModule", Context);
721 if (!LoadAssemblyInto(&TempModule, Assembly)) {
726 raw_string_ostream OS(Result);
727 WriteBitcodeToFile(&TempModule, OS);
732 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
733 // lazily. The associated Module (owned by the ExecutionEngine) is returned in
734 // M. Both will be NULL on an error. Bitcode must live at least as long as the
736 ExecutionEngine *getJITFromBitcode(
737 LLVMContext &Context, const std::string &Bitcode, Module *&M) {
738 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
739 MemoryBuffer *BitcodeBuffer =
740 MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
742 M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
744 ADD_FAILURE() << errMsg;
745 delete BitcodeBuffer;
748 ExecutionEngine *TheJIT = EngineBuilder(M)
749 .setEngineKind(EngineKind::JIT)
750 .setErrorStr(&errMsg)
752 if (TheJIT == NULL) {
753 ADD_FAILURE() << errMsg;
761 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
763 const std::string Bitcode =
764 AssembleToBitcode(Context,
765 "define available_externally i32 "
766 " @JITTest_AvailableExternallyFunction() { "
770 "define i32 @func() { "
771 " %result = tail call i32 "
772 " @JITTest_AvailableExternallyFunction() "
775 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
777 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
778 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
779 TheJIT->DisableLazyCompilation(true);
781 Function *funcIR = M->getFunction("func");
782 Function *availableFunctionIR =
783 M->getFunction("JITTest_AvailableExternallyFunction");
785 // Double-check that the available_externally function is still unmaterialized
786 // when getPointerToFunction needs to find out if it's available_externally.
787 EXPECT_TRUE(availableFunctionIR->isMaterializable());
789 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
790 (intptr_t)TheJIT->getPointerToFunction(funcIR));
791 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
792 << " not 7 from the IR version.";
795 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
797 const std::string Bitcode =
798 AssembleToBitcode(Context,
799 "define i32 @recur1(i32 %a) { "
800 " %zero = icmp eq i32 %a, 0 "
801 " br i1 %zero, label %done, label %notdone "
805 " %am1 = sub i32 %a, 1 "
806 " %result = call i32 @recur2(i32 %am1) "
810 "define i32 @recur2(i32 %b) { "
811 " %result = call i32 @recur1(i32 %b) "
814 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
816 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
817 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
818 TheJIT->DisableLazyCompilation(true);
820 Function *recur1IR = M->getFunction("recur1");
821 Function *recur2IR = M->getFunction("recur2");
822 EXPECT_TRUE(recur1IR->isMaterializable());
823 EXPECT_TRUE(recur2IR->isMaterializable());
825 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
826 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
827 EXPECT_EQ(3, recur1(4));
829 #endif // !defined(__arm__) && !defined(__powerpc__)
831 // This code is copied from JITEventListenerTest, but it only runs once for all
832 // the tests in this directory. Everything seems fine, but that's strange
834 class JITEnvironment : public testing::Environment {
835 virtual void SetUp() {
836 // Required to create a JIT.
837 InitializeNativeTarget();
840 testing::Environment* const jit_env =
841 testing::AddGlobalTestEnvironment(new JITEnvironment);