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