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