Simplify JIT unit test #ifdefs
[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 "llvm/ExecutionEngine/JIT.h"
11 #include "llvm/ADT/OwningPtr.h"
12 #include "llvm/ADT/SmallPtrSet.h"
13 #include "llvm/Assembly/Parser.h"
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/ExecutionEngine/JITMemoryManager.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Constant.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/IR/TypeBuilder.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TargetSelect.h"
31 #include "gtest/gtest.h"
32 #include <vector>
33
34 using namespace llvm;
35
36 namespace {
37
38 // Tests on ARM and PowerPC disabled as we're running the old jit
39 #if !defined(__arm__) && !defined(__powerpc__)
40
41 Function *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {
42   std::vector<Type*> params;
43   FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),
44                                               params, false);
45   Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);
46   BasicBlock *Entry = BasicBlock::Create(M->getContext(), "entry", F);
47   IRBuilder<> builder(Entry);
48   Value *Load = builder.CreateLoad(G);
49   Type *GTy = G->getType()->getElementType();
50   Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));
51   builder.CreateStore(Add, G);
52   builder.CreateRet(Add);
53   return F;
54 }
55
56 std::string DumpFunction(const Function *F) {
57   std::string Result;
58   raw_string_ostream(Result) << "" << *F;
59   return Result;
60 }
61
62 class RecordingJITMemoryManager : public JITMemoryManager {
63   const OwningPtr<JITMemoryManager> Base;
64 public:
65   RecordingJITMemoryManager()
66     : Base(JITMemoryManager::CreateDefaultMemManager()) {
67     stubsAllocated = 0;
68   }
69   virtual void *getPointerToNamedFunction(const std::string &Name,
70                                           bool AbortOnFailure = true) {
71     return Base->getPointerToNamedFunction(Name, AbortOnFailure);
72   }
73
74   virtual void setMemoryWritable() { Base->setMemoryWritable(); }
75   virtual void setMemoryExecutable() { Base->setMemoryExecutable(); }
76   virtual void setPoisonMemory(bool poison) { Base->setPoisonMemory(poison); }
77   virtual void AllocateGOT() { Base->AllocateGOT(); }
78   virtual uint8_t *getGOTBase() const { return Base->getGOTBase(); }
79   struct StartFunctionBodyCall {
80     StartFunctionBodyCall(uint8_t *Result, const Function *F,
81                           uintptr_t ActualSize, uintptr_t ActualSizeResult)
82       : Result(Result), F(F), F_dump(DumpFunction(F)),
83         ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
84     uint8_t *Result;
85     const Function *F;
86     std::string F_dump;
87     uintptr_t ActualSize;
88     uintptr_t ActualSizeResult;
89   };
90   std::vector<StartFunctionBodyCall> startFunctionBodyCalls;
91   virtual uint8_t *startFunctionBody(const Function *F,
92                                      uintptr_t &ActualSize) {
93     uintptr_t InitialActualSize = ActualSize;
94     uint8_t *Result = Base->startFunctionBody(F, ActualSize);
95     startFunctionBodyCalls.push_back(
96       StartFunctionBodyCall(Result, F, InitialActualSize, ActualSize));
97     return Result;
98   }
99   int stubsAllocated;
100   virtual uint8_t *allocateStub(const GlobalValue* F, unsigned StubSize,
101                                 unsigned Alignment) {
102     stubsAllocated++;
103     return Base->allocateStub(F, StubSize, Alignment);
104   }
105   struct EndFunctionBodyCall {
106     EndFunctionBodyCall(const Function *F, uint8_t *FunctionStart,
107                         uint8_t *FunctionEnd)
108       : F(F), F_dump(DumpFunction(F)),
109         FunctionStart(FunctionStart), FunctionEnd(FunctionEnd) {}
110     const Function *F;
111     std::string F_dump;
112     uint8_t *FunctionStart;
113     uint8_t *FunctionEnd;
114   };
115   std::vector<EndFunctionBodyCall> endFunctionBodyCalls;
116   virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
117                                uint8_t *FunctionEnd) {
118     endFunctionBodyCalls.push_back(
119       EndFunctionBodyCall(F, FunctionStart, FunctionEnd));
120     Base->endFunctionBody(F, FunctionStart, FunctionEnd);
121   }
122   virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
123                                        unsigned SectionID, bool IsReadOnly) {
124     return Base->allocateDataSection(Size, Alignment, SectionID, IsReadOnly);
125   }
126   virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
127                                        unsigned SectionID) {
128     return Base->allocateCodeSection(Size, Alignment, SectionID);
129   }
130   virtual bool applyPermissions(std::string *ErrMsg) { return false; }
131   virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) {
132     return Base->allocateSpace(Size, Alignment);
133   }
134   virtual uint8_t *allocateGlobal(uintptr_t Size, unsigned Alignment) {
135     return Base->allocateGlobal(Size, Alignment);
136   }
137   struct DeallocateFunctionBodyCall {
138     DeallocateFunctionBodyCall(const void *Body) : Body(Body) {}
139     const void *Body;
140   };
141   std::vector<DeallocateFunctionBodyCall> deallocateFunctionBodyCalls;
142   virtual void deallocateFunctionBody(void *Body) {
143     deallocateFunctionBodyCalls.push_back(DeallocateFunctionBodyCall(Body));
144     Base->deallocateFunctionBody(Body);
145   }
146   struct DeallocateExceptionTableCall {
147     DeallocateExceptionTableCall(const void *ET) : ET(ET) {}
148     const void *ET;
149   };
150   std::vector<DeallocateExceptionTableCall> deallocateExceptionTableCalls;
151   virtual void deallocateExceptionTable(void *ET) {
152     deallocateExceptionTableCalls.push_back(DeallocateExceptionTableCall(ET));
153     Base->deallocateExceptionTable(ET);
154   }
155   struct StartExceptionTableCall {
156     StartExceptionTableCall(uint8_t *Result, const Function *F,
157                             uintptr_t ActualSize, uintptr_t ActualSizeResult)
158       : Result(Result), F(F), F_dump(DumpFunction(F)),
159         ActualSize(ActualSize), ActualSizeResult(ActualSizeResult) {}
160     uint8_t *Result;
161     const Function *F;
162     std::string F_dump;
163     uintptr_t ActualSize;
164     uintptr_t ActualSizeResult;
165   };
166   std::vector<StartExceptionTableCall> startExceptionTableCalls;
167   virtual uint8_t *startExceptionTable(const Function *F,
168                                        uintptr_t &ActualSize) {
169     uintptr_t InitialActualSize = ActualSize;
170     uint8_t *Result = Base->startExceptionTable(F, ActualSize);
171     startExceptionTableCalls.push_back(
172       StartExceptionTableCall(Result, F, InitialActualSize, ActualSize));
173     return Result;
174   }
175   struct EndExceptionTableCall {
176     EndExceptionTableCall(const Function *F, uint8_t *TableStart,
177                           uint8_t *TableEnd, uint8_t* FrameRegister)
178       : F(F), F_dump(DumpFunction(F)),
179         TableStart(TableStart), TableEnd(TableEnd),
180         FrameRegister(FrameRegister) {}
181     const Function *F;
182     std::string F_dump;
183     uint8_t *TableStart;
184     uint8_t *TableEnd;
185     uint8_t *FrameRegister;
186   };
187   std::vector<EndExceptionTableCall> endExceptionTableCalls;
188   virtual void endExceptionTable(const Function *F, uint8_t *TableStart,
189                                  uint8_t *TableEnd, uint8_t* FrameRegister) {
190       endExceptionTableCalls.push_back(
191           EndExceptionTableCall(F, TableStart, TableEnd, FrameRegister));
192     return Base->endExceptionTable(F, TableStart, TableEnd, FrameRegister);
193   }
194 };
195
196 bool LoadAssemblyInto(Module *M, const char *assembly) {
197   SMDiagnostic Error;
198   bool success =
199     NULL != ParseAssemblyString(assembly, M, Error, M->getContext());
200   std::string errMsg;
201   raw_string_ostream os(errMsg);
202   Error.print("", os);
203   EXPECT_TRUE(success) << os.str();
204   return success;
205 }
206
207 class JITTest : public testing::Test {
208  protected:
209   virtual RecordingJITMemoryManager *createMemoryManager() {
210     return new RecordingJITMemoryManager;
211   }
212
213   virtual void SetUp() {
214     M = new Module("<main>", Context);
215     RJMM = createMemoryManager();
216     RJMM->setPoisonMemory(true);
217     std::string Error;
218     TargetOptions Options;
219     Options.JITExceptionHandling = true;
220     TheJIT.reset(EngineBuilder(M).setEngineKind(EngineKind::JIT)
221                  .setJITMemoryManager(RJMM)
222                  .setErrorStr(&Error)
223                  .setTargetOptions(Options).create());
224     ASSERT_TRUE(TheJIT.get() != NULL) << Error;
225   }
226
227   void LoadAssembly(const char *assembly) {
228     LoadAssemblyInto(M, assembly);
229   }
230
231   LLVMContext Context;
232   Module *M;  // Owned by ExecutionEngine.
233   RecordingJITMemoryManager *RJMM;
234   OwningPtr<ExecutionEngine> TheJIT;
235 };
236
237 // Regression test for a bug.  The JIT used to allocate globals inside the same
238 // memory block used for the function, and when the function code was freed,
239 // the global was left in the same place.  This test allocates a function
240 // that uses and global, deallocates it, and then makes sure that the global
241 // stays alive after that.
242 TEST(JIT, GlobalInFunction) {
243   LLVMContext context;
244   Module *M = new Module("<main>", context);
245
246   JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();
247   // Tell the memory manager to poison freed memory so that accessing freed
248   // memory is more easily tested.
249   MemMgr->setPoisonMemory(true);
250   std::string Error;
251   OwningPtr<ExecutionEngine> JIT(EngineBuilder(M)
252                                  .setEngineKind(EngineKind::JIT)
253                                  .setErrorStr(&Error)
254                                  .setJITMemoryManager(MemMgr)
255                                  // The next line enables the fix:
256                                  .setAllocateGVsWithCode(false)
257                                  .create());
258   ASSERT_EQ(Error, "");
259
260   // Create a global variable.
261   Type *GTy = Type::getInt32Ty(context);
262   GlobalVariable *G = new GlobalVariable(
263       *M,
264       GTy,
265       false,  // Not constant.
266       GlobalValue::InternalLinkage,
267       Constant::getNullValue(GTy),
268       "myglobal");
269
270   // Make a function that points to a global.
271   Function *F1 = makeReturnGlobal("F1", G, M);
272
273   // Get the pointer to the native code to force it to JIT the function and
274   // allocate space for the global.
275   void (*F1Ptr)() =
276       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F1));
277
278   // Since F1 was codegen'd, a pointer to G should be available.
279   int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);
280   ASSERT_NE((int32_t*)NULL, GPtr);
281   EXPECT_EQ(0, *GPtr);
282
283   // F1() should increment G.
284   F1Ptr();
285   EXPECT_EQ(1, *GPtr);
286
287   // Make a second function identical to the first, referring to the same
288   // global.
289   Function *F2 = makeReturnGlobal("F2", G, M);
290   void (*F2Ptr)() =
291       reinterpret_cast<void(*)()>((intptr_t)JIT->getPointerToFunction(F2));
292
293   // F2() should increment G.
294   F2Ptr();
295   EXPECT_EQ(2, *GPtr);
296
297   // Deallocate F1.
298   JIT->freeMachineCodeForFunction(F1);
299
300   // F2() should *still* increment G.
301   F2Ptr();
302   EXPECT_EQ(3, *GPtr);
303 }
304
305 // Regression test for a bug.  The JITEmitter wasn't checking to verify that
306 // it hadn't run out of space while generating the DWARF exception information
307 // for an emitted function.
308
309 class ExceptionMemoryManagerMock : public RecordingJITMemoryManager {
310  public:
311   virtual uint8_t *startExceptionTable(const Function *F,
312                                        uintptr_t &ActualSize) {
313     // force an insufficient size the first time through.
314     bool ChangeActualSize = false;
315     if (ActualSize == 0)
316       ChangeActualSize = true;;
317     uint8_t *result =
318       RecordingJITMemoryManager::startExceptionTable(F, ActualSize);
319     if (ChangeActualSize)
320       ActualSize = 1;
321     return result;
322   }
323 };
324
325 class JITExceptionMemoryTest : public JITTest {
326  protected:
327   virtual RecordingJITMemoryManager *createMemoryManager() {
328     return new ExceptionMemoryManagerMock;
329   }
330 };
331
332 TEST_F(JITExceptionMemoryTest, ExceptionTableOverflow) {
333   Function *F = Function::Create(TypeBuilder<void(void), false>::get(Context),
334                                  Function::ExternalLinkage,
335                                  "func1", M);
336   BasicBlock *Block = BasicBlock::Create(Context, "block", F);
337   IRBuilder<> Builder(Block);
338   Builder.CreateRetVoid();
339   TheJIT->getPointerToFunction(F);
340   ASSERT_TRUE(RJMM->startExceptionTableCalls.size() == 2);
341   ASSERT_TRUE(RJMM->deallocateExceptionTableCalls.size() == 1);
342   ASSERT_TRUE(RJMM->endExceptionTableCalls.size() == 1);
343 }
344
345 int PlusOne(int arg) {
346   return arg + 1;
347 }
348
349 TEST_F(JITTest, FarCallToKnownFunction) {
350   // x86-64 can only make direct calls to functions within 32 bits of
351   // the current PC.  To call anything farther away, we have to load
352   // the address into a register and call through the register.  The
353   // current JIT does this by allocating a stub for any far call.
354   // There was a bug in which the JIT tried to emit a direct call when
355   // the target was already in the JIT's global mappings and lazy
356   // compilation was disabled.
357
358   Function *KnownFunction = Function::Create(
359       TypeBuilder<int(int), false>::get(Context),
360       GlobalValue::ExternalLinkage, "known", M);
361   TheJIT->addGlobalMapping(KnownFunction, (void*)(intptr_t)PlusOne);
362
363   // int test() { return known(7); }
364   Function *TestFunction = Function::Create(
365       TypeBuilder<int(), false>::get(Context),
366       GlobalValue::ExternalLinkage, "test", M);
367   BasicBlock *Entry = BasicBlock::Create(Context, "entry", TestFunction);
368   IRBuilder<> Builder(Entry);
369   Value *result = Builder.CreateCall(
370       KnownFunction,
371       ConstantInt::get(TypeBuilder<int, false>::get(Context), 7));
372   Builder.CreateRet(result);
373
374   TheJIT->DisableLazyCompilation(true);
375   int (*TestFunctionPtr)() = reinterpret_cast<int(*)()>(
376       (intptr_t)TheJIT->getPointerToFunction(TestFunction));
377   // This used to crash in trying to call PlusOne().
378   EXPECT_EQ(8, TestFunctionPtr());
379 }
380
381 // Test a function C which calls A and B which call each other.
382 TEST_F(JITTest, NonLazyCompilationStillNeedsStubs) {
383   TheJIT->DisableLazyCompilation(true);
384
385   FunctionType *Func1Ty =
386       cast<FunctionType>(TypeBuilder<void(void), false>::get(Context));
387   std::vector<Type*> arg_types;
388   arg_types.push_back(Type::getInt1Ty(Context));
389   FunctionType *FuncTy = FunctionType::get(
390       Type::getVoidTy(Context), arg_types, false);
391   Function *Func1 = Function::Create(Func1Ty, Function::ExternalLinkage,
392                                      "func1", M);
393   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
394                                      "func2", M);
395   Function *Func3 = Function::Create(FuncTy, Function::InternalLinkage,
396                                      "func3", M);
397   BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
398   BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
399   BasicBlock *True2 = BasicBlock::Create(Context, "cond_true", Func2);
400   BasicBlock *False2 = BasicBlock::Create(Context, "cond_false", Func2);
401   BasicBlock *Block3 = BasicBlock::Create(Context, "block3", Func3);
402   BasicBlock *True3 = BasicBlock::Create(Context, "cond_true", Func3);
403   BasicBlock *False3 = BasicBlock::Create(Context, "cond_false", Func3);
404
405   // Make Func1 call Func2(0) and Func3(0).
406   IRBuilder<> Builder(Block1);
407   Builder.CreateCall(Func2, ConstantInt::getTrue(Context));
408   Builder.CreateCall(Func3, ConstantInt::getTrue(Context));
409   Builder.CreateRetVoid();
410
411   // void Func2(bool b) { if (b) { Func3(false); return; } return; }
412   Builder.SetInsertPoint(Block2);
413   Builder.CreateCondBr(Func2->arg_begin(), True2, False2);
414   Builder.SetInsertPoint(True2);
415   Builder.CreateCall(Func3, ConstantInt::getFalse(Context));
416   Builder.CreateRetVoid();
417   Builder.SetInsertPoint(False2);
418   Builder.CreateRetVoid();
419
420   // void Func3(bool b) { if (b) { Func2(false); return; } return; }
421   Builder.SetInsertPoint(Block3);
422   Builder.CreateCondBr(Func3->arg_begin(), True3, False3);
423   Builder.SetInsertPoint(True3);
424   Builder.CreateCall(Func2, ConstantInt::getFalse(Context));
425   Builder.CreateRetVoid();
426   Builder.SetInsertPoint(False3);
427   Builder.CreateRetVoid();
428
429   // Compile the function to native code
430   void (*F1Ptr)() =
431      reinterpret_cast<void(*)()>((intptr_t)TheJIT->getPointerToFunction(Func1));
432
433   F1Ptr();
434 }
435
436 // Regression test for PR5162.  This used to trigger an AssertingVH inside the
437 // JIT's Function to stub mapping.
438 TEST_F(JITTest, NonLazyLeaksNoStubs) {
439   TheJIT->DisableLazyCompilation(true);
440
441   // Create two functions with a single basic block each.
442   FunctionType *FuncTy =
443       cast<FunctionType>(TypeBuilder<int(), false>::get(Context));
444   Function *Func1 = Function::Create(FuncTy, Function::ExternalLinkage,
445                                      "func1", M);
446   Function *Func2 = Function::Create(FuncTy, Function::InternalLinkage,
447                                      "func2", M);
448   BasicBlock *Block1 = BasicBlock::Create(Context, "block1", Func1);
449   BasicBlock *Block2 = BasicBlock::Create(Context, "block2", Func2);
450
451   // The first function calls the second and returns the result
452   IRBuilder<> Builder(Block1);
453   Value *Result = Builder.CreateCall(Func2);
454   Builder.CreateRet(Result);
455
456   // The second function just returns a constant
457   Builder.SetInsertPoint(Block2);
458   Builder.CreateRet(ConstantInt::get(TypeBuilder<int, false>::get(Context),42));
459
460   // Compile the function to native code
461   (void)TheJIT->getPointerToFunction(Func1);
462
463   // Free the JIT state for the functions
464   TheJIT->freeMachineCodeForFunction(Func1);
465   TheJIT->freeMachineCodeForFunction(Func2);
466
467   // Delete the first function (and show that is has no users)
468   EXPECT_EQ(Func1->getNumUses(), 0u);
469   Func1->eraseFromParent();
470
471   // Delete the second function (and show that it has no users - it had one,
472   // func1 but that's gone now)
473   EXPECT_EQ(Func2->getNumUses(), 0u);
474   Func2->eraseFromParent();
475 }
476
477 TEST_F(JITTest, ModuleDeletion) {
478   TheJIT->DisableLazyCompilation(false);
479   LoadAssembly("define void @main() { "
480                "  call i32 @computeVal() "
481                "  ret void "
482                "} "
483                " "
484                "define internal i32 @computeVal()  { "
485                "  ret i32 0 "
486                "} ");
487   Function *func = M->getFunction("main");
488   TheJIT->getPointerToFunction(func);
489   TheJIT->removeModule(M);
490   delete M;
491
492   SmallPtrSet<const void*, 2> FunctionsDeallocated;
493   for (unsigned i = 0, e = RJMM->deallocateFunctionBodyCalls.size();
494        i != e; ++i) {
495     FunctionsDeallocated.insert(RJMM->deallocateFunctionBodyCalls[i].Body);
496   }
497   for (unsigned i = 0, e = RJMM->startFunctionBodyCalls.size(); i != e; ++i) {
498     EXPECT_TRUE(FunctionsDeallocated.count(
499                   RJMM->startFunctionBodyCalls[i].Result))
500       << "Function leaked: \n" << RJMM->startFunctionBodyCalls[i].F_dump;
501   }
502   EXPECT_EQ(RJMM->startFunctionBodyCalls.size(),
503             RJMM->deallocateFunctionBodyCalls.size());
504
505   SmallPtrSet<const void*, 2> ExceptionTablesDeallocated;
506   unsigned NumTablesDeallocated = 0;
507   for (unsigned i = 0, e = RJMM->deallocateExceptionTableCalls.size();
508        i != e; ++i) {
509     ExceptionTablesDeallocated.insert(
510         RJMM->deallocateExceptionTableCalls[i].ET);
511     if (RJMM->deallocateExceptionTableCalls[i].ET != NULL) {
512         // If JITEmitDebugInfo is off, we'll "deallocate" NULL, which doesn't
513         // appear in startExceptionTableCalls.
514         NumTablesDeallocated++;
515     }
516   }
517   for (unsigned i = 0, e = RJMM->startExceptionTableCalls.size(); i != e; ++i) {
518     EXPECT_TRUE(ExceptionTablesDeallocated.count(
519                   RJMM->startExceptionTableCalls[i].Result))
520       << "Function's exception table leaked: \n"
521       << RJMM->startExceptionTableCalls[i].F_dump;
522   }
523   EXPECT_EQ(RJMM->startExceptionTableCalls.size(),
524             NumTablesDeallocated);
525 }
526
527 // ARM, MIPS and PPC still emit stubs for calls since the target may be
528 // too far away to call directly.  This #if can probably be removed when
529 // http://llvm.org/PR5201 is fixed.
530 #if !defined(__arm__) && !defined(__mips__) && \
531     !defined(__powerpc__) && !defined(__ppc__)
532 typedef int (*FooPtr) ();
533
534 TEST_F(JITTest, NoStubs) {
535   LoadAssembly("define void @bar() {"
536                "entry: "
537                "ret void"
538                "}"
539                " "
540                "define i32 @foo() {"
541                "entry:"
542                "call void @bar()"
543                "ret i32 undef"
544                "}"
545                " "
546                "define i32 @main() {"
547                "entry:"
548                "%0 = call i32 @foo()"
549                "call void @bar()"
550                "ret i32 undef"
551                "}");
552   Function *foo = M->getFunction("foo");
553   uintptr_t tmp = (uintptr_t)(TheJIT->getPointerToFunction(foo));
554   FooPtr ptr = (FooPtr)(tmp);
555
556   (ptr)();
557
558   // We should now allocate no more stubs, we have the code to foo
559   // and the existing stub for bar.
560   int stubsBefore = RJMM->stubsAllocated;
561   Function *func = M->getFunction("main");
562   TheJIT->getPointerToFunction(func);
563
564   Function *bar = M->getFunction("bar");
565   TheJIT->getPointerToFunction(bar);
566
567   ASSERT_EQ(stubsBefore, RJMM->stubsAllocated);
568 }
569 #endif  // !ARM && !PPC
570
571 TEST_F(JITTest, FunctionPointersOutliveTheirCreator) {
572   TheJIT->DisableLazyCompilation(true);
573   LoadAssembly("define i8()* @get_foo_addr() { "
574                "  ret i8()* @foo "
575                "} "
576                " "
577                "define i8 @foo() { "
578                "  ret i8 42 "
579                "} ");
580   Function *F_get_foo_addr = M->getFunction("get_foo_addr");
581
582   typedef char(*fooT)();
583   fooT (*get_foo_addr)() = reinterpret_cast<fooT(*)()>(
584       (intptr_t)TheJIT->getPointerToFunction(F_get_foo_addr));
585   fooT foo_addr = get_foo_addr();
586
587   // Now free get_foo_addr.  This should not free the machine code for foo or
588   // any call stub returned as foo's canonical address.
589   TheJIT->freeMachineCodeForFunction(F_get_foo_addr);
590
591   // Check by calling the reported address of foo.
592   EXPECT_EQ(42, foo_addr());
593
594   // The reported address should also be the same as the result of a subsequent
595   // getPointerToFunction(foo).
596 #if 0
597   // Fails until PR5126 is fixed:
598   Function *F_foo = M->getFunction("foo");
599   fooT foo = reinterpret_cast<fooT>(
600       (intptr_t)TheJIT->getPointerToFunction(F_foo));
601   EXPECT_EQ((intptr_t)foo, (intptr_t)foo_addr);
602 #endif
603 }
604
605 // ARM does not have an implementation of replaceMachineCodeForFunction(),
606 // so recompileAndRelinkFunction doesn't work.
607 #if !defined(__arm__)
608 TEST_F(JITTest, FunctionIsRecompiledAndRelinked) {
609   Function *F = Function::Create(TypeBuilder<int(void), false>::get(Context),
610                                  GlobalValue::ExternalLinkage, "test", M);
611   BasicBlock *Entry = BasicBlock::Create(Context, "entry", F);
612   IRBuilder<> Builder(Entry);
613   Value *Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 1);
614   Builder.CreateRet(Val);
615
616   TheJIT->DisableLazyCompilation(true);
617   // Compile the function once, and make sure it works.
618   int (*OrigFPtr)() = reinterpret_cast<int(*)()>(
619     (intptr_t)TheJIT->recompileAndRelinkFunction(F));
620   EXPECT_EQ(1, OrigFPtr());
621
622   // Now change the function to return a different value.
623   Entry->eraseFromParent();
624   BasicBlock *NewEntry = BasicBlock::Create(Context, "new_entry", F);
625   Builder.SetInsertPoint(NewEntry);
626   Val = ConstantInt::get(TypeBuilder<int, false>::get(Context), 2);
627   Builder.CreateRet(Val);
628   // Recompile it, which should produce a new function pointer _and_ update the
629   // old one.
630   int (*NewFPtr)() = reinterpret_cast<int(*)()>(
631     (intptr_t)TheJIT->recompileAndRelinkFunction(F));
632
633   EXPECT_EQ(2, NewFPtr())
634     << "The new pointer should call the new version of the function";
635   EXPECT_EQ(2, OrigFPtr())
636     << "The old pointer's target should now jump to the new version";
637 }
638 #endif  // !defined(__arm__)
639
640 }  // anonymous namespace
641 // This variable is intentionally defined differently in the statically-compiled
642 // program from the IR input to the JIT to assert that the JIT doesn't use its
643 // definition.
644 extern "C" int32_t JITTest_AvailableExternallyGlobal;
645 int32_t JITTest_AvailableExternallyGlobal LLVM_ATTRIBUTE_USED = 42;
646 namespace {
647
648 TEST_F(JITTest, AvailableExternallyGlobalIsntEmitted) {
649   TheJIT->DisableLazyCompilation(true);
650   LoadAssembly("@JITTest_AvailableExternallyGlobal = "
651                "  available_externally global i32 7 "
652                " "
653                "define i32 @loader() { "
654                "  %result = load i32* @JITTest_AvailableExternallyGlobal "
655                "  ret i32 %result "
656                "} ");
657   Function *loaderIR = M->getFunction("loader");
658
659   int32_t (*loader)() = reinterpret_cast<int32_t(*)()>(
660     (intptr_t)TheJIT->getPointerToFunction(loaderIR));
661   EXPECT_EQ(42, loader()) << "func should return 42 from the external global,"
662                           << " not 7 from the IR version.";
663 }
664 }  // anonymous namespace
665 // This function is intentionally defined differently in the statically-compiled
666 // program from the IR input to the JIT to assert that the JIT doesn't use its
667 // definition.
668 extern "C" int32_t JITTest_AvailableExternallyFunction() LLVM_ATTRIBUTE_USED;
669 extern "C" int32_t JITTest_AvailableExternallyFunction() {
670   return 42;
671 }
672 namespace {
673
674 TEST_F(JITTest, AvailableExternallyFunctionIsntCompiled) {
675   TheJIT->DisableLazyCompilation(true);
676   LoadAssembly("define available_externally i32 "
677                "    @JITTest_AvailableExternallyFunction() { "
678                "  ret i32 7 "
679                "} "
680                " "
681                "define i32 @func() { "
682                "  %result = tail call i32 "
683                "    @JITTest_AvailableExternallyFunction() "
684                "  ret i32 %result "
685                "} ");
686   Function *funcIR = M->getFunction("func");
687
688   int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
689     (intptr_t)TheJIT->getPointerToFunction(funcIR));
690   EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
691                         << " not 7 from the IR version.";
692 }
693
694 TEST_F(JITTest, EscapedLazyStubStillCallable) {
695   TheJIT->DisableLazyCompilation(false);
696   LoadAssembly("define internal i32 @stubbed() { "
697                "  ret i32 42 "
698                "} "
699                " "
700                "define i32()* @get_stub() { "
701                "  ret i32()* @stubbed "
702                "} ");
703   typedef int32_t(*StubTy)();
704
705   // Call get_stub() to get the address of @stubbed without actually JITting it.
706   Function *get_stubIR = M->getFunction("get_stub");
707   StubTy (*get_stub)() = reinterpret_cast<StubTy(*)()>(
708     (intptr_t)TheJIT->getPointerToFunction(get_stubIR));
709   StubTy stubbed = get_stub();
710   // Now get_stubIR is the only reference to stubbed's stub.
711   get_stubIR->eraseFromParent();
712   // Now there are no references inside the JIT, but we've got a pointer outside
713   // it.  The stub should be callable and return the right value.
714   EXPECT_EQ(42, stubbed());
715 }
716
717 // Converts the LLVM assembly to bitcode and returns it in a std::string.  An
718 // empty string indicates an error.
719 std::string AssembleToBitcode(LLVMContext &Context, const char *Assembly) {
720   Module TempModule("TempModule", Context);
721   if (!LoadAssemblyInto(&TempModule, Assembly)) {
722     return "";
723   }
724
725   std::string Result;
726   raw_string_ostream OS(Result);
727   WriteBitcodeToFile(&TempModule, OS);
728   OS.flush();
729   return Result;
730 }
731
732 // Returns a newly-created ExecutionEngine that reads the bitcode in 'Bitcode'
733 // lazily.  The associated Module (owned by the ExecutionEngine) is returned in
734 // M.  Both will be NULL on an error.  Bitcode must live at least as long as the
735 // ExecutionEngine.
736 ExecutionEngine *getJITFromBitcode(
737   LLVMContext &Context, const std::string &Bitcode, Module *&M) {
738   // c_str() is null-terminated like MemoryBuffer::getMemBuffer requires.
739   MemoryBuffer *BitcodeBuffer =
740     MemoryBuffer::getMemBuffer(Bitcode, "Bitcode for test");
741   std::string errMsg;
742   M = getLazyBitcodeModule(BitcodeBuffer, Context, &errMsg);
743   if (M == NULL) {
744     ADD_FAILURE() << errMsg;
745     delete BitcodeBuffer;
746     return NULL;
747   }
748   ExecutionEngine *TheJIT = EngineBuilder(M)
749     .setEngineKind(EngineKind::JIT)
750     .setErrorStr(&errMsg)
751     .create();
752   if (TheJIT == NULL) {
753     ADD_FAILURE() << errMsg;
754     delete M;
755     M = NULL;
756     return NULL;
757   }
758   return TheJIT;
759 }
760
761 TEST(LazyLoadedJITTest, MaterializableAvailableExternallyFunctionIsntCompiled) {
762   LLVMContext Context;
763   const std::string Bitcode =
764     AssembleToBitcode(Context,
765                       "define available_externally i32 "
766                       "    @JITTest_AvailableExternallyFunction() { "
767                       "  ret i32 7 "
768                       "} "
769                       " "
770                       "define i32 @func() { "
771                       "  %result = tail call i32 "
772                       "    @JITTest_AvailableExternallyFunction() "
773                       "  ret i32 %result "
774                       "} ");
775   ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
776   Module *M;
777   OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
778   ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
779   TheJIT->DisableLazyCompilation(true);
780
781   Function *funcIR = M->getFunction("func");
782   Function *availableFunctionIR =
783     M->getFunction("JITTest_AvailableExternallyFunction");
784
785   // Double-check that the available_externally function is still unmaterialized
786   // when getPointerToFunction needs to find out if it's available_externally.
787   EXPECT_TRUE(availableFunctionIR->isMaterializable());
788
789   int32_t (*func)() = reinterpret_cast<int32_t(*)()>(
790     (intptr_t)TheJIT->getPointerToFunction(funcIR));
791   EXPECT_EQ(42, func()) << "func should return 42 from the static version,"
792                         << " not 7 from the IR version.";
793 }
794
795 TEST(LazyLoadedJITTest, EagerCompiledRecursionThroughGhost) {
796   LLVMContext Context;
797   const std::string Bitcode =
798     AssembleToBitcode(Context,
799                       "define i32 @recur1(i32 %a) { "
800                       "  %zero = icmp eq i32 %a, 0 "
801                       "  br i1 %zero, label %done, label %notdone "
802                       "done: "
803                       "  ret i32 3 "
804                       "notdone: "
805                       "  %am1 = sub i32 %a, 1 "
806                       "  %result = call i32 @recur2(i32 %am1) "
807                       "  ret i32 %result "
808                       "} "
809                       " "
810                       "define i32 @recur2(i32 %b) { "
811                       "  %result = call i32 @recur1(i32 %b) "
812                       "  ret i32 %result "
813                       "} ");
814   ASSERT_FALSE(Bitcode.empty()) << "Assembling failed";
815   Module *M;
816   OwningPtr<ExecutionEngine> TheJIT(getJITFromBitcode(Context, Bitcode, M));
817   ASSERT_TRUE(TheJIT.get()) << "Failed to create JIT.";
818   TheJIT->DisableLazyCompilation(true);
819
820   Function *recur1IR = M->getFunction("recur1");
821   Function *recur2IR = M->getFunction("recur2");
822   EXPECT_TRUE(recur1IR->isMaterializable());
823   EXPECT_TRUE(recur2IR->isMaterializable());
824
825   int32_t (*recur1)(int32_t) = reinterpret_cast<int32_t(*)(int32_t)>(
826     (intptr_t)TheJIT->getPointerToFunction(recur1IR));
827   EXPECT_EQ(3, recur1(4));
828 }
829 #endif // !defined(__arm__) && !defined(__powerpc__)
830
831 // This code is copied from JITEventListenerTest, but it only runs once for all
832 // the tests in this directory.  Everything seems fine, but that's strange
833 // behavior.
834 class JITEnvironment : public testing::Environment {
835   virtual void SetUp() {
836     // Required to create a JIT.
837     InitializeNativeTarget();
838   }
839 };
840 testing::Environment* const jit_env =
841   testing::AddGlobalTestEnvironment(new JITEnvironment);
842
843 }