1#include "llvm/ADT/STLExtras.h"
2#include "llvm/Analysis/Passes.h"
3#include "llvm/ExecutionEngine/ExecutionEngine.h"
4#include "llvm/ExecutionEngine/GenericValue.h"
5#include "llvm/ExecutionEngine/MCJIT.h"
6#include "llvm/IR/Argument.h"
7#include "llvm/IR/Attributes.h"
8#include "llvm/IR/BasicBlock.h"
9#include "llvm/IR/Constants.h"
10#include "llvm/IR/DerivedTypes.h"
11#include "llvm/IR/Function.h"
12#include "llvm/IR/IRBuilder.h"
13#include "llvm/IR/Instructions.h"
14#include "llvm/IR/Intrinsics.h"
15#include "llvm/IR/LegacyPassManager.h"
16#include "llvm/IR/LLVMContext.h"
17#include "llvm/IR/Module.h"
18#include "llvm/IR/Type.h"
19#include "llvm/Support/Casting.h"
20#include "llvm/Support/ManagedStatic.h"
21#include "llvm/Support/TargetSelect.h"
22#include "llvm/Support/raw_ostream.h"
23#include "llvm/ADT/APFloat.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/IR/Verifier.h"
26#include "llvm/Support/TargetSelect.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Transforms/Scalar.h"
29#include "llvm/Transforms/Vectorize.h"
30#include "llvm/ExecutionEngine/ObjectCache.h"
31#include "llvm/Support/FileSystem.h"
32#include "llvm/Support/Path.h"
39#if (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 9) \
40 || (LLVM_VERSION_MAJOR > 3)
41#include <llvm/Transforms/Scalar/GVN.h>
44#if (LLVM_VERSION_MAJOR >= 7)
45#include <llvm/Transforms/InstCombine/InstCombine.h>
46#include <llvm/Transforms/Scalar/InstSimplifyPass.h>
47#include <llvm/Transforms/Utils.h>
50#include <symengine/llvm_double.h>
57#if (LLVM_VERSION_MAJOR >= 10)
58using std::make_unique;
60using llvm::make_unique;
67llvm::Value *LLVMVisitor::apply(
const Basic &b)
73void LLVMVisitor::init(
const vec_basic &x,
const Basic &b,
bool symbolic_cse,
76 init(x, b, symbolic_cse, LLVMVisitor::create_default_passes(opt_level),
80void LLVMVisitor::init(
const vec_basic &x,
const Basic &b,
bool symbolic_cse,
84 init(x, {b.rcp_from_this()}, symbolic_cse, passes, opt_level);
87llvm::Function *LLVMVisitor::get_function_type(llvm::LLVMContext *context)
90 for (
int i = 0; i < 2; i++) {
91 inp.
push_back(llvm::PointerType::get(get_float_type(context), 0));
93 llvm::FunctionType *function_type = llvm::FunctionType::get(
94 llvm::Type::getVoidTy(*context), inp,
false);
95 auto F = llvm::Function::Create(function_type,
96 llvm::Function::InternalLinkage,
"",
mod);
97 F->setCallingConv(llvm::CallingConv::C);
98#if (LLVM_VERSION_MAJOR < 5)
100 llvm::SmallVector<llvm::AttributeSet, 4> attrs;
101 llvm::AttributeSet PAS;
104 B.addAttribute(llvm::Attribute::ReadOnly);
105 B.addAttribute(llvm::Attribute::NoCapture);
106 PAS = llvm::AttributeSet::get(
mod->getContext(), 1U, B);
109 attrs.push_back(PAS);
112 B.addAttribute(llvm::Attribute::NoCapture);
113 PAS = llvm::AttributeSet::get(
mod->getContext(), 2U, B);
116 attrs.push_back(PAS);
119 B.addAttribute(llvm::Attribute::NoUnwind);
120 B.addAttribute(llvm::Attribute::UWTable);
121 PAS = llvm::AttributeSet::get(
mod->getContext(), ~0U, B);
124 attrs.push_back(PAS);
126 F->setAttributes(llvm::AttributeSet::get(
mod->getContext(), attrs));
129 F->addParamAttr(0, llvm::Attribute::ReadOnly);
130 F->addParamAttr(0, llvm::Attribute::NoCapture);
131 F->addParamAttr(1, llvm::Attribute::NoCapture);
132 F->addFnAttr(llvm::Attribute::NoUnwind);
133#if (LLVM_VERSION_MAJOR < 15)
134 F->addFnAttr(llvm::Attribute::UWTable);
136 F->addFnAttr(llvm::Attribute::getWithUWTableKind(
137 *context, llvm::UWTableKind::Default));
149#if (LLVM_VERSION_MAJOR < 4)
150 passes.
push_back(llvm::createInstructionCombiningPass());
152 passes.
push_back(llvm::createInstructionCombiningPass(optlevel > 1));
154 passes.
push_back(llvm::createDeadCodeEliminationPass());
155 passes.
push_back(llvm::createPromoteMemoryToRegisterPass());
156 passes.
push_back(llvm::createReassociatePass());
158 passes.
push_back(llvm::createCFGSimplificationPass());
159 passes.
push_back(llvm::createPartiallyInlineLibCallsPass());
160#if (LLVM_VERSION_MAJOR < 5)
161 passes.
push_back(llvm::createLoadCombinePass());
163#if LLVM_VERSION_MAJOR >= 7
164 passes.
push_back(llvm::createInstSimplifyLegacyPass());
166 passes.
push_back(llvm::createInstructionSimplifierPass());
168 passes.
push_back(llvm::createMemCpyOptPass());
169 passes.
push_back(llvm::createSROAPass());
170 passes.
push_back(llvm::createMergedLoadStoreMotionPass());
171 passes.
push_back(llvm::createBitTrackingDCEPass());
172 passes.
push_back(llvm::createAggressiveDCEPass());
174 passes.
push_back(llvm::createSLPVectorizerPass());
175#if LLVM_VERSION_MAJOR >= 7
176 passes.
push_back(llvm::createInstSimplifyLegacyPass());
178 passes.
push_back(llvm::createInstructionSimplifierPass());
184void LLVMVisitor::init(
const vec_basic &inputs,
const vec_basic &outputs,
185 const bool symbolic_cse,
unsigned opt_level)
187 init(inputs, outputs, symbolic_cse,
188 LLVMVisitor::create_default_passes(opt_level), opt_level);
191void LLVMVisitor::init(
const vec_basic &inputs,
const vec_basic &outputs,
192 const bool symbolic_cse,
196 executionengine.reset();
197 llvm::InitializeNativeTarget();
198 llvm::InitializeNativeTargetAsmPrinter();
199 llvm::InitializeNativeTargetAsmParser();
200 context = std::make_shared<llvm::LLVMContext>();
205 = make_unique<llvm::Module>(
"SymEngine", *context.get());
206 module->setDataLayout(
"");
210 fpm = std::make_shared<llvm::legacy::FunctionPassManager>(
mod);
211 for (
auto pass : passes) {
214 fpm->doInitialization();
216 auto F = get_function_type(context.get());
221 llvm::BasicBlock *BB = llvm::BasicBlock::Create(*context,
"EntryBlock", F);
226 llvm::IRBuilder<> _builder(BB);
227 builder =
reinterpret_cast<IRBuilder *
>(&_builder);
228 builder->SetInsertPoint(BB);
229 auto fmf = llvm::FastMathFlags();
231 builder->setFastMathFlags(fmf);
234 auto input_arg = &(*(F->args().begin()));
235 for (
unsigned i = 0; i < inputs.size(); i++) {
236 if (not is_a<Symbol>(*inputs[i])) {
237 throw SymEngineException(
"Input contains a non-symbol.");
240 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*context), i);
241 auto ptr = builder->CreateGEP(get_float_type(context.get()), input_arg,
243 result_ = builder->CreateLoad(get_float_type(context.get()), ptr);
244 symbol_ptrs.push_back(result_);
247 auto it = F->args().begin();
248#if (LLVM_VERSION_MAJOR < 5)
249 auto out = &(*(++it));
251 auto out = &(*(it + 1));
256 vec_basic reduced_exprs;
257 vec_pair replacements;
259 SymEngine::cse(replacements, reduced_exprs, outputs);
260 for (
auto &rep : replacements) {
262 replacement_symbol_ptrs[rep.first] = apply(*(rep.second));
265 for (
unsigned i = 0; i < outputs.size(); i++) {
266 output_vals.
push_back(apply(*reduced_exprs[i]));
270 for (
unsigned i = 0; i < outputs.size(); i++) {
271 output_vals.
push_back(apply(*outputs[i]));
276 for (
unsigned i = 0; i < outputs.size(); i++) {
278 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*context), i);
280 = builder->CreateGEP(get_float_type(context.get()), out, index);
281 builder->CreateStore(output_vals[i], ptr);
285 builder->CreateRetVoid();
288 llvm::verifyFunction(*F, &llvm::outs());
307 .setEngineKind(llvm::EngineKind::Kind::JIT)
308 .setOptLevel(
static_cast<llvm::CodeGenOpt::Level
>(opt_level))
313 class MemoryBufferRefCallback :
public llvm::ObjectCache
317 MemoryBufferRefCallback(
std::string &ss) : ss_(ss) {}
319 void notifyObjectCompiled(
const llvm::Module *M,
320 llvm::MemoryBufferRef obj)
override
322 const char *c = obj.getBufferStart();
324 ss_.
assign(c, obj.getBufferSize());
328 getObject(
const llvm::Module *M)
override
334 MemoryBufferRefCallback callback(membuffer);
335 executionengine->setObjectCache(&callback);
337 executionengine->finalizeObject();
340 func = (intptr_t)executionengine->getPointerToFunction(F);
342 replacement_symbol_ptrs.clear();
349 ((double (*)(
const double *,
double *))func)(vec.
data(), &ret);
353void LLVMDoubleVisitor::call(
double *outs,
const double *inps)
const
355 ((double (*)(
const double *,
double *))func)(inps, outs);
358#ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
363 ((
long double (*)(
const long double *,
long double *))func)(vec.
data(),
368void LLVMLongDoubleVisitor::call(
long double *outs,
369 const long double *inps)
const
371 ((
long double (*)(
const long double *,
long double *))func)(inps, outs);
378 ((float (*)(
const float *,
float *))func)(vec.
data(), &ret);
382void LLVMFloatVisitor::call(
float *outs,
const float *inps)
const
384 ((float (*)(
const float *,
float *))func)(inps, outs);
387void LLVMVisitor::set_double(
double d)
389 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()), d);
392void LLVMVisitor::bvisit(
const Integer &x)
394 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()),
395 mp_get_d(x.as_integer_class()));
398#ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
399void LLVMLongDoubleVisitor::convert_from_mpfr(
const Basic &x)
401#ifndef HAVE_SYMENGINE_MPFR
402 throw NotImplementedError(
"Cannot convert to long double without MPFR");
404 RCP<const Basic> m = evalf(x, 128, EvalfDomain::Real);
405 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()),
410void LLVMLongDoubleVisitor::visit(
const Integer &x)
412 result_ = llvm::ConstantFP::get(get_float_type(&
mod->getContext()),
417void LLVMVisitor::bvisit(
const Rational &x)
419 set_double(mp_get_d(x.as_rational_class()));
422#ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
423void LLVMLongDoubleVisitor::visit(
const Rational &x)
425 convert_from_mpfr(x);
429void LLVMVisitor::bvisit(
const RealDouble &x)
434#ifdef HAVE_SYMENGINE_MPFR
435void LLVMVisitor::bvisit(
const RealMPFR &x)
437 set_double(mpfr_get_d(x.i.get_mpfr_t(), MPFR_RNDN));
439#ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
440void LLVMLongDoubleVisitor::visit(
const RealMPFR &x)
442 convert_from_mpfr(x);
447void LLVMVisitor::bvisit(
const Add &x)
449 llvm::Value *tmp, *tmp1, *tmp2;
450 auto it = x.get_dict().begin();
452 if (
eq(*x.get_coef(), *zero)) {
454 if (
eq(*one, *(it->second))) {
455 tmp = apply(*(it->first));
457 tmp1 = apply(*(it->first));
458 tmp2 = apply(*(it->second));
459 tmp = builder->CreateFMul(tmp1, tmp2);
463 tmp = apply(*x.get_coef());
466 for (; it != x.get_dict().
end(); ++it) {
467 if (
eq(*one, *(it->second))) {
468 tmp1 = apply(*(it->first));
469 tmp = builder->CreateFAdd(tmp, tmp1);
476 tmp1 = apply(*(it->first));
477 tmp2 = apply(*(it->second));
478 tmp = builder->CreateFAdd(tmp, builder->CreateFMul(tmp1, tmp2));
484void LLVMVisitor::bvisit(
const Mul &x)
486 llvm::Value *tmp =
nullptr;
488 for (
const auto &p : x.get_args()) {
492 tmp = builder->CreateFMul(tmp, apply(*p));
499llvm::Function *LLVMVisitor::get_powi()
503#if (LLVM_VERSION_MAJOR > 12)
504 arg_type.
push_back(llvm::Type::getInt32Ty(
mod->getContext()));
506 return llvm::Intrinsic::getDeclaration(
mod, llvm::Intrinsic::powi,
510llvm::Function *get_float_intrinsic(llvm::Type *type, llvm::Intrinsic::ID
id,
511 unsigned n, llvm::Module *
mod)
514 return llvm::Intrinsic::getDeclaration(
mod,
id, arg_type);
517void LLVMVisitor::bvisit(
const Pow &x)
521 if (
eq(*(x.get_base()), *E)) {
523 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
524 llvm::Intrinsic::exp, 1,
mod);
526 }
else if (
eq(*(x.get_base()), *
integer(2))) {
528 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
529 llvm::Intrinsic::exp2, 1,
mod);
532 if (is_a<Integer>(*x.get_exp())) {
534 llvm::Value *tmp = apply(*x.get_base());
535 result_ = builder->CreateFMul(tmp, tmp);
539 int d = numeric_cast<int>(
540 mp_get_si(
static_cast<const Integer &
>(*x.get_exp())
541 .as_integer_class()));
542 result_ = llvm::ConstantInt::get(
543 llvm::Type::getInt32Ty(
mod->getContext()), d,
true);
550 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
551 llvm::Intrinsic::pow, 1,
mod);
554 auto r = builder->CreateCall(fun, args);
555 r->setTailCall(
true);
559void LLVMVisitor::bvisit(
const Sin &x)
564 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
565 llvm::Intrinsic::sin, 1,
mod);
566 auto r = builder->CreateCall(fun, args);
567 r->setTailCall(
true);
571void LLVMVisitor::bvisit(
const Cos &x)
576 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
577 llvm::Intrinsic::cos, 1,
mod);
578 auto r = builder->CreateCall(fun, args);
579 r->setTailCall(
true);
583void LLVMVisitor::bvisit(
const Piecewise &x)
587 RCP<const Piecewise> pw = x.rcp_from_this_cast<
const Piecewise>();
589 if (
neq(*pw->get_vec().back().second, *boolTrue)) {
590 throw SymEngineException(
591 "LLVMDouble requires a (Expr, True) at the end of Piecewise");
594 if (pw->get_vec().size() > 2) {
595 PiecewiseVec rest = pw->get_vec();
596 rest.
erase(rest.begin());
597 auto rest_pw = piecewise(
std::move(rest));
599 new_pw.
push_back(*pw->get_vec().begin());
600 new_pw.push_back({rest_pw, pw->get_vec().back().second});
602 ->rcp_from_this_cast<
const Piecewise>();
603 }
else if (pw->get_vec().size() < 2) {
604 throw SymEngineException(
"Invalid Piecewise object");
607 auto cond_basic = pw->get_vec().front().second;
608 llvm::Value *cond = apply(*cond_basic);
610 cond = builder->CreateFCmpONE(
611 cond, llvm::ConstantFP::get(get_float_type(&
mod->getContext()), 0.0),
613 llvm::Function *function = builder->GetInsertBlock()->getParent();
617 llvm::BasicBlock *then_bb
618 = llvm::BasicBlock::Create(
mod->getContext(),
"then", function);
619 llvm::BasicBlock *else_bb
620 = llvm::BasicBlock::Create(
mod->getContext(),
"else");
621 llvm::BasicBlock *merge_bb
622 = llvm::BasicBlock::Create(
mod->getContext(),
"ifcont");
623 builder->CreateCondBr(cond, then_bb, else_bb);
626 builder->SetInsertPoint(then_bb);
627 llvm::Value *then_value = apply(*pw->get_vec().front().first);
628 builder->CreateBr(merge_bb);
632 then_bb = builder->GetInsertBlock();
635#if (LLVM_VERSION_MAJOR < 16)
636 function->getBasicBlockList().push_back(else_bb);
638 function->insert(function->end(), else_bb);
640 builder->SetInsertPoint(else_bb);
641 llvm::Value *else_value = apply(*pw->get_vec().back().first);
642 builder->CreateBr(merge_bb);
646 else_bb = builder->GetInsertBlock();
649#if (LLVM_VERSION_MAJOR < 16)
650 function->getBasicBlockList().push_back(merge_bb);
652 function->insert(function->end(), merge_bb);
654 builder->SetInsertPoint(merge_bb);
655 llvm::PHINode *phi_node
656 = builder->CreatePHI(get_float_type(&
mod->getContext()), 2);
658 phi_node->addIncoming(then_value, then_bb);
659 phi_node->addIncoming(else_value, else_bb);
663void LLVMVisitor::bvisit(
const Sign &x)
665 const auto x2 = x.get_arg();
667 new_pw.
push_back({real_double(0.0),
Eq(x2, real_double(0.0))});
668 new_pw.push_back({real_double(-1.0),
Lt(x2, real_double(0.0))});
669 new_pw.push_back({real_double(1.0), boolTrue});
670 auto pw = rcp_static_cast<const Piecewise>(piecewise(
std::move(new_pw)));
674void LLVMVisitor::bvisit(
const Contains &cts)
676 llvm::Value *expr = apply(*cts.get_expr());
677 const auto set = cts.get_set();
678 if (is_a<Interval>(*set)) {
679 const auto &interv = down_cast<const Interval &>(*set);
680 llvm::Value *start = apply(*interv.get_start());
681 llvm::Value *
end = apply(*interv.get_end());
682 const bool left_open = interv.get_left_open();
683 const bool right_open = interv.get_right_open();
684 llvm::Value *left_ok;
685 llvm::Value *right_ok;
686 left_ok = (left_open) ? builder->CreateFCmpOLT(start, expr)
687 : builder->CreateFCmpOLE(start, expr);
688 right_ok = (right_open) ? builder->CreateFCmpOLT(expr, end)
689 : builder->CreateFCmpOLE(expr, end);
690 result_ = builder->CreateAnd(left_ok, right_ok);
691 result_ = builder->CreateUIToFP(result_,
692 get_float_type(&
mod->getContext()));
694 throw SymEngineException(
"LLVMVisitor: only ``Interval`` "
695 "implemented for ``Contains``.");
699void LLVMVisitor::bvisit(
const Infty &x)
701 if (x.is_negative_infinity()) {
702 result_ = llvm::ConstantFP::getInfinity(
703 get_float_type(&
mod->getContext()),
true);
704 }
else if (x.is_positive_infinity()) {
705 result_ = llvm::ConstantFP::getInfinity(
706 get_float_type(&
mod->getContext()),
false);
708 throw SymEngineException(
709 "LLVMDouble can only represent real valued infinity");
713void LLVMVisitor::bvisit(
const NaN &x)
715 result_ = llvm::ConstantFP::getNaN(get_float_type(&
mod->getContext()),
719void LLVMVisitor::bvisit(
const BooleanAtom &x)
721 const bool val = x.get_val();
722 set_double(val ? 1.0 : 0.0);
725void LLVMVisitor::bvisit(
const Log &x)
730 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
731 llvm::Intrinsic::log, 1,
mod);
732 auto r = builder->CreateCall(fun, args);
733 r->setTailCall(
true);
737#define SYMENGINE_LOGIC_FUNCTION(Class, method) \
738 void LLVMVisitor::bvisit(const Class &x) \
740 llvm::Value *value = nullptr; \
743 llvm::Value *zero_val = result_; \
744 for (auto &p : x.get_container()) { \
745 tmp = builder->CreateFCmpONE(apply(*p), zero_val); \
746 if (value == nullptr) { \
749 value = builder->method(value, tmp); \
752 result_ = builder->CreateUIToFP(value, \
753 get_float_type(&mod->getContext())); \
756SYMENGINE_LOGIC_FUNCTION(And, CreateAnd);
757SYMENGINE_LOGIC_FUNCTION(Or, CreateOr);
758SYMENGINE_LOGIC_FUNCTION(Xor, CreateXor);
760void LLVMVisitor::bvisit(
const Not &x)
762 builder->CreateNot(apply(*x.get_arg()));
765#define SYMENGINE_RELATIONAL_FUNCTION(Class, method) \
766 void LLVMVisitor::bvisit(const Class &x) \
768 llvm::Value *left = apply(*x.get_arg1()); \
769 llvm::Value *right = apply(*x.get_arg2()); \
770 result_ = builder->method(left, right); \
771 result_ = builder->CreateUIToFP(result_, \
772 get_float_type(&mod->getContext())); \
775SYMENGINE_RELATIONAL_FUNCTION(Equality, CreateFCmpOEQ);
776SYMENGINE_RELATIONAL_FUNCTION(Unequality, CreateFCmpONE);
777SYMENGINE_RELATIONAL_FUNCTION(LessThan, CreateFCmpOLE);
778SYMENGINE_RELATIONAL_FUNCTION(StrictLessThan, CreateFCmpOLT);
780#define _SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
781 void LLVMDoubleVisitor::visit(const Class &x) \
783 vec_basic basic_args = x.get_args(); \
784 llvm::Function *func = get_external_function(#ext, basic_args.size()); \
785 std::vector<llvm::Value *> args; \
786 for (const auto &arg : basic_args) { \
787 args.push_back(apply(*arg)); \
789 auto r = builder->CreateCall(func, args); \
790 r->setTailCall(true); \
793 void LLVMFloatVisitor::visit(const Class &x) \
795 vec_basic basic_args = x.get_args(); \
796 llvm::Function *func = get_external_function(#ext + std::string("f"), \
797 basic_args.size()); \
798 std::vector<llvm::Value *> args; \
799 for (const auto &arg : basic_args) { \
800 args.push_back(apply(*arg)); \
802 auto r = builder->CreateCall(func, args); \
803 r->setTailCall(true); \
807#ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
808#define SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
809 _SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
810 void LLVMLongDoubleVisitor::visit(const Class &x) \
812 vec_basic basic_args = x.get_args(); \
813 llvm::Function *func = get_external_function(#ext + std::string("l"), \
814 basic_args.size()); \
815 std::vector<llvm::Value *> args; \
816 for (const auto &arg : basic_args) { \
817 args.push_back(apply(*arg)); \
819 auto r = builder->CreateCall(func, args); \
820 r->setTailCall(true); \
824#define SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext) \
825 _SYMENGINE_MACRO_EXTERNAL_FUNCTION(Class, ext)
828SYMENGINE_MACRO_EXTERNAL_FUNCTION(Tan,
tan)
829SYMENGINE_MACRO_EXTERNAL_FUNCTION(ASin,
asin)
830SYMENGINE_MACRO_EXTERNAL_FUNCTION(ACos,
acos)
831SYMENGINE_MACRO_EXTERNAL_FUNCTION(ATan,
atan)
832SYMENGINE_MACRO_EXTERNAL_FUNCTION(ATan2,
atan2)
833SYMENGINE_MACRO_EXTERNAL_FUNCTION(Sinh,
sinh)
834SYMENGINE_MACRO_EXTERNAL_FUNCTION(Cosh,
cosh)
835SYMENGINE_MACRO_EXTERNAL_FUNCTION(Tanh,
tanh)
836SYMENGINE_MACRO_EXTERNAL_FUNCTION(ASinh,
asinh)
837SYMENGINE_MACRO_EXTERNAL_FUNCTION(ACosh,
acosh)
838SYMENGINE_MACRO_EXTERNAL_FUNCTION(ATanh,
atanh)
839SYMENGINE_MACRO_EXTERNAL_FUNCTION(Gamma, tgamma)
840SYMENGINE_MACRO_EXTERNAL_FUNCTION(LogGamma, lgamma)
841SYMENGINE_MACRO_EXTERNAL_FUNCTION(Erf,
erf)
842SYMENGINE_MACRO_EXTERNAL_FUNCTION(Erfc,
erfc)
844void LLVMVisitor::bvisit(
const Abs &x)
849 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
850 llvm::Intrinsic::fabs, 1,
mod);
851 auto r = builder->CreateCall(fun, args);
852 r->setTailCall(
true);
856void LLVMVisitor::bvisit(
const Min &x)
858 llvm::Value *value =
nullptr;
860 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
861 llvm::Intrinsic::minnum, 1,
mod);
862 for (
auto &arg : x.get_vec()) {
863 if (value !=
nullptr) {
867 auto r = builder->CreateCall(fun, args);
868 r->setTailCall(
true);
877void LLVMVisitor::bvisit(
const Max &x)
879 llvm::Value *value =
nullptr;
881 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
882 llvm::Intrinsic::maxnum, 1,
mod);
883 for (
auto &arg : x.get_vec()) {
884 if (value !=
nullptr) {
888 auto r = builder->CreateCall(fun, args);
889 r->setTailCall(
true);
898void LLVMVisitor::bvisit(
const Symbol &x)
901 for (
auto &symb : symbols) {
903 result_ = symbol_ptrs[i];
908 auto it = replacement_symbol_ptrs.find(x.rcp_from_this());
909 if (it != replacement_symbol_ptrs.end()) {
910 result_ = it->second;
914 throw SymEngineException(
"Symbol " + x.__str__()
915 +
" not in the symbols vector.");
918llvm::Function *LLVMVisitor::get_external_function(
const std::string &name,
922 get_float_type(&
mod->getContext()));
923 llvm::FunctionType *func_type = llvm::FunctionType::get(
924 get_float_type(&
mod->getContext()), func_args,
false);
926 llvm::Function *func =
mod->getFunction(name);
928 func = llvm::Function::Create(
929 func_type, llvm::GlobalValue::ExternalLinkage, name,
mod);
930 func->setCallingConv(llvm::CallingConv::C);
932#if (LLVM_VERSION_MAJOR < 5)
933 llvm::AttributeSet func_attr_set;
935 llvm::SmallVector<llvm::AttributeSet, 4> attrs;
936 llvm::AttributeSet attr_set;
938 llvm::AttrBuilder attr_builder;
939 attr_builder.addAttribute(llvm::Attribute::NoUnwind);
941 = llvm::AttributeSet::get(
mod->getContext(), ~0U, attr_builder);
944 attrs.push_back(attr_set);
945 func_attr_set = llvm::AttributeSet::get(
mod->getContext(), attrs);
947 func->setAttributes(func_attr_set);
949 func->addFnAttr(llvm::Attribute::NoUnwind);
954void LLVMVisitor::bvisit(
const Constant &x)
956 set_double(eval_double(x));
959#ifdef SYMENGINE_HAVE_LLVM_LONG_DOUBLE
960void LLVMLongDoubleVisitor::visit(
const Constant &x)
962 convert_from_mpfr(x);
966void LLVMVisitor::bvisit(
const Basic &x)
968 throw NotImplementedError(x.__str__());
979 llvm::InitializeNativeTarget();
980 llvm::InitializeNativeTargetAsmPrinter();
981 llvm::InitializeNativeTargetAsmParser();
982 context = std::make_shared<llvm::LLVMContext>();
986 = make_unique<llvm::Module>(
"SymEngine", *context);
987 module->setDataLayout(
"");
994 auto F = get_function_type(context.get());
999 .setEngineKind(llvm::EngineKind::Kind::JIT)
1000 .setOptLevel(llvm::CodeGenOpt::Level::Aggressive)
1001 .setErrorStr(&error)
1004 class MCJITObjectLoader :
public llvm::ObjectCache
1009 MCJITObjectLoader(
const std::string &s) : s_(s) {}
1010 void notifyObjectCompiled(
const llvm::Module *M,
1011 llvm::MemoryBufferRef obj)
override
1018 getObject(
const llvm::Module *M)
override
1020 return llvm::MemoryBuffer::getMemBufferCopy(llvm::StringRef(s_));
1024 MCJITObjectLoader loader(s);
1025 executionengine->setObjectCache(&loader);
1026 executionengine->finalizeObject();
1028 func = (intptr_t)executionengine->getPointerToFunction(F);
1031void LLVMVisitor::bvisit(
const Floor &x)
1034 llvm::Function *fun;
1036 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
1037 llvm::Intrinsic::floor, 1,
mod);
1038 auto r = builder->CreateCall(fun, args);
1039 r->setTailCall(
true);
1043void LLVMVisitor::bvisit(
const Ceiling &x)
1046 llvm::Function *fun;
1048 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
1049 llvm::Intrinsic::ceil, 1,
mod);
1050 auto r = builder->CreateCall(fun, args);
1051 r->setTailCall(
true);
1055void LLVMVisitor::bvisit(
const UnevaluatedExpr &x)
1057 apply(*x.get_arg());
1060void LLVMVisitor::bvisit(
const Truncate &x)
1063 llvm::Function *fun;
1065 fun = get_float_intrinsic(get_float_type(&
mod->getContext()),
1066 llvm::Intrinsic::trunc, 1,
mod);
1067 auto r = builder->CreateCall(fun, args);
1068 r->setTailCall(
true);
1072llvm::Type *LLVMDoubleVisitor::get_float_type(llvm::LLVMContext *context)
1074 return llvm::Type::getDoubleTy(*context);
1077llvm::Type *LLVMFloatVisitor::get_float_type(llvm::LLVMContext *context)
1079 return llvm::Type::getFloatTy(*context);
1082#if defined(SYMENGINE_HAVE_LLVM_LONG_DOUBLE)
1083llvm::Type *LLVMLongDoubleVisitor::get_float_type(llvm::LLVMContext *context)
1085 return llvm::Type::getX86_FP80Ty(*context);
The lowest unit of symbolic representation.
Main namespace for SymEngine package.
RCP< const Basic > acos(const RCP< const Basic > &arg)
Canonicalize ACos:
bool eq(const Basic &a, const Basic &b)
Checks equality for a and b
RCP< const Boolean > Lt(const RCP< const Basic > &lhs, const RCP< const Basic > &rhs)
Returns the canonicalized StrictLessThan object from the arguments.
RCP< const Integer > mod(const Integer &n, const Integer &d)
modulo round toward zero
RCP< const Basic > atan2(const RCP< const Basic > &num, const RCP< const Basic > &den)
Canonicalize ATan2:
RCP< const Basic > asin(const RCP< const Basic > &arg)
Canonicalize ASin:
RCP< const Basic > tan(const RCP< const Basic > &arg)
Canonicalize Tan:
RCP< const Basic > cosh(const RCP< const Basic > &arg)
Canonicalize Cosh:
RCP< const Basic > atan(const RCP< const Basic > &arg)
Canonicalize ATan:
RCP< const Basic > asinh(const RCP< const Basic > &arg)
Canonicalize ASinh:
RCP< const Basic > tanh(const RCP< const Basic > &arg)
Canonicalize Tanh:
RCP< const Basic > atanh(const RCP< const Basic > &arg)
Canonicalize ATanh:
RCP< const Basic > erfc(const RCP< const Basic > &arg)
Canonicalize Erfc:
RCP< const Basic > acosh(const RCP< const Basic > &arg)
Canonicalize ACosh:
RCP< const Boolean > Eq(const RCP< const Basic > &lhs)
Returns the canonicalized Equality object from a single argument.
bool neq(const Basic &a, const Basic &b)
Checks inequality for a and b
std::enable_if< std::is_integral< T >::value, RCP< constInteger > >::type integer(T i)
RCP< const Basic > erf(const RCP< const Basic > &arg)
Canonicalize Erf:
RCP< const Basic > sinh(const RCP< const Basic > &arg)
Canonicalize Sinh: