16 #include <llvm-c/Analysis.h>
17 #include <llvm-c/BitReader.h>
18 #include <llvm-c/BitWriter.h>
19 #include <llvm-c/Core.h>
20 #include <llvm-c/ExecutionEngine.h>
21 #if LLVM_VERSION_MAJOR > 16
22 #include <llvm-c/Transforms/PassBuilder.h>
24 #if LLVM_VERSION_MAJOR > 11
25 #include <llvm-c/Orc.h>
26 #include <llvm-c/OrcEE.h>
27 #include <llvm-c/LLJIT.h>
29 #include <llvm-c/OrcBindings.h>
31 #include <llvm-c/Support.h>
32 #include <llvm-c/Target.h>
33 #if LLVM_VERSION_MAJOR < 17
34 #include <llvm-c/Transforms/IPO.h>
35 #include <llvm-c/Transforms/PassManagerBuilder.h>
36 #include <llvm-c/Transforms/Scalar.h>
37 #include <llvm-c/Transforms/Utils.h>
48 #define LLVMJIT_LLVM_CONTEXT_REUSE_MAX 100
53 #if LLVM_VERSION_MAJOR > 11
54 LLVMOrcLLJITRef lljit;
55 LLVMOrcResourceTrackerRef resource_tracker;
106 #if LLVM_VERSION_MAJOR > 11
107 static LLVMOrcThreadSafeContextRef llvm_ts_context;
127 #if LLVM_VERSION_MAJOR > 11
128 static LLVMOrcLLJITRef llvm_create_jit_instance(LLVMTargetMachineRef
tm);
129 static char *llvm_error_message(LLVMErrorRef
error);
137 .
name =
"LLVM JIT context",
188 elog(
ERROR,
"Trying to recreate a non-existing context");
248 sizeof(LLVMJitContext));
249 context->base.flags = jitFlags;
266 LLVMJitContext *llvm_jit_context = (LLVMJitContext *)
context;
285 if (llvm_jit_context->module)
287 LLVMDisposeModule(llvm_jit_context->module);
288 llvm_jit_context->module = NULL;
291 foreach(lc, llvm_jit_context->handles)
295 #if LLVM_VERSION_MAJOR > 11
297 LLVMOrcExecutionSessionRef ee;
298 LLVMOrcSymbolStringPoolRef sp;
300 LLVMOrcResourceTrackerRemove(jit_handle->resource_tracker);
301 LLVMOrcReleaseResourceTracker(jit_handle->resource_tracker);
309 ee = LLVMOrcLLJITGetExecutionSession(jit_handle->lljit);
310 sp = LLVMOrcExecutionSessionGetSymbolStringPool(ee);
311 LLVMOrcSymbolStringPoolClearDeadEntries(sp);
322 llvm_jit_context->handles =
NIL;
326 if (llvm_jit_context->resowner)
363 context->base.instr.created_functions++;
400 #if LLVM_VERSION_MAJOR > 11
407 LLVMOrcJITTargetAddress addr;
414 elog(
ERROR,
"failed to look up symbol \"%s\": %s",
428 return (
void *) (uintptr_t) addr;
433 LLVMOrcTargetAddress addr;
440 return (
void *) (uintptr_t) addr;
456 LLVMValueRef v_srcvar;
462 elog(
ERROR,
"variable %s not in llvmjit_types.c", varname);
464 typ = LLVMGlobalGetValueType(v_srcvar);
476 LLVMValueRef v_srcvar;
481 elog(
ERROR,
"function %s not in llvmjit_types.c", varname);
498 LLVMValueRef v_srcfn;
502 v_fn = LLVMGetNamedFunction(mod,
funcname);
511 v_fn = LLVMAddFunction(mod,
527 LLVMAttributeRef *attrs;
529 num_attributes = LLVMGetAttributeCountAtIndex(v_from,
index);
531 if (num_attributes == 0)
534 attrs =
palloc(
sizeof(LLVMAttributeRef) * num_attributes);
535 LLVMGetAttributesAtIndex(v_from,
index, attrs);
537 for (
int attno = 0; attno < num_attributes; attno++)
538 LLVMAddAttributeAtIndex(v_to,
index, attrs[attno]);
562 param_count = LLVMCountParams(v_from);
564 for (
int paramidx = 1; paramidx <= param_count; paramidx++)
573 LLVMBuilderRef builder,
585 if (modname != NULL && basename != NULL)
590 else if (basename != NULL)
602 LLVMValueRef v_fn_addr;
606 v_fn = LLVMGetNamedGlobal(mod,
funcname);
613 LLVMSetInitializer(v_fn, v_fn_addr);
614 LLVMSetGlobalConstant(v_fn,
true);
615 LLVMSetLinkage(v_fn, LLVMPrivateLinkage);
616 LLVMSetUnnamedAddr(v_fn,
true);
622 v_fn = LLVMGetNamedFunction(mod,
funcname);
637 #if LLVM_VERSION_MAJOR < 17
638 LLVMPassManagerBuilderRef llvm_pmb;
639 LLVMPassManagerRef llvm_mpm;
640 LLVMPassManagerRef llvm_fpm;
642 int compile_optlevel;
645 compile_optlevel = 3;
647 compile_optlevel = 0;
654 llvm_pmb = LLVMPassManagerBuilderCreate();
655 LLVMPassManagerBuilderSetOptLevel(llvm_pmb, compile_optlevel);
656 llvm_fpm = LLVMCreateFunctionPassManagerForModule(module);
661 LLVMPassManagerBuilderUseInlinerWithThreshold(llvm_pmb, 512);
666 LLVMAddPromoteMemoryToRegisterPass(llvm_fpm);
669 LLVMPassManagerBuilderPopulateFunctionPassManager(llvm_pmb, llvm_fpm);
675 LLVMInitializeFunctionPassManager(llvm_fpm);
676 for (func = LLVMGetFirstFunction(
context->module);
678 func = LLVMGetNextFunction(func))
679 LLVMRunFunctionPassManager(llvm_fpm, func);
680 LLVMFinalizeFunctionPassManager(llvm_fpm);
681 LLVMDisposePassManager(llvm_fpm);
687 llvm_mpm = LLVMCreatePassManager();
688 LLVMPassManagerBuilderPopulateModulePassManager(llvm_pmb,
692 LLVMAddAlwaysInlinerPass(llvm_mpm);
696 LLVMAddFunctionInliningPass(llvm_mpm);
697 LLVMRunPassManager(llvm_mpm,
context->module);
698 LLVMDisposePassManager(llvm_mpm);
700 LLVMPassManagerBuilderDispose(llvm_pmb);
702 LLVMPassBuilderOptionsRef
options;
707 passes =
"default<O3>";
709 passes =
"default<O0>,mem2reg";
711 options = LLVMCreatePassBuilderOptions();
713 #ifdef LLVM_PASS_DEBUG
714 LLVMPassBuilderOptionsSetDebugLogging(
options, 1);
718 #ifdef USE_ASSERT_CHECKING
719 LLVMPassBuilderOptionsSetVerifyEach(
options,
true);
722 LLVMPassBuilderOptionsSetInlinerThreshold(
options, 512);
724 err = LLVMRunPasses(module, passes, NULL,
options);
727 elog(
ERROR,
"failed to JIT module: %s", llvm_error_message(
err));
729 LLVMDisposePassBuilderOptions(
options);
743 #if LLVM_VERSION_MAJOR > 11
744 LLVMOrcLLJITRef compile_orc;
746 LLVMOrcJITStackRef compile_orc;
804 #if LLVM_VERSION_MAJOR > 11
806 LLVMOrcThreadSafeModuleRef ts_module;
808 LLVMOrcJITDylibRef jd = LLVMOrcLLJITGetMainJITDylib(compile_orc);
810 ts_module = LLVMOrcCreateNewThreadSafeModule(
context->module, llvm_ts_context);
812 handle->lljit = compile_orc;
813 handle->resource_tracker = LLVMOrcJITDylibCreateResourceTracker(jd);
822 error = LLVMOrcLLJITAddLLVMIRModuleWithRT(compile_orc,
823 handle->resource_tracker,
828 llvm_error_message(
error));
834 handle->
stack = compile_orc;
835 if (LLVMOrcAddEagerlyCompiledIR(compile_orc, &handle->
orc_handle,
context->module,
873 char *features = NULL;
874 LLVMTargetMachineRef opt0_tm;
875 LLVMTargetMachineRef opt3_tm;
882 LLVMInitializeNativeTarget();
883 LLVMInitializeNativeAsmPrinter();
884 LLVMInitializeNativeAsmParser();
903 #if LLVM_VERSION_MAJOR == 15
904 LLVMContextSetOpaquePointers(LLVMGetGlobalContext(),
false);
929 cpu = LLVMGetHostCPUName();
930 features = LLVMGetHostCPUFeatures();
931 elog(
DEBUG2,
"LLVMJIT detected CPU \"%s\", with features \"%s\"",
936 LLVMCodeGenLevelNone,
938 LLVMCodeModelJITDefault);
941 LLVMCodeGenLevelAggressive,
943 LLVMCodeModelJITDefault);
945 LLVMDisposeMessage(cpu);
947 LLVMDisposeMessage(features);
951 LLVMLoadLibraryPermanently(NULL);
953 #if LLVM_VERSION_MAJOR > 11
955 llvm_ts_context = LLVMOrcCreateNewThreadSafeContext();
968 #if defined(HAVE_DECL_LLVMCREATEGDBREGISTRATIONLISTENER) && HAVE_DECL_LLVMCREATEGDBREGISTRATIONLISTENER
971 LLVMJITEventListenerRef l = LLVMCreateGDBRegistrationListener();
977 #if defined(HAVE_DECL_LLVMCREATEPERFJITEVENTLISTENER) && HAVE_DECL_LLVMCREATEPERFJITEVENTLISTENER
980 LLVMJITEventListenerRef l = LLVMCreatePerfJITEventListener();
1014 elog(
PANIC,
"LLVMJitContext in use count not 0 at exit (is %zu)",
1017 #if LLVM_VERSION_MAJOR > 11
1029 if (llvm_ts_context)
1031 LLVMOrcDisposeThreadSafeContext(llvm_ts_context);
1032 llvm_ts_context = NULL;
1062 value = LLVMGetNamedFunction(mod,
name);
1079 elog(
ERROR,
"failed to extract target information, llvmjit_types.c not loaded");
1098 LLVMMemoryBufferRef
buf;
1104 if (LLVMCreateMemoryBufferWithContentsOfFile(path, &
buf, &msg))
1106 elog(
ERROR,
"LLVMCreateMemoryBufferWithContentsOfFile(%s) failed: %s",
1113 elog(
ERROR,
"LLVMParseBitcodeInContext2 of %s failed", path);
1115 LLVMDisposeMemoryBuffer(
buf);
1157 if (strncmp(
name,
"pgextern.", strlen(
"pgextern.")) == 0)
1193 #if defined(__darwin__)
1194 if (symname[0] !=
'_')
1195 elog(
ERROR,
"expected prefixed symbol name, but got \"%s\"", symname);
1208 addr = (uintptr_t) LLVMSearchForAddressOfSymbol(symname);
1216 elog(
WARNING,
"failed to resolve name %s", symname);
1218 return (uint64_t) addr;
1221 #if LLVM_VERSION_MAJOR > 11
1224 llvm_resolve_symbols(LLVMOrcDefinitionGeneratorRef GeneratorObj,
void *Ctx,
1225 LLVMOrcLookupStateRef *LookupState, LLVMOrcLookupKind Kind,
1226 LLVMOrcJITDylibRef JD, LLVMOrcJITDylibLookupFlags JDLookupFlags,
1227 LLVMOrcCLookupSet LookupSet,
size_t LookupSetSize)
1229 #if LLVM_VERSION_MAJOR > 14
1230 LLVMOrcCSymbolMapPairs symbols =
palloc0(
sizeof(LLVMOrcCSymbolMapPair) * LookupSetSize);
1232 LLVMOrcCSymbolMapPairs symbols =
palloc0(
sizeof(LLVMJITCSymbolMapPair) * LookupSetSize);
1235 LLVMOrcMaterializationUnitRef mu;
1237 for (
int i = 0;
i < LookupSetSize;
i++)
1239 const char *
name = LLVMOrcSymbolStringPoolEntryStr(LookupSet[
i].
Name);
1241 #if LLVM_VERSION_MAJOR > 12
1242 LLVMOrcRetainSymbolStringPoolEntry(LookupSet[
i].
Name);
1244 symbols[
i].Name = LookupSet[
i].Name;
1246 symbols[
i].Sym.Flags.GenericFlags = LLVMJITSymbolGenericFlagsExported;
1249 mu = LLVMOrcAbsoluteSymbols(symbols, LookupSetSize);
1250 error = LLVMOrcJITDylibDefine(JD, mu);
1251 if (
error != LLVMErrorSuccess)
1252 LLVMOrcDisposeMaterializationUnit(mu);
1269 llvm_log_jit_error(
void *ctx, LLVMErrorRef
error)
1272 llvm_error_message(
error));
1278 static LLVMOrcObjectLayerRef
1279 llvm_create_object_layer(
void *Ctx, LLVMOrcExecutionSessionRef ES,
const char *Triple)
1281 LLVMOrcObjectLayerRef objlayer =
1282 LLVMOrcCreateRTDyldObjectLinkingLayerWithSectionMemoryManager(ES);
1284 #if defined(HAVE_DECL_LLVMCREATEGDBREGISTRATIONLISTENER) && HAVE_DECL_LLVMCREATEGDBREGISTRATIONLISTENER
1287 LLVMJITEventListenerRef l = LLVMCreateGDBRegistrationListener();
1289 LLVMOrcRTDyldObjectLinkingLayerRegisterJITEventListener(objlayer, l);
1293 #if defined(HAVE_DECL_LLVMCREATEPERFJITEVENTLISTENER) && HAVE_DECL_LLVMCREATEPERFJITEVENTLISTENER
1296 LLVMJITEventListenerRef l = LLVMCreatePerfJITEventListener();
1298 LLVMOrcRTDyldObjectLinkingLayerRegisterJITEventListener(objlayer, l);
1309 static LLVMOrcLLJITRef
1310 llvm_create_jit_instance(LLVMTargetMachineRef
tm)
1312 LLVMOrcLLJITRef lljit;
1313 LLVMOrcJITTargetMachineBuilderRef tm_builder;
1314 LLVMOrcLLJITBuilderRef lljit_builder;
1316 LLVMOrcDefinitionGeneratorRef main_gen;
1317 LLVMOrcDefinitionGeneratorRef ref_gen;
1319 lljit_builder = LLVMOrcCreateLLJITBuilder();
1320 tm_builder = LLVMOrcJITTargetMachineBuilderCreateFromTargetMachine(
tm);
1321 LLVMOrcLLJITBuilderSetJITTargetMachineBuilder(lljit_builder, tm_builder);
1323 LLVMOrcLLJITBuilderSetObjectLinkingLayerCreator(lljit_builder,
1324 llvm_create_object_layer,
1327 error = LLVMOrcCreateLLJIT(&lljit, lljit_builder);
1329 elog(
ERROR,
"failed to create lljit instance: %s",
1330 llvm_error_message(
error));
1332 LLVMOrcExecutionSessionSetErrorReporter(LLVMOrcLLJITGetExecutionSession(lljit),
1333 llvm_log_jit_error, NULL);
1339 error = LLVMOrcCreateDynamicLibrarySearchGeneratorForProcess(&main_gen,
1340 LLVMOrcLLJITGetGlobalPrefix(lljit),
1343 elog(
ERROR,
"failed to create generator: %s",
1344 llvm_error_message(
error));
1345 LLVMOrcJITDylibAddGenerator(LLVMOrcLLJITGetMainJITDylib(lljit), main_gen);
1351 #if LLVM_VERSION_MAJOR > 14
1352 ref_gen = LLVMOrcCreateCustomCAPIDefinitionGenerator(llvm_resolve_symbols, NULL, NULL);
1354 ref_gen = LLVMOrcCreateCustomCAPIDefinitionGenerator(llvm_resolve_symbols, NULL);
1356 LLVMOrcJITDylibAddGenerator(LLVMOrcLLJITGetMainJITDylib(lljit), ref_gen);
1362 llvm_error_message(LLVMErrorRef
error)
1364 char *orig = LLVMGetErrorMessage(
error);
1367 LLVMDisposeErrorMessage(orig);
#define Assert(condition)
static void PGresult * res
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
int errmsg_internal(const char *fmt,...)
int errhidestmt(bool hide_stmt)
int errhidecontext(bool hide_ctx)
#define ereport(elevel,...)
void err(int eval, const char *fmt,...)
void fmgr_symbol(Oid functionId, char **mod, char **fn)
char pkglib_path[MAXPGPATH]
#define INSTR_TIME_SET_CURRENT(t)
#define INSTR_TIME_GET_DOUBLE(t)
#define INSTR_TIME_ACCUM_DIFF(x, y, z)
void on_proc_exit(pg_on_exit_callback function, Datum arg)
bool proc_exit_inprogress
void jit_release_context(JitContext *context)
bool jit_profiling_support
bool jit_debugging_support
List * lappend(List *list, void *datum)
void list_free(List *list)
LLVMTypeRef StructFunctionCallInfoData
LLVMTypeRef StructMinimalTupleData
LLVMTypeRef StructMinimalTupleTableSlot
LLVMTypeRef StructPlanState
static LLVMContextRef llvm_context
static LLVMOrcJITStackRef llvm_opt3_orc
LLVMTypeRef StructExprState
static const char * llvm_triple
LLVMTypeRef StructExprEvalStep
LLVMValueRef llvm_pg_func(LLVMModuleRef mod, const char *funcname)
static void llvm_recreate_llvm_context(void)
struct LLVMJitHandle LLVMJitHandle
LLVMTypeRef TypeParamBool
LLVMTypeRef StructMemoryContextData
static void llvm_set_target(void)
static LLVMTargetRef llvm_targetref
static bool llvm_session_initialized
LLVMTypeRef StructAggStatePerGroupData
static void llvm_create_types(void)
LLVMTypeRef llvm_pg_var_type(const char *varname)
static void ResourceOwnerRememberJIT(ResourceOwner owner, LLVMJitContext *handle)
static void llvm_session_initialize(void)
static size_t llvm_jit_context_in_use_count
static const char * llvm_layout
LLVMValueRef llvm_function_reference(LLVMJitContext *context, LLVMBuilderRef builder, LLVMModuleRef mod, FunctionCallInfo fcinfo)
char * llvm_expand_funcname(struct LLVMJitContext *context, const char *basename)
static LLVMOrcJITStackRef llvm_opt0_orc
static void ResOwnerReleaseJitContext(Datum res)
void llvm_split_symbol_name(const char *name, char **modname, char **funcname)
LLVMTypeRef llvm_pg_var_func_type(const char *varname)
LLVMTypeRef StructTupleTableSlot
LLVMTypeRef TypeStorageBool
static LLVMTypeRef load_return_type(LLVMModuleRef mod, const char *name)
static size_t llvm_generation
static void ResourceOwnerForgetJIT(ResourceOwner owner, LLVMJitContext *handle)
static void llvm_compile_module(LLVMJitContext *context)
LLVMTypeRef StructHeapTupleTableSlot
static LLVMModuleRef llvm_types_module
static void llvm_shutdown(int code, Datum arg)
LLVMJitContext * llvm_create_context(int jitFlags)
static const ResourceOwnerDesc jit_resowner_desc
#define LLVMJIT_LLVM_CONTEXT_REUSE_MAX
static void llvm_copy_attributes_at_index(LLVMValueRef v_from, LLVMValueRef v_to, uint32 index)
LLVMModuleRef llvm_mutable_module(LLVMJitContext *context)
LLVMTypeRef StructAggState
LLVMTypeRef TypePGFunction
LLVMTypeRef StructTupleDescData
LLVMValueRef AttributeTemplate
static size_t llvm_llvm_context_reuse_count
LLVMTypeRef StructExprContext
static void llvm_optimize_module(LLVMJitContext *context, LLVMModuleRef module)
static uint64_t llvm_resolve_symbol(const char *name, void *ctx)
LLVMTypeRef StructHeapTupleHeaderData
LLVMTypeRef StructHeapTupleData
static void llvm_release_context(JitContext *context)
LLVMTypeRef StructNullableDatum
LLVMValueRef ExecEvalSubroutineTemplate
LLVMValueRef ExecEvalBoolSubroutineTemplate
void _PG_jit_provider_init(JitProviderCallbacks *cb)
void * llvm_get_function(LLVMJitContext *context, const char *funcname)
LLVMTypeRef StructAggStatePerTransData
void llvm_copy_attributes(LLVMValueRef v_from, LLVMValueRef v_to)
void llvm_enter_fatal_on_oom(void)
bool llvm_in_fatal_on_oom(void)
void llvm_assert_in_fatal_section(void)
void llvm_reset_after_error(void)
void llvm_leave_fatal_on_oom(void)
bool llvm_compile_expr(ExprState *state)
void llvm_inline(LLVMModuleRef M)
void llvm_inline_reset_caches(void)
LLVMTypeRef LLVMGetFunctionReturnType(LLVMValueRef r)
LLVMTypeRef LLVMGetFunctionType(LLVMValueRef r)
char * pnstrdup(const char *in, Size len)
char * pstrdup(const char *in)
void pfree(void *pointer)
MemoryContext TopMemoryContext
void * palloc0(Size size)
void * MemoryContextAllocZero(MemoryContext context, Size size)
void * MemoryContextAlloc(MemoryContext context, Size size)
static Datum PointerGetDatum(const void *X)
static Pointer DatumGetPointer(Datum X)
char * psprintf(const char *fmt,...)
MemoryContextSwitchTo(old_ctx)
ResourceOwner CurrentResourceOwner
void ResourceOwnerForget(ResourceOwner owner, Datum value, const ResourceOwnerDesc *kind)
void ResourceOwnerRemember(ResourceOwner owner, Datum value, const ResourceOwnerDesc *kind)
void ResourceOwnerEnlarge(ResourceOwner owner)
#define RELEASE_PRIO_JIT_CONTEXTS
@ RESOURCE_RELEASE_BEFORE_LOCKS
JitProviderCompileExprCB compile_expr
JitProviderResetAfterErrorCB reset_after_error
JitProviderReleaseContextCB release_context
LLVMOrcModuleHandle orc_handle