Revert the API changes from r85295 to make it easier for people to build
[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   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) {}
78     uint8_t *Result;
79     const Function *F;
80     std::string F_dump;
81     uintptr_t ActualSize;
82     uintptr_t ActualSizeResult;
83   };
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));
91     return Result;
92   }
93   virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
94                                 unsigned Alignment) {
95     return Base->allocateStub(F, StubSize, Alignment);
96   }
97   struct EndFunctionBodyCall {
98     EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
99                         uint8_t *FunctionEnd)
100       : F(F), F_dump(DumpFunction(F)),
101         FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
102     const Function *F;
103     std::string F_dump;
104     uint8_t *FunctionStart;
105     uint8_t *FunctionEnd;
106   };
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);
113   }
114   virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
115     return Base->allocateSpace(Size, Alignment);
116   }
117   virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
118     return Base->allocateGlobal(Size, Alignment);
119   }
120   struct DeallocateFunctionBodyCall {
121     DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
122     const void *Body;
123   };
124   std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
125   virtual void deallocateFunctionBody(void *Body) {
126     deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
127     Base->deallocateFunctionBody(Body);
128   }
129   struct DeallocateExceptionTableCall {
130     DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
131     const void *ET;
132   };
133   std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
134   virtual void deallocateExceptionTable(void *ET) {
135     deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
136     Base->deallocateExceptionTable(ET);
137   }
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) {}
143     uint8_t *Result;
144     const Function *F;
145     std::string F_dump;
146     uintptr_t ActualSize;
147     uintptr_t ActualSizeResult;
148   };
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));
156     return Result;
157   }
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) {}
164     const Function *F;
165     std::string F_dump;
166     uint8_t *TableStart;
167     uint8_t *TableEnd;
168     uint8_t *FrameRegister;
169   };
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);
176   }
177 };
178
179 class JITTest : public testing::Test {
180  protected:
181   virtual void SetUp() {
182     M = new Module("<main>", Context);
183     MP = new ExistingModuleProvider(M);
184     RJMM = new RecordingJITMemoryManager;
185     std::string Error;
186     TheJIT.reset(EngineBuilder(MP).setEngineKind(EngineKind::JIT)
187                  .setJITMemoryManager(RJMM)
188                  .setErrorStr(&Error).create());
189     ASSERT_TRUE(TheJIT.get() != NULL) << Error;
190   }
191
192   void LoadAssembly(const char *assembly) {
193     SMDiagnostic Error;
194     bool success = NULL != ParseAssemblyString(assembly, M, Error, Context);
195     std::string errMsg;
196     raw_string_ostream os(errMsg);
197     Error.Print("", os);
198     ASSERT_TRUE(success) << os.str();
199   }
200
201   LLVMContext Context;
202   Module *M;  // Owned by MP.
203   ModuleProvider *MP;  // Owned by ExecutionEngine.
204   RecordingJITMemoryManager *RJMM;
205   OwningPtr<ExecutionEngine> TheJIT;
206 };
207
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) {
214   LLVMContext context;
215   Module *M = new Module("<main>", context);
216   ExistingModuleProvider *MP = new ExistingModuleProvider(M);
217
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);
222   std::string Error;
223   OwningPtr<ExecutionEngine> JIT(EngineBuilder(MP)
224                                  .setEngineKind(EngineKind::JIT)
225                                  .setErrorStr(&Error)
226                                  .setJITMemoryManager(MemMgr)
227                                  // The next line enables the fix:
228                                  .setAllocateGVsWithCode(false)
229                                  .create());
230   ASSERT_EQ(Error, "");
231
232   // Create a global variable.
233   const Type *GTy = Type::getInt32Ty(context);
234   GlobalVariable *G = new GlobalVariable(
235       *M,
236       GTy,
237       false,  // Not constant.
238       GlobalValue::InternalLinkage,
239       Constant::getNullValue(GTy),
240       "myglobal");
241
242   // Make a function that points to a global.
243   Function *F1 = makeReturnGlobal("F1", G, M);
244
245   // Get the pointer to the native code to force it to JIT the function and
246   // allocate space for the global.
247   void (*F1Ptr)() =
248       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
249
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);
253   EXPECT_EQ(0, *GPtr);
254
255   // F1() should increment G.
256   F1Ptr();
257   EXPECT_EQ(1, *GPtr);
258
259   // Make a second function identical to the first, referring to the same
260   // global.
261   Function *F2 = makeReturnGlobal("F2", G, M);
262   void (*F2Ptr)() =
263       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
264
265   // F2() should increment G.
266   F2Ptr();
267   EXPECT_EQ(2, *GPtr);
268
269   // Deallocate F1.
270   JIT->freeMachineCodeForFunction(F1);
271
272   // F2() should *still* increment G.
273   F2Ptr();
274   EXPECT_EQ(3, *GPtr);
275 }
276
277 int PlusOne(int arg) {
278   return arg + 1;
279 }
280
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.
289
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);
294
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(
302       KnownFunction,
303       ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
304   Builder.CreateRet(result);
305
306   TheJIT->EnableDlsymStubs(false);
307   TheJIT->DisableLazyCompilation(true);
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());
312 }
313
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(true);
318
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,
326                                      "func1", M);
327   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
328                                      "func2", M);
329   Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
330                                      "func3", M);
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);
338
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();
344
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();
353
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();
362
363   // Compile the function to native code
364   void (*F1Ptr)() =
365      reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
366
367   F1Ptr();
368 }
369
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(true);
374
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,
379                                      "func1", M);
380   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
381                                      "func2", M);
382   BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
383   BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
384
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);
389
390   // The second function just returns a constant
391   Builder.SetInsertPoint(Block2);
392   Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
393
394   // Compile the function to native code
395   (void)TheJIT->getPointerToFunction(Func1);
396
397   // Free the JIT state for the functions
398   TheJIT->freeMachineCodeForFunction(Func1);
399   TheJIT->freeMachineCodeForFunction(Func2);
400
401   // Delete the first function (and show that is has no users)
402   EXPECT_EQ(Func1->getNumUses(), 0u);
403   Func1->eraseFromParent();
404
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();
409 }
410 #endif
411
412 TEST_F(JITTest, ModuleDeletion) {
413   LoadAssembly("define void @main() { "
414                "  call i32 @computeVal() "
415                "  ret void "
416                "} "
417                " "
418                "define internal i32 @computeVal()  { "
419                "  ret i32 0 "
420                "} ");
421   Function *func = M->getFunction("main");
422   TheJIT->getPointerToFunction(func);
423   TheJIT->deleteModuleProvider(MP);
424
425   SmallPtrSet<const void*, 2> FunctionsDeallocated;
426   for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
427        i != e; ++i) {
428     FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
429   }
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;
434   }
435   EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
436             RJMM->deallocateFunctionBodyCalls.size());
437
438   SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
439   for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
440        i != e; ++i) {
441     ExceptionTablesDeallocated.insert(
442         RJMM->deallocateExceptionTableCalls[i].ET);
443   }
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;
449   }
450   EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
451             RJMM->deallocateExceptionTableCalls.size());
452 }
453
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
456 // behavior.
457 class JITEnvironment : public testing::Environment {
458   virtual void SetUp() {
459     // Required to create a JIT.
460     InitializeNativeTarget();
461   }
462 };
463 testing::Environment* const jit_env =
464   testing::AddGlobalTestEnvironment(new JITEnvironment);
465
466 }