1 //===--- OrcCAPITest.cpp - Unit tests for the OrcJIT v2 C API ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm-c/Core.h"
10 #include "llvm-c/Error.h"
11 #include "llvm-c/LLJIT.h"
12 #include "llvm-c/Orc.h"
13 #include "gtest/gtest.h"
14 
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IRReader/IRReader.h"
20 #include "llvm/Support/Error.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include <string>
23 
24 using namespace llvm;
25 using namespace llvm::orc;
26 
27 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ThreadSafeModule, LLVMOrcThreadSafeModuleRef)
28 
29 // OrcCAPITestBase contains several helper methods and pointers for unit tests
30 // written for the LLVM-C API. It provides the following helpers:
31 //
32 // 1. Jit: an LLVMOrcLLJIT instance which is freed upon test exit
33 // 2. ExecutionSession: the LLVMOrcExecutionSession for the JIT
34 // 3. MainDylib: the main JITDylib for the LLJIT instance
35 // 4. materializationUnitFn: function pointer to an empty function, used for
36 //                           materialization unit testing
37 // 5. definitionGeneratorFn: function pointer for a basic
38 //                           LLVMOrcCAPIDefinitionGeneratorTryToGenerateFunction
39 // 6. createTestModule: helper method for creating a basic thread-safe-module
40 class OrcCAPITestBase : public testing::Test {
41 protected:
42   LLVMOrcLLJITRef Jit = nullptr;
43   LLVMOrcExecutionSessionRef ExecutionSession = nullptr;
44   LLVMOrcJITDylibRef MainDylib = nullptr;
45 
46 public:
47   static void SetUpTestCase() {
48     LLVMInitializeNativeTarget();
49     LLVMInitializeNativeAsmParser();
50     LLVMInitializeNativeAsmPrinter();
51 
52     // Attempt to set up a JIT instance once to verify that we can.
53     LLVMOrcJITTargetMachineBuilderRef JTMB = nullptr;
54     if (LLVMErrorRef E = LLVMOrcJITTargetMachineBuilderDetectHost(&JTMB)) {
55       // If setup fails then disable these tests.
56       LLVMConsumeError(E);
57       TargetSupported = false;
58       return;
59     }
60 
61     // Capture the target triple. We'll use it for both verification that
62     // this target is *supposed* to be supported, and error messages in
63     // the case that it fails anyway.
64     char *TT = LLVMOrcJITTargetMachineBuilderGetTargetTriple(JTMB);
65     TargetTriple = TT;
66     LLVMOrcJITTargetMachineBuilderDisposeTargetTriple(JTMB, TT);
67 
68     if (!isSupported(TargetTriple)) {
69       // If this triple isn't supported then bail out.
70       TargetSupported = false;
71       LLVMOrcDisposeJITTargetMachineBuilder(JTMB);
72       return;
73     }
74 
75     LLVMOrcLLJITBuilderRef Builder = LLVMOrcCreateLLJITBuilder();
76     LLVMOrcLLJITBuilderSetJITTargetMachineBuilder(Builder, JTMB);
77     LLVMOrcLLJITRef J;
78     if (LLVMErrorRef E = LLVMOrcCreateLLJIT(&J, Builder)) {
79       // If setup fails then disable these tests.
80       TargetSupported = false;
81       LLVMConsumeError(E);
82       return;
83     }
84 
85     LLVMOrcDisposeLLJIT(J);
86     TargetSupported = true;
87   }
88 
89   void SetUp() override {
90     if (!TargetSupported)
91       return;
92 
93     LLVMOrcJITTargetMachineBuilderRef JTMB = nullptr;
94     LLVMErrorRef E1 = LLVMOrcJITTargetMachineBuilderDetectHost(&JTMB);
95     assert(E1 == LLVMErrorSuccess && "Expected call to detect host to succeed");
96     (void)E1;
97 
98     LLVMOrcLLJITBuilderRef Builder = LLVMOrcCreateLLJITBuilder();
99     LLVMOrcLLJITBuilderSetJITTargetMachineBuilder(Builder, JTMB);
100     LLVMErrorRef E2 = LLVMOrcCreateLLJIT(&Jit, Builder);
101     assert(E2 == LLVMErrorSuccess &&
102            "Expected call to create LLJIT to succeed");
103     (void)E2;
104     ExecutionSession = LLVMOrcLLJITGetExecutionSession(Jit);
105     MainDylib = LLVMOrcLLJITGetMainJITDylib(Jit);
106   }
107   void TearDown() override {
108     LLVMOrcDisposeLLJIT(Jit);
109     Jit = nullptr;
110   }
111 
112 protected:
113   static bool isSupported(StringRef Triple) {
114     // TODO: Print error messages in failure logs, use them to audit this list.
115     // Some architectures may be unsupportable or missing key components, but
116     // some may just be failing due to bugs in this testcase.
117     if (Triple.startswith("armv7") || Triple.startswith("armv8l"))
118       return false;
119     return true;
120   }
121 
122   static void materializationUnitFn() {}
123 
124   // Stub definition generator, where all Names are materialized from the
125   // materializationUnitFn() test function and defined into the JIT Dylib
126   static LLVMErrorRef
127   definitionGeneratorFn(LLVMOrcDefinitionGeneratorRef G, void *Ctx,
128                         LLVMOrcLookupStateRef *LS, LLVMOrcLookupKind K,
129                         LLVMOrcJITDylibRef JD, LLVMOrcJITDylibLookupFlags F,
130                         LLVMOrcCLookupSet Names, size_t NamesCount) {
131     for (size_t I = 0; I < NamesCount; I++) {
132       LLVMOrcCLookupSetElement Element = Names[I];
133       LLVMOrcJITTargetAddress Addr =
134           (LLVMOrcJITTargetAddress)(&materializationUnitFn);
135       LLVMJITSymbolFlags Flags = {LLVMJITSymbolGenericFlagsWeak, 0};
136       LLVMJITEvaluatedSymbol Sym = {Addr, Flags};
137       LLVMOrcRetainSymbolStringPoolEntry(Element.Name);
138       LLVMJITCSymbolMapPair Pair = {Element.Name, Sym};
139       LLVMJITCSymbolMapPair Pairs[] = {Pair};
140       LLVMOrcMaterializationUnitRef MU = LLVMOrcAbsoluteSymbols(Pairs, 1);
141       LLVMErrorRef Err = LLVMOrcJITDylibDefine(JD, MU);
142       if (Err)
143         return Err;
144     }
145     return LLVMErrorSuccess;
146   }
147 
148   static Error createSMDiagnosticError(llvm::SMDiagnostic &Diag) {
149     std::string Msg;
150     {
151       raw_string_ostream OS(Msg);
152       Diag.print("", OS);
153     }
154     return make_error<StringError>(std::move(Msg), inconvertibleErrorCode());
155   }
156 
157   // Create an LLVM IR module from the given StringRef.
158   static Expected<std::unique_ptr<Module>>
159   parseTestModule(LLVMContext &Ctx, StringRef Source, StringRef Name) {
160     assert(TargetSupported &&
161            "Attempted to create module for unsupported target");
162     SMDiagnostic Err;
163     if (auto M = parseIR(MemoryBufferRef(Source, Name), Err, Ctx))
164       return std::move(M);
165     return createSMDiagnosticError(Err);
166   }
167 
168   // returns the sum of its two parameters
169   static LLVMOrcThreadSafeModuleRef createTestModule(StringRef Source,
170                                                      StringRef Name) {
171     auto Ctx = std::make_unique<LLVMContext>();
172     auto M = cantFail(parseTestModule(*Ctx, Source, Name));
173     return wrap(new ThreadSafeModule(std::move(M), std::move(Ctx)));
174   }
175 
176   static LLVMMemoryBufferRef createTestObject(StringRef Source,
177                                               StringRef Name) {
178     auto Ctx = std::make_unique<LLVMContext>();
179     auto M = cantFail(parseTestModule(*Ctx, Source, Name));
180 
181     auto JTMB = cantFail(JITTargetMachineBuilder::detectHost());
182     M->setDataLayout(cantFail(JTMB.getDefaultDataLayoutForTarget()));
183     auto TM = cantFail(JTMB.createTargetMachine());
184 
185     SimpleCompiler SC(*TM);
186     auto ObjBuffer = cantFail(SC(*M));
187     return wrap(ObjBuffer.release());
188   }
189 
190   static std::string TargetTriple;
191   static bool TargetSupported;
192 };
193 
194 std::string OrcCAPITestBase::TargetTriple;
195 bool OrcCAPITestBase::TargetSupported = false;
196 
197 namespace {
198 
199 constexpr StringRef SumExample =
200     R"(
201     define i32 @sum(i32 %x, i32 %y) {
202     entry:
203       %r = add nsw i32 %x, %y
204       ret i32 %r
205     }
206   )";
207 
208 } // end anonymous namespace.
209 
210 // Consumes the given error ref and returns the string error message.
211 static std::string toString(LLVMErrorRef E) {
212   char *ErrMsg = LLVMGetErrorMessage(E);
213   std::string Result(ErrMsg);
214   LLVMDisposeErrorMessage(ErrMsg);
215   return Result;
216 }
217 
218 TEST_F(OrcCAPITestBase, SymbolStringPoolUniquing) {
219   if (!Jit) {
220     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
221     return;
222   }
223 
224   LLVMOrcSymbolStringPoolEntryRef E1 =
225       LLVMOrcExecutionSessionIntern(ExecutionSession, "aaa");
226   LLVMOrcSymbolStringPoolEntryRef E2 =
227       LLVMOrcExecutionSessionIntern(ExecutionSession, "aaa");
228   LLVMOrcSymbolStringPoolEntryRef E3 =
229       LLVMOrcExecutionSessionIntern(ExecutionSession, "bbb");
230   const char *SymbolName = LLVMOrcSymbolStringPoolEntryStr(E1);
231   ASSERT_EQ(E1, E2) << "String pool entries are not unique";
232   ASSERT_NE(E1, E3) << "Unique symbol pool entries are equal";
233   ASSERT_STREQ("aaa", SymbolName) << "String value of symbol is not equal";
234   LLVMOrcReleaseSymbolStringPoolEntry(E1);
235   LLVMOrcReleaseSymbolStringPoolEntry(E2);
236   LLVMOrcReleaseSymbolStringPoolEntry(E3);
237 }
238 
239 TEST_F(OrcCAPITestBase, JITDylibLookup) {
240   if (!Jit) {
241     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
242     return;
243   }
244   LLVMOrcJITDylibRef DoesNotExist =
245       LLVMOrcExecutionSessionGetJITDylibByName(ExecutionSession, "test");
246   ASSERT_FALSE(!!DoesNotExist);
247   LLVMOrcJITDylibRef L1 =
248       LLVMOrcExecutionSessionCreateBareJITDylib(ExecutionSession, "test");
249   LLVMOrcJITDylibRef L2 =
250       LLVMOrcExecutionSessionGetJITDylibByName(ExecutionSession, "test");
251   ASSERT_EQ(L1, L2) << "Located JIT Dylib is not equal to original";
252 }
253 
254 TEST_F(OrcCAPITestBase, MaterializationUnitCreation) {
255   if (!Jit) {
256     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
257     return;
258   }
259 
260   LLVMOrcSymbolStringPoolEntryRef Name =
261       LLVMOrcLLJITMangleAndIntern(Jit, "test");
262   LLVMJITSymbolFlags Flags = {LLVMJITSymbolGenericFlagsWeak, 0};
263   LLVMOrcJITTargetAddress Addr =
264       (LLVMOrcJITTargetAddress)(&materializationUnitFn);
265   LLVMJITEvaluatedSymbol Sym = {Addr, Flags};
266   LLVMJITCSymbolMapPair Pair = {Name, Sym};
267   LLVMJITCSymbolMapPair Pairs[] = {Pair};
268   LLVMOrcMaterializationUnitRef MU = LLVMOrcAbsoluteSymbols(Pairs, 1);
269   LLVMOrcJITDylibDefine(MainDylib, MU);
270   LLVMOrcJITTargetAddress OutAddr;
271   if (LLVMErrorRef E = LLVMOrcLLJITLookup(Jit, &OutAddr, "test"))
272     FAIL() << "Failed to look up \"test\" symbol (triple = " << TargetTriple
273            << "): " << toString(E);
274   ASSERT_EQ(Addr, OutAddr);
275 }
276 
277 TEST_F(OrcCAPITestBase, DefinitionGenerators) {
278   if (!Jit) {
279     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
280     return;
281   }
282 
283   LLVMOrcDefinitionGeneratorRef Gen =
284       LLVMOrcCreateCustomCAPIDefinitionGenerator(&definitionGeneratorFn,
285                                                  nullptr);
286   LLVMOrcJITDylibAddGenerator(MainDylib, Gen);
287   LLVMOrcJITTargetAddress OutAddr;
288   if (LLVMErrorRef E = LLVMOrcLLJITLookup(Jit, &OutAddr, "test"))
289     FAIL() << "The DefinitionGenerator did not create symbol \"test\" "
290            << "(triple = " << TargetTriple << "): " << toString(E);
291   LLVMOrcJITTargetAddress ExpectedAddr =
292       (LLVMOrcJITTargetAddress)(&materializationUnitFn);
293   ASSERT_EQ(ExpectedAddr, OutAddr);
294 }
295 
296 TEST_F(OrcCAPITestBase, ResourceTrackerDefinitionLifetime) {
297   if (!Jit) {
298     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
299     return;
300   }
301 
302   // This test case ensures that all symbols loaded into a JITDylib with a
303   // ResourceTracker attached are cleared from the JITDylib once the RT is
304   // removed.
305   LLVMOrcResourceTrackerRef RT =
306       LLVMOrcJITDylibCreateResourceTracker(MainDylib);
307   LLVMOrcThreadSafeModuleRef TSM = createTestModule(SumExample, "sum.ll");
308   if (LLVMErrorRef E = LLVMOrcLLJITAddLLVMIRModuleWithRT(Jit, RT, TSM))
309     FAIL() << "Failed to add LLVM IR module to LLJIT (triple = " << TargetTriple
310            << "): " << toString(E);
311   LLVMOrcJITTargetAddress TestFnAddr;
312   if (LLVMErrorRef E = LLVMOrcLLJITLookup(Jit, &TestFnAddr, "sum"))
313     FAIL() << "Symbol \"sum\" was not added into JIT (triple = " << TargetTriple
314            << "): " << toString(E);
315   ASSERT_TRUE(!!TestFnAddr);
316   LLVMOrcResourceTrackerRemove(RT);
317   LLVMOrcJITTargetAddress OutAddr;
318   LLVMErrorRef Err = LLVMOrcLLJITLookup(Jit, &OutAddr, "sum");
319   ASSERT_TRUE(Err);
320   LLVMConsumeError(Err);
321 
322   ASSERT_FALSE(OutAddr);
323   LLVMOrcReleaseResourceTracker(RT);
324 }
325 
326 TEST_F(OrcCAPITestBase, ResourceTrackerTransfer) {
327   if (!Jit) {
328     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
329     return;
330   }
331 
332   LLVMOrcResourceTrackerRef DefaultRT =
333       LLVMOrcJITDylibGetDefaultResourceTracker(MainDylib);
334   LLVMOrcResourceTrackerRef RT2 =
335       LLVMOrcJITDylibCreateResourceTracker(MainDylib);
336   LLVMOrcThreadSafeModuleRef TSM = createTestModule(SumExample, "sum.ll");
337   if (LLVMErrorRef E = LLVMOrcLLJITAddLLVMIRModuleWithRT(Jit, DefaultRT, TSM))
338     FAIL() << "Failed to add LLVM IR module to LLJIT (triple = " << TargetTriple
339            << "): " << toString(E);
340   LLVMOrcJITTargetAddress Addr;
341   if (LLVMErrorRef E = LLVMOrcLLJITLookup(Jit, &Addr, "sum"))
342     FAIL() << "Symbol \"sum\" was not added into JIT (triple = " << TargetTriple
343            << "): " << toString(E);
344   LLVMOrcResourceTrackerTransferTo(DefaultRT, RT2);
345   LLVMErrorRef Err = LLVMOrcLLJITLookup(Jit, &Addr, "sum");
346   ASSERT_FALSE(Err);
347   LLVMOrcReleaseResourceTracker(RT2);
348 }
349 
350 TEST_F(OrcCAPITestBase, AddObjectBuffer) {
351   if (!Jit) {
352     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
353     return;
354   }
355 
356   LLVMOrcObjectLayerRef ObjLinkingLayer = LLVMOrcLLJITGetObjLinkingLayer(Jit);
357   LLVMMemoryBufferRef ObjBuffer = createTestObject(SumExample, "sum.ll");
358 
359   if (LLVMErrorRef E = LLVMOrcObjectLayerAddObjectFile(ObjLinkingLayer,
360                                                        MainDylib, ObjBuffer))
361     FAIL() << "Failed to add object file to ObjLinkingLayer (triple = "
362            << TargetTriple << "): " << toString(E);
363 
364   LLVMOrcJITTargetAddress SumAddr;
365   if (LLVMErrorRef E = LLVMOrcLLJITLookup(Jit, &SumAddr, "sum"))
366     FAIL() << "Symbol \"sum\" was not added into JIT (triple = " << TargetTriple
367            << "): " << toString(E);
368   ASSERT_TRUE(!!SumAddr);
369 }
370 
371 TEST_F(OrcCAPITestBase, ExecutionTest) {
372   if (!Jit) {
373     // TODO: Use GTEST_SKIP() when GTest is updated to version 1.10.0
374     return;
375   }
376 
377   using SumFunctionType = int32_t (*)(int32_t, int32_t);
378 
379   // This test performs OrcJIT compilation of a simple sum module
380   LLVMInitializeNativeAsmPrinter();
381   LLVMOrcThreadSafeModuleRef TSM = createTestModule(SumExample, "sum.ll");
382   if (LLVMErrorRef E = LLVMOrcLLJITAddLLVMIRModule(Jit, MainDylib, TSM))
383     FAIL() << "Failed to add LLVM IR module to LLJIT (triple = " << TargetTriple
384            << ")" << toString(E);
385   LLVMOrcJITTargetAddress TestFnAddr;
386   if (LLVMErrorRef E = LLVMOrcLLJITLookup(Jit, &TestFnAddr, "sum"))
387     FAIL() << "Symbol \"sum\" was not added into JIT (triple = " << TargetTriple
388            << "): " << toString(E);
389   auto *SumFn = (SumFunctionType)(TestFnAddr);
390   int32_t Result = SumFn(1, 1);
391   ASSERT_EQ(2, Result);
392 }
393