331 lines · c
1//===- MCJITTestBase.h - Common base class for MCJIT Unit tests -*- 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-exception6//7//===----------------------------------------------------------------------===//8//9// This class implements common functionality required by the MCJIT unit tests,10// as well as logic to skip tests on unsupported architectures and operating11// systems.12//13//===----------------------------------------------------------------------===//14 15#ifndef LLVM_UNITTESTS_EXECUTIONENGINE_MCJIT_MCJITTESTBASE_H16#define LLVM_UNITTESTS_EXECUTIONENGINE_MCJIT_MCJITTESTBASE_H17 18#include "MCJITTestAPICommon.h"19#include "llvm/Config/config.h"20#include "llvm/ExecutionEngine/ExecutionEngine.h"21#include "llvm/ExecutionEngine/SectionMemoryManager.h"22#include "llvm/IR/Function.h"23#include "llvm/IR/IRBuilder.h"24#include "llvm/IR/LLVMContext.h"25#include "llvm/IR/Module.h"26#include "llvm/IR/Type.h"27#include "llvm/Support/CodeGen.h"28 29namespace llvm {30 31/// Helper class that can build very simple Modules32class TrivialModuleBuilder {33protected:34 LLVMContext Context;35 IRBuilder<> Builder;36 const Triple &BuilderTriple;37 38 TrivialModuleBuilder(const Triple &TT)39 : Builder(Context), BuilderTriple(TT) {}40 41 Module *createEmptyModule(StringRef Name = StringRef()) {42 Module * M = new Module(Name, Context);43 M->setTargetTriple(BuilderTriple);44 return M;45 }46 47 Function *startFunction(Module *M, FunctionType *FT, StringRef Name) {48 Function *Result =49 Function::Create(FT, GlobalValue::ExternalLinkage, Name, M);50 51 BasicBlock *BB = BasicBlock::Create(Context, Name, Result);52 Builder.SetInsertPoint(BB);53 54 return Result;55 }56 57 void endFunctionWithRet(Function *Func, Value *RetValue) {58 Builder.CreateRet(RetValue);59 }60 61 // Inserts a simple function that invokes Callee and takes the same arguments:62 // int Caller(...) { return Callee(...); }63 Function *insertSimpleCallFunction(Module *M, Function *Callee) {64 Function *Result = startFunction(M, Callee->getFunctionType(), "caller");65 66 SmallVector<Value *, 1> CallArgs(llvm::make_pointer_range(Result->args()));67 68 Value *ReturnCode = Builder.CreateCall(Callee, CallArgs);69 Builder.CreateRet(ReturnCode);70 return Result;71 }72 73 // Inserts a function named 'main' that returns a uint32_t:74 // int32_t main() { return X; }75 // where X is given by returnCode76 Function *insertMainFunction(Module *M, uint32_t returnCode) {77 Function *Result = startFunction(78 M, FunctionType::get(Type::getInt32Ty(Context), {}, false), "main");79 80 Value *ReturnVal = ConstantInt::get(Context, APInt(32, returnCode));81 endFunctionWithRet(Result, ReturnVal);82 83 return Result;84 }85 86 // Inserts a function87 // int32_t add(int32_t a, int32_t b) { return a + b; }88 // in the current module and returns a pointer to it.89 Function *insertAddFunction(Module *M, StringRef Name = "add") {90 Function *Result = startFunction(91 M,92 FunctionType::get(93 Type::getInt32Ty(Context),94 {Type::getInt32Ty(Context), Type::getInt32Ty(Context)}, false),95 Name);96 97 Function::arg_iterator args = Result->arg_begin();98 Value *Arg1 = &*args;99 Value *Arg2 = &*++args;100 Value *AddResult = Builder.CreateAdd(Arg1, Arg2);101 102 endFunctionWithRet(Result, AddResult);103 104 return Result;105 }106 107 // Inserts a declaration to a function defined elsewhere108 Function *insertExternalReferenceToFunction(Module *M, FunctionType *FTy,109 StringRef Name) {110 Function *Result =111 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);112 return Result;113 }114 115 // Inserts an declaration to a function defined elsewhere116 Function *insertExternalReferenceToFunction(Module *M, Function *Func) {117 Function *Result = Function::Create(Func->getFunctionType(),118 GlobalValue::ExternalLinkage,119 Func->getName(), M);120 return Result;121 }122 123 // Inserts a global variable of type int32124 // FIXME: make this a template function to support any type125 GlobalVariable *insertGlobalInt32(Module *M,126 StringRef name,127 int32_t InitialValue) {128 Type *GlobalTy = Type::getInt32Ty(Context);129 Constant *IV = ConstantInt::get(Context, APInt(32, InitialValue));130 GlobalVariable *Global = new GlobalVariable(*M,131 GlobalTy,132 false,133 GlobalValue::ExternalLinkage,134 IV,135 name);136 return Global;137 }138 139 // Inserts a function140 // int32_t recursive_add(int32_t num) {141 // if (num == 0) {142 // return num;143 // } else {144 // int32_t recursive_param = num - 1;145 // return num + Helper(recursive_param);146 // }147 // }148 // NOTE: if Helper is left as the default parameter, Helper == recursive_add.149 Function *insertAccumulateFunction(Module *M,150 Function *Helper = nullptr,151 StringRef Name = "accumulate") {152 Function *Result =153 startFunction(M,154 FunctionType::get(Type::getInt32Ty(Context),155 {Type::getInt32Ty(Context)}, false),156 Name);157 if (!Helper)158 Helper = Result;159 160 BasicBlock *BaseCase = BasicBlock::Create(Context, "", Result);161 BasicBlock *RecursiveCase = BasicBlock::Create(Context, "", Result);162 163 // if (num == 0)164 Value *Param = &*Result->arg_begin();165 Value *Zero = ConstantInt::get(Context, APInt(32, 0));166 Builder.CreateCondBr(Builder.CreateICmpEQ(Param, Zero),167 BaseCase, RecursiveCase);168 169 // return num;170 Builder.SetInsertPoint(BaseCase);171 Builder.CreateRet(Param);172 173 // int32_t recursive_param = num - 1;174 // return Helper(recursive_param);175 Builder.SetInsertPoint(RecursiveCase);176 Value *One = ConstantInt::get(Context, APInt(32, 1));177 Value *RecursiveParam = Builder.CreateSub(Param, One);178 Value *RecursiveReturn = Builder.CreateCall(Helper, RecursiveParam);179 Value *Accumulator = Builder.CreateAdd(Param, RecursiveReturn);180 Builder.CreateRet(Accumulator);181 182 return Result;183 }184 185 // Populates Modules A and B:186 // Module A { Extern FB1, Function FA which calls FB1 },187 // Module B { Extern FA, Function FB1, Function FB2 which calls FA },188 void createCrossModuleRecursiveCase(std::unique_ptr<Module> &A, Function *&FA,189 std::unique_ptr<Module> &B,190 Function *&FB1, Function *&FB2) {191 // Define FB1 in B.192 B.reset(createEmptyModule("B"));193 FB1 = insertAccumulateFunction(B.get(), nullptr, "FB1");194 195 // Declare FB1 in A (as an external).196 A.reset(createEmptyModule("A"));197 Function *FB1Extern = insertExternalReferenceToFunction(A.get(), FB1);198 199 // Define FA in A (with a call to FB1).200 FA = insertAccumulateFunction(A.get(), FB1Extern, "FA");201 202 // Declare FA in B (as an external)203 Function *FAExtern = insertExternalReferenceToFunction(B.get(), FA);204 205 // Define FB2 in B (with a call to FA)206 FB2 = insertAccumulateFunction(B.get(), FAExtern, "FB2");207 }208 209 // Module A { Function FA },210 // Module B { Extern FA, Function FB which calls FA },211 // Module C { Extern FB, Function FC which calls FB },212 void213 createThreeModuleChainedCallsCase(std::unique_ptr<Module> &A, Function *&FA,214 std::unique_ptr<Module> &B, Function *&FB,215 std::unique_ptr<Module> &C, Function *&FC) {216 A.reset(createEmptyModule("A"));217 FA = insertAddFunction(A.get());218 219 B.reset(createEmptyModule("B"));220 Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);221 FB = insertSimpleCallFunction(B.get(), FAExtern_in_B);222 223 C.reset(createEmptyModule("C"));224 Function *FBExtern_in_C = insertExternalReferenceToFunction(C.get(), FB);225 FC = insertSimpleCallFunction(C.get(), FBExtern_in_C);226 }227 228 // Module A { Function FA },229 // Populates Modules A and B:230 // Module B { Function FB }231 void createTwoModuleCase(std::unique_ptr<Module> &A, Function *&FA,232 std::unique_ptr<Module> &B, Function *&FB) {233 A.reset(createEmptyModule("A"));234 FA = insertAddFunction(A.get());235 236 B.reset(createEmptyModule("B"));237 FB = insertAddFunction(B.get());238 }239 240 // Module A { Function FA },241 // Module B { Extern FA, Function FB which calls FA }242 void createTwoModuleExternCase(std::unique_ptr<Module> &A, Function *&FA,243 std::unique_ptr<Module> &B, Function *&FB) {244 A.reset(createEmptyModule("A"));245 FA = insertAddFunction(A.get());246 247 B.reset(createEmptyModule("B"));248 Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);249 FB = insertSimpleCallFunction(B.get(), FAExtern_in_B);250 }251 252 // Module A { Function FA },253 // Module B { Extern FA, Function FB which calls FA },254 // Module C { Extern FB, Function FC which calls FA },255 void createThreeModuleCase(std::unique_ptr<Module> &A, Function *&FA,256 std::unique_ptr<Module> &B, Function *&FB,257 std::unique_ptr<Module> &C, Function *&FC) {258 A.reset(createEmptyModule("A"));259 FA = insertAddFunction(A.get());260 261 B.reset(createEmptyModule("B"));262 Function *FAExtern_in_B = insertExternalReferenceToFunction(B.get(), FA);263 FB = insertSimpleCallFunction(B.get(), FAExtern_in_B);264 265 C.reset(createEmptyModule("C"));266 Function *FAExtern_in_C = insertExternalReferenceToFunction(C.get(), FA);267 FC = insertSimpleCallFunction(C.get(), FAExtern_in_C);268 }269};270 271class MCJITTestBase : public MCJITTestAPICommon, public TrivialModuleBuilder {272protected:273 MCJITTestBase()274 : TrivialModuleBuilder(HostTriple), OptLevel(CodeGenOptLevel::None),275 CodeModel(CodeModel::Small), MArch(""), MM(new SectionMemoryManager) {276 // The architectures below are known to be compatible with MCJIT as they277 // are copied from test/ExecutionEngine/MCJIT/lit.local.cfg and should be278 // kept in sync.279 SupportedArchs.push_back(Triple::aarch64);280 SupportedArchs.push_back(Triple::arm);281 SupportedArchs.push_back(Triple::mips);282 SupportedArchs.push_back(Triple::mipsel);283 SupportedArchs.push_back(Triple::mips64);284 SupportedArchs.push_back(Triple::mips64el);285 SupportedArchs.push_back(Triple::x86);286 SupportedArchs.push_back(Triple::x86_64);287 288 // Some architectures have sub-architectures in which tests will fail, like289 // ARM. These two vectors will define if they do have sub-archs (to avoid290 // extra work for those who don't), and if so, if they are listed to work291 HasSubArchs.push_back(Triple::arm);292 SupportedSubArchs.push_back("armv6");293 SupportedSubArchs.push_back("armv7");294 295 UnsupportedEnvironments.push_back(Triple::Cygnus);296 }297 298 void createJIT(std::unique_ptr<Module> M) {299 300 // Due to the EngineBuilder constructor, it is required to have a Module301 // in order to construct an ExecutionEngine (i.e. MCJIT)302 assert(M != 0 && "a non-null Module must be provided to create MCJIT");303 304 EngineBuilder EB(std::move(M));305 std::string Error;306 TheJIT.reset(EB.setEngineKind(EngineKind::JIT)307 .setMCJITMemoryManager(std::move(MM))308 .setErrorStr(&Error)309 .setOptLevel(CodeGenOptLevel::None)310 .setMArch(MArch)311 .setMCPU(sys::getHostCPUName())312 //.setMAttrs(MAttrs)313 .create());314 // At this point, we cannot modify the module any more.315 assert(TheJIT.get() != NULL && "error creating MCJIT with EngineBuilder");316 }317 318 CodeGenOptLevel OptLevel;319 CodeModel::Model CodeModel;320 StringRef MArch;321 SmallVector<std::string, 1> MAttrs;322 std::unique_ptr<ExecutionEngine> TheJIT;323 std::unique_ptr<RTDyldMemoryManager> MM;324 325 std::unique_ptr<Module> M;326};327 328} // namespace llvm329 330#endif // LLVM_UNITTESTS_EXECUTIONENGINE_MCJIT_MCJITTESTBASE_H331