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 "gtest/gtest.h"
11 #include "llvm/ADT/OwningPtr.h"
12 #include "llvm/ADT/SmallPtrSet.h"
13 #include "llvm/Assembly/Parser.h"
14 #include "llvm/BasicBlock.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/ExecutionEngine/JIT.h"
19 #include "llvm/ExecutionEngine/JITMemoryManager.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalValue.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/ModuleProvider.h"
26 #include "llvm/Support/IRBuilder.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/TypeBuilder.h"
29 #include "llvm/Target/TargetSelect.h"
30 #include "llvm/Type.h"
38 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
39 std::vector<const Type*> params;
40 const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
42 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
43 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
44 IRBuilder<> builder(Entry);
45 Value *Load = builder.CreateLoad(G);
46 const Type *GTy = G->getType()->getElementType();
47 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
48 builder.CreateStore(Add, G);
49 builder.CreateRet(Add);
53 std::string DumpFunction(const Function *F) {
55 raw_string_ostream(Result) << "" << *F;
59 class RecordingJITMemoryManager : public JITMemoryManager {
60 const OwningPtr<JITMemoryManager> Base;
62 RecordingJITMemoryManager()
63 : Base(JITMemoryManager::CreateDefaultMemManager()) {
66 virtual void setMemoryWritable() { Base->setMemoryWritable(); }
67 virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
68 virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
69 virtual void AllocateGOT() { Base->AllocateGOT(); }
70 virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
71 struct StartFunctionBodyCall {
72 StartFunctionBodyCall(uint8_t *Result, const Function *F,
73 uintptr_t ActualSize, uintptr_t ActualSizeResult)
74 : Result(Result), F(F), F_dump(DumpFunction(F)),
75 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
80 uintptr_t ActualSizeResult;
82 std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
83 virtual uint8_t *startFunctionBody(const Function *F,
84 uintptr_t &ActualSize) {
85 uintptr_t InitialActualSize = ActualSize;
86 uint8_t *Result = Base->startFunctionBody(F, ActualSize);
87 startFunctionBodyCalls.push_back(
88 StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
91 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
93 return Base->allocateStub(F, StubSize, Alignment);
95 struct EndFunctionBodyCall {
96 EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
98 : F(F), F_dump(DumpFunction(F)),
99 FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
102 uint8_t *FunctionStart;
103 uint8_t *FunctionEnd;
105 std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
106 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
107 uint8_t *FunctionEnd) {
108 endFunctionBodyCalls.push_back(
109 EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
110 Base->endFunctionBody(F, FunctionStart, FunctionEnd);
112 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
113 return Base->allocateSpace(Size, Alignment);
115 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
116 return Base->allocateGlobal(Size, Alignment);
118 struct DeallocateFunctionBodyCall {
119 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
122 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
123 virtual void deallocateFunctionBody(void *Body) {
124 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
125 Base->deallocateFunctionBody(Body);
127 struct DeallocateExceptionTableCall {
128 DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
131 std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
132 virtual void deallocateExceptionTable(void *ET) {
133 deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
134 Base->deallocateExceptionTable(ET);
136 struct StartExceptionTableCall {
137 StartExceptionTableCall(uint8_t *Result, const Function *F,
138 uintptr_t ActualSize, uintptr_t ActualSizeResult)
139 : Result(Result), F(F), F_dump(DumpFunction(F)),
140 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
144 uintptr_t ActualSize;
145 uintptr_t ActualSizeResult;
147 std::vector<StartExceptionTableCall> startExceptionTableCalls;
148 virtual uint8_t* startExceptionTable(const Function* F,
149 uintptr_t &ActualSize) {
150 uintptr_t InitialActualSize = ActualSize;
151 uint8_t *Result = Base->startExceptionTable(F, ActualSize);
152 startExceptionTableCalls.push_back(
153 StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
156 struct EndExceptionTableCall {
157 EndExceptionTableCall(const Function *F, uint8_t *TableStart,
158 uint8_t *TableEnd, uint8_t* FrameRegister)
159 : F(F), F_dump(DumpFunction(F)),
160 TableStart(TableStart), TableEnd(TableEnd),
161 FrameRegister(FrameRegister) {}
166 uint8_t *FrameRegister;
168 std::vector<EndExceptionTableCall> endExceptionTableCalls;
169 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
170 uint8_t *TableEnd, uint8_t* FrameRegister) {
171 endExceptionTableCalls.push_back(
172 EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
173 return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
177 class JITTest : public testing::Test {
179 virtual void SetUp() {
180 M = new Module("<main>", Context);
181 MP = new ExistingModuleProvider(M);
182 RJMM = new RecordingJITMemoryManager;
184 TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
185 .setJITMemoryManager(RJMM)
186 .setErrorStr(&Error).create());
187 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
190 void LoadAssembly(const char *assembly) {
192 bool success = NULL != ParseAssemblyString(assembly, M, Error, Context);
194 raw_string_ostream os(errMsg);
196 ASSERT_TRUE(success) << os.str();
200 Module *M; // Owned by MP.
201 ModuleProvider *MP; // Owned by ExecutionEngine.
202 RecordingJITMemoryManager *RJMM;
203 OwningPtr<ExecutionEngine> TheJIT;
206 // Regression test for a bug. The JIT used to allocate globals inside the same
207 // memory block used for the function, and when the function code was freed,
208 // the global was left in the same place. This test allocates a function
209 // that uses and global, deallocates it, and then makes sure that the global
210 // stays alive after that.
211 TEST(JIT, GlobalInFunction) {
213 Module *M = new Module("<main>", context);
214 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
216 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
217 // Tell the memory manager to poison freed memory so that accessing freed
218 // memory is more easily tested.
219 MemMgr->setPoisonMemory(true);
221 OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
222 .setEngineKind(EngineKind::JIT)
224 .setJITMemoryManager(MemMgr)
225 // The next line enables the fix:
226 .setAllocateGVsWithCode(false)
228 ASSERT_EQ(Error, "");
230 // Create a global variable.
231 const Type *GTy = Type::getInt32Ty(context);
232 GlobalVariable *G = new GlobalVariable(
235 false, // Not constant.
236 GlobalValue::InternalLinkage,
237 Constant::getNullValue(GTy),
240 // Make a function that points to a global.
241 Function *F1 = makeReturnGlobal("F1", G, M);
243 // Get the pointer to the native code to force it to JIT the function and
244 // allocate space for the global.
246 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
248 // Since F1 was codegen'd, a pointer to G should be available.
249 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
250 ASSERT_NE((int32_t*)NULL, GPtr);
253 // F1() should increment G.
257 // Make a second function identical to the first, referring to the same
259 Function *F2 = makeReturnGlobal("F2", G, M);
261 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
263 // F2() should increment G.
268 JIT->freeMachineCodeForFunction(F1);
270 // F2() should *still* increment G.
275 int PlusOne(int arg) {
279 TEST_F(JITTest, FarCallToKnownFunction) {
280 // x86-64 can only make direct calls to functions within 32 bits of
281 // the current PC. To call anything farther away, we have to load
282 // the address into a register and call through the register. The
283 // current JIT does this by allocating a stub for any far call.
284 // There was a bug in which the JIT tried to emit a direct call when
285 // the target was already in the JIT's global mappings and lazy
286 // compilation was disabled.
288 Function *KnownFunction = Function::Create(
289 TypeBuilder<int(int), false>::get(Context),
290 GlobalValue::ExternalLinkage, "known", M);
291 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
293 // int test() { return known(7); }
294 Function *TestFunction = Function::Create(
295 TypeBuilder<int(), false>::get(Context),
296 GlobalValue::ExternalLinkage, "test", M);
297 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
298 IRBuilder<> Builder(Entry);
299 Value *result = Builder.CreateCall(
301 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
302 Builder.CreateRet(result);
304 TheJIT->DisableLazyCompilation(true);
305 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
306 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
307 // This used to crash in trying to call PlusOne().
308 EXPECT_EQ(8, TestFunctionPtr());
311 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__ppc__)
312 // Test a function C which calls A and B which call each other.
313 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
314 TheJIT->DisableLazyCompilation(true);
316 const FunctionType *Func1Ty =
317 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
318 std::vector<const Type*> arg_types;
319 arg_types.push_back(Type::getInt1Ty(Context));
320 const 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 const 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();
409 TEST_F(JITTest, ModuleDeletion) {
410 TheJIT->DisableLazyCompilation(false);
411 LoadAssembly("define void @main() { "
412 " call i32 @computeVal() "
416 "define internal i32 @computeVal() { "
419 Function *func = M->getFunction("main");
420 TheJIT->getPointerToFunction(func);
421 TheJIT->deleteModuleProvider(MP);
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());
436 SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
437 for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
439 ExceptionTablesDeallocated.insert(
440 RJMM->deallocateExceptionTableCalls[i].ET);
442 for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
443 EXPECT_TRUE(ExceptionTablesDeallocated.count(
444 RJMM->startExceptionTableCalls[i].Result))
445 << "Function's exception table leaked: \n"
446 << RJMM->startExceptionTableCalls[i].F_dump;
448 EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
449 RJMM->deallocateExceptionTableCalls.size());
452 // This code is copied from JITEventListenerTest, but it only runs once for all
453 // the tests in this directory. Everything seems fine, but that's strange
455 class JITEnvironment : public testing::Environment {
456 virtual void SetUp() {
457 // Required to create a JIT.
458 InitializeNativeTarget();
461 testing::Environment* const jit_env =
462 testing::AddGlobalTestEnvironment(new JITEnvironment);