1 //===- MCJITTest.cpp - Unit tests for the MCJIT ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This test suite verifies basic MCJIT functionality when invoked form the C
13 //===----------------------------------------------------------------------===//
15 #include "llvm-c/Analysis.h"
16 #include "MCJITTestAPICommon.h"
17 #include "llvm-c/Core.h"
18 #include "llvm-c/ExecutionEngine.h"
19 #include "llvm-c/Target.h"
20 #include "llvm-c/Transforms/PassManagerBuilder.h"
21 #include "llvm-c/Transforms/Scalar.h"
22 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Host.h"
25 #include "gtest/gtest.h"
29 static bool didCallAllocateCodeSection;
30 static bool didAllocateCompactUnwindSection;
31 static bool didCallYield;
33 static uint8_t *roundTripAllocateCodeSection(void *object, uintptr_t size,
36 const char *sectionName) {
37 didCallAllocateCodeSection = true;
38 return static_cast<SectionMemoryManager*>(object)->allocateCodeSection(
39 size, alignment, sectionID, sectionName);
42 static uint8_t *roundTripAllocateDataSection(void *object, uintptr_t size,
45 const char *sectionName,
46 LLVMBool isReadOnly) {
47 if (!strcmp(sectionName, "__compact_unwind"))
48 didAllocateCompactUnwindSection = true;
49 return static_cast<SectionMemoryManager*>(object)->allocateDataSection(
50 size, alignment, sectionID, sectionName, isReadOnly);
53 static LLVMBool roundTripFinalizeMemory(void *object, char **errMsg) {
54 std::string errMsgString;
56 static_cast<SectionMemoryManager*>(object)->finalizeMemory(&errMsgString);
58 *errMsg = LLVMCreateMessage(errMsgString.c_str());
64 static void roundTripDestroy(void *object) {
65 delete static_cast<SectionMemoryManager*>(object);
68 static void yield(LLVMContextRef, void *) {
74 // memory manager to test reserve allocation space callback
75 class TestReserveAllocationSpaceMemoryManager: public SectionMemoryManager {
77 uintptr_t ReservedCodeSize;
78 uintptr_t UsedCodeSize;
79 uintptr_t ReservedDataSizeRO;
80 uintptr_t UsedDataSizeRO;
81 uintptr_t ReservedDataSizeRW;
82 uintptr_t UsedDataSizeRW;
84 TestReserveAllocationSpaceMemoryManager() :
85 ReservedCodeSize(0), UsedCodeSize(0), ReservedDataSizeRO(0),
86 UsedDataSizeRO(0), ReservedDataSizeRW(0), UsedDataSizeRW(0) {
89 virtual bool needsToReserveAllocationSpace() {
93 virtual void reserveAllocationSpace(
94 uintptr_t CodeSize, uintptr_t DataSizeRO, uintptr_t DataSizeRW) {
95 ReservedCodeSize = CodeSize;
96 ReservedDataSizeRO = DataSizeRO;
97 ReservedDataSizeRW = DataSizeRW;
100 void useSpace(uintptr_t* UsedSize, uintptr_t Size, unsigned Alignment) {
101 uintptr_t AlignedSize = (Size + Alignment - 1) / Alignment * Alignment;
102 uintptr_t AlignedBegin = (*UsedSize + Alignment - 1) / Alignment * Alignment;
103 *UsedSize = AlignedBegin + AlignedSize;
106 virtual uint8_t* allocateDataSection(uintptr_t Size, unsigned Alignment,
107 unsigned SectionID, StringRef SectionName, bool IsReadOnly) {
108 useSpace(IsReadOnly ? &UsedDataSizeRO : &UsedDataSizeRW, Size, Alignment);
109 return SectionMemoryManager::allocateDataSection(Size, Alignment,
110 SectionID, SectionName, IsReadOnly);
113 uint8_t* allocateCodeSection(uintptr_t Size, unsigned Alignment,
114 unsigned SectionID, StringRef SectionName) {
115 useSpace(&UsedCodeSize, Size, Alignment);
116 return SectionMemoryManager::allocateCodeSection(Size, Alignment,
117 SectionID, SectionName);
121 class MCJITCAPITest : public testing::Test, public MCJITTestAPICommon {
124 // The architectures below are known to be compatible with MCJIT as they
125 // are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be
127 SupportedArchs.push_back(Triple::aarch64);
128 SupportedArchs.push_back(Triple::arm);
129 SupportedArchs.push_back(Triple::mips);
130 SupportedArchs.push_back(Triple::x86);
131 SupportedArchs.push_back(Triple::x86_64);
133 // Some architectures have sub-architectures in which tests will fail, like
134 // ARM. These two vectors will define if they do have sub-archs (to avoid
135 // extra work for those who don't), and if so, if they are listed to work
136 HasSubArchs.push_back(Triple::arm);
137 SupportedSubArchs.push_back("armv6");
138 SupportedSubArchs.push_back("armv7");
140 // The operating systems below are known to be sufficiently incompatible
141 // that they will fail the MCJIT C API tests.
142 UnsupportedEnvironments.push_back(Triple::Cygnus);
145 virtual void SetUp() {
146 didCallAllocateCodeSection = false;
147 didAllocateCompactUnwindSection = false;
148 didCallYield = false;
155 virtual void TearDown() {
157 LLVMDisposeExecutionEngine(Engine);
159 LLVMDisposeModule(Module);
162 void buildSimpleFunction() {
163 Module = LLVMModuleCreateWithName("simple_module");
165 LLVMSetTarget(Module, HostTriple.c_str());
167 Function = LLVMAddFunction(Module, "simple_function",
168 LLVMFunctionType(LLVMInt32Type(), nullptr,0, 0));
169 LLVMSetFunctionCallConv(Function, LLVMCCallConv);
171 LLVMBasicBlockRef entry = LLVMAppendBasicBlock(Function, "entry");
172 LLVMBuilderRef builder = LLVMCreateBuilder();
173 LLVMPositionBuilderAtEnd(builder, entry);
174 LLVMBuildRet(builder, LLVMConstInt(LLVMInt32Type(), 42, 0));
176 LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
177 LLVMDisposeMessage(Error);
179 LLVMDisposeBuilder(builder);
182 void buildFunctionThatUsesStackmap() {
183 Module = LLVMModuleCreateWithName("simple_module");
185 LLVMSetTarget(Module, HostTriple.c_str());
187 LLVMTypeRef stackmapParamTypes[] = { LLVMInt64Type(), LLVMInt32Type() };
188 LLVMValueRef stackmap = LLVMAddFunction(
189 Module, "llvm.experimental.stackmap",
190 LLVMFunctionType(LLVMVoidType(), stackmapParamTypes, 2, 1));
191 LLVMSetLinkage(stackmap, LLVMExternalLinkage);
193 Function = LLVMAddFunction(Module, "simple_function",
194 LLVMFunctionType(LLVMInt32Type(), nullptr, 0, 0));
196 LLVMBasicBlockRef entry = LLVMAppendBasicBlock(Function, "entry");
197 LLVMBuilderRef builder = LLVMCreateBuilder();
198 LLVMPositionBuilderAtEnd(builder, entry);
199 LLVMValueRef stackmapArgs[] = {
200 LLVMConstInt(LLVMInt64Type(), 0, 0), LLVMConstInt(LLVMInt32Type(), 5, 0),
201 LLVMConstInt(LLVMInt32Type(), 42, 0)
203 LLVMBuildCall(builder, stackmap, stackmapArgs, 3, "");
204 LLVMBuildRet(builder, LLVMConstInt(LLVMInt32Type(), 42, 0));
206 LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
207 LLVMDisposeMessage(Error);
209 LLVMDisposeBuilder(builder);
212 void buildModuleWithCodeAndData() {
213 Module = LLVMModuleCreateWithName("simple_module");
215 LLVMSetTarget(Module, HostTriple.c_str());
217 // build a global int32 variable initialized to 42.
218 LLVMValueRef GlobalVar = LLVMAddGlobal(Module, LLVMInt32Type(), "intVal");
219 LLVMSetInitializer(GlobalVar, LLVMConstInt(LLVMInt32Type(), 42, 0));
222 Function = LLVMAddFunction(Module, "getGlobal",
223 LLVMFunctionType(LLVMInt32Type(), nullptr, 0, 0));
224 LLVMSetFunctionCallConv(Function, LLVMCCallConv);
226 LLVMBasicBlockRef Entry = LLVMAppendBasicBlock(Function, "entry");
227 LLVMBuilderRef Builder = LLVMCreateBuilder();
228 LLVMPositionBuilderAtEnd(Builder, Entry);
230 LLVMValueRef IntVal = LLVMBuildLoad(Builder, GlobalVar, "intVal");
231 LLVMBuildRet(Builder, IntVal);
233 LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
234 LLVMDisposeMessage(Error);
236 LLVMDisposeBuilder(Builder);
240 LLVMTypeRef ParamTypes[] = { LLVMInt32Type() };
241 Function2 = LLVMAddFunction(
242 Module, "setGlobal", LLVMFunctionType(LLVMVoidType(), ParamTypes, 1, 0));
243 LLVMSetFunctionCallConv(Function2, LLVMCCallConv);
245 LLVMBasicBlockRef Entry = LLVMAppendBasicBlock(Function2, "entry");
246 LLVMBuilderRef Builder = LLVMCreateBuilder();
247 LLVMPositionBuilderAtEnd(Builder, Entry);
249 LLVMValueRef Arg = LLVMGetParam(Function2, 0);
250 LLVMBuildStore(Builder, Arg, GlobalVar);
251 LLVMBuildRetVoid(Builder);
253 LLVMVerifyModule(Module, LLVMAbortProcessAction, &Error);
254 LLVMDisposeMessage(Error);
256 LLVMDisposeBuilder(Builder);
260 void buildMCJITOptions() {
261 LLVMInitializeMCJITCompilerOptions(&Options, sizeof(Options));
262 Options.OptLevel = 2;
264 // Just ensure that this field still exists.
265 Options.NoFramePointerElim = false;
268 void useRoundTripSectionMemoryManager() {
269 Options.MCJMM = LLVMCreateSimpleMCJITMemoryManager(
270 new SectionMemoryManager(),
271 roundTripAllocateCodeSection,
272 roundTripAllocateDataSection,
273 roundTripFinalizeMemory,
277 void buildMCJITEngine() {
279 0, LLVMCreateMCJITCompilerForModule(&Engine, Module, &Options,
280 sizeof(Options), &Error));
283 void buildAndRunPasses() {
284 LLVMPassManagerRef pass = LLVMCreatePassManager();
285 LLVMAddTargetData(LLVMGetExecutionEngineTargetData(Engine), pass);
286 LLVMAddConstantPropagationPass(pass);
287 LLVMAddInstructionCombiningPass(pass);
288 LLVMRunPassManager(pass, Module);
289 LLVMDisposePassManager(pass);
292 void buildAndRunOptPasses() {
293 LLVMPassManagerBuilderRef passBuilder;
295 passBuilder = LLVMPassManagerBuilderCreate();
296 LLVMPassManagerBuilderSetOptLevel(passBuilder, 2);
297 LLVMPassManagerBuilderSetSizeLevel(passBuilder, 0);
299 LLVMPassManagerRef functionPasses =
300 LLVMCreateFunctionPassManagerForModule(Module);
301 LLVMPassManagerRef modulePasses =
302 LLVMCreatePassManager();
304 LLVMAddTargetData(LLVMGetExecutionEngineTargetData(Engine), modulePasses);
306 LLVMPassManagerBuilderPopulateFunctionPassManager(passBuilder,
308 LLVMPassManagerBuilderPopulateModulePassManager(passBuilder, modulePasses);
310 LLVMPassManagerBuilderDispose(passBuilder);
312 LLVMInitializeFunctionPassManager(functionPasses);
313 for (LLVMValueRef value = LLVMGetFirstFunction(Module);
314 value; value = LLVMGetNextFunction(value))
315 LLVMRunFunctionPassManager(functionPasses, value);
316 LLVMFinalizeFunctionPassManager(functionPasses);
318 LLVMRunPassManager(modulePasses, Module);
320 LLVMDisposePassManager(functionPasses);
321 LLVMDisposePassManager(modulePasses);
324 LLVMModuleRef Module;
325 LLVMValueRef Function;
326 LLVMValueRef Function2;
327 LLVMMCJITCompilerOptions Options;
328 LLVMExecutionEngineRef Engine;
331 } // end anonymous namespace
333 TEST_F(MCJITCAPITest, simple_function) {
334 SKIP_UNSUPPORTED_PLATFORM;
336 buildSimpleFunction();
345 functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
347 EXPECT_EQ(42, functionPointer.usable());
350 TEST_F(MCJITCAPITest, gva) {
351 SKIP_UNSUPPORTED_PLATFORM;
353 Module = LLVMModuleCreateWithName("simple_module");
354 LLVMSetTarget(Module, HostTriple.c_str());
355 LLVMValueRef GlobalVar = LLVMAddGlobal(Module, LLVMInt32Type(), "simple_value");
356 LLVMSetInitializer(GlobalVar, LLVMConstInt(LLVMInt32Type(), 42, 0));
362 uint64_t raw = LLVMGetGlobalValueAddress(Engine, "simple_value");
363 int32_t *usable = (int32_t *) raw;
365 EXPECT_EQ(42, *usable);
368 TEST_F(MCJITCAPITest, gfa) {
369 SKIP_UNSUPPORTED_PLATFORM;
371 buildSimpleFunction();
376 uint64_t raw = LLVMGetFunctionAddress(Engine, "simple_function");
377 int (*usable)() = (int (*)()) raw;
379 EXPECT_EQ(42, usable());
382 TEST_F(MCJITCAPITest, custom_memory_manager) {
383 SKIP_UNSUPPORTED_PLATFORM;
385 buildSimpleFunction();
387 useRoundTripSectionMemoryManager();
395 functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
397 EXPECT_EQ(42, functionPointer.usable());
398 EXPECT_TRUE(didCallAllocateCodeSection);
401 TEST_F(MCJITCAPITest, stackmap_creates_compact_unwind_on_darwin) {
402 SKIP_UNSUPPORTED_PLATFORM;
404 // This test is also not supported on non-x86 platforms.
405 if (Triple(HostTriple).getArch() != Triple::x86_64)
408 buildFunctionThatUsesStackmap();
410 useRoundTripSectionMemoryManager();
412 buildAndRunOptPasses();
418 functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
420 EXPECT_EQ(42, functionPointer.usable());
421 EXPECT_TRUE(didCallAllocateCodeSection);
423 // Up to this point, the test is specific only to X86-64. But this next
424 // expectation is only valid on Darwin because it assumes that unwind
425 // data is made available only through compact_unwind. It would be
426 // worthwhile to extend this to handle non-Darwin platforms, in which
427 // case you'd want to look for an eh_frame or something.
429 // FIXME: Currently, MCJIT relies on a configure-time check to determine which
430 // sections to emit. The JIT client should have runtime control over this.
432 Triple(HostTriple).getOS() != Triple::Darwin ||
433 Triple(HostTriple).isMacOSXVersionLT(10, 7) ||
434 didAllocateCompactUnwindSection);
437 TEST_F(MCJITCAPITest, reserve_allocation_space) {
438 SKIP_UNSUPPORTED_PLATFORM;
440 TestReserveAllocationSpaceMemoryManager* MM = new TestReserveAllocationSpaceMemoryManager();
442 buildModuleWithCodeAndData();
444 Options.MCJMM = wrap(MM);
452 GetGlobalFct.raw = LLVMGetPointerToGlobal(Engine, Function);
458 SetGlobalFct.raw = LLVMGetPointerToGlobal(Engine, Function2);
460 SetGlobalFct.usable(789);
461 EXPECT_EQ(789, GetGlobalFct.usable());
462 EXPECT_LE(MM->UsedCodeSize, MM->ReservedCodeSize);
463 EXPECT_LE(MM->UsedDataSizeRO, MM->ReservedDataSizeRO);
464 EXPECT_LE(MM->UsedDataSizeRW, MM->ReservedDataSizeRW);
465 EXPECT_TRUE(MM->UsedCodeSize > 0);
466 EXPECT_TRUE(MM->UsedDataSizeRW > 0);
469 TEST_F(MCJITCAPITest, yield) {
470 SKIP_UNSUPPORTED_PLATFORM;
472 buildSimpleFunction();
475 LLVMContextRef C = LLVMGetGlobalContext();
476 LLVMContextSetYieldCallback(C, yield, nullptr);
483 functionPointer.raw = LLVMGetPointerToGlobal(Engine, Function);
485 EXPECT_EQ(42, functionPointer.usable());
486 EXPECT_TRUE(didCallYield);