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 virtual void SetDlsymTable(void *ptr) { Base->SetDlsymTable(ptr); }
72 virtual void *getDlsymTable() const { return Base->getDlsymTable(); }
73 struct StartFunctionBodyCall {
74 StartFunctionBodyCall(uint8_t *Result, const Function *F,
75 uintptr_t ActualSize, uintptr_t ActualSizeResult)
76 : Result(Result), F(F), F_dump(DumpFunction(F)),
77 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
82 uintptr_t ActualSizeResult;
84 std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
85 virtual uint8_t *startFunctionBody(const Function *F,
86 uintptr_t &ActualSize) {
87 uintptr_t InitialActualSize = ActualSize;
88 uint8_t *Result = Base->startFunctionBody(F, ActualSize);
89 startFunctionBodyCalls.push_back(
90 StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
93 virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
95 return Base->allocateStub(F, StubSize, Alignment);
97 struct EndFunctionBodyCall {
98 EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
100 : F(F), F_dump(DumpFunction(F)),
101 FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
104 uint8_t *FunctionStart;
105 uint8_t *FunctionEnd;
107 std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
108 virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
109 uint8_t *FunctionEnd) {
110 endFunctionBodyCalls.push_back(
111 EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
112 Base->endFunctionBody(F, FunctionStart, FunctionEnd);
114 virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
115 return Base->allocateSpace(Size, Alignment);
117 virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
118 return Base->allocateGlobal(Size, Alignment);
120 struct DeallocateFunctionBodyCall {
121 DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
124 std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
125 virtual void deallocateFunctionBody(void *Body) {
126 deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
127 Base->deallocateFunctionBody(Body);
129 struct DeallocateExceptionTableCall {
130 DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
133 std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
134 virtual void deallocateExceptionTable(void *ET) {
135 deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
136 Base->deallocateExceptionTable(ET);
138 struct StartExceptionTableCall {
139 StartExceptionTableCall(uint8_t *Result, const Function *F,
140 uintptr_t ActualSize, uintptr_t ActualSizeResult)
141 : Result(Result), F(F), F_dump(DumpFunction(F)),
142 ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
146 uintptr_t ActualSize;
147 uintptr_t ActualSizeResult;
149 std::vector<StartExceptionTableCall> startExceptionTableCalls;
150 virtual uint8_t* startExceptionTable(const Function* F,
151 uintptr_t &ActualSize) {
152 uintptr_t InitialActualSize = ActualSize;
153 uint8_t *Result = Base->startExceptionTable(F, ActualSize);
154 startExceptionTableCalls.push_back(
155 StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
158 struct EndExceptionTableCall {
159 EndExceptionTableCall(const Function *F, uint8_t *TableStart,
160 uint8_t *TableEnd, uint8_t* FrameRegister)
161 : F(F), F_dump(DumpFunction(F)),
162 TableStart(TableStart), TableEnd(TableEnd),
163 FrameRegister(FrameRegister) {}
168 uint8_t *FrameRegister;
170 std::vector<EndExceptionTableCall> endExceptionTableCalls;
171 virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
172 uint8_t *TableEnd, uint8_t* FrameRegister) {
173 endExceptionTableCalls.push_back(
174 EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
175 return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
179 class JITTest : public testing::Test {
181 virtual void SetUp() {
182 M = new Module("<main>", Context);
183 MP = new ExistingModuleProvider(M);
184 RJMM = new RecordingJITMemoryManager;
186 TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
187 .setJITMemoryManager(RJMM)
188 .setErrorStr(&Error).create());
189 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
192 void LoadAssembly(const char *assembly) {
194 bool success = NULL != ParseAssemblyString(assembly, M, Error, Context);
196 raw_string_ostream os(errMsg);
198 ASSERT_TRUE(success) << os.str();
202 Module *M; // Owned by MP.
203 ModuleProvider *MP; // Owned by ExecutionEngine.
204 RecordingJITMemoryManager *RJMM;
205 OwningPtr<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);
216 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
218 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
219 // Tell the memory manager to poison freed memory so that accessing freed
220 // memory is more easily tested.
221 MemMgr->setPoisonMemory(true);
223 OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
224 .setEngineKind(EngineKind::JIT)
226 .setJITMemoryManager(MemMgr)
227 // The next line enables the fix:
228 .setAllocateGVsWithCode(false)
230 ASSERT_EQ(Error, "");
232 // Create a global variable.
233 const Type *GTy = Type::getInt32Ty(context);
234 GlobalVariable *G = new GlobalVariable(
237 false, // Not constant.
238 GlobalValue::InternalLinkage,
239 Constant::getNullValue(GTy),
242 // Make a function that points to a global.
243 Function *F1 = makeReturnGlobal("F1", G, M);
245 // Get the pointer to the native code to force it to JIT the function and
246 // allocate space for the global.
248 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
250 // Since F1 was codegen'd, a pointer to G should be available.
251 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
252 ASSERT_NE((int32_t*)NULL, GPtr);
255 // F1() should increment G.
259 // Make a second function identical to the first, referring to the same
261 Function *F2 = makeReturnGlobal("F2", G, M);
263 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
265 // F2() should increment G.
270 JIT->freeMachineCodeForFunction(F1);
272 // F2() should *still* increment G.
277 int PlusOne(int arg) {
281 TEST_F(JITTest, FarCallToKnownFunction) {
282 // x86-64 can only make direct calls to functions within 32 bits of
283 // the current PC. To call anything farther away, we have to load
284 // the address into a register and call through the register. The
285 // current JIT does this by allocating a stub for any far call.
286 // There was a bug in which the JIT tried to emit a direct call when
287 // the target was already in the JIT's global mappings and lazy
288 // compilation was disabled.
290 Function *KnownFunction = Function::Create(
291 TypeBuilder<int(int), false>::get(Context),
292 GlobalValue::ExternalLinkage, "known", M);
293 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
295 // int test() { return known(7); }
296 Function *TestFunction = Function::Create(
297 TypeBuilder<int(), false>::get(Context),
298 GlobalValue::ExternalLinkage, "test", M);
299 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
300 IRBuilder<> Builder(Entry);
301 Value *result = Builder.CreateCall(
303 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
304 Builder.CreateRet(result);
306 TheJIT->EnableDlsymStubs(false);
307 TheJIT->DisableLazyCompilation();
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 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__ppc__)
315 // Test a function C which calls A and B which call each other.
316 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
317 TheJIT->DisableLazyCompilation();
319 const FunctionType *Func1Ty =
320 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
321 std::vector<const Type*> arg_types;
322 arg_types.push_back(Type::getInt1Ty(Context));
323 const FunctionType *FuncTy = FunctionType::get(
324 Type::getVoidTy(Context), arg_types, false);
325 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
327 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
329 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
331 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
332 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
333 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
334 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
335 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
336 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
337 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
339 // Make Func1 call Func2(0) and Func3(0).
340 IRBuilder<> Builder(Block1);
341 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
342 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
343 Builder.CreateRetVoid();
345 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
346 Builder.SetInsertPoint(Block2);
347 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
348 Builder.SetInsertPoint(True2);
349 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
350 Builder.CreateRetVoid();
351 Builder.SetInsertPoint(False2);
352 Builder.CreateRetVoid();
354 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
355 Builder.SetInsertPoint(Block3);
356 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
357 Builder.SetInsertPoint(True3);
358 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
359 Builder.CreateRetVoid();
360 Builder.SetInsertPoint(False3);
361 Builder.CreateRetVoid();
363 // Compile the function to native code
365 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
370 // Regression test for PR5162. This used to trigger an AssertingVH inside the
371 // JIT's Function to stub mapping.
372 TEST_F(JITTest, NonLazyLeaksNoStubs) {
373 TheJIT->DisableLazyCompilation();
375 // Create two functions with a single basic block each.
376 const FunctionType *FuncTy =
377 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
378 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
380 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
382 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
383 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
385 // The first function calls the second and returns the result
386 IRBuilder<> Builder(Block1);
387 Value *Result = Builder.CreateCall(Func2);
388 Builder.CreateRet(Result);
390 // The second function just returns a constant
391 Builder.SetInsertPoint(Block2);
392 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
394 // Compile the function to native code
395 (void)TheJIT->getPointerToFunction(Func1);
397 // Free the JIT state for the functions
398 TheJIT->freeMachineCodeForFunction(Func1);
399 TheJIT->freeMachineCodeForFunction(Func2);
401 // Delete the first function (and show that is has no users)
402 EXPECT_EQ(Func1->getNumUses(), 0u);
403 Func1->eraseFromParent();
405 // Delete the second function (and show that it has no users - it had one,
406 // func1 but that's gone now)
407 EXPECT_EQ(Func2->getNumUses(), 0u);
408 Func2->eraseFromParent();
412 TEST_F(JITTest, ModuleDeletion) {
413 LoadAssembly("define void @main() { "
414 " call i32 @computeVal() "
418 "define internal i32 @computeVal() { "
421 Function *func = M->getFunction("main");
422 TheJIT->getPointerToFunction(func);
423 TheJIT->deleteModuleProvider(MP);
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());
438 SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
439 for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
441 ExceptionTablesDeallocated.insert(
442 RJMM->deallocateExceptionTableCalls[i].ET);
444 for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
445 EXPECT_TRUE(ExceptionTablesDeallocated.count(
446 RJMM->startExceptionTableCalls[i].Result))
447 << "Function's exception table leaked: \n"
448 << RJMM->startExceptionTableCalls[i].F_dump;
450 EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
451 RJMM->deallocateExceptionTableCalls.size());
454 // This code is copied from JITEventListenerTest, but it only runs once for all
455 // the tests in this directory. Everything seems fine, but that's strange
457 class JITEnvironment : public testing::Environment {
458 virtual void SetUp() {
459 // Required to create a JIT.
460 InitializeNativeTarget();
463 testing::Environment* const jit_env =
464 testing::AddGlobalTestEnvironment(new JITEnvironment);