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/BasicBlock.h"
11 #include "llvm/Constant.h"
12 #include "llvm/Constants.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/Function.h"
15 #include "llvm/GlobalValue.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/IRBuilder.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/Type.h"
21 #include "llvm/TypeBuilder.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/Assembly/Parser.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/ExecutionEngine/JIT.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TargetSelect.h"
32 #include "gtest/gtest.h"
39 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
40 std::vector<Type*> params;
41 FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
43 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
44 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
45 IRBuilder<> builder(Entry);
46 Value *Load = builder.CreateLoad(G);
47 Type *GTy = G->getType()->getElementType();
48 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
49 builder.CreateStore(Add, G);
50 builder.CreateRet(Add);
54 std::string DumpFunction(const Function *F) {
56 raw_string_ostream(Result) << "" << *F;
60 class RecordingJITMemoryManager : public JITMemoryManager {
61 const OwningPtr<JITMemoryManager> Base;
63 RecordingJITMemoryManager()
64 : Base(JITMemoryManager::CreateDefaultMemManager()) {
67 virtual void *getPointerToNamedFunction(const std::string &Name,
68 bool AbortOnFailure = true) {
69 return Base->getPointerToNamedFunction(Name, AbortOnFailure);
72 virtual void setMemoryWritable() { Base->setMemoryWritable(); }
73 virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
74 virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
75 virtual void AllocateGOT() { Base->AllocateGOT(); }
76 virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
77 struct StartFunctionBodyCall {
78 StartFunctionBodyCall(uint8_t *Result, const Function *F,
79 uintptr_t ActualSize, uintptr_t ActualSizeResult)
80 : Result(Result), F(F), F_dump(DumpFunction(F)),
81 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
86 uintptr_t ActualSizeResult;
88 std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
89 virtual uint8_t *startFunctionBody(const Function *F,
90 uintptr_t &ActualSize) {
91 uintptr_t InitialActualSize = ActualSize;
92 uint8_t *Result = Base->startFunctionBody(F, ActualSize);
93 startFunctionBodyCalls.push_back(
94 StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
98 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
101 return Base->allocateStub(F, StubSize, Alignment);
103 struct EndFunctionBodyCall {
104 EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
105 uint8_t *FunctionEnd)
106 : F(F), F_dump(DumpFunction(F)),
107 FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
110 uint8_t *FunctionStart;
111 uint8_t *FunctionEnd;
113 std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
114 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
115 uint8_t *FunctionEnd) {
116 endFunctionBodyCalls.push_back(
117 EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
118 Base->endFunctionBody(F, FunctionStart, FunctionEnd);
120 virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
121 unsigned SectionID, bool IsReadOnly) {
122 return Base->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
124 virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
125 unsigned SectionID) {
126 return Base->allocateCodeSection(Size, Alignment, SectionID);
128 virtual bool applyPermissions(std::string *ErrMsg) { return false; }
129 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
130 return Base->allocateSpace(Size, Alignment);
132 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
133 return Base->allocateGlobal(Size, Alignment);
135 struct DeallocateFunctionBodyCall {
136 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
139 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
140 virtual void deallocateFunctionBody(void *Body) {
141 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
142 Base->deallocateFunctionBody(Body);
144 struct DeallocateExceptionTableCall {
145 DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
148 std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
149 virtual void deallocateExceptionTable(void *ET) {
150 deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
151 Base->deallocateExceptionTable(ET);
153 struct StartExceptionTableCall {
154 StartExceptionTableCall(uint8_t *Result, const Function *F,
155 uintptr_t ActualSize, uintptr_t ActualSizeResult)
156 : Result(Result), F(F), F_dump(DumpFunction(F)),
157 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
161 uintptr_t ActualSize;
162 uintptr_t ActualSizeResult;
164 std::vector<StartExceptionTableCall> startExceptionTableCalls;
165 virtual uint8_t* startExceptionTable(const Function* F,
166 uintptr_t &ActualSize) {
167 uintptr_t InitialActualSize = ActualSize;
168 uint8_t *Result = Base->startExceptionTable(F, ActualSize);
169 startExceptionTableCalls.push_back(
170 StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
173 struct EndExceptionTableCall {
174 EndExceptionTableCall(const Function *F, uint8_t *TableStart,
175 uint8_t *TableEnd, uint8_t* FrameRegister)
176 : F(F), F_dump(DumpFunction(F)),
177 TableStart(TableStart), TableEnd(TableEnd),
178 FrameRegister(FrameRegister) {}
183 uint8_t *FrameRegister;
185 std::vector<EndExceptionTableCall> endExceptionTableCalls;
186 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
187 uint8_t *TableEnd, uint8_t* FrameRegister) {
188 endExceptionTableCalls.push_back(
189 EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
190 return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
194 bool LoadAssemblyInto(Module *M, const char *assembly) {
197 NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
199 raw_string_ostream os(errMsg);
201 EXPECT_TRUE(success) << os.str();
205 class JITTest : public testing::Test {
207 virtual void SetUp() {
208 M = new Module("<main>", Context);
209 RJMM = new RecordingJITMemoryManager;
210 RJMM->setPoisonMemory(true);
212 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
213 .setJITMemoryManager(RJMM)
214 .setErrorStr(&Error).create());
215 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
218 void LoadAssembly(const char *assembly) {
219 LoadAssemblyInto(M, assembly);
223 Module *M; // Owned by ExecutionEngine.
224 RecordingJITMemoryManager *RJMM;
225 OwningPtr<ExecutionEngine> TheJIT;
228 // Tests on ARM and PowerPC disabled as we're running the old jit
229 #if !defined(__arm__) && !defined(__powerpc__)
231 // Regression test for a bug. The JIT used to allocate globals inside the same
232 // memory block used for the function, and when the function code was freed,
233 // the global was left in the same place. This test allocates a function
234 // that uses and global, deallocates it, and then makes sure that the global
235 // stays alive after that.
236 TEST(JIT, GlobalInFunction) {
238 Module *M = new Module("<main>", context);
240 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
241 // Tell the memory manager to poison freed memory so that accessing freed
242 // memory is more easily tested.
243 MemMgr->setPoisonMemory(true);
245 OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
246 .setEngineKind(EngineKind::JIT)
248 .setJITMemoryManager(MemMgr)
249 // The next line enables the fix:
250 .setAllocateGVsWithCode(false)
252 ASSERT_EQ(Error, "");
254 // Create a global variable.
255 Type *GTy = Type::getInt32Ty(context);
256 GlobalVariable *G = new GlobalVariable(
259 false, // Not constant.
260 GlobalValue::InternalLinkage,
261 Constant::getNullValue(GTy),
264 // Make a function that points to a global.
265 Function *F1 = makeReturnGlobal("F1", G, M);
267 // Get the pointer to the native code to force it to JIT the function and
268 // allocate space for the global.
270 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
272 // Since F1 was codegen'd, a pointer to G should be available.
273 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
274 ASSERT_NE((int32_t*)NULL, GPtr);
277 // F1() should increment G.
281 // Make a second function identical to the first, referring to the same
283 Function *F2 = makeReturnGlobal("F2", G, M);
285 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
287 // F2() should increment G.
292 JIT->freeMachineCodeForFunction(F1);
294 // F2() should *still* increment G.
299 #endif // !defined(__arm__) && !defined(__powerpc__)
301 int PlusOne(int arg) {
305 // ARM and PowerPC tests disabled pending fix for PR10783.
306 #if !defined(__arm__) && !defined(__powerpc__)
307 TEST_F(JITTest, FarCallToKnownFunction) {
308 // x86-64 can only make direct calls to functions within 32 bits of
309 // the current PC. To call anything farther away, we have to load
310 // the address into a register and call through the register. The
311 // current JIT does this by allocating a stub for any far call.
312 // There was a bug in which the JIT tried to emit a direct call when
313 // the target was already in the JIT's global mappings and lazy
314 // compilation was disabled.
316 Function *KnownFunction = Function::Create(
317 TypeBuilder<int(int), false>::get(Context),
318 GlobalValue::ExternalLinkage, "known", M);
319 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
321 // int test() { return known(7); }
322 Function *TestFunction = Function::Create(
323 TypeBuilder<int(), false>::get(Context),
324 GlobalValue::ExternalLinkage, "test", M);
325 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
326 IRBuilder<> Builder(Entry);
327 Value *result = Builder.CreateCall(
329 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
330 Builder.CreateRet(result);
332 TheJIT->DisableLazyCompilation(true);
333 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
334 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
335 // This used to crash in trying to call PlusOne().
336 EXPECT_EQ(8, TestFunctionPtr());
339 // Test a function C which calls A and B which call each other.
340 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
341 TheJIT->DisableLazyCompilation(true);
343 FunctionType *Func1Ty =
344 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
345 std::vector<Type*> arg_types;
346 arg_types.push_back(Type::getInt1Ty(Context));
347 FunctionType *FuncTy = FunctionType::get(
348 Type::getVoidTy(Context), arg_types, false);
349 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
351 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
353 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
355 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
356 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
357 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
358 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
359 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
360 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
361 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
363 // Make Func1 call Func2(0) and Func3(0).
364 IRBuilder<> Builder(Block1);
365 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
366 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
367 Builder.CreateRetVoid();
369 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
370 Builder.SetInsertPoint(Block2);
371 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
372 Builder.SetInsertPoint(True2);
373 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
374 Builder.CreateRetVoid();
375 Builder.SetInsertPoint(False2);
376 Builder.CreateRetVoid();
378 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
379 Builder.SetInsertPoint(Block3);
380 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
381 Builder.SetInsertPoint(True3);
382 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
383 Builder.CreateRetVoid();
384 Builder.SetInsertPoint(False3);
385 Builder.CreateRetVoid();
387 // Compile the function to native code
389 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
394 // Regression test for PR5162. This used to trigger an AssertingVH inside the
395 // JIT's Function to stub mapping.
396 TEST_F(JITTest, NonLazyLeaksNoStubs) {
397 TheJIT->DisableLazyCompilation(true);
399 // Create two functions with a single basic block each.
400 FunctionType *FuncTy =
401 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
402 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
404 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
406 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
407 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
409 // The first function calls the second and returns the result
410 IRBuilder<> Builder(Block1);
411 Value *Result = Builder.CreateCall(Func2);
412 Builder.CreateRet(Result);
414 // The second function just returns a constant
415 Builder.SetInsertPoint(Block2);
416 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
418 // Compile the function to native code
419 (void)TheJIT->getPointerToFunction(Func1);
421 // Free the JIT state for the functions
422 TheJIT->freeMachineCodeForFunction(Func1);
423 TheJIT->freeMachineCodeForFunction(Func2);
425 // Delete the first function (and show that is has no users)
426 EXPECT_EQ(Func1->getNumUses(), 0u);
427 Func1->eraseFromParent();
429 // Delete the second function (and show that it has no users - it had one,
430 // func1 but that's gone now)
431 EXPECT_EQ(Func2->getNumUses(), 0u);
432 Func2->eraseFromParent();
435 TEST_F(JITTest, ModuleDeletion) {
436 TheJIT->DisableLazyCompilation(false);
437 LoadAssembly("define void @main() { "
438 " call i32 @computeVal() "
442 "define internal i32 @computeVal() { "
445 Function *func = M->getFunction("main");
446 TheJIT->getPointerToFunction(func);
447 TheJIT->removeModule(M);
450 SmallPtrSet<const void*, 2> FunctionsDeallocated;
451 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
453 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
455 for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
456 EXPECT_TRUE(FunctionsDeallocated.count(
457 RJMM->startFunctionBodyCalls[i].Result))
458 << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
460 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
461 RJMM->deallocateFunctionBodyCalls.size());
463 SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
464 unsigned NumTablesDeallocated = 0;
465 for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
467 ExceptionTablesDeallocated.insert(
468 RJMM->deallocateExceptionTableCalls[i].ET);
469 if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
470 // If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
471 // appear in startExceptionTableCalls.
472 NumTablesDeallocated++;
475 for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
476 EXPECT_TRUE(ExceptionTablesDeallocated.count(
477 RJMM->startExceptionTableCalls[i].Result))
478 << "Function's exception table leaked: \n"
479 << RJMM->startExceptionTableCalls[i].F_dump;
481 EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
482 NumTablesDeallocated);
484 #endif // !defined(__arm__) && !defined(__powerpc__)
486 // ARM, MIPS and PPC still emit stubs for calls since the target may be
487 // too far away to call directly. This #if can probably be removed when
488 // http://llvm.org/PR5201 is fixed.
489 #if !defined(__arm__) && !defined(__mips__) && \
490 !defined(__powerpc__) && !defined(__ppc__)
491 typedef int (*FooPtr) ();
493 TEST_F(JITTest, NoStubs) {
494 LoadAssembly("define void @bar() {"
499 "define i32 @foo() {"
505 "define i32 @main() {"
507 "%0 = call i32 @foo()"
511 Function *foo = M->getFunction("foo");
512 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
513 FooPtr ptr = (FooPtr)(tmp);
517 // We should now allocate no more stubs, we have the code to foo
518 // and the existing stub for bar.
519 int stubsBefore = RJMM->stubsAllocated;
520 Function *func = M->getFunction("main");
521 TheJIT->getPointerToFunction(func);
523 Function *bar = M->getFunction("bar");
524 TheJIT->getPointerToFunction(bar);
526 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
528 #endif // !ARM && !PPC
530 // Tests on ARM and PowerPC disabled as we're running the old jit
531 #if !defined(__arm__) && !defined(__powerpc__)
533 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
534 TheJIT->DisableLazyCompilation(true);
535 LoadAssembly("define i8()* @get_foo_addr() { "
539 "define i8 @foo() { "
542 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
544 typedef char(*fooT)();
545 fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
546 (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
547 fooT foo_addr = get_foo_addr();
549 // Now free get_foo_addr. This should not free the machine code for foo or
550 // any call stub returned as foo's canonical address.
551 TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
553 // Check by calling the reported address of foo.
554 EXPECT_EQ(42, foo_addr());
556 // The reported address should also be the same as the result of a subsequent
557 // getPointerToFunction(foo).
559 // Fails until PR5126 is fixed:
560 Function *F_foo = M->getFunction("foo");
561 fooT foo = reinterpret_cast<fooT>(
562 (intptr_t)TheJIT->getPointerToFunction(F_foo));
563 EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
567 #endif //!defined(__arm__) && !defined(__powerpc__)
569 // Tests on ARM and PowerPC disabled as we're running the old jit
570 // In addition, ARM does not have an implementation
571 // of replaceMachineCodeForFunction(), so recompileAndRelinkFunction
573 #if !defined(__arm__) && !defined(__powerpc__)
574 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
575 Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
576 GlobalValue::ExternalLinkage, "test", M);
577 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
578 IRBuilder<> Builder(Entry);
579 Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
580 Builder.CreateRet(Val);
582 TheJIT->DisableLazyCompilation(true);
583 // Compile the function once, and make sure it works.
584 int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
585 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
586 EXPECT_EQ(1, OrigFPtr());
588 // Now change the function to return a different value.
589 Entry->eraseFromParent();
590 BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
591 Builder.SetInsertPoint(NewEntry);
592 Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
593 Builder.CreateRet(Val);
594 // Recompile it, which should produce a new function pointer _and_ update the
596 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
597 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
599 EXPECT_EQ(2, NewFPtr())
600 << "The new pointer should call the new version of the function";
601 EXPECT_EQ(2, OrigFPtr())
602 << "The old pointer's target should now jump to the new version";
604 #endif // !defined(__arm__) && !defined(__powerpc__)
606 } // anonymous namespace
607 // This variable is intentionally defined differently in the statically-compiled
608 // program from the IR input to the JIT to assert that the JIT doesn't use its
610 extern "C" int32_t JITTest_AvailableExternallyGlobal;
611 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
614 // Tests on ARM and PowerPC disabled as we're running the old jit
615 #if !defined(__arm__) && !defined(__powerpc__)
617 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
618 TheJIT->DisableLazyCompilation(true);
619 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
620 " available_externally global i32 7 "
622 "define i32 @loader() { "
623 " %result = load i32* @JITTest_AvailableExternallyGlobal "
626 Function *loaderIR = M->getFunction("loader");
628 int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
629 (intptr_t)TheJIT->getPointerToFunction(loaderIR));
630 EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
631 << " not 7 from the IR version.";
633 #endif //!defined(__arm__) && !defined(__powerpc__)
634 } // anonymous namespace
635 // This function is intentionally defined differently in the statically-compiled
636 // program from the IR input to the JIT to assert that the JIT doesn't use its
638 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
639 extern "C" int32_t JITTest_AvailableExternallyFunction() {
644 // ARM and PowerPC tests disabled pending fix for PR10783.
645 #if !defined(__arm__) && !defined(__powerpc__)
646 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
647 TheJIT->DisableLazyCompilation(true);
648 LoadAssembly("define available_externally i32 "
649 " @JITTest_AvailableExternallyFunction() { "
653 "define i32 @func() { "
654 " %result = tail call i32 "
655 " @JITTest_AvailableExternallyFunction() "
658 Function *funcIR = M->getFunction("func");
660 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
661 (intptr_t)TheJIT->getPointerToFunction(funcIR));
662 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
663 << " not 7 from the IR version.";
666 TEST_F(JITTest, EscapedLazyStubStillCallable) {
667 TheJIT->DisableLazyCompilation(false);
668 LoadAssembly("define internal i32 @stubbed() { "
672 "define i32()* @get_stub() { "
673 " ret i32()* @stubbed "
675 typedef int32_t(*StubTy)();
677 // Call get_stub() to get the address of @stubbed without actually JITting it.
678 Function *get_stubIR = M->getFunction("get_stub");
679 StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
680 (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
681 StubTy stubbed = get_stub();
682 // Now get_stubIR is the only reference to stubbed's stub.
683 get_stubIR->eraseFromParent();
684 // Now there are no references inside the JIT, but we've got a pointer outside
685 // it. The stub should be callable and return the right value.
686 EXPECT_EQ(42, stubbed());
689 // Converts the LLVM assembly to bitcode and returns it in a std::string. An
690 // empty string indicates an error.
691 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
692 Module TempModule("TempModule", Context);
693 if (!LoadAssemblyInto(&TempModule, Assembly)) {
698 raw_string_ostream OS(Result);
699 WriteBitcodeToFile(&TempModule, OS);
704 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
705 // lazily. The associated Module (owned by the ExecutionEngine) is returned in
706 // M. Both will be NULL on an error. Bitcode must live at least as long as the
708 ExecutionEngine *getJITFromBitcode(
709 LLVMContext &Context, const std::string &Bitcode, Module *&M) {
710 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
711 MemoryBuffer *BitcodeBuffer =
712 MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
714 M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
716 ADD_FAILURE() << errMsg;
717 delete BitcodeBuffer;
720 ExecutionEngine *TheJIT = EngineBuilder(M)
721 .setEngineKind(EngineKind::JIT)
722 .setErrorStr(&errMsg)
724 if (TheJIT == NULL) {
725 ADD_FAILURE() << errMsg;
733 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
735 const std::string Bitcode =
736 AssembleToBitcode(Context,
737 "define available_externally i32 "
738 " @JITTest_AvailableExternallyFunction() { "
742 "define i32 @func() { "
743 " %result = tail call i32 "
744 " @JITTest_AvailableExternallyFunction() "
747 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
749 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
750 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
751 TheJIT->DisableLazyCompilation(true);
753 Function *funcIR = M->getFunction("func");
754 Function *availableFunctionIR =
755 M->getFunction("JITTest_AvailableExternallyFunction");
757 // Double-check that the available_externally function is still unmaterialized
758 // when getPointerToFunction needs to find out if it's available_externally.
759 EXPECT_TRUE(availableFunctionIR->isMaterializable());
761 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
762 (intptr_t)TheJIT->getPointerToFunction(funcIR));
763 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
764 << " not 7 from the IR version.";
767 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
769 const std::string Bitcode =
770 AssembleToBitcode(Context,
771 "define i32 @recur1(i32 %a) { "
772 " %zero = icmp eq i32 %a, 0 "
773 " br i1 %zero, label %done, label %notdone "
777 " %am1 = sub i32 %a, 1 "
778 " %result = call i32 @recur2(i32 %am1) "
782 "define i32 @recur2(i32 %b) { "
783 " %result = call i32 @recur1(i32 %b) "
786 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
788 OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
789 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
790 TheJIT->DisableLazyCompilation(true);
792 Function *recur1IR = M->getFunction("recur1");
793 Function *recur2IR = M->getFunction("recur2");
794 EXPECT_TRUE(recur1IR->isMaterializable());
795 EXPECT_TRUE(recur2IR->isMaterializable());
797 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
798 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
799 EXPECT_EQ(3, recur1(4));
801 #endif // !defined(__arm__) && !defined(__powerpc__)
803 // This code is copied from JITEventListenerTest, but it only runs once for all
804 // the tests in this directory. Everything seems fine, but that's strange
806 class JITEnvironment : public testing::Environment {
807 virtual void SetUp() {
808 // Required to create a JIT.
809 InitializeNativeTarget();
812 testing::Environment* const jit_env =
813 testing::AddGlobalTestEnvironment(new JITEnvironment);