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/Assembly/Parser.h"
13 #include "llvm/BasicBlock.h"
14 #include "llvm/Constant.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/ExecutionEngine/JIT.h"
18 #include "llvm/ExecutionEngine/JITMemoryManager.h"
19 #include "llvm/Function.h"
20 #include "llvm/GlobalValue.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/ModuleProvider.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TypeBuilder.h"
28 #include "llvm/Target/TargetSelect.h"
29 #include "llvm/Type.h"
35 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
36 std::vector<const Type*> params;
37 const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
39 Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
40 BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
41 IRBuilder<> builder(Entry);
42 Value *Load = builder.CreateLoad(G);
43 const Type *GTy = G->getType()->getElementType();
44 Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
45 builder.CreateStore(Add, G);
46 builder.CreateRet(Add);
50 class JITTest : public testing::Test {
52 virtual void SetUp() {
53 M = new Module("<main>", Context);
54 MP = new ExistingModuleProvider(M);
56 TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
57 .setErrorStr(&Error).create());
58 ASSERT_TRUE(TheJIT.get() != NULL) << Error;
61 void LoadAssembly(const char *assembly) {
63 bool success = NULL != ParseAssemblyString(assembly, M, Error, Context);
65 raw_string_ostream os(errMsg);
67 ASSERT_TRUE(success) << os.str();
71 Module *M; // Owned by MP.
72 ModuleProvider *MP; // Owned by ExecutionEngine.
73 OwningPtr<ExecutionEngine> TheJIT;
76 // Regression test for a bug. The JIT used to allocate globals inside the same
77 // memory block used for the function, and when the function code was freed,
78 // the global was left in the same place. This test allocates a function
79 // that uses and global, deallocates it, and then makes sure that the global
80 // stays alive after that.
81 TEST(JIT, GlobalInFunction) {
83 Module *M = new Module("<main>", context);
84 ExistingModuleProvider *MP = new ExistingModuleProvider(M);
86 JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
87 // Tell the memory manager to poison freed memory so that accessing freed
88 // memory is more easily tested.
89 MemMgr->setPoisonMemory(true);
91 OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
92 .setEngineKind(EngineKind::JIT)
94 .setJITMemoryManager(MemMgr)
95 // The next line enables the fix:
96 .setAllocateGVsWithCode(false)
100 // Create a global variable.
101 const Type *GTy = Type::getInt32Ty(context);
102 GlobalVariable *G = new GlobalVariable(
105 false, // Not constant.
106 GlobalValue::InternalLinkage,
107 Constant::getNullValue(GTy),
110 // Make a function that points to a global.
111 Function *F1 = makeReturnGlobal("F1", G, M);
113 // Get the pointer to the native code to force it to JIT the function and
114 // allocate space for the global.
116 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
118 // Since F1 was codegen'd, a pointer to G should be available.
119 int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
120 ASSERT_NE((int32_t*)NULL, GPtr);
123 // F1() should increment G.
127 // Make a second function identical to the first, referring to the same
129 Function *F2 = makeReturnGlobal("F2", G, M);
131 reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
133 // F2() should increment G.
138 JIT->freeMachineCodeForFunction(F1);
140 // F2() should *still* increment G.
145 int PlusOne(int arg) {
149 TEST_F(JITTest, FarCallToKnownFunction) {
150 // x86-64 can only make direct calls to functions within 32 bits of
151 // the current PC. To call anything farther away, we have to load
152 // the address into a register and call through the register. The
153 // current JIT does this by allocating a stub for any far call.
154 // There was a bug in which the JIT tried to emit a direct call when
155 // the target was already in the JIT's global mappings and lazy
156 // compilation was disabled.
158 Function *KnownFunction = Function::Create(
159 TypeBuilder<int(int), false>::get(Context),
160 GlobalValue::ExternalLinkage, "known", M);
161 TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
163 // int test() { return known(7); }
164 Function *TestFunction = Function::Create(
165 TypeBuilder<int(), false>::get(Context),
166 GlobalValue::ExternalLinkage, "test", M);
167 BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
168 IRBuilder<> Builder(Entry);
169 Value *result = Builder.CreateCall(
171 ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
172 Builder.CreateRet(result);
174 TheJIT->EnableDlsymStubs(false);
175 TheJIT->DisableLazyCompilation();
176 int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
177 (intptr_t)TheJIT->getPointerToFunction(TestFunction));
178 // This used to crash in trying to call PlusOne().
179 EXPECT_EQ(8, TestFunctionPtr());
182 #if !defined(__arm__) && !defined(__powerpc__) && !defined(__ppc__)
183 // Test a function C which calls A and B which call each other.
184 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
185 TheJIT->DisableLazyCompilation();
187 const FunctionType *Func1Ty =
188 cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
189 std::vector<const Type*> arg_types;
190 arg_types.push_back(Type::getInt1Ty(Context));
191 const FunctionType *FuncTy = FunctionType::get(
192 Type::getVoidTy(Context), arg_types, false);
193 Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
195 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
197 Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
199 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
200 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
201 BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
202 BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
203 BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
204 BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
205 BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
207 // Make Func1 call Func2(0) and Func3(0).
208 IRBuilder<> Builder(Block1);
209 Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
210 Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
211 Builder.CreateRetVoid();
213 // void Func2(bool b) { if (b) { Func3(false); return; } return; }
214 Builder.SetInsertPoint(Block2);
215 Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
216 Builder.SetInsertPoint(True2);
217 Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
218 Builder.CreateRetVoid();
219 Builder.SetInsertPoint(False2);
220 Builder.CreateRetVoid();
222 // void Func3(bool b) { if (b) { Func2(false); return; } return; }
223 Builder.SetInsertPoint(Block3);
224 Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
225 Builder.SetInsertPoint(True3);
226 Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
227 Builder.CreateRetVoid();
228 Builder.SetInsertPoint(False3);
229 Builder.CreateRetVoid();
231 // Compile the function to native code
233 reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
238 // Regression test for PR5162. This used to trigger an AssertingVH inside the
239 // JIT's Function to stub mapping.
240 TEST_F(JITTest, NonLazyLeaksNoStubs) {
241 TheJIT->DisableLazyCompilation();
243 // Create two functions with a single basic block each.
244 const FunctionType *FuncTy =
245 cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
246 Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
248 Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
250 BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
251 BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
253 // The first function calls the second and returns the result
254 IRBuilder<> Builder(Block1);
255 Value *Result = Builder.CreateCall(Func2);
256 Builder.CreateRet(Result);
258 // The second function just returns a constant
259 Builder.SetInsertPoint(Block2);
260 Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
262 // Compile the function to native code
263 (void)TheJIT->getPointerToFunction(Func1);
265 // Free the JIT state for the functions
266 TheJIT->freeMachineCodeForFunction(Func1);
267 TheJIT->freeMachineCodeForFunction(Func2);
269 // Delete the first function (and show that is has no users)
270 EXPECT_EQ(Func1->getNumUses(), 0u);
271 Func1->eraseFromParent();
273 // Delete the second function (and show that it has no users - it had one,
274 // func1 but that's gone now)
275 EXPECT_EQ(Func2->getNumUses(), 0u);
276 Func2->eraseFromParent();
280 TEST_F(JITTest, ModuleDeletion) {
281 LoadAssembly("define void @main() { "
282 " call i32 @computeVal() "
286 "define internal i32 @computeVal() { "
289 Function *func = M->getFunction("main");
290 TheJIT->getPointerToFunction(func);
291 TheJIT->deleteModuleProvider(MP);
294 // This code is copied from JITEventListenerTest, but it only runs once for all
295 // the tests in this directory. Everything seems fine, but that's strange
297 class JITEnvironment : public testing::Environment {
298 virtual void SetUp() {
299 // Required to create a JIT.
300 InitializeNativeTarget();
303 testing::Environment* const jit_env =
304 testing::AddGlobalTestEnvironment(new JITEnvironment);