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"
34 using std::error_code;
36 // This variable is intentionally defined differently in the statically-compiled
37 // program from the IR input to the JIT to assert that the JIT doesn't use its
38 // definition. Note that this variable must be defined even on platforms where
39 // JIT tests are disabled as it is referenced from the .def file.
40 extern "C" int32_t JITTest_AvailableExternallyGlobal;
41 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
43 // This function is intentionally defined differently in the statically-compiled
44 // program from the IR input to the JIT to assert that the JIT doesn't use its
45 // definition. Note that this function must be defined even on platforms where
46 // JIT tests are disabled as it is referenced from the .def file.
47 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
48 extern "C" int32_t JITTest_AvailableExternallyFunction() {
54 // Tests on ARM, PowerPC and SystemZ disabled as we're running the old jit
55 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__) \
56 && !defined(__aarch64__)
58 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
59 std::vector<Type*> params;
60 FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
62 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
63 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
64 IRBuilder<> builder(Entry);
65 Value *Load = builder.CreateLoad(G);
66 Type *GTy = G->getType()->getElementType();
67 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
68 builder.CreateStore(Add, G);
69 builder.CreateRet(Add);
73 std::string DumpFunction(const Function *F) {
75 raw_string_ostream(Result) << "" << *F;
79 class RecordingJITMemoryManager : public JITMemoryManager {
80 const std::unique_ptr<JITMemoryManager> Base;
83 RecordingJITMemoryManager()
84 : Base(JITMemoryManager::CreateDefaultMemManager()) {
87 virtual void *getPointerToNamedFunction(const std::string &Name,
88 bool AbortOnFailure = true) {
89 return Base->getPointerToNamedFunction(Name, AbortOnFailure);
92 virtual void setMemoryWritable() { Base->setMemoryWritable(); }
93 virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
94 virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
95 virtual void AllocateGOT() { Base->AllocateGOT(); }
96 virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
97 struct StartFunctionBodyCall {
98 StartFunctionBodyCall(uint8_t *Result, const Function *F,
99 uintptr_t ActualSize, uintptr_t ActualSizeResult)
100 : Result(Result), F(F), F_dump(DumpFunction(F)),
101 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
105 uintptr_t ActualSize;
106 uintptr_t ActualSizeResult;
108 std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
109 virtual uint8_t *startFunctionBody(const Function *F,
110 uintptr_t &ActualSize) {
111 uintptr_t InitialActualSize = ActualSize;
112 uint8_t *Result = Base->startFunctionBody(F, ActualSize);
113 startFunctionBodyCalls.push_back(
114 StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
118 uint8_t *allocateStub(const GlobalValue *F, unsigned StubSize,
119 unsigned Alignment) override {
121 return Base->allocateStub(F, StubSize, Alignment);
123 struct EndFunctionBodyCall {
124 EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
125 uint8_t *FunctionEnd)
126 : F(F), F_dump(DumpFunction(F)),
127 FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
130 uint8_t *FunctionStart;
131 uint8_t *FunctionEnd;
133 std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
134 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
135 uint8_t *FunctionEnd) {
136 endFunctionBodyCalls.push_back(
137 EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
138 Base->endFunctionBody(F, FunctionStart, FunctionEnd);
140 virtual uint8_t *allocateDataSection(
141 uintptr_t Size, unsigned Alignment, unsigned SectionID,
142 StringRef SectionName, bool IsReadOnly) {
143 return Base->allocateDataSection(
144 Size, Alignment, SectionID, SectionName, IsReadOnly);
146 virtual uint8_t *allocateCodeSection(
147 uintptr_t Size, unsigned Alignment, unsigned SectionID,
148 StringRef SectionName) {
149 return Base->allocateCodeSection(
150 Size, Alignment, SectionID, SectionName);
152 virtual bool finalizeMemory(std::string *ErrMsg) { return false; }
153 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
154 return Base->allocateSpace(Size, Alignment);
156 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
157 return Base->allocateGlobal(Size, Alignment);
159 struct DeallocateFunctionBodyCall {
160 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
163 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
164 virtual void deallocateFunctionBody(void *Body) {
165 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
166 Base->deallocateFunctionBody(Body);
170 bool LoadAssemblyInto(Module *M, const char *assembly) {
173 nullptr != ParseAssemblyString(assembly, M, Error, M->getContext());
175 raw_string_ostream os(errMsg);
177 EXPECT_TRUE(success) << os.str();
181 class JITTest : public testing::Test {
183 virtual RecordingJITMemoryManager *createMemoryManager() {
184 return new RecordingJITMemoryManager;
187 virtual void SetUp() {
188 M = new Module("<main>", Context);
189 RJMM = createMemoryManager();
190 RJMM->setPoisonMemory(true);
192 TargetOptions Options;
193 TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
194 .setJITMemoryManager(RJMM)
196 .setTargetOptions(Options).create());
197 ASSERT_TRUE(TheJIT.get() != nullptr) << Error;
200 void LoadAssembly(const char *assembly) {
201 LoadAssemblyInto(M, assembly);
205 Module *M; // Owned by ExecutionEngine.
206 RecordingJITMemoryManager *RJMM;
207 std::unique_ptr<ExecutionEngine> TheJIT;
210 // Regression test for a bug. The JIT used to allocate globals inside the same
211 // memory block used for the function, and when the function code was freed,
212 // the global was left in the same place. This test allocates a function
213 // that uses and global, deallocates it, and then makes sure that the global
214 // stays alive after that.
215 TEST(JIT, GlobalInFunction) {
217 Module *M = new Module("<main>", context);
219 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
220 // Tell the memory manager to poison freed memory so that accessing freed
221 // memory is more easily tested.
222 MemMgr->setPoisonMemory(true);
224 std::unique_ptr<ExecutionEngine> JIT(EngineBuilder(M)
225 .setEngineKind(EngineKind::JIT)
227 .setJITMemoryManager(MemMgr)
228 // The next line enables the fix:
229 .setAllocateGVsWithCode(false)
231 ASSERT_EQ(Error, "");
233 // Create a global variable.
234 Type *GTy = Type::getInt32Ty(context);
235 GlobalVariable *G = new GlobalVariable(
238 false, // Not constant.
239 GlobalValue::InternalLinkage,
240 Constant::getNullValue(GTy),
243 // Make a function that points to a global.
244 Function *F1 = makeReturnGlobal("F1", G, M);
246 // Get the pointer to the native code to force it to JIT the function and
247 // allocate space for the global.
249 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
251 // Since F1 was codegen'd, a pointer to G should be available.
252 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
253 ASSERT_NE((int32_t*)nullptr, GPtr);
256 // F1() should increment G.
260 // Make a second function identical to the first, referring to the same
262 Function *F2 = makeReturnGlobal("F2", G, M);
264 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
266 // F2() should increment G.
271 JIT->freeMachineCodeForFunction(F1);
273 // F2() should *still* increment G.
278 int PlusOne(int arg) {
282 TEST_F(JITTest, FarCallToKnownFunction) {
283 // x86-64 can only make direct calls to functions within 32 bits of
284 // the current PC. To call anything farther away, we have to load
285 // the address into a register and call through the register. The
286 // current JIT does this by allocating a stub for any far call.
287 // There was a bug in which the JIT tried to emit a direct call when
288 // the target was already in the JIT's global mappings and lazy
289 // compilation was disabled.
291 Function *KnownFunction = Function::Create(
292 TypeBuilder<int(int), false>::get(Context),
293 GlobalValue::ExternalLinkage, "known", M);
294 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
296 // int test() { return known(7); }
297 Function *TestFunction = Function::Create(
298 TypeBuilder<int(), false>::get(Context),
299 GlobalValue::ExternalLinkage, "test", M);
300 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
301 IRBuilder<> Builder(Entry);
302 Value *result = Builder.CreateCall(
304 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
305 Builder.CreateRet(result);
307 TheJIT->DisableLazyCompilation(true);
308 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
309 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
310 // This used to crash in trying to call PlusOne().
311 EXPECT_EQ(8, TestFunctionPtr());
314 // Test a function C which calls A and B which call each other.
315 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
316 TheJIT->DisableLazyCompilation(true);
318 FunctionType *Func1Ty =
319 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
320 std::vector<Type*> arg_types;
321 arg_types.push_back(Type::getInt1Ty(Context));
322 FunctionType *FuncTy = FunctionType::get(
323 Type::getVoidTy(Context), arg_types, false);
324 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
326 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
328 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
330 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
331 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
332 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
333 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
334 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
335 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
336 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
338 // Make Func1 call Func2(0) and Func3(0).
339 IRBuilder<> Builder(Block1);
340 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
341 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
342 Builder.CreateRetVoid();
344 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
345 Builder.SetInsertPoint(Block2);
346 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
347 Builder.SetInsertPoint(True2);
348 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
349 Builder.CreateRetVoid();
350 Builder.SetInsertPoint(False2);
351 Builder.CreateRetVoid();
353 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
354 Builder.SetInsertPoint(Block3);
355 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
356 Builder.SetInsertPoint(True3);
357 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
358 Builder.CreateRetVoid();
359 Builder.SetInsertPoint(False3);
360 Builder.CreateRetVoid();
362 // Compile the function to native code
364 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
369 // Regression test for PR5162. This used to trigger an AssertingVH inside the
370 // JIT's Function to stub mapping.
371 TEST_F(JITTest, NonLazyLeaksNoStubs) {
372 TheJIT->DisableLazyCompilation(true);
374 // Create two functions with a single basic block each.
375 FunctionType *FuncTy =
376 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
377 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
379 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
381 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
382 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
384 // The first function calls the second and returns the result
385 IRBuilder<> Builder(Block1);
386 Value *Result = Builder.CreateCall(Func2);
387 Builder.CreateRet(Result);
389 // The second function just returns a constant
390 Builder.SetInsertPoint(Block2);
391 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
393 // Compile the function to native code
394 (void)TheJIT->getPointerToFunction(Func1);
396 // Free the JIT state for the functions
397 TheJIT->freeMachineCodeForFunction(Func1);
398 TheJIT->freeMachineCodeForFunction(Func2);
400 // Delete the first function (and show that is has no users)
401 EXPECT_EQ(Func1->getNumUses(), 0u);
402 Func1->eraseFromParent();
404 // Delete the second function (and show that it has no users - it had one,
405 // func1 but that's gone now)
406 EXPECT_EQ(Func2->getNumUses(), 0u);
407 Func2->eraseFromParent();
410 TEST_F(JITTest, ModuleDeletion) {
411 TheJIT->DisableLazyCompilation(false);
412 LoadAssembly("define void @main() { "
413 " call i32 @computeVal() "
417 "define internal i32 @computeVal() { "
420 Function *func = M->getFunction("main");
421 TheJIT->getPointerToFunction(func);
422 TheJIT->removeModule(M);
425 SmallPtrSet<const void*, 2> FunctionsDeallocated;
426 for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
428 FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
430 for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
431 EXPECT_TRUE(FunctionsDeallocated.count(
432 RJMM->startFunctionBodyCalls[i].Result))
433 << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
435 EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
436 RJMM->deallocateFunctionBodyCalls.size());
439 // ARM, MIPS and PPC still emit stubs for calls since the target may be
440 // too far away to call directly. This #if can probably be removed when
441 // http://llvm.org/PR5201 is fixed.
442 #if !defined(__arm__) && !defined(__mips__) && \
443 !defined(__powerpc__) && !defined(__ppc__) && !defined(__aarch64__)
444 typedef int (*FooPtr) ();
446 TEST_F(JITTest, NoStubs) {
447 LoadAssembly("define void @bar() {"
452 "define i32 @foo() {"
458 "define i32 @main() {"
460 "%0 = call i32 @foo()"
464 Function *foo = M->getFunction("foo");
465 uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
466 FooPtr ptr = (FooPtr)(tmp);
470 // We should now allocate no more stubs, we have the code to foo
471 // and the existing stub for bar.
472 int stubsBefore = RJMM->stubsAllocated;
473 Function *func = M->getFunction("main");
474 TheJIT->getPointerToFunction(func);
476 Function *bar = M->getFunction("bar");
477 TheJIT->getPointerToFunction(bar);
479 ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
481 #endif // !ARM && !PPC
483 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
484 TheJIT->DisableLazyCompilation(true);
485 LoadAssembly("define i8()* @get_foo_addr() { "
489 "define i8 @foo() { "
492 Function *F_get_foo_addr = M->getFunction("get_foo_addr");
494 typedef char(*fooT)();
495 fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
496 (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
497 fooT foo_addr = get_foo_addr();
499 // Now free get_foo_addr. This should not free the machine code for foo or
500 // any call stub returned as foo's canonical address.
501 TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
503 // Check by calling the reported address of foo.
504 EXPECT_EQ(42, foo_addr());
506 // The reported address should also be the same as the result of a subsequent
507 // getPointerToFunction(foo).
509 // Fails until PR5126 is fixed:
510 Function *F_foo = M->getFunction("foo");
511 fooT foo = reinterpret_cast<fooT>(
512 (intptr_t)TheJIT->getPointerToFunction(F_foo));
513 EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
517 // ARM does not have an implementation of replaceMachineCodeForFunction(),
518 // so recompileAndRelinkFunction doesn't work.
519 #if !defined(__arm__) && !defined(__aarch64__)
520 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
521 Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
522 GlobalValue::ExternalLinkage, "test", M);
523 BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
524 IRBuilder<> Builder(Entry);
525 Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
526 Builder.CreateRet(Val);
528 TheJIT->DisableLazyCompilation(true);
529 // Compile the function once, and make sure it works.
530 int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
531 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
532 EXPECT_EQ(1, OrigFPtr());
534 // Now change the function to return a different value.
535 Entry->eraseFromParent();
536 BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
537 Builder.SetInsertPoint(NewEntry);
538 Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
539 Builder.CreateRet(Val);
540 // Recompile it, which should produce a new function pointer _and_ update the
542 int (*NewFPtr)() = reinterpret_cast<int(*)()>(
543 (intptr_t)TheJIT->recompileAndRelinkFunction(F));
545 EXPECT_EQ(2, NewFPtr())
546 << "The new pointer should call the new version of the function";
547 EXPECT_EQ(2, OrigFPtr())
548 << "The old pointer's target should now jump to the new version";
550 #endif // !defined(__arm__)
552 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
553 TheJIT->DisableLazyCompilation(true);
554 LoadAssembly("@JITTest_AvailableExternallyGlobal = "
555 " available_externally global i32 7 "
557 "define i32 @loader() { "
558 " %result = load i32* @JITTest_AvailableExternallyGlobal "
561 Function *loaderIR = M->getFunction("loader");
563 int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
564 (intptr_t)TheJIT->getPointerToFunction(loaderIR));
565 EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
566 << " not 7 from the IR version.";
569 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
570 TheJIT->DisableLazyCompilation(true);
571 LoadAssembly("define available_externally i32 "
572 " @JITTest_AvailableExternallyFunction() { "
576 "define i32 @func() { "
577 " %result = tail call i32 "
578 " @JITTest_AvailableExternallyFunction() "
581 Function *funcIR = M->getFunction("func");
583 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
584 (intptr_t)TheJIT->getPointerToFunction(funcIR));
585 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
586 << " not 7 from the IR version.";
589 TEST_F(JITTest, EscapedLazyStubStillCallable) {
590 TheJIT->DisableLazyCompilation(false);
591 LoadAssembly("define internal i32 @stubbed() { "
595 "define i32()* @get_stub() { "
596 " ret i32()* @stubbed "
598 typedef int32_t(*StubTy)();
600 // Call get_stub() to get the address of @stubbed without actually JITting it.
601 Function *get_stubIR = M->getFunction("get_stub");
602 StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
603 (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
604 StubTy stubbed = get_stub();
605 // Now get_stubIR is the only reference to stubbed's stub.
606 get_stubIR->eraseFromParent();
607 // Now there are no references inside the JIT, but we've got a pointer outside
608 // it. The stub should be callable and return the right value.
609 EXPECT_EQ(42, stubbed());
612 // Converts the LLVM assembly to bitcode and returns it in a std::string. An
613 // empty string indicates an error.
614 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
615 Module TempModule("TempModule", Context);
616 if (!LoadAssemblyInto(&TempModule, Assembly)) {
621 raw_string_ostream OS(Result);
622 WriteBitcodeToFile(&TempModule, OS);
627 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
628 // lazily. The associated Module (owned by the ExecutionEngine) is returned in
629 // M. Both will be NULL on an error. Bitcode must live at least as long as the
631 ExecutionEngine *getJITFromBitcode(
632 LLVMContext &Context, const std::string &Bitcode, Module *&M) {
633 // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
634 MemoryBuffer *BitcodeBuffer =
635 MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
636 ErrorOr<Module*> ModuleOrErr = getLazyBitcodeModule(BitcodeBuffer, Context);
637 if (error_code EC = ModuleOrErr.getError()) {
638 ADD_FAILURE() << EC.message();
639 delete BitcodeBuffer;
642 M = ModuleOrErr.get();
644 ExecutionEngine *TheJIT = EngineBuilder(M)
645 .setEngineKind(EngineKind::JIT)
646 .setErrorStr(&errMsg)
648 if (TheJIT == nullptr) {
649 ADD_FAILURE() << errMsg;
657 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
659 const std::string Bitcode =
660 AssembleToBitcode(Context,
661 "define available_externally i32 "
662 " @JITTest_AvailableExternallyFunction() { "
666 "define i32 @func() { "
667 " %result = tail call i32 "
668 " @JITTest_AvailableExternallyFunction() "
671 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
673 std::unique_ptr<ExecutionEngine> TheJIT(
674 getJITFromBitcode(Context, Bitcode, M));
675 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
676 TheJIT->DisableLazyCompilation(true);
678 Function *funcIR = M->getFunction("func");
679 Function *availableFunctionIR =
680 M->getFunction("JITTest_AvailableExternallyFunction");
682 // Double-check that the available_externally function is still unmaterialized
683 // when getPointerToFunction needs to find out if it's available_externally.
684 EXPECT_TRUE(availableFunctionIR->isMaterializable());
686 int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
687 (intptr_t)TheJIT->getPointerToFunction(funcIR));
688 EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
689 << " not 7 from the IR version.";
692 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
694 const std::string Bitcode =
695 AssembleToBitcode(Context,
696 "define i32 @recur1(i32 %a) { "
697 " %zero = icmp eq i32 %a, 0 "
698 " br i1 %zero, label %done, label %notdone "
702 " %am1 = sub i32 %a, 1 "
703 " %result = call i32 @recur2(i32 %am1) "
707 "define i32 @recur2(i32 %b) { "
708 " %result = call i32 @recur1(i32 %b) "
711 ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
713 std::unique_ptr<ExecutionEngine> TheJIT(
714 getJITFromBitcode(Context, Bitcode, M));
715 ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
716 TheJIT->DisableLazyCompilation(true);
718 Function *recur1IR = M->getFunction("recur1");
719 Function *recur2IR = M->getFunction("recur2");
720 EXPECT_TRUE(recur1IR->isMaterializable());
721 EXPECT_TRUE(recur2IR->isMaterializable());
723 int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
724 (intptr_t)TheJIT->getPointerToFunction(recur1IR));
725 EXPECT_EQ(3, recur1(4));
727 #endif // !defined(__arm__) && !defined(__powerpc__) && !defined(__s390__)