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/SmallPtrSet.h"
12 #include "llvm/AsmParser/Parser.h"
13 #include "llvm/Bitcode/ReaderWriter.h"
14 #include "llvm/ExecutionEngine/JITMemoryManager.h"
15 #include "llvm/IR/BasicBlock.h"
16 #include "llvm/IR/Constant.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalValue.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/IR/TypeBuilder.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "gtest/gtest.h"
35 // This variable is intentionally defined differently in the statically-compiled
36 // program from the IR input to the JIT to assert that the JIT doesn't use its
37 // definition. Note that this variable must be defined even on platforms where
38 // JIT tests are disabled as it is referenced from the .def file.
39 extern "C" int32_t JITTest_AvailableExternallyGlobal;
40 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
42 // This function is intentionally defined differently in the statically-compiled
43 // program from the IR input to the JIT to assert that the JIT doesn't use its
44 // definition. Note that this function must be defined even on platforms where
45 // JIT tests are disabled as it is referenced from the .def file.
46 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
47 extern "C" int32_t JITTest_AvailableExternallyFunction() {
53 // Tests on ARM, PowerPC and SystemZ disabled as we're running the old jit
54 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__) \
55 && !defined(__aarch64__)
57 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
58 std::vector<Type*> params;
59 FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
61 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
62 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
63 IRBuilder<> builder(Entry);
64 Value *Load = builder.CreateLoad(G);
65 Type *GTy = G->getType()->getElementType();
66 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
67 builder.CreateStore(Add, G);
68 builder.CreateRet(Add);
72 std::string DumpFunction(const Function *F) {
73 string_ostream Result;
78 class RecordingJITMemoryManager : public JITMemoryManager {
79 const std::unique_ptr<JITMemoryManager> Base;
82 RecordingJITMemoryManager()
83 : Base(JITMemoryManager::CreateDefaultMemManager()) {
86 virtual void *getPointerToNamedFunction(const std::string &Name,
87 bool AbortOnFailure = true) {
88 return Base->getPointerToNamedFunction(Name, AbortOnFailure);
91 virtual void setMemoryWritable() { Base->setMemoryWritable(); }
92 virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
93 virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
94 virtual void AllocateGOT() { Base->AllocateGOT(); }
95 virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
96 struct StartFunctionBodyCall {
97 StartFunctionBodyCall(uint8_t *Result, const Function *F,
98 uintptr_t ActualSize, uintptr_t ActualSizeResult)
99 : Result(Result), F(F), F_dump(DumpFunction(F)),
100 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
104 uintptr_t ActualSize;
105 uintptr_t ActualSizeResult;
107 std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
108 virtual uint8_t *startFunctionBody(const Function *F,
109 uintptr_t &ActualSize) {
110 uintptr_t InitialActualSize = ActualSize;
111 uint8_t *Result = Base->startFunctionBody(F, ActualSize);
112 startFunctionBodyCalls.push_back(
113 StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
117 uint8_t *allocateStub(const GlobalValue *F, unsigned StubSize,
118 unsigned Alignment) override {
120 return Base->allocateStub(F, StubSize, Alignment);
122 struct EndFunctionBodyCall {
123 EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
124 uint8_t *FunctionEnd)
125 : F(F), F_dump(DumpFunction(F)),
126 FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
129 uint8_t *FunctionStart;
130 uint8_t *FunctionEnd;
132 std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
133 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
134 uint8_t *FunctionEnd) {
135 endFunctionBodyCalls.push_back(
136 EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
137 Base->endFunctionBody(F, FunctionStart, FunctionEnd);
139 virtual uint8_t *allocateDataSection(
140 uintptr_t Size, unsigned Alignment, unsigned SectionID,
141 StringRef SectionName, bool IsReadOnly) {
142 return Base->allocateDataSection(
143 Size, Alignment, SectionID, SectionName, IsReadOnly);
145 virtual uint8_t *allocateCodeSection(
146 uintptr_t Size, unsigned Alignment, unsigned SectionID,
147 StringRef SectionName) {
148 return Base->allocateCodeSection(
149 Size, Alignment, SectionID, SectionName);
151 virtual bool finalizeMemory(std::string *ErrMsg) { return false; }
152 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
153 return Base->allocateSpace(Size, Alignment);
155 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
156 return Base->allocateGlobal(Size, Alignment);
158 struct DeallocateFunctionBodyCall {
159 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
162 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
163 virtual void deallocateFunctionBody(void *Body) {
164 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
165 Base->deallocateFunctionBody(Body);
169 bool LoadAssemblyInto(Module *M, const char *assembly) {
172 nullptr != ParseAssemblyString(assembly, M, Error, M->getContext());
173 string_ostream errMsg;
174 Error.print("", errMsg);
175 EXPECT_TRUE(success) << errMsg.str();
179 class JITTest : public testing::Test {
181 virtual RecordingJITMemoryManager *createMemoryManager() {
182 return new RecordingJITMemoryManager;
185 virtual void SetUp() {
186 M = new Module("<main>", Context);
187 RJMM = createMemoryManager();
188 RJMM->setPoisonMemory(true);
190 TargetOptions Options;
191 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
192 .setJITMemoryManager(RJMM)
194 .setTargetOptions(Options).create());
195 ASSERT_TRUE(TheJIT.get() != nullptr) << Error;
198 void LoadAssembly(const char *assembly) {
199 LoadAssemblyInto(M, assembly);
203 Module *M; // Owned by ExecutionEngine.
204 RecordingJITMemoryManager *RJMM;
205 std::unique_ptr<ExecutionEngine> TheJIT;
208 // Regression test for a bug. The JIT used to allocate globals inside the same
209 // memory block used for the function, and when the function code was freed,
210 // the global was left in the same place. This test allocates a function
211 // that uses and global, deallocates it, and then makes sure that the global
212 // stays alive after that.
213 TEST(JIT, GlobalInFunction) {
215 Module *M = new Module("<main>", context);
217 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
218 // Tell the memory manager to poison freed memory so that accessing freed
219 // memory is more easily tested.
220 MemMgr->setPoisonMemory(true);
222 std::unique_ptr<ExecutionEngine> JIT(EngineBuilder(M)
223 .setEngineKind(EngineKind::JIT)
225 .setJITMemoryManager(MemMgr)
226 // The next line enables the fix:
227 .setAllocateGVsWithCode(false)
229 ASSERT_EQ(Error, "");
231 // Create a global variable.
232 Type *GTy = Type::getInt32Ty(context);
233 GlobalVariable *G = new GlobalVariable(
236 false, // Not constant.
237 GlobalValue::InternalLinkage,
238 Constant::getNullValue(GTy),
241 // Make a function that points to a global.
242 Function *F1 = makeReturnGlobal("F1", G, M);
244 // Get the pointer to the native code to force it to JIT the function and
245 // allocate space for the global.
247 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
249 // Since F1 was codegen'd, a pointer to G should be available.
250 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
251 ASSERT_NE((int32_t*)nullptr, GPtr);
254 // F1() should increment G.
258 // Make a second function identical to the first, referring to the same
260 Function *F2 = makeReturnGlobal("F2", G, M);
262 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
264 // F2() should increment G.
269 JIT->freeMachineCodeForFunction(F1);
271 // F2() should *still* increment G.
276 int PlusOne(int arg) {
280 TEST_F(JITTest, FarCallToKnownFunction) {
281 // x86-64 can only make direct calls to functions within 32 bits of
282 // the current PC. To call anything farther away, we have to load
283 // the address into a register and call through the register. The
284 // current JIT does this by allocating a stub for any far call.
285 // There was a bug in which the JIT tried to emit a direct call when
286 // the target was already in the JIT's global mappings and lazy
287 // compilation was disabled.
289 Function *KnownFunction = Function::Create(
290 TypeBuilder<int(int), false>::get(Context),
291 GlobalValue::ExternalLinkage, "known", M);
292 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
294 // int test() { return known(7); }
295 Function *TestFunction = Function::Create(
296 TypeBuilder<int(), false>::get(Context),
297 GlobalValue::ExternalLinkage, "test", M);
298 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
299 IRBuilder<> Builder(Entry);
300 Value *result = Builder.CreateCall(
302 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
303 Builder.CreateRet(result);
305 TheJIT->DisableLazyCompilation(true);
306 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
307 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
308 // This used to crash in trying to call PlusOne().
309 EXPECT_EQ(8, TestFunctionPtr());
312 // Test a function C which calls A and B which call each other.
313 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
314 TheJIT->DisableLazyCompilation(true);
316 FunctionType *Func1Ty =
317 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
318 std::vector<Type*> arg_types;
319 arg_types.push_back(Type::getInt1Ty(Context));
320 FunctionType *FuncTy = FunctionType::get(
321 Type::getVoidTy(Context), arg_types, false);
322 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
324 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
326 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
328 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
329 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
330 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
331 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
332 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
333 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
334 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
336 // Make Func1 call Func2(0) and Func3(0).
337 IRBuilder<> Builder(Block1);
338 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
339 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
340 Builder.CreateRetVoid();
342 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
343 Builder.SetInsertPoint(Block2);
344 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
345 Builder.SetInsertPoint(True2);
346 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
347 Builder.CreateRetVoid();
348 Builder.SetInsertPoint(False2);
349 Builder.CreateRetVoid();
351 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
352 Builder.SetInsertPoint(Block3);
353 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
354 Builder.SetInsertPoint(True3);
355 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
356 Builder.CreateRetVoid();
357 Builder.SetInsertPoint(False3);
358 Builder.CreateRetVoid();
360 // Compile the function to native code
362 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
367 // Regression test for PR5162. This used to trigger an AssertingVH inside the
368 // JIT's Function to stub mapping.
369 TEST_F(JITTest, NonLazyLeaksNoStubs) {
370 TheJIT->DisableLazyCompilation(true);
372 // Create two functions with a single basic block each.
373 FunctionType *FuncTy =
374 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
375 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
377 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
379 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
380 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
382 // The first function calls the second and returns the result
383 IRBuilder<> Builder(Block1);
384 Value *Result = Builder.CreateCall(Func2);
385 Builder.CreateRet(Result);
387 // The second function just returns a constant
388 Builder.SetInsertPoint(Block2);
389 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
391 // Compile the function to native code
392 (void)TheJIT->getPointerToFunction(Func1);
394 // Free the JIT state for the functions
395 TheJIT->freeMachineCodeForFunction(Func1);
396 TheJIT->freeMachineCodeForFunction(Func2);
398 // Delete the first function (and show that is has no users)
399 EXPECT_EQ(Func1->getNumUses(), 0u);
400 Func1->eraseFromParent();
402 // Delete the second function (and show that it has no users - it had one,
403 // func1 but that's gone now)
404 EXPECT_EQ(Func2->getNumUses(), 0u);
405 Func2->eraseFromParent();
408 TEST_F(JITTest, ModuleDeletion) {
409 TheJIT->DisableLazyCompilation(false);
410 LoadAssembly("define void @main() { "
411 " call i32 @computeVal() "
415 "define internal i32 @computeVal() { "
418 Function *func = M->getFunction("main");
419 TheJIT->getPointerToFunction(func);
420 TheJIT->removeModule(M);
423 SmallPtrSet<const void*, 2> FunctionsDeallocated;
424 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
426 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
428 for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
429 EXPECT_TRUE(FunctionsDeallocated.count(
430 RJMM->startFunctionBodyCalls[i].Result))
431 << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
433 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
434 RJMM->deallocateFunctionBodyCalls.size());
437 // ARM, MIPS and PPC still emit stubs for calls since the target may be
438 // too far away to call directly. This #if can probably be removed when
439 // http://llvm.org/PR5201 is fixed.
440 #if !defined(__arm__) && !defined(__mips__) && \
441 !defined(__powerpc__) && !defined(__ppc__) && !defined(__aarch64__)
442 typedef int (*FooPtr) ();
444 TEST_F(JITTest, NoStubs) {
445 LoadAssembly("define void @bar() {"
450 "define i32 @foo() {"
456 "define i32 @main() {"
458 "%0 = call i32 @foo()"
462 Function *foo = M->getFunction("foo");
463 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
464 FooPtr ptr = (FooPtr)(tmp);
468 // We should now allocate no more stubs, we have the code to foo
469 // and the existing stub for bar.
470 int stubsBefore = RJMM->stubsAllocated;
471 Function *func = M->getFunction("main");
472 TheJIT->getPointerToFunction(func);
474 Function *bar = M->getFunction("bar");
475 TheJIT->getPointerToFunction(bar);
477 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
479 #endif // !ARM && !PPC
481 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
482 TheJIT->DisableLazyCompilation(true);
483 LoadAssembly("define i8()* @get_foo_addr() { "
487 "define i8 @foo() { "
490 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
492 typedef char(*fooT)();
493 fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
494 (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
495 fooT foo_addr = get_foo_addr();
497 // Now free get_foo_addr. This should not free the machine code for foo or
498 // any call stub returned as foo's canonical address.
499 TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
501 // Check by calling the reported address of foo.
502 EXPECT_EQ(42, foo_addr());
504 // The reported address should also be the same as the result of a subsequent
505 // getPointerToFunction(foo).
507 // Fails until PR5126 is fixed:
508 Function *F_foo = M->getFunction("foo");
509 fooT foo = reinterpret_cast<fooT>(
510 (intptr_t)TheJIT->getPointerToFunction(F_foo));
511 EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
515 // ARM does not have an implementation of replaceMachineCodeForFunction(),
516 // so recompileAndRelinkFunction doesn't work.
517 #if !defined(__arm__) && !defined(__aarch64__)
518 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
519 Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
520 GlobalValue::ExternalLinkage, "test", M);
521 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
522 IRBuilder<> Builder(Entry);
523 Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
524 Builder.CreateRet(Val);
526 TheJIT->DisableLazyCompilation(true);
527 // Compile the function once, and make sure it works.
528 int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
529 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
530 EXPECT_EQ(1, OrigFPtr());
532 // Now change the function to return a different value.
533 Entry->eraseFromParent();
534 BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
535 Builder.SetInsertPoint(NewEntry);
536 Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
537 Builder.CreateRet(Val);
538 // Recompile it, which should produce a new function pointer _and_ update the
540 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
541 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
543 EXPECT_EQ(2, NewFPtr())
544 << "The new pointer should call the new version of the function";
545 EXPECT_EQ(2, OrigFPtr())
546 << "The old pointer's target should now jump to the new version";
548 #endif // !defined(__arm__)
550 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
551 TheJIT->DisableLazyCompilation(true);
552 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
553 " available_externally global i32 7 "
555 "define i32 @loader() { "
556 " %result = load i32* @JITTest_AvailableExternallyGlobal "
559 Function *loaderIR = M->getFunction("loader");
561 int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
562 (intptr_t)TheJIT->getPointerToFunction(loaderIR));
563 EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
564 << " not 7 from the IR version.";
567 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
568 TheJIT->DisableLazyCompilation(true);
569 LoadAssembly("define available_externally i32 "
570 " @JITTest_AvailableExternallyFunction() { "
574 "define i32 @func() { "
575 " %result = tail call i32 "
576 " @JITTest_AvailableExternallyFunction() "
579 Function *funcIR = M->getFunction("func");
581 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
582 (intptr_t)TheJIT->getPointerToFunction(funcIR));
583 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
584 << " not 7 from the IR version.";
587 TEST_F(JITTest, EscapedLazyStubStillCallable) {
588 TheJIT->DisableLazyCompilation(false);
589 LoadAssembly("define internal i32 @stubbed() { "
593 "define i32()* @get_stub() { "
594 " ret i32()* @stubbed "
596 typedef int32_t(*StubTy)();
598 // Call get_stub() to get the address of @stubbed without actually JITting it.
599 Function *get_stubIR = M->getFunction("get_stub");
600 StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
601 (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
602 StubTy stubbed = get_stub();
603 // Now get_stubIR is the only reference to stubbed's stub.
604 get_stubIR->eraseFromParent();
605 // Now there are no references inside the JIT, but we've got a pointer outside
606 // it. The stub should be callable and return the right value.
607 EXPECT_EQ(42, stubbed());
610 // Converts the LLVM assembly to bitcode and returns it in a std::string. An
611 // empty string indicates an error.
612 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
613 Module TempModule("TempModule", Context);
614 if (!LoadAssemblyInto(&TempModule, Assembly)) {
619 raw_string_ostream OS(Result);
620 WriteBitcodeToFile(&TempModule, OS);
625 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
626 // lazily. The associated Module (owned by the ExecutionEngine) is returned in
627 // M. Both will be NULL on an error. Bitcode must live at least as long as the
629 ExecutionEngine *getJITFromBitcode(
630 LLVMContext &Context, const std::string &Bitcode, Module *&M) {
631 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
632 MemoryBuffer *BitcodeBuffer =
633 MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
634 ErrorOr<Module*> ModuleOrErr = getLazyBitcodeModule(BitcodeBuffer, Context);
635 if (std::error_code EC = ModuleOrErr.getError()) {
636 ADD_FAILURE() << EC.message();
637 delete BitcodeBuffer;
640 M = ModuleOrErr.get();
642 ExecutionEngine *TheJIT = EngineBuilder(M)
643 .setEngineKind(EngineKind::JIT)
644 .setErrorStr(&errMsg)
646 if (TheJIT == nullptr) {
647 ADD_FAILURE() << errMsg;
655 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
657 const std::string Bitcode =
658 AssembleToBitcode(Context,
659 "define available_externally i32 "
660 " @JITTest_AvailableExternallyFunction() { "
664 "define i32 @func() { "
665 " %result = tail call i32 "
666 " @JITTest_AvailableExternallyFunction() "
669 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
671 std::unique_ptr<ExecutionEngine> TheJIT(
672 getJITFromBitcode(Context, Bitcode, M));
673 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
674 TheJIT->DisableLazyCompilation(true);
676 Function *funcIR = M->getFunction("func");
677 Function *availableFunctionIR =
678 M->getFunction("JITTest_AvailableExternallyFunction");
680 // Double-check that the available_externally function is still unmaterialized
681 // when getPointerToFunction needs to find out if it's available_externally.
682 EXPECT_TRUE(availableFunctionIR->isMaterializable());
684 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
685 (intptr_t)TheJIT->getPointerToFunction(funcIR));
686 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
687 << " not 7 from the IR version.";
690 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
692 const std::string Bitcode =
693 AssembleToBitcode(Context,
694 "define i32 @recur1(i32 %a) { "
695 " %zero = icmp eq i32 %a, 0 "
696 " br i1 %zero, label %done, label %notdone "
700 " %am1 = sub i32 %a, 1 "
701 " %result = call i32 @recur2(i32 %am1) "
705 "define i32 @recur2(i32 %b) { "
706 " %result = call i32 @recur1(i32 %b) "
709 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
711 std::unique_ptr<ExecutionEngine> TheJIT(
712 getJITFromBitcode(Context, Bitcode, M));
713 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
714 TheJIT->DisableLazyCompilation(true);
716 Function *recur1IR = M->getFunction("recur1");
717 Function *recur2IR = M->getFunction("recur2");
718 EXPECT_TRUE(recur1IR->isMaterializable());
719 EXPECT_TRUE(recur2IR->isMaterializable());
721 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
722 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
723 EXPECT_EQ(3, recur1(4));
725 #endif // !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__)