Fix http://llvm.org/PR4822: allow module deletion after a function has been
[oota-llvm.git] / unittests / ExecutionEngine / JIT / JITTest.cpp
1 //===- JITTest.cpp - Unit tests for the JIT -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
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"
30
31 using namespace llvm;
32
33 namespace {
34
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(),
38                                               params, false);
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);
47   return F;
48 }
49
50 class JITTest : public testing::Test {
51  protected:
52   virtual void SetUp() {
53     M = new Module("<main>", Context);
54     MP = new ExistingModuleProvider(M);
55     std::string Error;
56     TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
57                  .setErrorStr(&Error).create());
58     ASSERT_TRUE(TheJIT.get() != NULL) << Error;
59   }
60
61   void LoadAssembly(const char *assembly) {
62     SMDiagnostic Error;
63     bool success = NULL != ParseAssemblyString(assembly, M, Error, Context);
64     std::string errMsg;
65     raw_string_ostream os(errMsg);
66     Error.Print("", os);
67     ASSERT_TRUE(success) << os.str();
68   }
69
70   LLVMContext Context;
71   Module *M;  // Owned by MP.
72   ModuleProvider *MP;  // Owned by ExecutionEngine.
73   OwningPtr<ExecutionEngine> TheJIT;
74 };
75
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) {
82   LLVMContext context;
83   Module *M = new Module("<main>", context);
84   ExistingModuleProvider *MP = new ExistingModuleProvider(M);
85
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);
90   std::string Error;
91   OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
92                                  .setEngineKind(EngineKind::JIT)
93                                  .setErrorStr(&Error)
94                                  .setJITMemoryManager(MemMgr)
95                                  // The next line enables the fix:
96                                  .setAllocateGVsWithCode(false)
97                                  .create());
98   ASSERT_EQ(Error, "");
99
100   // Create a global variable.
101   const Type *GTy = Type::getInt32Ty(context);
102   GlobalVariable *G = new GlobalVariable(
103       *M,
104       GTy,
105       false,  // Not constant.
106       GlobalValue::InternalLinkage,
107       Constant::getNullValue(GTy),
108       "myglobal");
109
110   // Make a function that points to a global.
111   Function *F1 = makeReturnGlobal("F1", G, M);
112
113   // Get the pointer to the native code to force it to JIT the function and
114   // allocate space for the global.
115   void (*F1Ptr)() =
116       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
117
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);
121   EXPECT_EQ(0, *GPtr);
122
123   // F1() should increment G.
124   F1Ptr();
125   EXPECT_EQ(1, *GPtr);
126
127   // Make a second function identical to the first, referring to the same
128   // global.
129   Function *F2 = makeReturnGlobal("F2", G, M);
130   void (*F2Ptr)() =
131       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
132
133   // F2() should increment G.
134   F2Ptr();
135   EXPECT_EQ(2, *GPtr);
136
137   // Deallocate F1.
138   JIT->freeMachineCodeForFunction(F1);
139
140   // F2() should *still* increment G.
141   F2Ptr();
142   EXPECT_EQ(3, *GPtr);
143 }
144
145 int PlusOne(int arg) {
146   return arg + 1;
147 }
148
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.
157
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);
162
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(
170       KnownFunction,
171       ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
172   Builder.CreateRet(result);
173
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());
180 }
181
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();
186
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,
194                                      "func1", M);
195   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
196                                      "func2", M);
197   Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
198                                      "func3", M);
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);
206
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();
212
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();
221
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();
230
231   // Compile the function to native code
232   void (*F1Ptr)() =
233      reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
234
235   F1Ptr();
236 }
237
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();
242
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,
247                                      "func1", M);
248   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
249                                      "func2", M);
250   BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
251   BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
252
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);
257
258   // The second function just returns a constant
259   Builder.SetInsertPoint(Block2);
260   Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
261
262   // Compile the function to native code
263   (void)TheJIT->getPointerToFunction(Func1);
264
265   // Free the JIT state for the functions
266   TheJIT->freeMachineCodeForFunction(Func1);
267   TheJIT->freeMachineCodeForFunction(Func2);
268
269   // Delete the first function (and show that is has no users)
270   EXPECT_EQ(Func1->getNumUses(), 0u);
271   Func1->eraseFromParent();
272
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();
277 }
278 #endif
279
280 TEST_F(JITTest, ModuleDeletion) {
281   LoadAssembly("define void @main() { "
282                "  call i32 @computeVal() "
283                "  ret void "
284                "} "
285                " "
286                "define internal i32 @computeVal()  { "
287                "  ret i32 0 "
288                "} ");
289   Function *func = M->getFunction("main");
290   TheJIT->getPointerToFunction(func);
291   TheJIT->deleteModuleProvider(MP);
292 }
293
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
296 // behavior.
297 class JITEnvironment : public testing::Environment {
298   virtual void SetUp() {
299     // Required to create a JIT.
300     InitializeNativeTarget();
301   }
302 };
303 testing::Environment* const jit_env =
304   testing::AddGlobalTestEnvironment(new JITEnvironment);
305
306 }