Remove dlsym stubs, with Nate Begeman's permission.
[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/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"
31
32 #include <vector>
33
34 using namespace llvm;
35
36 namespace {
37
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(),
41                                               params, false);
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);
50   return F;
51 }
52
53 std::string DumpFunction(const Function *F) {
54   std::string Result;
55   raw_string_ostream(Result) << "" << *F;
56   return Result;
57 }
58
59 class RecordingJITMemoryManager : public JITMemoryManager {
60   const OwningPtr<JITMemoryManager> Base;
61 public:
62   RecordingJITMemoryManager()
63     : Base(JITMemoryManager::CreateDefaultMemManager()) {
64   }
65
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) {}
76     uint8_t *Result;
77     const Function *F;
78     std::string F_dump;
79     uintptr_t ActualSize;
80     uintptr_t ActualSizeResult;
81   };
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));
89     return Result;
90   }
91   virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
92                                 unsigned Alignment) {
93     return Base->allocateStub(F, StubSize, Alignment);
94   }
95   struct EndFunctionBodyCall {
96     EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
97                         uint8_t *FunctionEnd)
98       : F(F), F_dump(DumpFunction(F)),
99         FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
100     const Function *F;
101     std::string F_dump;
102     uint8_t *FunctionStart;
103     uint8_t *FunctionEnd;
104   };
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);
111   }
112   virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
113     return Base->allocateSpace(Size, Alignment);
114   }
115   virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
116     return Base->allocateGlobal(Size, Alignment);
117   }
118   struct DeallocateFunctionBodyCall {
119     DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
120     const void *Body;
121   };
122   std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
123   virtual void deallocateFunctionBody(void *Body) {
124     deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
125     Base->deallocateFunctionBody(Body);
126   }
127   struct DeallocateExceptionTableCall {
128     DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
129     const void *ET;
130   };
131   std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
132   virtual void deallocateExceptionTable(void *ET) {
133     deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
134     Base->deallocateExceptionTable(ET);
135   }
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) {}
141     uint8_t *Result;
142     const Function *F;
143     std::string F_dump;
144     uintptr_t ActualSize;
145     uintptr_t ActualSizeResult;
146   };
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));
154     return Result;
155   }
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) {}
162     const Function *F;
163     std::string F_dump;
164     uint8_t *TableStart;
165     uint8_t *TableEnd;
166     uint8_t *FrameRegister;
167   };
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);
174   }
175 };
176
177 class JITTest : public testing::Test {
178  protected:
179   virtual void SetUp() {
180     M = new Module("<main>", Context);
181     MP = new ExistingModuleProvider(M);
182     RJMM = new RecordingJITMemoryManager;
183     std::string Error;
184     TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
185                  .setJITMemoryManager(RJMM)
186                  .setErrorStr(&Error).create());
187     ASSERT_TRUE(TheJIT.get() != NULL) << Error;
188   }
189
190   void LoadAssembly(const char *assembly) {
191     SMDiagnostic Error;
192     bool success = NULL != ParseAssemblyString(assembly, M, Error, Context);
193     std::string errMsg;
194     raw_string_ostream os(errMsg);
195     Error.Print("", os);
196     ASSERT_TRUE(success) << os.str();
197   }
198
199   LLVMContext Context;
200   Module *M;  // Owned by MP.
201   ModuleProvider *MP;  // Owned by ExecutionEngine.
202   RecordingJITMemoryManager *RJMM;
203   OwningPtr<ExecutionEngine> TheJIT;
204 };
205
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) {
212   LLVMContext context;
213   Module *M = new Module("<main>", context);
214   ExistingModuleProvider *MP = new ExistingModuleProvider(M);
215
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);
220   std::string Error;
221   OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
222                                  .setEngineKind(EngineKind::JIT)
223                                  .setErrorStr(&Error)
224                                  .setJITMemoryManager(MemMgr)
225                                  // The next line enables the fix:
226                                  .setAllocateGVsWithCode(false)
227                                  .create());
228   ASSERT_EQ(Error, "");
229
230   // Create a global variable.
231   const Type *GTy = Type::getInt32Ty(context);
232   GlobalVariable *G = new GlobalVariable(
233       *M,
234       GTy,
235       false,  // Not constant.
236       GlobalValue::InternalLinkage,
237       Constant::getNullValue(GTy),
238       "myglobal");
239
240   // Make a function that points to a global.
241   Function *F1 = makeReturnGlobal("F1", G, M);
242
243   // Get the pointer to the native code to force it to JIT the function and
244   // allocate space for the global.
245   void (*F1Ptr)() =
246       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
247
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);
251   EXPECT_EQ(0, *GPtr);
252
253   // F1() should increment G.
254   F1Ptr();
255   EXPECT_EQ(1, *GPtr);
256
257   // Make a second function identical to the first, referring to the same
258   // global.
259   Function *F2 = makeReturnGlobal("F2", G, M);
260   void (*F2Ptr)() =
261       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
262
263   // F2() should increment G.
264   F2Ptr();
265   EXPECT_EQ(2, *GPtr);
266
267   // Deallocate F1.
268   JIT->freeMachineCodeForFunction(F1);
269
270   // F2() should *still* increment G.
271   F2Ptr();
272   EXPECT_EQ(3, *GPtr);
273 }
274
275 int PlusOne(int arg) {
276   return arg + 1;
277 }
278
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.
287
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);
292
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(
300       KnownFunction,
301       ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
302   Builder.CreateRet(result);
303
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());
309 }
310
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);
315
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,
323                                      "func1", M);
324   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
325                                      "func2", M);
326   Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
327                                      "func3", M);
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);
335
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();
341
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();
350
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();
359
360   // Compile the function to native code
361   void (*F1Ptr)() =
362      reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
363
364   F1Ptr();
365 }
366
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);
371
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,
376                                      "func1", M);
377   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
378                                      "func2", M);
379   BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
380   BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
381
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);
386
387   // The second function just returns a constant
388   Builder.SetInsertPoint(Block2);
389   Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
390
391   // Compile the function to native code
392   (void)TheJIT->getPointerToFunction(Func1);
393
394   // Free the JIT state for the functions
395   TheJIT->freeMachineCodeForFunction(Func1);
396   TheJIT->freeMachineCodeForFunction(Func2);
397
398   // Delete the first function (and show that is has no users)
399   EXPECT_EQ(Func1->getNumUses(), 0u);
400   Func1->eraseFromParent();
401
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();
406 }
407 #endif
408
409 TEST_F(JITTest, ModuleDeletion) {
410   TheJIT->DisableLazyCompilation(false);
411   LoadAssembly("define void @main() { "
412                "  call i32 @computeVal() "
413                "  ret void "
414                "} "
415                " "
416                "define internal i32 @computeVal()  { "
417                "  ret i32 0 "
418                "} ");
419   Function *func = M->getFunction("main");
420   TheJIT->getPointerToFunction(func);
421   TheJIT->deleteModuleProvider(MP);
422
423   SmallPtrSet<const void*, 2> FunctionsDeallocated;
424   for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
425        i != e; ++i) {
426     FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
427   }
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;
432   }
433   EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
434             RJMM->deallocateFunctionBodyCalls.size());
435
436   SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
437   for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
438        i != e; ++i) {
439     ExceptionTablesDeallocated.insert(
440         RJMM->deallocateExceptionTableCalls[i].ET);
441   }
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;
447   }
448   EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
449             RJMM->deallocateExceptionTableCalls.size());
450 }
451
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
454 // behavior.
455 class JITEnvironment : public testing::Environment {
456   virtual void SetUp() {
457     // Required to create a JIT.
458     InitializeNativeTarget();
459   }
460 };
461 testing::Environment* const jit_env =
462   testing::AddGlobalTestEnvironment(new JITEnvironment);
463
464 }