diff options
Diffstat (limited to 'contrib/llvm/bindings/ocaml')
31 files changed, 7315 insertions, 0 deletions
diff --git a/contrib/llvm/bindings/ocaml/Makefile b/contrib/llvm/bindings/ocaml/Makefile new file mode 100644 index 0000000..a89caef --- /dev/null +++ b/contrib/llvm/bindings/ocaml/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../.. +DIRS = llvm bitreader bitwriter analysis target executionengine transforms +ExtraMakefiles = $(PROJ_OBJ_DIR)/Makefile.ocaml + +ocamldoc: + $(Verb) for i in $(DIRS) ; do \ + $(MAKE) -C $$i ocamldoc; \ + done + +include $(LEVEL)/Makefile.common diff --git a/contrib/llvm/bindings/ocaml/Makefile.ocaml b/contrib/llvm/bindings/ocaml/Makefile.ocaml new file mode 100644 index 0000000..1cff422 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/Makefile.ocaml @@ -0,0 +1,410 @@ +##===- tools/ml/Makefile -----------------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# An ocaml library is a unique project type in the context of LLVM, so rules are +# here rather than in Makefile.rules. +# +# Reference materials on installing ocaml libraries: +# +# https://fedoraproject.org/wiki/Packaging/OCaml +# http://pkg-ocaml-maint.alioth.debian.org/ocaml_packaging_policy.txt +# +##===----------------------------------------------------------------------===## + +include $(LEVEL)/Makefile.config + +# CFLAGS needs to be set before Makefile.rules is included. +CXX.Flags += -I"$(shell $(OCAMLC) -where)" +C.Flags += -I"$(shell $(OCAMLC) -where)" + +include $(LEVEL)/Makefile.common + +# Intentionally ignore PROJ_prefix here. We want the ocaml stdlib. However, the +# user can override this with OCAML_LIBDIR or configure --with-ocaml-libdir=. +PROJ_libocamldir := $(DESTDIR)$(OCAML_LIBDIR) +OcamlDir := $(LibDir)/ocaml + +# Info from llvm-config and similar +ifndef IS_CLEANING_TARGET +ifdef UsedComponents +UsedLibs = $(shell $(LLVM_CONFIG) --libs $(UsedComponents)) +UsedLibNames = $(shell $(LLVM_CONFIG) --libnames $(UsedComponents)) +endif +endif + +# Tools +OCAMLCFLAGS += -I $(ObjDir) -I $(OcamlDir) +ifndef IS_CLEANING_TARGET +ifneq ($(ObjectsO),) +OCAMLAFLAGS += $(patsubst %,-cclib %, \ + $(filter-out -L$(LibDir),-l$(LIBRARYNAME) \ + $(shell $(LLVM_CONFIG) --ldflags)) \ + $(UsedLibs)) +else +OCAMLAFLAGS += $(patsubst %,-cclib %, \ + $(filter-out -L$(LibDir),$(shell $(LLVM_CONFIG) --ldflags)) \ + $(UsedLibs)) +endif +endif + +# -g was introduced in 3.10.0. +#ifneq ($(ENABLE_OPTIMIZED),1) +# OCAMLDEBUGFLAG := -g +#endif + +Compile.CMI := $(strip $(OCAMLC) -c $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG) -o) +Compile.CMO := $(strip $(OCAMLC) -c $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG) -o) +Archive.CMA := $(strip $(OCAMLC) -a -custom $(OCAMLAFLAGS) $(OCAMLDEBUGFLAG) \ + -o) + +Compile.CMX := $(strip $(OCAMLOPT) -c $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG) -o) +Archive.CMXA := $(strip $(OCAMLOPT) -a $(OCAMLAFLAGS) $(OCAMLDEBUGFLAG) -o) + +ifdef OCAMLOPT +Archive.EXE := $(strip $(OCAMLOPT) -cc $(CXX) $(OCAMLCFLAGS) $(UsedOcamLibs:%=%.cmxa) $(OCAMLDEBUGFLAG) -o) +else +Archive.EXE := $(strip $(OCAMLC) -cc $(CXX) $(OCAMLCFLAGS) $(OCAMLDEBUGFLAG:%=%.cma) -o) +endif + +# Source files +OcamlSources1 := $(sort $(wildcard $(PROJ_SRC_DIR)/*.ml)) +OcamlHeaders1 := $(sort $(wildcard $(PROJ_SRC_DIR)/*.mli)) + +OcamlSources2 := $(filter-out $(ExcludeSources),$(OcamlSources1)) +OcamlHeaders2 := $(filter-out $(ExcludeHeaders),$(OcamlHeaders1)) + +OcamlSources := $(OcamlSources2:$(PROJ_SRC_DIR)/%=$(ObjDir)/%) +OcamlHeaders := $(OcamlHeaders2:$(PROJ_SRC_DIR)/%=$(ObjDir)/%) + +# Intermediate files +ObjectsCMI := $(OcamlSources:%.ml=%.cmi) +ObjectsCMO := $(OcamlSources:%.ml=%.cmo) +ObjectsCMX := $(OcamlSources:%.ml=%.cmx) + +ifdef LIBRARYNAME +LibraryCMA := $(ObjDir)/$(LIBRARYNAME).cma +LibraryCMXA := $(ObjDir)/$(LIBRARYNAME).cmxa +endif + +ifdef TOOLNAME +ToolEXE := $(ObjDir)/$(TOOLNAME)$(EXEEXT) +endif + +# Output files +# The .cmo files are the only intermediates; all others are to be installed. +OutputsCMI := $(ObjectsCMI:$(ObjDir)/%.cmi=$(OcamlDir)/%.cmi) +OutputsCMX := $(ObjectsCMX:$(ObjDir)/%.cmx=$(OcamlDir)/%.cmx) +OutputLibs := $(UsedLibNames:%=$(OcamlDir)/%) + +ifdef LIBRARYNAME +LibraryA := $(OcamlDir)/lib$(LIBRARYNAME).a +OutputCMA := $(LibraryCMA:$(ObjDir)/%.cma=$(OcamlDir)/%.cma) +OutputCMXA := $(LibraryCMXA:$(ObjDir)/%.cmxa=$(OcamlDir)/%.cmxa) +endif + +ifdef TOOLNAME +ifdef EXAMPLE_TOOL +OutputEXE := $(ExmplDir)/$(strip $(TOOLNAME))$(EXEEXT) +else +OutputEXE := $(ToolDir)/$(strip $(TOOLNAME))$(EXEEXT) +endif +endif + +# Installation targets +DestLibs := $(UsedLibNames:%=$(PROJ_libocamldir)/%) + +ifdef LIBRARYNAME +DestA := $(PROJ_libocamldir)/lib$(LIBRARYNAME).a +DestCMA := $(PROJ_libocamldir)/$(LIBRARYNAME).cma +DestCMXA := $(PROJ_libocamldir)/$(LIBRARYNAME).cmxa +endif + +##===- Dependencies -------------------------------------------------------===## +# Copy the sources into the intermediate directory because older ocamlc doesn't +# support -o except when linking (outputs are placed next to inputs). + +$(ObjDir)/%.mli: $(PROJ_SRC_DIR)/%.mli $(ObjDir)/.dir + $(Verb) $(CP) -f $< $@ + +$(ObjDir)/%.ml: $(PROJ_SRC_DIR)/%.ml $(ObjDir)/.dir + $(Verb) $(CP) -f $< $@ + +$(ObjectsCMI): $(UsedOcamlInterfaces:%=$(OcamlDir)/%.cmi) + +ifdef LIBRARYNAME +$(ObjDir)/$(LIBRARYNAME).ocamldep: $(OcamlSources) $(OcamlHeaders) \ + $(OcamlDir)/.dir $(ObjDir)/.dir + $(Verb) $(OCAMLDEP) $(OCAMLCFLAGS) $(OcamlSources) $(OcamlHeaders) > $@ + +-include $(ObjDir)/$(LIBRARYNAME).ocamldep +endif + +ifdef TOOLNAME +$(ObjDir)/$(TOOLNAME).ocamldep: $(OcamlSources) $(OcamlHeaders) \ + $(OcamlDir)/.dir $(ObjDir)/.dir + $(Verb) $(OCAMLDEP) $(OCAMLCFLAGS) $(OcamlSources) $(OcamlHeaders) > $@ + +-include $(ObjDir)/$(TOOLNAME).ocamldep +endif + +##===- Build static library from C sources --------------------------------===## + +ifdef LibraryA +all-local:: $(LibraryA) +clean-local:: clean-a +install-local:: install-a +uninstall-local:: uninstall-a + +$(LibraryA): $(ObjectsO) $(OcamlDir)/.dir + $(Echo) "Building $(BuildMode) $(notdir $@)" + -$(Verb) $(RM) -f $@ + $(Verb) $(Archive) $@ $(ObjectsO) + $(Verb) $(Ranlib) $@ + +clean-a:: + -$(Verb) $(RM) -f $(LibraryA) + +install-a:: $(LibraryA) + $(Echo) "Installing $(BuildMode) $(DestA)" + $(Verb) $(MKDIR) $(PROJ_libocamldir) + $(Verb) $(INSTALL) $(LibraryA) $(DestA) + $(Verb) + +uninstall-a:: + $(Echo) "Uninstalling $(DestA)" + -$(Verb) $(RM) -f $(DestA) +endif + + +##===- Deposit dependent libraries adjacent to Ocaml libs -----------------===## + +all-local:: build-deplibs +clean-local:: clean-deplibs +install-local:: install-deplibs +uninstall-local:: uninstall-deplibs + +build-deplibs: $(OutputLibs) + +$(OcamlDir)/%.a: $(LibDir)/%.a + $(Verb) ln -sf $< $@ + +$(OcamlDir)/%.o: $(LibDir)/%.o + $(Verb) ln -sf $< $@ + +clean-deplibs: + $(Verb) $(RM) -f $(OutputLibs) + +install-deplibs: + $(Verb) $(MKDIR) $(PROJ_libocamldir) + $(Verb) for i in $(DestLibs:$(PROJ_libocamldir)/%=%); do \ + ln -sf "$(PROJ_libdir)/$$i" "$(PROJ_libocamldir)/$$i"; \ + done + +uninstall-deplibs: + $(Verb) $(RM) -f $(DestLibs) + + +##===- Build ocaml interfaces (.mli's -> .cmi's) --------------------------===## + +ifneq ($(OcamlHeaders),) +all-local:: build-cmis +clean-local:: clean-cmis +install-local:: install-cmis +uninstall-local:: uninstall-cmis + +build-cmis: $(OutputsCMI) + +$(OcamlDir)/%.cmi: $(ObjDir)/%.cmi $(OcamlDir)/.dir + $(Verb) $(CP) -f $< $@ + +$(ObjDir)/%.cmi: $(ObjDir)/%.mli $(ObjDir)/.dir + $(Echo) "Compiling $(notdir $<) for $(BuildMode) build" + $(Verb) $(Compile.CMI) $@ $< + +clean-cmis:: + -$(Verb) $(RM) -f $(OutputsCMI) + +# Also install the .mli's (headers) as documentation. +install-cmis: $(OutputsCMI) $(OcamlHeaders) + $(Verb) $(MKDIR) $(PROJ_libocamldir) + $(Verb) for i in $(OutputsCMI:$(OcamlDir)/%=%); do \ + $(EchoCmd) "Installing $(BuildMode) $(PROJ_libocamldir)/$$i"; \ + $(DataInstall) $(OcamlDir)/$$i "$(PROJ_libocamldir)/$$i"; \ + done + $(Verb) for i in $(OcamlHeaders:$(ObjDir)/%=%); do \ + $(EchoCmd) "Installing $(BuildMode) $(PROJ_libocamldir)/$$i"; \ + $(DataInstall) $(ObjDir)/$$i "$(PROJ_libocamldir)/$$i"; \ + done + +uninstall-cmis:: + $(Verb) for i in $(OutputsCMI:$(OcamlDir)/%=%); do \ + $(EchoCmd) "Uninstalling $(PROJ_libocamldir)/$$i"; \ + $(RM) -f "$(PROJ_libocamldir)/$$i"; \ + done + $(Verb) for i in $(OcamlHeaders:$(ObjDir)/%=%); do \ + $(EchoCmd) "Uninstalling $(PROJ_libocamldir)/$$i"; \ + $(RM) -f "$(PROJ_libocamldir)/$$i"; \ + done +endif + + +##===- Build ocaml bytecode archive (.ml's -> .cmo's -> .cma) -------------===## + +$(ObjDir)/%.cmo: $(ObjDir)/%.ml + $(Echo) "Compiling $(notdir $<) for $(BuildMode) build" + $(Verb) $(Compile.CMO) $@ $< + +ifdef LIBRARYNAME +all-local:: $(OutputCMA) +clean-local:: clean-cma +install-local:: install-cma +uninstall-local:: uninstall-cma + +$(OutputCMA): $(LibraryCMA) $(OcamlDir)/.dir + $(Verb) $(CP) -f $< $@ + +$(LibraryCMA): $(ObjectsCMO) $(OcamlDir)/.dir + $(Echo) "Archiving $(notdir $@) for $(BuildMode) build" + $(Verb) $(Archive.CMA) $@ $(ObjectsCMO) + +clean-cma:: + $(Verb) $(RM) -f $(OutputCMA) $(UsedLibNames:%=$(OcamlDir)/%) + +install-cma:: $(OutputCMA) + $(Echo) "Installing $(BuildMode) $(DestCMA)" + $(Verb) $(MKDIR) $(PROJ_libocamldir) + $(Verb) $(DataInstall) $(OutputCMA) "$(DestCMA)" + +uninstall-cma:: + $(Echo) "Uninstalling $(DestCMA)" + -$(Verb) $(RM) -f $(DestCMA) +endif + +##===- Build optimized ocaml archive (.ml's -> .cmx's -> .cmxa, .a) -------===## + +# The ocamlopt compiler is supported on a set of targets disjoint from LLVM's. +# If unavailable, 'configure' will not define OCAMLOPT in Makefile.config. +ifdef OCAMLOPT + +$(OcamlDir)/%.cmx: $(ObjDir)/%.cmx + $(Verb) $(CP) -f $< $@ + +$(ObjDir)/%.cmx: $(ObjDir)/%.ml + $(Echo) "Compiling optimized $(notdir $<) for $(BuildMode) build" + $(Verb) $(Compile.CMX) $@ $< + +ifdef LIBRARYNAME +all-local:: $(OutputCMXA) $(OutputsCMX) +clean-local:: clean-cmxa +install-local:: install-cmxa +uninstall-local:: uninstall-cmxa + +$(OutputCMXA): $(LibraryCMXA) + $(Verb) $(CP) -f $< $@ + $(Verb) $(CP) -f $(<:.cmxa=.a) $(@:.cmxa=.a) + +$(LibraryCMXA): $(ObjectsCMX) + $(Echo) "Archiving $(notdir $@) for $(BuildMode) build" + $(Verb) $(Archive.CMXA) $@ $(ObjectsCMX) + $(Verb) $(RM) -f $(@:.cmxa=.o) + +clean-cmxa:: + $(Verb) $(RM) -f $(OutputCMXA) $(OutputCMXA:.cmxa=.a) $(OutputsCMX) + +install-cmxa:: $(OutputCMXA) $(OutputsCMX) + $(Verb) $(MKDIR) $(PROJ_libocamldir) + $(Echo) "Installing $(BuildMode) $(DestCMXA)" + $(Verb) $(DataInstall) $(OutputCMXA) $(DestCMXA) + $(Echo) "Installing $(BuildMode) $(DestCMXA:.cmxa=.a)" + $(Verb) $(DataInstall) $(OutputCMXA:.cmxa=.a) $(DestCMXA:.cmxa=.a) + $(Verb) for i in $(OutputsCMX:$(OcamlDir)/%=%); do \ + $(EchoCmd) "Installing $(BuildMode) $(PROJ_libocamldir)/$$i"; \ + $(DataInstall) $(OcamlDir)/$$i "$(PROJ_libocamldir)/$$i"; \ + done + +uninstall-cmxa:: + $(Echo) "Uninstalling $(DestCMXA)" + $(Verb) $(RM) -f $(DestCMXA) + $(Echo) "Uninstalling $(DestCMXA:.cmxa=.a)" + $(Verb) $(RM) -f $(DestCMXA:.cmxa=.a) + $(Verb) for i in $(OutputsCMX:$(OcamlDir)/%=%); do \ + $(EchoCmd) "Uninstalling $(PROJ_libocamldir)/$$i"; \ + $(RM) -f $(PROJ_libocamldir)/$$i; \ + done +endif +endif + +##===- Build executables --------------------------------------------------===## + +ifdef TOOLNAME +all-local:: $(OutputEXE) +clean-local:: clean-exe + +$(OutputEXE): $(ToolEXE) $(OcamlDir)/.dir + $(Verb) $(CP) -f $< $@ + +ifndef OCAMLOPT +$(ToolEXE): $(ObjectsCMO) $(OcamlDir)/.dir + $(Echo) "Archiving $(notdir $@) for $(BuildMode) build" + $(Verb) $(Archive.EXE) $@ $< +else +$(ToolEXE): $(ObjectsCMX) $(OcamlDir)/.dir + $(Echo) "Archiving $(notdir $@) for $(BuildMode) build" + $(Verb) $(Archive.EXE) $@ $< +endif +endif + +##===- Generate documentation ---------------------------------------------===## + +$(ObjDir)/$(LIBRARYNAME).odoc: $(ObjectsCMI) + $(Echo) "Documenting $(notdir $@)" + $(Verb) $(OCAMLDOC) -I $(ObjDir) -I $(OcamlDir) -dump $@ $(OcamlHeaders) + +ocamldoc: $(ObjDir)/$(LIBRARYNAME).odoc + +##===- Debugging gunk -----------------------------------------------------===## +printvars:: printcamlvars + +printcamlvars:: + $(Echo) "LLVM_CONFIG : " '$(LLVM_CONFIG)' + $(Echo) "OCAMLCFLAGS : " '$(OCAMLCFLAGS)' + $(Echo) "OCAMLAFLAGS : " '$(OCAMLAFLAGS)' + $(Echo) "OCAMLC : " '$(OCAMLC)' + $(Echo) "OCAMLOPT : " '$(OCAMLOPT)' + $(Echo) "OCAMLDEP : " '$(OCAMLDEP)' + $(Echo) "Compile.CMI : " '$(Compile.CMI)' + $(Echo) "Compile.CMO : " '$(Compile.CMO)' + $(Echo) "Archive.CMA : " '$(Archive.CMA)' + $(Echo) "Compile.CMX : " '$(Compile.CMX)' + $(Echo) "Archive.CMXA : " '$(Archive.CMXA)' + $(Echo) "CAML_LIBDIR : " '$(CAML_LIBDIR)' + $(Echo) "LibraryCMA : " '$(LibraryCMA)' + $(Echo) "LibraryCMXA : " '$(LibraryCMXA)' + $(Echo) "OcamlSources1: " '$(OcamlSources1)' + $(Echo) "OcamlSources2: " '$(OcamlSources2)' + $(Echo) "OcamlSources : " '$(OcamlSources)' + $(Echo) "OcamlHeaders1: " '$(OcamlHeaders1)' + $(Echo) "OcamlHeaders2: " '$(OcamlHeaders2)' + $(Echo) "OcamlHeaders : " '$(OcamlHeaders)' + $(Echo) "ObjectsCMI : " '$(ObjectsCMI)' + $(Echo) "ObjectsCMO : " '$(ObjectsCMO)' + $(Echo) "ObjectsCMX : " '$(ObjectsCMX)' + $(Echo) "OCAML_LIBDIR : " '$(OCAML_LIBDIR)' + $(Echo) "DestA : " '$(DestA)' + $(Echo) "DestCMA : " '$(DestCMA)' + $(Echo) "DestCMXA : " '$(DestCMXA)' + $(Echo) "UsedLibs : " '$(UsedLibs)' + $(Echo) "UsedLibNames : " '$(UsedLibNames)' + +.PHONY: printcamlvars build-cmis \ + clean-a clean-cmis clean-cma clean-cmxa \ + install-a install-cmis install-cma install-cmxa \ + install-exe \ + uninstall-a uninstall-cmis uninstall-cma uninstall-cmxa \ + uninstall-exe diff --git a/contrib/llvm/bindings/ocaml/analysis/Makefile b/contrib/llvm/bindings/ocaml/analysis/Makefile new file mode 100644 index 0000000..cbfcb24 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/analysis/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/analysis/Makefile --------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_analysis interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_analysis +UsedComponents := analysis +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/contrib/llvm/bindings/ocaml/analysis/analysis_ocaml.c b/contrib/llvm/bindings/ocaml/analysis/analysis_ocaml.c new file mode 100644 index 0000000..9716705 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/analysis/analysis_ocaml.c @@ -0,0 +1,72 @@ +/*===-- analysis_ocaml.c - LLVM Ocaml Glue ----------------------*- C++ -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file glues LLVM's ocaml interface to its C interface. These functions *| +|* are by and large transparent wrappers to the corresponding C functions. *| +|* *| +|* Note that these functions intentionally take liberties with the CAMLparamX *| +|* macros, since most of the parameters are not GC heap objects. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#include "llvm-c/Analysis.h" +#include "caml/alloc.h" +#include "caml/mlvalues.h" +#include "caml/memory.h" + + +/* Llvm.llmodule -> string option */ +CAMLprim value llvm_verify_module(LLVMModuleRef M) { + CAMLparam0(); + CAMLlocal2(String, Option); + + char *Message; + int Result = LLVMVerifyModule(M, LLVMReturnStatusAction, &Message); + + if (0 == Result) { + Option = Val_int(0); + } else { + Option = alloc(1, 0); + String = copy_string(Message); + Store_field(Option, 0, String); + } + + LLVMDisposeMessage(Message); + + CAMLreturn(Option); +} + +/* Llvm.llvalue -> bool */ +CAMLprim value llvm_verify_function(LLVMValueRef Fn) { + return Val_bool(LLVMVerifyFunction(Fn, LLVMReturnStatusAction) == 0); +} + +/* Llvm.llmodule -> unit */ +CAMLprim value llvm_assert_valid_module(LLVMModuleRef M) { + LLVMVerifyModule(M, LLVMAbortProcessAction, 0); + return Val_unit; +} + +/* Llvm.llvalue -> unit */ +CAMLprim value llvm_assert_valid_function(LLVMValueRef Fn) { + LLVMVerifyFunction(Fn, LLVMAbortProcessAction); + return Val_unit; +} + +/* Llvm.llvalue -> unit */ +CAMLprim value llvm_view_function_cfg(LLVMValueRef Fn) { + LLVMViewFunctionCFG(Fn); + return Val_unit; +} + +/* Llvm.llvalue -> unit */ +CAMLprim value llvm_view_function_cfg_only(LLVMValueRef Fn) { + LLVMViewFunctionCFGOnly(Fn); + return Val_unit; +} diff --git a/contrib/llvm/bindings/ocaml/analysis/llvm_analysis.ml b/contrib/llvm/bindings/ocaml/analysis/llvm_analysis.ml new file mode 100644 index 0000000..fc4d203 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/analysis/llvm_analysis.ml @@ -0,0 +1,22 @@ +(*===-- llvm_analysis.ml - LLVM Ocaml Interface -----------------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + + +external verify_module : Llvm.llmodule -> string option = "llvm_verify_module" + +external verify_function : Llvm.llvalue -> bool = "llvm_verify_function" + +external assert_valid_module : Llvm.llmodule -> unit + = "llvm_assert_valid_module" + +external assert_valid_function : Llvm.llvalue -> unit + = "llvm_assert_valid_function" +external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg" +external view_function_cfg_only : Llvm.llvalue -> unit + = "llvm_view_function_cfg_only" diff --git a/contrib/llvm/bindings/ocaml/analysis/llvm_analysis.mli b/contrib/llvm/bindings/ocaml/analysis/llvm_analysis.mli new file mode 100644 index 0000000..793f482 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/analysis/llvm_analysis.mli @@ -0,0 +1,46 @@ +(*===-- llvm_analysis.mli - LLVM Ocaml Interface ----------------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +(** Intermediate representation analysis. + + This interface provides an ocaml API for LLVM IR analyses, the classes in + the Analysis library. *) + +(** [verify_module m] returns [None] if the module [m] is valid, and + [Some reason] if it is invalid. [reason] is a string containing a + human-readable validation report. See [llvm::verifyModule]. *) +external verify_module : Llvm.llmodule -> string option = "llvm_verify_module" + +(** [verify_function f] returns [None] if the function [f] is valid, and + [Some reason] if it is invalid. [reason] is a string containing a + human-readable validation report. See [llvm::verifyFunction]. *) +external verify_function : Llvm.llvalue -> bool = "llvm_verify_function" + +(** [verify_module m] returns if the module [m] is valid, but prints a + validation report to [stderr] and aborts the program if it is invalid. See + [llvm::verifyModule]. *) +external assert_valid_module : Llvm.llmodule -> unit + = "llvm_assert_valid_module" + +(** [verify_function f] returns if the function [f] is valid, but prints a + validation report to [stderr] and aborts the program if it is invalid. See + [llvm::verifyFunction]. *) +external assert_valid_function : Llvm.llvalue -> unit + = "llvm_assert_valid_function" + +(** [view_function_cfg f] opens up a ghostscript window displaying the CFG of + the current function with the code for each basic block inside. + See [llvm::Function::viewCFG]. *) +external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg" + +(** [view_function_cfg_only f] works just like [view_function_cfg], but does not + include the contents of basic blocks into the nodes. + See [llvm::Function::viewCFGOnly]. *) +external view_function_cfg_only : Llvm.llvalue -> unit + = "llvm_view_function_cfg_only" diff --git a/contrib/llvm/bindings/ocaml/bitreader/Makefile b/contrib/llvm/bindings/ocaml/bitreader/Makefile new file mode 100644 index 0000000..a1c7de8 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitreader/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/bitreader/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_bitreader interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_bitreader +UsedComponents := bitreader +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/contrib/llvm/bindings/ocaml/bitreader/bitreader_ocaml.c b/contrib/llvm/bindings/ocaml/bitreader/bitreader_ocaml.c new file mode 100644 index 0000000..ef72ce2 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitreader/bitreader_ocaml.c @@ -0,0 +1,73 @@ +/*===-- bitwriter_ocaml.c - LLVM Ocaml Glue ---------------------*- C++ -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file glues LLVM's ocaml interface to its C interface. These functions *| +|* are by and large transparent wrappers to the corresponding C functions. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#include "llvm-c/BitReader.h" +#include "caml/alloc.h" +#include "caml/fail.h" +#include "caml/memory.h" + + +/* Can't use the recommended caml_named_value mechanism for backwards + compatibility reasons. This is largely equivalent. */ +static value llvm_bitreader_error_exn; + +CAMLprim value llvm_register_bitreader_exns(value Error) { + llvm_bitreader_error_exn = Field(Error, 0); + register_global_root(&llvm_bitreader_error_exn); + return Val_unit; +} + +static void llvm_raise(value Prototype, char *Message) { + CAMLparam1(Prototype); + CAMLlocal1(CamlMessage); + + CamlMessage = copy_string(Message); + LLVMDisposeMessage(Message); + + raise_with_arg(Prototype, CamlMessage); + abort(); /* NOTREACHED */ +#ifdef CAMLnoreturn + CAMLnoreturn; /* Silences warnings, but is missing in some versions. */ +#endif +} + + +/*===-- Modules -----------------------------------------------------------===*/ + +/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */ +CAMLprim value llvm_get_module(LLVMContextRef C, LLVMMemoryBufferRef MemBuf) { + CAMLparam0(); + CAMLlocal2(Variant, MessageVal); + char *Message; + + LLVMModuleRef M; + if (LLVMGetBitcodeModuleInContext(C, MemBuf, &M, &Message)) + llvm_raise(llvm_bitreader_error_exn, Message); + + CAMLreturn((value) M); +} + +/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */ +CAMLprim value llvm_parse_bitcode(LLVMContextRef C, + LLVMMemoryBufferRef MemBuf) { + CAMLparam0(); + CAMLlocal2(Variant, MessageVal); + LLVMModuleRef M; + char *Message; + + if (LLVMParseBitcodeInContext(C, MemBuf, &M, &Message)) + llvm_raise(llvm_bitreader_error_exn, Message); + + CAMLreturn((value) M); +} diff --git a/contrib/llvm/bindings/ocaml/bitreader/llvm_bitreader.ml b/contrib/llvm/bindings/ocaml/bitreader/llvm_bitreader.ml new file mode 100644 index 0000000..8b9d01d --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitreader/llvm_bitreader.ml @@ -0,0 +1,20 @@ +(*===-- llvm_bitreader.ml - LLVM Ocaml Interface ----------------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + + +exception Error of string + +external register_exns : exn -> unit = "llvm_register_bitreader_exns" +let _ = register_exns (Error "") + +external get_module : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule + = "llvm_get_module" + +external parse_bitcode : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule + = "llvm_parse_bitcode" diff --git a/contrib/llvm/bindings/ocaml/bitreader/llvm_bitreader.mli b/contrib/llvm/bindings/ocaml/bitreader/llvm_bitreader.mli new file mode 100644 index 0000000..5e22409 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitreader/llvm_bitreader.mli @@ -0,0 +1,29 @@ +(*===-- llvm_bitreader.mli - LLVM Ocaml Interface ---------------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +(** Bitcode reader. + + This interface provides an ocaml API for the LLVM bitcode reader, the + classes in the Bitreader library. *) + +exception Error of string + +(** [get_module context mb] reads the bitcode for a new module [m] from the + memory buffer [mb] in the context [context]. Returns [m] if successful, or + raises [Error msg] otherwise, where [msg] is a description of the error + encountered. See the function [llvm::getBitcodeModule]. *) +external get_module : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule + = "llvm_get_module" + +(** [parse_bitcode context mb] parses the bitcode for a new module [m] from the + memory buffer [mb] in the context [context]. Returns [m] if successful, or + raises [Error msg] otherwise, where [msg] is a description of the error + encountered. See the function [llvm::ParseBitcodeFile]. *) +external parse_bitcode : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule + = "llvm_parse_bitcode" diff --git a/contrib/llvm/bindings/ocaml/bitwriter/Makefile b/contrib/llvm/bindings/ocaml/bitwriter/Makefile new file mode 100644 index 0000000..cec0a59 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitwriter/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/bitwriter/Makefile -------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_bitwriter interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_bitwriter +UsedComponents := bitwriter +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/contrib/llvm/bindings/ocaml/bitwriter/bitwriter_ocaml.c b/contrib/llvm/bindings/ocaml/bitwriter/bitwriter_ocaml.c new file mode 100644 index 0000000..53c93cb --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitwriter/bitwriter_ocaml.c @@ -0,0 +1,45 @@ +/*===-- bitwriter_ocaml.c - LLVM Ocaml Glue ---------------------*- C++ -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file glues LLVM's ocaml interface to its C interface. These functions *| +|* are by and large transparent wrappers to the corresponding C functions. *| +|* *| +|* Note that these functions intentionally take liberties with the CAMLparamX *| +|* macros, since most of the parameters are not GC heap objects. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#include "llvm-c/BitWriter.h" +#include "llvm-c/Core.h" +#include "caml/alloc.h" +#include "caml/mlvalues.h" +#include "caml/memory.h" + +/*===-- Modules -----------------------------------------------------------===*/ + +/* Llvm.llmodule -> string -> bool */ +CAMLprim value llvm_write_bitcode_file(value M, value Path) { + int res = LLVMWriteBitcodeToFile((LLVMModuleRef) M, String_val(Path)); + return Val_bool(res == 0); +} + +/* ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool */ +CAMLprim value llvm_write_bitcode_to_fd(value U, value M, value FD) { + int Unbuffered; + int res; + + if (U == Val_int(0)) { + Unbuffered = 0; + } else { + Unbuffered = Bool_val(Field(U,0)); + } + + res = LLVMWriteBitcodeToFD((LLVMModuleRef) M, Int_val(FD), 0, Unbuffered); + return Val_bool(res == 0); +} diff --git a/contrib/llvm/bindings/ocaml/bitwriter/llvm_bitwriter.ml b/contrib/llvm/bindings/ocaml/bitwriter/llvm_bitwriter.ml new file mode 100644 index 0000000..3e69a3c --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitwriter/llvm_bitwriter.ml @@ -0,0 +1,25 @@ +(*===-- llvm_bitwriter.ml - LLVM Ocaml Interface ----------------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------=== + * + * This interface provides an ocaml API for the LLVM intermediate + * representation, the classes in the VMCore library. + * + *===----------------------------------------------------------------------===*) + + +(* Writes the bitcode for module the given path. Returns true if successful. *) +external write_bitcode_file : Llvm.llmodule -> string -> bool + = "llvm_write_bitcode_file" + +external write_bitcode_to_fd : ?unbuffered:bool -> Llvm.llmodule + -> Unix.file_descr -> bool + = "llvm_write_bitcode_to_fd" + +let output_bitcode ?unbuffered channel m = + write_bitcode_to_fd ?unbuffered m (Unix.descr_of_out_channel channel) diff --git a/contrib/llvm/bindings/ocaml/bitwriter/llvm_bitwriter.mli b/contrib/llvm/bindings/ocaml/bitwriter/llvm_bitwriter.mli new file mode 100644 index 0000000..ea9a876 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/bitwriter/llvm_bitwriter.mli @@ -0,0 +1,30 @@ +(*===-- llvm_bitwriter.mli - LLVM Ocaml Interface ---------------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +(** Bitcode writer. + + This interface provides an ocaml API for the LLVM bitcode writer, the + classes in the Bitwriter library. *) + +(** [write_bitcode_file m path] writes the bitcode for module [m] to the file at + [path]. Returns [true] if successful, [false] otherwise. *) +external write_bitcode_file : Llvm.llmodule -> string -> bool + = "llvm_write_bitcode_file" + +(** [write_bitcode_to_fd ~unbuffered fd m] writes the bitcode for module + [m] to the channel [c]. If [unbuffered] is [true], after every write the fd + will be flushed. Returns [true] if successful, [false] otherwise. *) +external write_bitcode_to_fd : ?unbuffered:bool -> Llvm.llmodule + -> Unix.file_descr -> bool + = "llvm_write_bitcode_to_fd" + +(** [output_bitcode ~unbuffered c m] writes the bitcode for module [m] + to the channel [c]. If [unbuffered] is [true], after every write the fd + will be flushed. Returns [true] if successful, [false] otherwise. *) +val output_bitcode : ?unbuffered:bool -> out_channel -> Llvm.llmodule -> bool diff --git a/contrib/llvm/bindings/ocaml/executionengine/Makefile b/contrib/llvm/bindings/ocaml/executionengine/Makefile new file mode 100644 index 0000000..5fa3f22 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/executionengine/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/executionengine/Makefile --------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_executionengine interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_executionengine +UsedComponents := executionengine jit interpreter native +UsedOcamlInterfaces := llvm llvm_target + +include ../Makefile.ocaml diff --git a/contrib/llvm/bindings/ocaml/executionengine/executionengine_ocaml.c b/contrib/llvm/bindings/ocaml/executionengine/executionengine_ocaml.c new file mode 100644 index 0000000..5b1e32e --- /dev/null +++ b/contrib/llvm/bindings/ocaml/executionengine/executionengine_ocaml.c @@ -0,0 +1,323 @@ +/*===-- executionengine_ocaml.c - LLVM Ocaml Glue ---------------*- C++ -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file glues LLVM's ocaml interface to its C interface. These functions *| +|* are by and large transparent wrappers to the corresponding C functions. *| +|* *| +|* Note that these functions intentionally take liberties with the CAMLparamX *| +|* macros, since most of the parameters are not GC heap objects. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#include "llvm-c/ExecutionEngine.h" +#include "llvm-c/Target.h" +#include "caml/alloc.h" +#include "caml/custom.h" +#include "caml/fail.h" +#include "caml/memory.h" +#include <string.h> +#include <assert.h> + +/* Force the LLVM interpreter and JIT to be linked in. */ +void llvm_initialize(void) { + LLVMLinkInInterpreter(); + LLVMLinkInJIT(); +} + +/* unit -> bool */ +CAMLprim value llvm_initialize_native_target(value Unit) { + return Val_bool(LLVMInitializeNativeTarget()); +} + +/* Can't use the recommended caml_named_value mechanism for backwards + compatibility reasons. This is largely equivalent. */ +static value llvm_ee_error_exn; + +CAMLprim value llvm_register_ee_exns(value Error) { + llvm_ee_error_exn = Field(Error, 0); + register_global_root(&llvm_ee_error_exn); + return Val_unit; +} + +static void llvm_raise(value Prototype, char *Message) { + CAMLparam1(Prototype); + CAMLlocal1(CamlMessage); + + CamlMessage = copy_string(Message); + LLVMDisposeMessage(Message); + + raise_with_arg(Prototype, CamlMessage); + abort(); /* NOTREACHED */ +#ifdef CAMLnoreturn + CAMLnoreturn; /* Silences warnings, but is missing in some versions. */ +#endif +} + + +/*--... Operations on generic values .......................................--*/ + +#define Genericvalue_val(v) (*(LLVMGenericValueRef *)(Data_custom_val(v))) + +static void llvm_finalize_generic_value(value GenVal) { + LLVMDisposeGenericValue(Genericvalue_val(GenVal)); +} + +static struct custom_operations generic_value_ops = { + (char *) "LLVMGenericValue", + llvm_finalize_generic_value, + custom_compare_default, + custom_hash_default, + custom_serialize_default, + custom_deserialize_default +}; + +static value alloc_generic_value(LLVMGenericValueRef Ref) { + value Val = alloc_custom(&generic_value_ops, sizeof(LLVMGenericValueRef), 0, 1); + Genericvalue_val(Val) = Ref; + return Val; +} + +/* Llvm.lltype -> float -> t */ +CAMLprim value llvm_genericvalue_of_float(LLVMTypeRef Ty, value N) { + CAMLparam1(N); + CAMLreturn(alloc_generic_value( + LLVMCreateGenericValueOfFloat(Ty, Double_val(N)))); +} + +/* 'a -> t */ +CAMLprim value llvm_genericvalue_of_pointer(value V) { + CAMLparam1(V); + CAMLreturn(alloc_generic_value(LLVMCreateGenericValueOfPointer(Op_val(V)))); +} + +/* Llvm.lltype -> int -> t */ +CAMLprim value llvm_genericvalue_of_int(LLVMTypeRef Ty, value Int) { + return alloc_generic_value(LLVMCreateGenericValueOfInt(Ty, Int_val(Int), 1)); +} + +/* Llvm.lltype -> int32 -> t */ +CAMLprim value llvm_genericvalue_of_int32(LLVMTypeRef Ty, value Int32) { + CAMLparam1(Int32); + CAMLreturn(alloc_generic_value( + LLVMCreateGenericValueOfInt(Ty, Int32_val(Int32), 1))); +} + +/* Llvm.lltype -> nativeint -> t */ +CAMLprim value llvm_genericvalue_of_nativeint(LLVMTypeRef Ty, value NatInt) { + CAMLparam1(NatInt); + CAMLreturn(alloc_generic_value( + LLVMCreateGenericValueOfInt(Ty, Nativeint_val(NatInt), 1))); +} + +/* Llvm.lltype -> int64 -> t */ +CAMLprim value llvm_genericvalue_of_int64(LLVMTypeRef Ty, value Int64) { + CAMLparam1(Int64); + CAMLreturn(alloc_generic_value( + LLVMCreateGenericValueOfInt(Ty, Int64_val(Int64), 1))); +} + +/* Llvm.lltype -> t -> float */ +CAMLprim value llvm_genericvalue_as_float(LLVMTypeRef Ty, value GenVal) { + CAMLparam1(GenVal); + CAMLreturn(copy_double( + LLVMGenericValueToFloat(Ty, Genericvalue_val(GenVal)))); +} + +/* t -> 'a */ +CAMLprim value llvm_genericvalue_as_pointer(value GenVal) { + return Val_op(LLVMGenericValueToPointer(Genericvalue_val(GenVal))); +} + +/* t -> int */ +CAMLprim value llvm_genericvalue_as_int(value GenVal) { + assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 8 * sizeof(value) + && "Generic value too wide to treat as an int!"); + return Val_int(LLVMGenericValueToInt(Genericvalue_val(GenVal), 1)); +} + +/* t -> int32 */ +CAMLprim value llvm_genericvalue_as_int32(value GenVal) { + CAMLparam1(GenVal); + assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 32 + && "Generic value too wide to treat as an int32!"); + CAMLreturn(copy_int32(LLVMGenericValueToInt(Genericvalue_val(GenVal), 1))); +} + +/* t -> int64 */ +CAMLprim value llvm_genericvalue_as_int64(value GenVal) { + CAMLparam1(GenVal); + assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 64 + && "Generic value too wide to treat as an int64!"); + CAMLreturn(copy_int64(LLVMGenericValueToInt(Genericvalue_val(GenVal), 1))); +} + +/* t -> nativeint */ +CAMLprim value llvm_genericvalue_as_nativeint(value GenVal) { + CAMLparam1(GenVal); + assert(LLVMGenericValueIntWidth(Genericvalue_val(GenVal)) <= 8 * sizeof(value) + && "Generic value too wide to treat as a nativeint!"); + CAMLreturn(copy_nativeint(LLVMGenericValueToInt(Genericvalue_val(GenVal),1))); +} + + +/*--... Operations on execution engines ....................................--*/ + +/* llmodule -> ExecutionEngine.t */ +CAMLprim LLVMExecutionEngineRef llvm_ee_create(LLVMModuleRef M) { + LLVMExecutionEngineRef Interp; + char *Error; + if (LLVMCreateExecutionEngineForModule(&Interp, M, &Error)) + llvm_raise(llvm_ee_error_exn, Error); + return Interp; +} + +/* llmodule -> ExecutionEngine.t */ +CAMLprim LLVMExecutionEngineRef +llvm_ee_create_interpreter(LLVMModuleRef M) { + LLVMExecutionEngineRef Interp; + char *Error; + if (LLVMCreateInterpreterForModule(&Interp, M, &Error)) + llvm_raise(llvm_ee_error_exn, Error); + return Interp; +} + +/* llmodule -> int -> ExecutionEngine.t */ +CAMLprim LLVMExecutionEngineRef +llvm_ee_create_jit(LLVMModuleRef M, value OptLevel) { + LLVMExecutionEngineRef JIT; + char *Error; + if (LLVMCreateJITCompilerForModule(&JIT, M, Int_val(OptLevel), &Error)) + llvm_raise(llvm_ee_error_exn, Error); + return JIT; +} + +/* ExecutionEngine.t -> unit */ +CAMLprim value llvm_ee_dispose(LLVMExecutionEngineRef EE) { + LLVMDisposeExecutionEngine(EE); + return Val_unit; +} + +/* llmodule -> ExecutionEngine.t -> unit */ +CAMLprim value llvm_ee_add_module(LLVMModuleRef M, LLVMExecutionEngineRef EE) { + LLVMAddModule(EE, M); + return Val_unit; +} + +/* llmodule -> ExecutionEngine.t -> llmodule */ +CAMLprim LLVMModuleRef llvm_ee_remove_module(LLVMModuleRef M, + LLVMExecutionEngineRef EE) { + LLVMModuleRef RemovedModule; + char *Error; + if (LLVMRemoveModule(EE, M, &RemovedModule, &Error)) + llvm_raise(llvm_ee_error_exn, Error); + return RemovedModule; +} + +/* string -> ExecutionEngine.t -> llvalue option */ +CAMLprim value llvm_ee_find_function(value Name, LLVMExecutionEngineRef EE) { + CAMLparam1(Name); + CAMLlocal1(Option); + LLVMValueRef Found; + if (LLVMFindFunction(EE, String_val(Name), &Found)) + CAMLreturn(Val_unit); + Option = alloc(1, 0); + Field(Option, 0) = Val_op(Found); + CAMLreturn(Option); +} + +/* llvalue -> GenericValue.t array -> ExecutionEngine.t -> GenericValue.t */ +CAMLprim value llvm_ee_run_function(LLVMValueRef F, value Args, + LLVMExecutionEngineRef EE) { + unsigned NumArgs; + LLVMGenericValueRef Result, *GVArgs; + unsigned I; + + NumArgs = Wosize_val(Args); + GVArgs = (LLVMGenericValueRef*) malloc(NumArgs * sizeof(LLVMGenericValueRef)); + for (I = 0; I != NumArgs; ++I) + GVArgs[I] = Genericvalue_val(Field(Args, I)); + + Result = LLVMRunFunction(EE, F, NumArgs, GVArgs); + + free(GVArgs); + return alloc_generic_value(Result); +} + +/* ExecutionEngine.t -> unit */ +CAMLprim value llvm_ee_run_static_ctors(LLVMExecutionEngineRef EE) { + LLVMRunStaticConstructors(EE); + return Val_unit; +} + +/* ExecutionEngine.t -> unit */ +CAMLprim value llvm_ee_run_static_dtors(LLVMExecutionEngineRef EE) { + LLVMRunStaticDestructors(EE); + return Val_unit; +} + +/* llvalue -> string array -> (string * string) array -> ExecutionEngine.t -> + int */ +CAMLprim value llvm_ee_run_function_as_main(LLVMValueRef F, + value Args, value Env, + LLVMExecutionEngineRef EE) { + CAMLparam2(Args, Env); + int I, NumArgs, NumEnv, EnvSize, Result; + const char **CArgs, **CEnv; + char *CEnvBuf, *Pos; + + NumArgs = Wosize_val(Args); + NumEnv = Wosize_val(Env); + + /* Build the environment. */ + CArgs = (const char **) malloc(NumArgs * sizeof(char*)); + for (I = 0; I != NumArgs; ++I) + CArgs[I] = String_val(Field(Args, I)); + + /* Compute the size of the environment string buffer. */ + for (I = 0, EnvSize = 0; I != NumEnv; ++I) { + EnvSize += strlen(String_val(Field(Field(Env, I), 0))) + 1; + EnvSize += strlen(String_val(Field(Field(Env, I), 1))) + 1; + } + + /* Build the environment. */ + CEnv = (const char **) malloc((NumEnv + 1) * sizeof(char*)); + CEnvBuf = (char*) malloc(EnvSize); + Pos = CEnvBuf; + for (I = 0; I != NumEnv; ++I) { + char *Name = String_val(Field(Field(Env, I), 0)), + *Value = String_val(Field(Field(Env, I), 1)); + int NameLen = strlen(Name), + ValueLen = strlen(Value); + + CEnv[I] = Pos; + memcpy(Pos, Name, NameLen); + Pos += NameLen; + *Pos++ = '='; + memcpy(Pos, Value, ValueLen); + Pos += ValueLen; + *Pos++ = '\0'; + } + CEnv[NumEnv] = NULL; + + Result = LLVMRunFunctionAsMain(EE, F, NumArgs, CArgs, CEnv); + + free(CArgs); + free(CEnv); + free(CEnvBuf); + + CAMLreturn(Val_int(Result)); +} + +/* llvalue -> ExecutionEngine.t -> unit */ +CAMLprim value llvm_ee_free_machine_code(LLVMValueRef F, + LLVMExecutionEngineRef EE) { + LLVMFreeMachineCodeForFunction(EE, F); + return Val_unit; +} + diff --git a/contrib/llvm/bindings/ocaml/executionengine/llvm_executionengine.ml b/contrib/llvm/bindings/ocaml/executionengine/llvm_executionengine.ml new file mode 100644 index 0000000..a8535b2 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/executionengine/llvm_executionengine.ml @@ -0,0 +1,112 @@ +(*===-- llvm_executionengine.ml - LLVM Ocaml Interface ----------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + + +exception Error of string + +external register_exns: exn -> unit + = "llvm_register_ee_exns" + + +module GenericValue = struct + type t + + external of_float: Llvm.lltype -> float -> t + = "llvm_genericvalue_of_float" + external of_pointer: 'a -> t + = "llvm_genericvalue_of_pointer" + external of_int32: Llvm.lltype -> int32 -> t + = "llvm_genericvalue_of_int32" + external of_int: Llvm.lltype -> int -> t + = "llvm_genericvalue_of_int" + external of_nativeint: Llvm.lltype -> nativeint -> t + = "llvm_genericvalue_of_nativeint" + external of_int64: Llvm.lltype -> int64 -> t + = "llvm_genericvalue_of_int64" + + external as_float: Llvm.lltype -> t -> float + = "llvm_genericvalue_as_float" + external as_pointer: t -> 'a + = "llvm_genericvalue_as_pointer" + external as_int32: t -> int32 + = "llvm_genericvalue_as_int32" + external as_int: t -> int + = "llvm_genericvalue_as_int" + external as_nativeint: t -> nativeint + = "llvm_genericvalue_as_nativeint" + external as_int64: t -> int64 + = "llvm_genericvalue_as_int64" +end + + +module ExecutionEngine = struct + type t + + (* FIXME: Ocaml is not running this setup code unless we use 'val' in the + interface, which causes the emission of a stub for each function; + using 'external' in the module allows direct calls into + ocaml_executionengine.c. This is hardly fatal, but it is unnecessary + overhead on top of the two stubs that are already invoked for each + call into LLVM. *) + let _ = register_exns (Error "") + + external create: Llvm.llmodule -> t + = "llvm_ee_create" + external create_interpreter: Llvm.llmodule -> t + = "llvm_ee_create_interpreter" + external create_jit: Llvm.llmodule -> int -> t + = "llvm_ee_create_jit" + external dispose: t -> unit + = "llvm_ee_dispose" + external add_module: Llvm.llmodule -> t -> unit + = "llvm_ee_add_module" + external remove_module: Llvm.llmodule -> t -> Llvm.llmodule + = "llvm_ee_remove_module" + external find_function: string -> t -> Llvm.llvalue option + = "llvm_ee_find_function" + external run_function: Llvm.llvalue -> GenericValue.t array -> t -> + GenericValue.t + = "llvm_ee_run_function" + external run_static_ctors: t -> unit + = "llvm_ee_run_static_ctors" + external run_static_dtors: t -> unit + = "llvm_ee_run_static_dtors" + external run_function_as_main: Llvm.llvalue -> string array -> + (string * string) array -> t -> int + = "llvm_ee_run_function_as_main" + external free_machine_code: Llvm.llvalue -> t -> unit + = "llvm_ee_free_machine_code" + + external target_data: t -> Llvm_target.TargetData.t + = "LLVMGetExecutionEngineTargetData" + + (* The following are not bound. Patches are welcome. + + get_target_data: t -> lltargetdata + add_global_mapping: llvalue -> llgenericvalue -> t -> unit + clear_all_global_mappings: t -> unit + update_global_mapping: llvalue -> llgenericvalue -> t -> unit + get_pointer_to_global_if_available: llvalue -> t -> llgenericvalue + get_pointer_to_global: llvalue -> t -> llgenericvalue + get_pointer_to_function: llvalue -> t -> llgenericvalue + get_pointer_to_function_or_stub: llvalue -> t -> llgenericvalue + get_global_value_at_address: llgenericvalue -> t -> llvalue option + store_value_to_memory: llgenericvalue -> llgenericvalue -> lltype -> unit + initialize_memory: llvalue -> llgenericvalue -> t -> unit + recompile_and_relink_function: llvalue -> t -> llgenericvalue + get_or_emit_global_variable: llvalue -> t -> llgenericvalue + disable_lazy_compilation: t -> unit + lazy_compilation_enabled: t -> bool + install_lazy_function_creator: (string -> llgenericvalue) -> t -> unit + + *) +end + +external initialize_native_target : unit -> bool + = "llvm_initialize_native_target" diff --git a/contrib/llvm/bindings/ocaml/executionengine/llvm_executionengine.mli b/contrib/llvm/bindings/ocaml/executionengine/llvm_executionengine.mli new file mode 100644 index 0000000..ce25f9d --- /dev/null +++ b/contrib/llvm/bindings/ocaml/executionengine/llvm_executionengine.mli @@ -0,0 +1,163 @@ +(*===-- llvm_executionengine.mli - LLVM Ocaml Interface ---------*- C++ -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +(** JIT Interpreter. + + This interface provides an ocaml API for LLVM execution engine (JIT/ + interpreter), the classes in the ExecutionEngine library. *) + +exception Error of string + +module GenericValue: sig + (** [GenericValue.t] is a boxed union type used to portably pass arguments to + and receive values from the execution engine. It supports only a limited + selection of types; for more complex argument types, it is necessary to + generate a stub function by hand or to pass parameters by reference. + See the struct [llvm::GenericValue]. *) + type t + + (** [of_float fpty n] boxes the float [n] in a float-valued generic value + according to the floating point type [fpty]. See the fields + [llvm::GenericValue::DoubleVal] and [llvm::GenericValue::FloatVal]. *) + external of_float : Llvm.lltype -> float -> t = "llvm_genericvalue_of_float" + + (** [of_pointer v] boxes the pointer value [v] in a generic value. See the + field [llvm::GenericValue::PointerVal]. *) + external of_pointer : 'a -> t = "llvm_genericvalue_of_pointer" + + (** [of_int32 n w] boxes the int32 [i] in a generic value with the bitwidth + [w]. See the field [llvm::GenericValue::IntVal]. *) + external of_int32 : Llvm.lltype -> int32 -> t = "llvm_genericvalue_of_int32" + + (** [of_int n w] boxes the int [i] in a generic value with the bitwidth + [w]. See the field [llvm::GenericValue::IntVal]. *) + external of_int : Llvm.lltype -> int -> t = "llvm_genericvalue_of_int" + + (** [of_natint n w] boxes the native int [i] in a generic value with the + bitwidth [w]. See the field [llvm::GenericValue::IntVal]. *) + external of_nativeint : Llvm.lltype -> nativeint -> t + = "llvm_genericvalue_of_nativeint" + + (** [of_int64 n w] boxes the int64 [i] in a generic value with the bitwidth + [w]. See the field [llvm::GenericValue::IntVal]. *) + external of_int64 : Llvm.lltype -> int64 -> t = "llvm_genericvalue_of_int64" + + (** [as_float fpty gv] unboxes the floating point-valued generic value [gv] of + floating point type [fpty]. See the fields [llvm::GenericValue::DoubleVal] + and [llvm::GenericValue::FloatVal]. *) + external as_float : Llvm.lltype -> t -> float = "llvm_genericvalue_as_float" + + (** [as_pointer gv] unboxes the pointer-valued generic value [gv]. See the + field [llvm::GenericValue::PointerVal]. *) + external as_pointer : t -> 'a = "llvm_genericvalue_as_pointer" + + (** [as_int32 gv] unboxes the integer-valued generic value [gv] as an [int32]. + Is invalid if [gv] has a bitwidth greater than 32 bits. See the field + [llvm::GenericValue::IntVal]. *) + external as_int32 : t -> int32 = "llvm_genericvalue_as_int32" + + (** [as_int gv] unboxes the integer-valued generic value [gv] as an [int]. + Is invalid if [gv] has a bitwidth greater than the host bit width (but the + most significant bit may be lost). See the field + [llvm::GenericValue::IntVal]. *) + external as_int : t -> int = "llvm_genericvalue_as_int" + + (** [as_natint gv] unboxes the integer-valued generic value [gv] as a + [nativeint]. Is invalid if [gv] has a bitwidth greater than + [nativeint]. See the field [llvm::GenericValue::IntVal]. *) + external as_nativeint : t -> nativeint = "llvm_genericvalue_as_nativeint" + + (** [as_int64 gv] returns the integer-valued generic value [gv] as an [int64]. + Is invalid if [gv] has a bitwidth greater than [int64]. See the field + [llvm::GenericValue::IntVal]. *) + external as_int64 : t -> int64 = "llvm_genericvalue_as_int64" +end + + +module ExecutionEngine: sig + (** An execution engine is either a JIT compiler or an interpreter, capable of + directly loading an LLVM module and executing its functions without first + invoking a static compiler and generating a native executable. *) + type t + + (** [create m] creates a new execution engine, taking ownership of the + module [m] if successful. Creates a JIT if possible, else falls back to an + interpreter. Raises [Error msg] if an error occurrs. The execution engine + is not garbage collected and must be destroyed with [dispose ee]. + See the function [llvm::EngineBuilder::create]. *) + external create : Llvm.llmodule -> t = "llvm_ee_create" + + (** [create_interpreter m] creates a new interpreter, taking ownership of the + module [m] if successful. Raises [Error msg] if an error occurrs. The + execution engine is not garbage collected and must be destroyed with + [dispose ee]. + See the function [llvm::EngineBuilder::create]. *) + external create_interpreter : Llvm.llmodule -> t = "llvm_ee_create_interpreter" + + (** [create_jit m optlevel] creates a new JIT (just-in-time compiler), taking + ownership of the module [m] if successful with the desired optimization + level [optlevel]. Raises [Error msg] if an error occurrs. The execution + engine is not garbage collected and must be destroyed with [dispose ee]. + See the function [llvm::EngineBuilder::create]. *) + external create_jit : Llvm.llmodule -> int -> t = "llvm_ee_create_jit" + + (** [dispose ee] releases the memory used by the execution engine and must be + invoked to avoid memory leaks. *) + external dispose : t -> unit = "llvm_ee_dispose" + + (** [add_module m ee] adds the module [m] to the execution engine [ee]. *) + external add_module : Llvm.llmodule -> t -> unit = "llvm_ee_add_module" + + (** [remove_module m ee] removes the module [m] from the execution engine + [ee], disposing of [m] and the module referenced by [mp]. Raises + [Error msg] if an error occurs. *) + external remove_module : Llvm.llmodule -> t -> Llvm.llmodule + = "llvm_ee_remove_module" + + (** [find_function n ee] finds the function named [n] defined in any of the + modules owned by the execution engine [ee]. Returns [None] if the function + is not found and [Some f] otherwise. *) + external find_function : string -> t -> Llvm.llvalue option + = "llvm_ee_find_function" + + (** [run_function f args ee] synchronously executes the function [f] with the + arguments [args], which must be compatible with the parameter types. *) + external run_function : Llvm.llvalue -> GenericValue.t array -> t -> + GenericValue.t + = "llvm_ee_run_function" + + (** [run_static_ctors ee] executes the static constructors of each module in + the execution engine [ee]. *) + external run_static_ctors : t -> unit = "llvm_ee_run_static_ctors" + + (** [run_static_dtors ee] executes the static destructors of each module in + the execution engine [ee]. *) + external run_static_dtors : t -> unit = "llvm_ee_run_static_dtors" + + (** [run_function_as_main f args env ee] executes the function [f] as a main + function, passing it [argv] and [argc] according to the string array + [args], and [envp] as specified by the array [env]. Returns the integer + return value of the function. *) + external run_function_as_main : Llvm.llvalue -> string array -> + (string * string) array -> t -> int + = "llvm_ee_run_function_as_main" + + (** [free_machine_code f ee] releases the memory in the execution engine [ee] + used to store the machine code for the function [f]. *) + external free_machine_code : Llvm.llvalue -> t -> unit + = "llvm_ee_free_machine_code" + + (** [target_data ee] is the target data owned by the execution engine + [ee]. *) + external target_data : t -> Llvm_target.TargetData.t + = "LLVMGetExecutionEngineTargetData" +end + +external initialize_native_target : unit -> bool + = "llvm_initialize_native_target" diff --git a/contrib/llvm/bindings/ocaml/llvm/Makefile b/contrib/llvm/bindings/ocaml/llvm/Makefile new file mode 100644 index 0000000..99e347b --- /dev/null +++ b/contrib/llvm/bindings/ocaml/llvm/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/llvm/Makefile ------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm +UsedComponents := core +UsedOcamLibs := llvm + +include ../Makefile.ocaml diff --git a/contrib/llvm/bindings/ocaml/llvm/llvm.ml b/contrib/llvm/bindings/ocaml/llvm/llvm.ml new file mode 100644 index 0000000..7ab6f51 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/llvm/llvm.ml @@ -0,0 +1,1072 @@ +(*===-- llvm/llvm.ml - LLVM Ocaml Interface --------------------------------===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + + +type llcontext +type llmodule +type lltype +type lltypehandle +type llvalue +type lluse +type llbasicblock +type llbuilder +type llmemorybuffer + +module TypeKind = struct + type t = + | Void + | Float + | Double + | X86fp80 + | Fp128 + | Ppc_fp128 + | Label + | Integer + | Function + | Struct + | Array + | Pointer + | Opaque + | Vector + | Metadata + | Union +end + +module Linkage = struct + type t = + | External + | Available_externally + | Link_once + | Link_once_odr + | Weak + | Weak_odr + | Appending + | Internal + | Private + | Dllimport + | Dllexport + | External_weak + | Ghost + | Common + | Linker_private +end + +module Visibility = struct + type t = + | Default + | Hidden + | Protected +end + +module CallConv = struct + let c = 0 + let fast = 8 + let cold = 9 + let x86_stdcall = 64 + let x86_fastcall = 65 +end + +module Attribute = struct + type t = + | Zext + | Sext + | Noreturn + | Inreg + | Structret + | Nounwind + | Noalias + | Byval + | Nest + | Readnone + | Readonly + | Noinline + | Alwaysinline + | Optsize + | Ssp + | Sspreq + | Alignment of int + | Nocapture + | Noredzone + | Noimplicitfloat + | Naked + | Inlinehint + | Stackalignment of int +end + +module Icmp = struct + type t = + | Eq + | Ne + | Ugt + | Uge + | Ult + | Ule + | Sgt + | Sge + | Slt + | Sle +end + +module Fcmp = struct + type t = + | False + | Oeq + | Ogt + | Oge + | Olt + | Ole + | One + | Ord + | Uno + | Ueq + | Ugt + | Uge + | Ult + | Ule + | Une + | True +end + +exception IoError of string + +external register_exns : exn -> unit = "llvm_register_core_exns" +let _ = register_exns (IoError "") + +type ('a, 'b) llpos = +| At_end of 'a +| Before of 'b + +type ('a, 'b) llrev_pos = +| At_start of 'a +| After of 'b + +(*===-- Contexts ----------------------------------------------------------===*) +external create_context : unit -> llcontext = "llvm_create_context" +external dispose_context : llcontext -> unit = "llvm_dispose_context" +external global_context : unit -> llcontext = "llvm_global_context" +external mdkind_id : llcontext -> string -> int = "llvm_mdkind_id" + +(*===-- Modules -----------------------------------------------------------===*) +external create_module : llcontext -> string -> llmodule = "llvm_create_module" +external dispose_module : llmodule -> unit = "llvm_dispose_module" +external target_triple: llmodule -> string + = "llvm_target_triple" +external set_target_triple: string -> llmodule -> unit + = "llvm_set_target_triple" +external data_layout: llmodule -> string + = "llvm_data_layout" +external set_data_layout: string -> llmodule -> unit + = "llvm_set_data_layout" +external define_type_name : string -> lltype -> llmodule -> bool + = "llvm_add_type_name" +external delete_type_name : string -> llmodule -> unit + = "llvm_delete_type_name" +external type_by_name : llmodule -> string -> lltype option + = "llvm_type_by_name" +external dump_module : llmodule -> unit = "llvm_dump_module" +external set_module_inline_asm : llmodule -> string -> unit + = "llvm_set_module_inline_asm" + +(*===-- Types -------------------------------------------------------------===*) +external classify_type : lltype -> TypeKind.t = "llvm_classify_type" +external type_context : lltype -> llcontext = "llvm_type_context" + +(*--... Operations on integer types ........................................--*) +external i1_type : llcontext -> lltype = "llvm_i1_type" +external i8_type : llcontext -> lltype = "llvm_i8_type" +external i16_type : llcontext -> lltype = "llvm_i16_type" +external i32_type : llcontext -> lltype = "llvm_i32_type" +external i64_type : llcontext -> lltype = "llvm_i64_type" + +external integer_type : llcontext -> int -> lltype = "llvm_integer_type" +external integer_bitwidth : lltype -> int = "llvm_integer_bitwidth" + +(*--... Operations on real types ...........................................--*) +external float_type : llcontext -> lltype = "llvm_float_type" +external double_type : llcontext -> lltype = "llvm_double_type" +external x86fp80_type : llcontext -> lltype = "llvm_x86fp80_type" +external fp128_type : llcontext -> lltype = "llvm_fp128_type" +external ppc_fp128_type : llcontext -> lltype = "llvm_ppc_fp128_type" + +(*--... Operations on function types .......................................--*) +external function_type : lltype -> lltype array -> lltype = "llvm_function_type" +external var_arg_function_type : lltype -> lltype array -> lltype + = "llvm_var_arg_function_type" +external is_var_arg : lltype -> bool = "llvm_is_var_arg" +external return_type : lltype -> lltype = "LLVMGetReturnType" +external param_types : lltype -> lltype array = "llvm_param_types" + +(*--... Operations on struct types .........................................--*) +external struct_type : llcontext -> lltype array -> lltype = "llvm_struct_type" +external packed_struct_type : llcontext -> lltype array -> lltype + = "llvm_packed_struct_type" +external struct_element_types : lltype -> lltype array + = "llvm_struct_element_types" +external is_packed : lltype -> bool = "llvm_is_packed" + +(*--... Operations on union types ..........................................--*) +external union_type : llcontext -> lltype array -> lltype = "llvm_union_type" +external union_element_types : lltype -> lltype array + = "llvm_union_element_types" + +(*--... Operations on pointer, vector, and array types .....................--*) +external array_type : lltype -> int -> lltype = "llvm_array_type" +external pointer_type : lltype -> lltype = "llvm_pointer_type" +external qualified_pointer_type : lltype -> int -> lltype + = "llvm_qualified_pointer_type" +external vector_type : lltype -> int -> lltype = "llvm_vector_type" + +external element_type : lltype -> lltype = "LLVMGetElementType" +external array_length : lltype -> int = "llvm_array_length" +external address_space : lltype -> int = "llvm_address_space" +external vector_size : lltype -> int = "llvm_vector_size" + +(*--... Operations on other types ..........................................--*) +external opaque_type : llcontext -> lltype = "llvm_opaque_type" +external void_type : llcontext -> lltype = "llvm_void_type" +external label_type : llcontext -> lltype = "llvm_label_type" + +(*--... Operations on type handles .........................................--*) +external handle_to_type : lltype -> lltypehandle = "llvm_handle_to_type" +external type_of_handle : lltypehandle -> lltype = "llvm_type_of_handle" +external refine_type : lltype -> lltype -> unit = "llvm_refine_type" + + +(*===-- Values ------------------------------------------------------------===*) +external type_of : llvalue -> lltype = "llvm_type_of" +external value_name : llvalue -> string = "llvm_value_name" +external set_value_name : string -> llvalue -> unit = "llvm_set_value_name" +external dump_value : llvalue -> unit = "llvm_dump_value" +external replace_all_uses_with : llvalue -> llvalue -> unit + = "LLVMReplaceAllUsesWith" + +(*--... Operations on uses .................................................--*) +external use_begin : llvalue -> lluse option = "llvm_use_begin" +external use_succ : lluse -> lluse option = "llvm_use_succ" +external user : lluse -> llvalue = "llvm_user" +external used_value : lluse -> llvalue = "llvm_used_value" + +let iter_uses f v = + let rec aux = function + | None -> () + | Some u -> + f u; + aux (use_succ u) + in + aux (use_begin v) + +let fold_left_uses f init v = + let rec aux init u = + match u with + | None -> init + | Some u -> aux (f init u) (use_succ u) + in + aux init (use_begin v) + +let fold_right_uses f v init = + let rec aux u init = + match u with + | None -> init + | Some u -> f u (aux (use_succ u) init) + in + aux (use_begin v) init + + +(*--... Operations on users ................................................--*) +external operand : llvalue -> int -> llvalue = "llvm_operand" + +(*--... Operations on constants of (mostly) any type .......................--*) +external is_constant : llvalue -> bool = "llvm_is_constant" +external const_null : lltype -> llvalue = "LLVMConstNull" +external const_all_ones : (*int|vec*)lltype -> llvalue = "LLVMConstAllOnes" +external const_pointer_null : lltype -> llvalue = "LLVMConstPointerNull" +external undef : lltype -> llvalue = "LLVMGetUndef" +external is_null : llvalue -> bool = "llvm_is_null" +external is_undef : llvalue -> bool = "llvm_is_undef" + +(*--... Operations on instructions .........................................--*) +external has_metadata : llvalue -> bool = "llvm_has_metadata" +external metadata : llvalue -> int -> llvalue option = "llvm_metadata" +external set_metadata : llvalue -> int -> llvalue -> unit = "llvm_set_metadata" +external clear_metadata : llvalue -> int -> unit = "llvm_clear_metadata" + +(*--... Operations on metadata .......,.....................................--*) +external mdstring : llcontext -> string -> llvalue = "llvm_mdstring" +external mdnode : llcontext -> llvalue array -> llvalue = "llvm_mdnode" + +(*--... Operations on scalar constants .....................................--*) +external const_int : lltype -> int -> llvalue = "llvm_const_int" +external const_of_int64 : lltype -> Int64.t -> bool -> llvalue + = "llvm_const_of_int64" +external const_int_of_string : lltype -> string -> int -> llvalue + = "llvm_const_int_of_string" +external const_float : lltype -> float -> llvalue = "llvm_const_float" +external const_float_of_string : lltype -> string -> llvalue + = "llvm_const_float_of_string" + +(*--... Operations on composite constants ..................................--*) +external const_string : llcontext -> string -> llvalue = "llvm_const_string" +external const_stringz : llcontext -> string -> llvalue = "llvm_const_stringz" +external const_array : lltype -> llvalue array -> llvalue = "llvm_const_array" +external const_struct : llcontext -> llvalue array -> llvalue + = "llvm_const_struct" +external const_packed_struct : llcontext -> llvalue array -> llvalue + = "llvm_const_packed_struct" +external const_vector : llvalue array -> llvalue = "llvm_const_vector" +external const_union : lltype -> llvalue -> llvalue = "LLVMConstUnion" + +(*--... Constant expressions ...............................................--*) +external align_of : lltype -> llvalue = "LLVMAlignOf" +external size_of : lltype -> llvalue = "LLVMSizeOf" +external const_neg : llvalue -> llvalue = "LLVMConstNeg" +external const_nsw_neg : llvalue -> llvalue = "LLVMConstNSWNeg" +external const_nuw_neg : llvalue -> llvalue = "LLVMConstNUWNeg" +external const_fneg : llvalue -> llvalue = "LLVMConstFNeg" +external const_not : llvalue -> llvalue = "LLVMConstNot" +external const_add : llvalue -> llvalue -> llvalue = "LLVMConstAdd" +external const_nsw_add : llvalue -> llvalue -> llvalue = "LLVMConstNSWAdd" +external const_nuw_add : llvalue -> llvalue -> llvalue = "LLVMConstNUWAdd" +external const_fadd : llvalue -> llvalue -> llvalue = "LLVMConstFAdd" +external const_sub : llvalue -> llvalue -> llvalue = "LLVMConstSub" +external const_nsw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNSWSub" +external const_nuw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNUWSub" +external const_fsub : llvalue -> llvalue -> llvalue = "LLVMConstFSub" +external const_mul : llvalue -> llvalue -> llvalue = "LLVMConstMul" +external const_nsw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNSWMul" +external const_nuw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNUWMul" +external const_fmul : llvalue -> llvalue -> llvalue = "LLVMConstFMul" +external const_udiv : llvalue -> llvalue -> llvalue = "LLVMConstUDiv" +external const_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstSDiv" +external const_exact_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstExactSDiv" +external const_fdiv : llvalue -> llvalue -> llvalue = "LLVMConstFDiv" +external const_urem : llvalue -> llvalue -> llvalue = "LLVMConstURem" +external const_srem : llvalue -> llvalue -> llvalue = "LLVMConstSRem" +external const_frem : llvalue -> llvalue -> llvalue = "LLVMConstFRem" +external const_and : llvalue -> llvalue -> llvalue = "LLVMConstAnd" +external const_or : llvalue -> llvalue -> llvalue = "LLVMConstOr" +external const_xor : llvalue -> llvalue -> llvalue = "LLVMConstXor" +external const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue + = "llvm_const_icmp" +external const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue + = "llvm_const_fcmp" +external const_shl : llvalue -> llvalue -> llvalue = "LLVMConstShl" +external const_lshr : llvalue -> llvalue -> llvalue = "LLVMConstLShr" +external const_ashr : llvalue -> llvalue -> llvalue = "LLVMConstAShr" +external const_gep : llvalue -> llvalue array -> llvalue = "llvm_const_gep" +external const_in_bounds_gep : llvalue -> llvalue array -> llvalue + = "llvm_const_in_bounds_gep" +external const_trunc : llvalue -> lltype -> llvalue = "LLVMConstTrunc" +external const_sext : llvalue -> lltype -> llvalue = "LLVMConstSExt" +external const_zext : llvalue -> lltype -> llvalue = "LLVMConstZExt" +external const_fptrunc : llvalue -> lltype -> llvalue = "LLVMConstFPTrunc" +external const_fpext : llvalue -> lltype -> llvalue = "LLVMConstFPExt" +external const_uitofp : llvalue -> lltype -> llvalue = "LLVMConstUIToFP" +external const_sitofp : llvalue -> lltype -> llvalue = "LLVMConstSIToFP" +external const_fptoui : llvalue -> lltype -> llvalue = "LLVMConstFPToUI" +external const_fptosi : llvalue -> lltype -> llvalue = "LLVMConstFPToSI" +external const_ptrtoint : llvalue -> lltype -> llvalue = "LLVMConstPtrToInt" +external const_inttoptr : llvalue -> lltype -> llvalue = "LLVMConstIntToPtr" +external const_bitcast : llvalue -> lltype -> llvalue = "LLVMConstBitCast" +external const_zext_or_bitcast : llvalue -> lltype -> llvalue + = "LLVMConstZExtOrBitCast" +external const_sext_or_bitcast : llvalue -> lltype -> llvalue + = "LLVMConstSExtOrBitCast" +external const_trunc_or_bitcast : llvalue -> lltype -> llvalue + = "LLVMConstTruncOrBitCast" +external const_pointercast : llvalue -> lltype -> llvalue + = "LLVMConstPointerCast" +external const_intcast : llvalue -> lltype -> llvalue = "LLVMConstIntCast" +external const_fpcast : llvalue -> lltype -> llvalue = "LLVMConstFPCast" +external const_select : llvalue -> llvalue -> llvalue -> llvalue + = "LLVMConstSelect" +external const_extractelement : llvalue -> llvalue -> llvalue + = "LLVMConstExtractElement" +external const_insertelement : llvalue -> llvalue -> llvalue -> llvalue + = "LLVMConstInsertElement" +external const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue + = "LLVMConstShuffleVector" +external const_extractvalue : llvalue -> int array -> llvalue + = "llvm_const_extractvalue" +external const_insertvalue : llvalue -> llvalue -> int array -> llvalue + = "llvm_const_insertvalue" +external const_inline_asm : lltype -> string -> string -> bool -> bool -> + llvalue + = "llvm_const_inline_asm" +external block_address : llvalue -> llbasicblock -> llvalue = "LLVMBlockAddress" + +(*--... Operations on global variables, functions, and aliases (globals) ...--*) +external global_parent : llvalue -> llmodule = "LLVMGetGlobalParent" +external is_declaration : llvalue -> bool = "llvm_is_declaration" +external linkage : llvalue -> Linkage.t = "llvm_linkage" +external set_linkage : Linkage.t -> llvalue -> unit = "llvm_set_linkage" +external section : llvalue -> string = "llvm_section" +external set_section : string -> llvalue -> unit = "llvm_set_section" +external visibility : llvalue -> Visibility.t = "llvm_visibility" +external set_visibility : Visibility.t -> llvalue -> unit = "llvm_set_visibility" +external alignment : llvalue -> int = "llvm_alignment" +external set_alignment : int -> llvalue -> unit = "llvm_set_alignment" +external is_global_constant : llvalue -> bool = "llvm_is_global_constant" +external set_global_constant : bool -> llvalue -> unit + = "llvm_set_global_constant" + +(*--... Operations on global variables .....................................--*) +external declare_global : lltype -> string -> llmodule -> llvalue + = "llvm_declare_global" +external declare_qualified_global : lltype -> string -> int -> llmodule -> + llvalue + = "llvm_declare_qualified_global" +external define_global : string -> llvalue -> llmodule -> llvalue + = "llvm_define_global" +external define_qualified_global : string -> llvalue -> int -> llmodule -> + llvalue + = "llvm_define_qualified_global" +external lookup_global : string -> llmodule -> llvalue option + = "llvm_lookup_global" +external delete_global : llvalue -> unit = "llvm_delete_global" +external global_initializer : llvalue -> llvalue = "LLVMGetInitializer" +external set_initializer : llvalue -> llvalue -> unit = "llvm_set_initializer" +external remove_initializer : llvalue -> unit = "llvm_remove_initializer" +external is_thread_local : llvalue -> bool = "llvm_is_thread_local" +external set_thread_local : bool -> llvalue -> unit = "llvm_set_thread_local" +external global_begin : llmodule -> (llmodule, llvalue) llpos + = "llvm_global_begin" +external global_succ : llvalue -> (llmodule, llvalue) llpos + = "llvm_global_succ" +external global_end : llmodule -> (llmodule, llvalue) llrev_pos + = "llvm_global_end" +external global_pred : llvalue -> (llmodule, llvalue) llrev_pos + = "llvm_global_pred" + +let rec iter_global_range f i e = + if i = e then () else + match i with + | At_end _ -> raise (Invalid_argument "Invalid global variable range.") + | Before bb -> + f bb; + iter_global_range f (global_succ bb) e + +let iter_globals f m = + iter_global_range f (global_begin m) (At_end m) + +let rec fold_left_global_range f init i e = + if i = e then init else + match i with + | At_end _ -> raise (Invalid_argument "Invalid global variable range.") + | Before bb -> fold_left_global_range f (f init bb) (global_succ bb) e + +let fold_left_globals f init m = + fold_left_global_range f init (global_begin m) (At_end m) + +let rec rev_iter_global_range f i e = + if i = e then () else + match i with + | At_start _ -> raise (Invalid_argument "Invalid global variable range.") + | After bb -> + f bb; + rev_iter_global_range f (global_pred bb) e + +let rev_iter_globals f m = + rev_iter_global_range f (global_end m) (At_start m) + +let rec fold_right_global_range f i e init = + if i = e then init else + match i with + | At_start _ -> raise (Invalid_argument "Invalid global variable range.") + | After bb -> fold_right_global_range f (global_pred bb) e (f bb init) + +let fold_right_globals f m init = + fold_right_global_range f (global_end m) (At_start m) init + +(*--... Operations on aliases ..............................................--*) +external add_alias : llmodule -> lltype -> llvalue -> string -> llvalue + = "llvm_add_alias" + +(*--... Operations on functions ............................................--*) +external declare_function : string -> lltype -> llmodule -> llvalue + = "llvm_declare_function" +external define_function : string -> lltype -> llmodule -> llvalue + = "llvm_define_function" +external lookup_function : string -> llmodule -> llvalue option + = "llvm_lookup_function" +external delete_function : llvalue -> unit = "llvm_delete_function" +external is_intrinsic : llvalue -> bool = "llvm_is_intrinsic" +external function_call_conv : llvalue -> int = "llvm_function_call_conv" +external set_function_call_conv : int -> llvalue -> unit + = "llvm_set_function_call_conv" +external gc : llvalue -> string option = "llvm_gc" +external set_gc : string option -> llvalue -> unit = "llvm_set_gc" +external function_begin : llmodule -> (llmodule, llvalue) llpos + = "llvm_function_begin" +external function_succ : llvalue -> (llmodule, llvalue) llpos + = "llvm_function_succ" +external function_end : llmodule -> (llmodule, llvalue) llrev_pos + = "llvm_function_end" +external function_pred : llvalue -> (llmodule, llvalue) llrev_pos + = "llvm_function_pred" + +let rec iter_function_range f i e = + if i = e then () else + match i with + | At_end _ -> raise (Invalid_argument "Invalid function range.") + | Before fn -> + f fn; + iter_function_range f (function_succ fn) e + +let iter_functions f m = + iter_function_range f (function_begin m) (At_end m) + +let rec fold_left_function_range f init i e = + if i = e then init else + match i with + | At_end _ -> raise (Invalid_argument "Invalid function range.") + | Before fn -> fold_left_function_range f (f init fn) (function_succ fn) e + +let fold_left_functions f init m = + fold_left_function_range f init (function_begin m) (At_end m) + +let rec rev_iter_function_range f i e = + if i = e then () else + match i with + | At_start _ -> raise (Invalid_argument "Invalid function range.") + | After fn -> + f fn; + rev_iter_function_range f (function_pred fn) e + +let rev_iter_functions f m = + rev_iter_function_range f (function_end m) (At_start m) + +let rec fold_right_function_range f i e init = + if i = e then init else + match i with + | At_start _ -> raise (Invalid_argument "Invalid function range.") + | After fn -> fold_right_function_range f (function_pred fn) e (f fn init) + +let fold_right_functions f m init = + fold_right_function_range f (function_end m) (At_start m) init + +external llvm_add_function_attr : llvalue -> int -> unit + = "llvm_add_function_attr" +external llvm_remove_function_attr : llvalue -> int -> unit + = "llvm_remove_function_attr" + +let pack_attr (attr:Attribute.t) : int = + match attr with + Attribute.Zext -> 1 lsl 0 + | Attribute.Sext -> 1 lsl 1 + | Attribute.Noreturn -> 1 lsl 2 + | Attribute.Inreg -> 1 lsl 3 + | Attribute.Structret -> 1 lsl 4 + | Attribute.Nounwind -> 1 lsl 5 + | Attribute.Noalias -> 1 lsl 6 + | Attribute.Byval -> 1 lsl 7 + | Attribute.Nest -> 1 lsl 8 + | Attribute.Readnone -> 1 lsl 9 + | Attribute.Readonly -> 1 lsl 10 + | Attribute.Noinline -> 1 lsl 11 + | Attribute.Alwaysinline -> 1 lsl 12 + | Attribute.Optsize -> 1 lsl 13 + | Attribute.Ssp -> 1 lsl 14 + | Attribute.Sspreq -> 1 lsl 15 + | Attribute.Alignment n -> n lsl 16 + | Attribute.Nocapture -> 1 lsl 21 + | Attribute.Noredzone -> 1 lsl 22 + | Attribute.Noimplicitfloat -> 1 lsl 23 + | Attribute.Naked -> 1 lsl 24 + | Attribute.Inlinehint -> 1 lsl 25 + | Attribute.Stackalignment n -> n lsl 26 + +let add_function_attr llval attr = + llvm_add_function_attr llval (pack_attr attr) + +let remove_function_attr llval attr = + llvm_remove_function_attr llval (pack_attr attr) + +(*--... Operations on params ...............................................--*) +external params : llvalue -> llvalue array = "llvm_params" +external param : llvalue -> int -> llvalue = "llvm_param" +external param_parent : llvalue -> llvalue = "LLVMGetParamParent" +external param_begin : llvalue -> (llvalue, llvalue) llpos = "llvm_param_begin" +external param_succ : llvalue -> (llvalue, llvalue) llpos = "llvm_param_succ" +external param_end : llvalue -> (llvalue, llvalue) llrev_pos = "llvm_param_end" +external param_pred : llvalue -> (llvalue, llvalue) llrev_pos ="llvm_param_pred" + +let rec iter_param_range f i e = + if i = e then () else + match i with + | At_end _ -> raise (Invalid_argument "Invalid parameter range.") + | Before p -> + f p; + iter_param_range f (param_succ p) e + +let iter_params f fn = + iter_param_range f (param_begin fn) (At_end fn) + +let rec fold_left_param_range f init i e = + if i = e then init else + match i with + | At_end _ -> raise (Invalid_argument "Invalid parameter range.") + | Before p -> fold_left_param_range f (f init p) (param_succ p) e + +let fold_left_params f init fn = + fold_left_param_range f init (param_begin fn) (At_end fn) + +let rec rev_iter_param_range f i e = + if i = e then () else + match i with + | At_start _ -> raise (Invalid_argument "Invalid parameter range.") + | After p -> + f p; + rev_iter_param_range f (param_pred p) e + +let rev_iter_params f fn = + rev_iter_param_range f (param_end fn) (At_start fn) + +let rec fold_right_param_range f init i e = + if i = e then init else + match i with + | At_start _ -> raise (Invalid_argument "Invalid parameter range.") + | After p -> fold_right_param_range f (f p init) (param_pred p) e + +let fold_right_params f fn init = + fold_right_param_range f init (param_end fn) (At_start fn) + +external llvm_add_param_attr : llvalue -> int -> unit + = "llvm_add_param_attr" +external llvm_remove_param_attr : llvalue -> int -> unit + = "llvm_remove_param_attr" + +let add_param_attr llval attr = + llvm_add_param_attr llval (pack_attr attr) + +let remove_param_attr llval attr = + llvm_remove_param_attr llval (pack_attr attr) + +external set_param_alignment : llvalue -> int -> unit + = "llvm_set_param_alignment" + +(*--... Operations on basic blocks .........................................--*) +external value_of_block : llbasicblock -> llvalue = "LLVMBasicBlockAsValue" +external value_is_block : llvalue -> bool = "llvm_value_is_block" +external block_of_value : llvalue -> llbasicblock = "LLVMValueAsBasicBlock" +external block_parent : llbasicblock -> llvalue = "LLVMGetBasicBlockParent" +external basic_blocks : llvalue -> llbasicblock array = "llvm_basic_blocks" +external entry_block : llvalue -> llbasicblock = "LLVMGetEntryBasicBlock" +external delete_block : llbasicblock -> unit = "llvm_delete_block" +external append_block : llcontext -> string -> llvalue -> llbasicblock + = "llvm_append_block" +external insert_block : llcontext -> string -> llbasicblock -> llbasicblock + = "llvm_insert_block" +external block_begin : llvalue -> (llvalue, llbasicblock) llpos + = "llvm_block_begin" +external block_succ : llbasicblock -> (llvalue, llbasicblock) llpos + = "llvm_block_succ" +external block_end : llvalue -> (llvalue, llbasicblock) llrev_pos + = "llvm_block_end" +external block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos + = "llvm_block_pred" + +let rec iter_block_range f i e = + if i = e then () else + match i with + | At_end _ -> raise (Invalid_argument "Invalid block range.") + | Before bb -> + f bb; + iter_block_range f (block_succ bb) e + +let iter_blocks f fn = + iter_block_range f (block_begin fn) (At_end fn) + +let rec fold_left_block_range f init i e = + if i = e then init else + match i with + | At_end _ -> raise (Invalid_argument "Invalid block range.") + | Before bb -> fold_left_block_range f (f init bb) (block_succ bb) e + +let fold_left_blocks f init fn = + fold_left_block_range f init (block_begin fn) (At_end fn) + +let rec rev_iter_block_range f i e = + if i = e then () else + match i with + | At_start _ -> raise (Invalid_argument "Invalid block range.") + | After bb -> + f bb; + rev_iter_block_range f (block_pred bb) e + +let rev_iter_blocks f fn = + rev_iter_block_range f (block_end fn) (At_start fn) + +let rec fold_right_block_range f init i e = + if i = e then init else + match i with + | At_start _ -> raise (Invalid_argument "Invalid block range.") + | After bb -> fold_right_block_range f (f bb init) (block_pred bb) e + +let fold_right_blocks f fn init = + fold_right_block_range f init (block_end fn) (At_start fn) + +(*--... Operations on instructions .........................................--*) +external instr_parent : llvalue -> llbasicblock = "LLVMGetInstructionParent" +external instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos + = "llvm_instr_begin" +external instr_succ : llvalue -> (llbasicblock, llvalue) llpos + = "llvm_instr_succ" +external instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos + = "llvm_instr_end" +external instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos + = "llvm_instr_pred" + +let rec iter_instrs_range f i e = + if i = e then () else + match i with + | At_end _ -> raise (Invalid_argument "Invalid instruction range.") + | Before i -> + f i; + iter_instrs_range f (instr_succ i) e + +let iter_instrs f bb = + iter_instrs_range f (instr_begin bb) (At_end bb) + +let rec fold_left_instrs_range f init i e = + if i = e then init else + match i with + | At_end _ -> raise (Invalid_argument "Invalid instruction range.") + | Before i -> fold_left_instrs_range f (f init i) (instr_succ i) e + +let fold_left_instrs f init bb = + fold_left_instrs_range f init (instr_begin bb) (At_end bb) + +let rec rev_iter_instrs_range f i e = + if i = e then () else + match i with + | At_start _ -> raise (Invalid_argument "Invalid instruction range.") + | After i -> + f i; + rev_iter_instrs_range f (instr_pred i) e + +let rev_iter_instrs f bb = + rev_iter_instrs_range f (instr_end bb) (At_start bb) + +let rec fold_right_instr_range f i e init = + if i = e then init else + match i with + | At_start _ -> raise (Invalid_argument "Invalid instruction range.") + | After i -> fold_right_instr_range f (instr_pred i) e (f i init) + +let fold_right_instrs f bb init = + fold_right_instr_range f (instr_end bb) (At_start bb) init + + +(*--... Operations on call sites ...........................................--*) +external instruction_call_conv: llvalue -> int + = "llvm_instruction_call_conv" +external set_instruction_call_conv: int -> llvalue -> unit + = "llvm_set_instruction_call_conv" + +external llvm_add_instruction_param_attr : llvalue -> int -> int -> unit + = "llvm_add_instruction_param_attr" +external llvm_remove_instruction_param_attr : llvalue -> int -> int -> unit + = "llvm_remove_instruction_param_attr" + +let add_instruction_param_attr llval i attr = + llvm_add_instruction_param_attr llval i (pack_attr attr) + +let remove_instruction_param_attr llval i attr = + llvm_remove_instruction_param_attr llval i (pack_attr attr) + +(*--... Operations on call instructions (only) .............................--*) +external is_tail_call : llvalue -> bool = "llvm_is_tail_call" +external set_tail_call : bool -> llvalue -> unit = "llvm_set_tail_call" + +(*--... Operations on phi nodes ............................................--*) +external add_incoming : (llvalue * llbasicblock) -> llvalue -> unit + = "llvm_add_incoming" +external incoming : llvalue -> (llvalue * llbasicblock) list = "llvm_incoming" + + +(*===-- Instruction builders ----------------------------------------------===*) +external builder : llcontext -> llbuilder = "llvm_builder" +external position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit + = "llvm_position_builder" +external insertion_block : llbuilder -> llbasicblock = "llvm_insertion_block" +external insert_into_builder : llvalue -> string -> llbuilder -> unit + = "llvm_insert_into_builder" + +let builder_at context ip = + let b = builder context in + position_builder ip b; + b + +let builder_before context i = builder_at context (Before i) +let builder_at_end context bb = builder_at context (At_end bb) + +let position_before i = position_builder (Before i) +let position_at_end bb = position_builder (At_end bb) + + +(*--... Metadata ...........................................................--*) +external set_current_debug_location : llbuilder -> llvalue -> unit + = "llvm_set_current_debug_location" +external clear_current_debug_location : llbuilder -> unit + = "llvm_clear_current_debug_location" +external current_debug_location : llbuilder -> llvalue option + = "llvm_current_debug_location" +external set_inst_debug_location : llbuilder -> llvalue -> unit + = "llvm_set_inst_debug_location" + + +(*--... Terminators ........................................................--*) +external build_ret_void : llbuilder -> llvalue = "llvm_build_ret_void" +external build_ret : llvalue -> llbuilder -> llvalue = "llvm_build_ret" +external build_aggregate_ret : llvalue array -> llbuilder -> llvalue + = "llvm_build_aggregate_ret" +external build_br : llbasicblock -> llbuilder -> llvalue = "llvm_build_br" +external build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder -> + llvalue = "llvm_build_cond_br" +external build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue + = "llvm_build_switch" +external add_case : llvalue -> llvalue -> llbasicblock -> unit + = "llvm_add_case" +external build_indirect_br : llvalue -> int -> llbuilder -> llvalue + = "llvm_build_indirect_br" +external add_destination : llvalue -> llbasicblock -> unit + = "llvm_add_destination" +external build_invoke : llvalue -> llvalue array -> llbasicblock -> + llbasicblock -> string -> llbuilder -> llvalue + = "llvm_build_invoke_bc" "llvm_build_invoke_nat" +external build_unwind : llbuilder -> llvalue = "llvm_build_unwind" +external build_unreachable : llbuilder -> llvalue = "llvm_build_unreachable" + +(*--... Arithmetic .........................................................--*) +external build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_add" +external build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_add" +external build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_add" +external build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fadd" +external build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_sub" +external build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_sub" +external build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_sub" +external build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fsub" +external build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_mul" +external build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_mul" +external build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_mul" +external build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fmul" +external build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_udiv" +external build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_sdiv" +external build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_exact_sdiv" +external build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fdiv" +external build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_urem" +external build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_srem" +external build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_frem" +external build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_shl" +external build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_lshr" +external build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_ashr" +external build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_and" +external build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_or" +external build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_xor" +external build_neg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_neg" +external build_nsw_neg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_neg" +external build_nuw_neg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_neg" +external build_fneg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fneg" +external build_not : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_not" + +(*--... Memory .............................................................--*) +external build_alloca : lltype -> string -> llbuilder -> llvalue + = "llvm_build_alloca" +external build_array_alloca : lltype -> llvalue -> string -> llbuilder -> + llvalue = "llvm_build_array_alloca" +external build_load : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_load" +external build_store : llvalue -> llvalue -> llbuilder -> llvalue + = "llvm_build_store" +external build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue + = "llvm_build_gep" +external build_in_bounds_gep : llvalue -> llvalue array -> string -> + llbuilder -> llvalue = "llvm_build_in_bounds_gep" +external build_struct_gep : llvalue -> int -> string -> llbuilder -> llvalue + = "llvm_build_struct_gep" + +external build_global_string : string -> string -> llbuilder -> llvalue + = "llvm_build_global_string" +external build_global_stringptr : string -> string -> llbuilder -> llvalue + = "llvm_build_global_stringptr" + +(*--... Casts ..............................................................--*) +external build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_trunc" +external build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_zext" +external build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_sext" +external build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fptoui" +external build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fptosi" +external build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_uitofp" +external build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_sitofp" +external build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fptrunc" +external build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fpext" +external build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_prttoint" +external build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_inttoptr" +external build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_bitcast" +external build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> + llvalue = "llvm_build_zext_or_bitcast" +external build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> + llvalue = "llvm_build_sext_or_bitcast" +external build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder -> + llvalue = "llvm_build_trunc_or_bitcast" +external build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_pointercast" +external build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_intcast" +external build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fpcast" + +(*--... Comparisons ........................................................--*) +external build_icmp : Icmp.t -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_icmp" +external build_fcmp : Fcmp.t -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_fcmp" + +(*--... Miscellaneous instructions .........................................--*) +external build_phi : (llvalue * llbasicblock) list -> string -> llbuilder -> + llvalue = "llvm_build_phi" +external build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue + = "llvm_build_call" +external build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder -> + llvalue = "llvm_build_select" +external build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_va_arg" +external build_extractelement : llvalue -> llvalue -> string -> llbuilder -> + llvalue = "llvm_build_extractelement" +external build_insertelement : llvalue -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_insertelement" +external build_shufflevector : llvalue -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_shufflevector" +external build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue + = "llvm_build_extractvalue" +external build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder -> + llvalue = "llvm_build_insertvalue" + +external build_is_null : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_is_null" +external build_is_not_null : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_is_not_null" +external build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_ptrdiff" + + +(*===-- Memory buffers ----------------------------------------------------===*) + +module MemoryBuffer = struct + external of_file : string -> llmemorybuffer = "llvm_memorybuffer_of_file" + external of_stdin : unit -> llmemorybuffer = "llvm_memorybuffer_of_stdin" + external dispose : llmemorybuffer -> unit = "llvm_memorybuffer_dispose" +end + + +(*===-- Pass Manager ------------------------------------------------------===*) + +module PassManager = struct + type 'a t + type any = [ `Module | `Function ] + external create : unit -> [ `Module ] t = "llvm_passmanager_create" + external create_function : llmodule -> [ `Function ] t + = "LLVMCreateFunctionPassManager" + external run_module : llmodule -> [ `Module ] t -> bool + = "llvm_passmanager_run_module" + external initialize : [ `Function ] t -> bool = "llvm_passmanager_initialize" + external run_function : llvalue -> [ `Function ] t -> bool + = "llvm_passmanager_run_function" + external finalize : [ `Function ] t -> bool = "llvm_passmanager_finalize" + external dispose : [< any ] t -> unit = "llvm_passmanager_dispose" +end + + +(*===-- Non-Externs -------------------------------------------------------===*) +(* These functions are built using the externals, so must be declared late. *) + +let concat2 sep arr = + let s = ref "" in + if 0 < Array.length arr then begin + s := !s ^ arr.(0); + for i = 1 to (Array.length arr) - 1 do + s := !s ^ sep ^ arr.(i) + done + end; + !s + +let rec string_of_lltype ty = + (* FIXME: stop infinite recursion! :) *) + match classify_type ty with + TypeKind.Integer -> "i" ^ string_of_int (integer_bitwidth ty) + | TypeKind.Pointer -> (string_of_lltype (element_type ty)) ^ "*" + | TypeKind.Struct -> + let s = "{ " ^ (concat2 ", " ( + Array.map string_of_lltype (struct_element_types ty) + )) ^ " }" in + if is_packed ty + then "<" ^ s ^ ">" + else s + | TypeKind.Union -> "union { " ^ (concat2 ", " ( + Array.map string_of_lltype (union_element_types ty) + )) ^ " }" + | TypeKind.Array -> "[" ^ (string_of_int (array_length ty)) ^ + " x " ^ (string_of_lltype (element_type ty)) ^ "]" + | TypeKind.Vector -> "<" ^ (string_of_int (vector_size ty)) ^ + " x " ^ (string_of_lltype (element_type ty)) ^ ">" + | TypeKind.Opaque -> "opaque" + | TypeKind.Function -> string_of_lltype (return_type ty) ^ + " (" ^ (concat2 ", " ( + Array.map string_of_lltype (param_types ty) + )) ^ ")" + | TypeKind.Label -> "label" + | TypeKind.Ppc_fp128 -> "ppc_fp128" + | TypeKind.Fp128 -> "fp128" + | TypeKind.X86fp80 -> "x86_fp80" + | TypeKind.Double -> "double" + | TypeKind.Float -> "float" + | TypeKind.Void -> "void" + | TypeKind.Metadata -> "metadata" diff --git a/contrib/llvm/bindings/ocaml/llvm/llvm.mli b/contrib/llvm/bindings/ocaml/llvm/llvm.mli new file mode 100644 index 0000000..742265c --- /dev/null +++ b/contrib/llvm/bindings/ocaml/llvm/llvm.mli @@ -0,0 +1,2269 @@ +(*===-- llvm/llvm.mli - LLVM Ocaml Interface -------------------------------===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +(** Core API. + + This interface provides an ocaml API for the LLVM intermediate + representation, the classes in the VMCore library. *) + + +(** {6 Abstract types} + + These abstract types correlate directly to the LLVM VMCore classes. *) + +(** The top-level container for all LLVM global data. See the + [llvm::LLVMContext] class. *) +type llcontext + +(** The top-level container for all other LLVM Intermediate Representation (IR) + objects. See the [llvm::Module] class. *) +type llmodule + +(** Each value in the LLVM IR has a type, an instance of [lltype]. See the + [llvm::Type] class. *) +type lltype + +(** When building recursive types using {!refine_type}, [lltype] values may + become invalid; use [lltypehandle] to resolve this problem. See the + [llvm::AbstractTypeHolder] class. *) +type lltypehandle + +(** Any value in the LLVM IR. Functions, instructions, global variables, + constants, and much more are all [llvalues]. See the [llvm::Value] class. + This type covers a wide range of subclasses. *) +type llvalue + +(** Used to store users and usees of values. See the [llvm::Use] class. *) +type lluse + +(** A basic block in LLVM IR. See the [llvm::BasicBlock] class. *) +type llbasicblock + +(** Used to generate instructions in the LLVM IR. See the [llvm::LLVMBuilder] + class. *) +type llbuilder + +(** Used to efficiently handle large buffers of read-only binary data. + See the [llvm::MemoryBuffer] class. *) +type llmemorybuffer + +(** The kind of an [lltype], the result of [classify_type ty]. See the + [llvm::Type::TypeID] enumeration. *) +module TypeKind : sig + type t = + Void + | Float + | Double + | X86fp80 + | Fp128 + | Ppc_fp128 + | Label + | Integer + | Function + | Struct + | Array + | Pointer + | Opaque + | Vector + | Metadata + | Union +end + +(** The linkage of a global value, accessed with {!linkage} and + {!set_linkage}. See [llvm::GlobalValue::LinkageTypes]. *) +module Linkage : sig + type t = + External + | Available_externally + | Link_once + | Link_once_odr + | Weak + | Weak_odr + | Appending + | Internal + | Private + | Dllimport + | Dllexport + | External_weak + | Ghost + | Common + | Linker_private +end + +(** The linker visibility of a global value, accessed with {!visibility} and + {!set_visibility}. See [llvm::GlobalValue::VisibilityTypes]. *) +module Visibility : sig + type t = + Default + | Hidden + | Protected +end + +(** The following calling convention values may be accessed with + {!function_call_conv} and {!set_function_call_conv}. Calling + conventions are open-ended. *) +module CallConv : sig + val c : int (** [c] is the C calling convention. *) + val fast : int (** [fast] is the calling convention to allow LLVM + maximum optimization opportunities. Use only with + internal linkage. *) + val cold : int (** [cold] is the calling convention for + callee-save. *) + val x86_stdcall : int (** [x86_stdcall] is the familiar stdcall calling + convention from C. *) + val x86_fastcall : int (** [x86_fastcall] is the familiar fastcall calling + convention from C. *) +end + +module Attribute : sig + type t = + | Zext + | Sext + | Noreturn + | Inreg + | Structret + | Nounwind + | Noalias + | Byval + | Nest + | Readnone + | Readonly + | Noinline + | Alwaysinline + | Optsize + | Ssp + | Sspreq + | Alignment of int + | Nocapture + | Noredzone + | Noimplicitfloat + | Naked + | Inlinehint + | Stackalignment of int +end + +(** The predicate for an integer comparison ([icmp]) instruction. + See the [llvm::ICmpInst::Predicate] enumeration. *) +module Icmp : sig + type t = + | Eq + | Ne + | Ugt + | Uge + | Ult + | Ule + | Sgt + | Sge + | Slt + | Sle +end + +(** The predicate for a floating-point comparison ([fcmp]) instruction. + See the [llvm::FCmpInst::Predicate] enumeration. *) +module Fcmp : sig + type t = + | False + | Oeq + | Ogt + | Oge + | Olt + | Ole + | One + | Ord + | Uno + | Ueq + | Ugt + | Uge + | Ult + | Ule + | Une + | True +end + + +(** {6 Iteration} *) + +(** [Before b] and [At_end a] specify positions from the start of the ['b] list + of [a]. [llpos] is used to specify positions in and for forward iteration + through the various value lists maintained by the LLVM IR. *) +type ('a, 'b) llpos = +| At_end of 'a +| Before of 'b + +(** [After b] and [At_start a] specify positions from the end of the ['b] list + of [a]. [llrev_pos] is used for reverse iteration through the various value + lists maintained by the LLVM IR. *) +type ('a, 'b) llrev_pos = +| At_start of 'a +| After of 'b + + +(** {6 Exceptions} *) + +exception IoError of string + + +(** {6 Contexts} *) + +(** [create_context ()] creates a context for storing the "global" state in + LLVM. See the constructor [llvm::LLVMContext]. *) +external create_context : unit -> llcontext = "llvm_create_context" + +(** [destroy_context ()] destroys a context. See the destructor + [llvm::LLVMContext::~LLVMContext]. *) +external dispose_context : llcontext -> unit = "llvm_dispose_context" + +(** See the function [llvm::getGlobalContext]. *) +external global_context : unit -> llcontext = "llvm_global_context" + +(** [mdkind_id context name] returns the MDKind ID that corresponds to the + name [name] in the context [context]. See the function + [llvm::LLVMContext::getMDKindID]. *) +external mdkind_id : llcontext -> string -> int = "llvm_mdkind_id" + + +(** {6 Modules} *) + +(** [create_module context id] creates a module with the supplied module ID in + the context [context]. Modules are not garbage collected; it is mandatory + to call {!dispose_module} to free memory. See the constructor + [llvm::Module::Module]. *) +external create_module : llcontext -> string -> llmodule = "llvm_create_module" + +(** [dispose_module m] destroys a module [m] and all of the IR objects it + contained. All references to subordinate objects are invalidated; + referencing them will invoke undefined behavior. See the destructor + [llvm::Module::~Module]. *) +external dispose_module : llmodule -> unit = "llvm_dispose_module" + +(** [target_triple m] is the target specifier for the module [m], something like + [i686-apple-darwin8]. See the method [llvm::Module::getTargetTriple]. *) +external target_triple: llmodule -> string + = "llvm_target_triple" + +(** [target_triple triple m] changes the target specifier for the module [m] to + the string [triple]. See the method [llvm::Module::setTargetTriple]. *) +external set_target_triple: string -> llmodule -> unit + = "llvm_set_target_triple" + +(** [data_layout m] is the data layout specifier for the module [m], something + like [e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-...-a0:0:64-f80:128:128]. See the + method [llvm::Module::getDataLayout]. *) +external data_layout: llmodule -> string + = "llvm_data_layout" + +(** [set_data_layout s m] changes the data layout specifier for the module [m] + to the string [s]. See the method [llvm::Module::setDataLayout]. *) +external set_data_layout: string -> llmodule -> unit + = "llvm_set_data_layout" + +(** [define_type_name name ty m] adds a named type to the module's symbol table. + Returns [true] if successful. If such a name already exists, then no entry + is added and [false] is returned. See the [llvm::Module::addTypeName] + method. *) +external define_type_name : string -> lltype -> llmodule -> bool + = "llvm_add_type_name" + +(** [delete_type_name name] removes a type name from the module's symbol + table. *) +external delete_type_name : string -> llmodule -> unit + = "llvm_delete_type_name" + +(** [type_by_name m n] returns the type in the module [m] named [n], or [None] + if it does not exist. See the method [llvm::Module::getTypeByName]. *) +external type_by_name : llmodule -> string -> lltype option + = "llvm_type_by_name" + +(** [dump_module m] prints the .ll representation of the module [m] to standard + error. See the method [llvm::Module::dump]. *) +external dump_module : llmodule -> unit = "llvm_dump_module" + +(** [set_module_inline_asm m asm] sets the inline assembler for the module. See + the method [llvm::Module::setModuleInlineAsm]. *) +external set_module_inline_asm : llmodule -> string -> unit + = "llvm_set_module_inline_asm" + + +(** {6 Types} *) + +(** [classify_type ty] returns the {!TypeKind.t} corresponding to the type [ty]. + See the method [llvm::Type::getTypeID]. *) +external classify_type : lltype -> TypeKind.t = "llvm_classify_type" + +(** [type_context ty] returns the {!llcontext} corresponding to the type [ty]. + See the method [llvm::Type::getContext]. *) +external type_context : lltype -> llcontext = "llvm_type_context" + +(** [string_of_lltype ty] returns a string describing the type [ty]. *) +val string_of_lltype : lltype -> string + +(** {7 Operations on integer types} *) + +(** [i1_type c] returns an integer type of bitwidth 1 in the context [c]. See + [llvm::Type::Int1Ty]. *) +external i1_type : llcontext -> lltype = "llvm_i1_type" + +(** [i8_type c] returns an integer type of bitwidth 8 in the context [c]. See + [llvm::Type::Int8Ty]. *) +external i8_type : llcontext -> lltype = "llvm_i8_type" + +(** [i16_type c] returns an integer type of bitwidth 16 in the context [c]. See + [llvm::Type::Int16Ty]. *) +external i16_type : llcontext -> lltype = "llvm_i16_type" + +(** [i32_type c] returns an integer type of bitwidth 32 in the context [c]. See + [llvm::Type::Int32Ty]. *) +external i32_type : llcontext -> lltype = "llvm_i32_type" + +(** [i64_type c] returns an integer type of bitwidth 64 in the context [c]. See + [llvm::Type::Int64Ty]. *) +external i64_type : llcontext -> lltype = "llvm_i64_type" + +(** [integer_type c n] returns an integer type of bitwidth [n] in the context + [c]. See the method [llvm::IntegerType::get]. *) +external integer_type : llcontext -> int -> lltype = "llvm_integer_type" + +(** [integer_bitwidth c ty] returns the number of bits in the integer type [ty] + in the context [c]. See the method [llvm::IntegerType::getBitWidth]. *) +external integer_bitwidth : lltype -> int = "llvm_integer_bitwidth" + + +(** {7 Operations on real types} *) + +(** [float_type c] returns the IEEE 32-bit floating point type in the context + [c]. See [llvm::Type::FloatTy]. *) +external float_type : llcontext -> lltype = "llvm_float_type" + +(** [double_type c] returns the IEEE 64-bit floating point type in the context + [c]. See [llvm::Type::DoubleTy]. *) +external double_type : llcontext -> lltype = "llvm_double_type" + +(** [x86fp80_type c] returns the x87 80-bit floating point type in the context + [c]. See [llvm::Type::X86_FP80Ty]. *) +external x86fp80_type : llcontext -> lltype = "llvm_x86fp80_type" + +(** [fp128_type c] returns the IEEE 128-bit floating point type in the context + [c]. See [llvm::Type::FP128Ty]. *) +external fp128_type : llcontext -> lltype = "llvm_fp128_type" + +(** [ppc_fp128_type c] returns the PowerPC 128-bit floating point type in the + context [c]. See [llvm::Type::PPC_FP128Ty]. *) +external ppc_fp128_type : llcontext -> lltype = "llvm_ppc_fp128_type" + + +(** {7 Operations on function types} *) + +(** [function_type ret_ty param_tys] returns the function type returning + [ret_ty] and taking [param_tys] as parameters. + See the method [llvm::FunctionType::get]. *) +external function_type : lltype -> lltype array -> lltype = "llvm_function_type" + +(** [va_arg_function_type ret_ty param_tys] is just like + [function_type ret_ty param_tys] except that it returns the function type + which also takes a variable number of arguments. + See the method [llvm::FunctionType::get]. *) +external var_arg_function_type : lltype -> lltype array -> lltype + = "llvm_var_arg_function_type" + +(** [is_var_arg fty] returns [true] if [fty] is a varargs function type, [false] + otherwise. See the method [llvm::FunctionType::isVarArg]. *) +external is_var_arg : lltype -> bool = "llvm_is_var_arg" + +(** [return_type fty] gets the return type of the function type [fty]. + See the method [llvm::FunctionType::getReturnType]. *) +external return_type : lltype -> lltype = "LLVMGetReturnType" + +(** [param_types fty] gets the parameter types of the function type [fty]. + See the method [llvm::FunctionType::getParamType]. *) +external param_types : lltype -> lltype array = "llvm_param_types" + + +(** {7 Operations on struct types} *) + +(** [struct_type context tys] returns the structure type in the context + [context] containing in the types in the array [tys]. See the method + [llvm::StructType::get]. *) +external struct_type : llcontext -> lltype array -> lltype + = "llvm_struct_type" + +(** [packed_struct_type context ys] returns the packed structure type in the + context [context] containing in the types in the array [tys]. See the method + [llvm::StructType::get]. *) +external packed_struct_type : llcontext -> lltype array -> lltype + = "llvm_packed_struct_type" + +(** [struct_element_types sty] returns the constituent types of the struct type + [sty]. See the method [llvm::StructType::getElementType]. *) +external struct_element_types : lltype -> lltype array + = "llvm_struct_element_types" + +(** [is_packed sty] returns [true] if the structure type [sty] is packed, + [false] otherwise. See the method [llvm::StructType::isPacked]. *) +external is_packed : lltype -> bool = "llvm_is_packed" + + +(** {7 Operations on union types} *) + +(** [union_type context tys] returns the union type in the context [context] + containing the types in the array [tys]. See the method + [llvm::UnionType::get] *) +external union_type : llcontext -> lltype array -> lltype = "llvm_union_type" + +(** [union_element_types uty] returns the constituent types of the union type + [uty]. See the method [llvm::UnionType::getElementType]. *) +external union_element_types : lltype -> lltype array + = "llvm_union_element_types" + + +(** {7 Operations on pointer, vector, and array types} *) + +(** [array_type ty n] returns the array type containing [n] elements of type + [ty]. See the method [llvm::ArrayType::get]. *) +external array_type : lltype -> int -> lltype = "llvm_array_type" + +(** [pointer_type ty] returns the pointer type referencing objects of type + [ty] in the default address space (0). + See the method [llvm::PointerType::getUnqual]. *) +external pointer_type : lltype -> lltype = "llvm_pointer_type" + +(** [qualified_pointer_type ty as] returns the pointer type referencing objects + of type [ty] in address space [as]. + See the method [llvm::PointerType::get]. *) +external qualified_pointer_type : lltype -> int -> lltype + = "llvm_qualified_pointer_type" + +(** [vector_type ty n] returns the array type containing [n] elements of the + primitive type [ty]. See the method [llvm::ArrayType::get]. *) +external vector_type : lltype -> int -> lltype = "llvm_vector_type" + +(** [element_type ty] returns the element type of the pointer, vector, or array + type [ty]. See the method [llvm::SequentialType::get]. *) +external element_type : lltype -> lltype = "LLVMGetElementType" + +(** [element_type aty] returns the element count of the array type [aty]. + See the method [llvm::ArrayType::getNumElements]. *) +external array_length : lltype -> int = "llvm_array_length" + +(** [address_space pty] returns the address space qualifier of the pointer type + [pty]. See the method [llvm::PointerType::getAddressSpace]. *) +external address_space : lltype -> int = "llvm_address_space" + +(** [element_type ty] returns the element count of the vector type [ty]. + See the method [llvm::VectorType::getNumElements]. *) +external vector_size : lltype -> int = "llvm_vector_size" + + +(** {7 Operations on other types} *) + +(** [opaque_type c] creates a new opaque type distinct from any other in the + context [c]. Opaque types are useful for building recursive types in + combination with {!refine_type}. See [llvm::OpaqueType::get]. *) +external opaque_type : llcontext -> lltype = "llvm_opaque_type" + +(** [void_type c] creates a type of a function which does not return any + value in the context [c]. See [llvm::Type::VoidTy]. *) +external void_type : llcontext -> lltype = "llvm_void_type" + +(** [label_type c] creates a type of a basic block in the context [c]. See + [llvm::Type::LabelTy]. *) +external label_type : llcontext -> lltype = "llvm_label_type" + +(** {7 Operations on type handles} *) + +(** [handle_to_type ty] creates a handle to the type [ty]. If [ty] is later + refined as a result of a call to {!refine_type}, the handle will be updated; + any bare [lltype] references will become invalid. + See the class [llvm::PATypeHolder]. *) +external handle_to_type : lltype -> lltypehandle = "llvm_handle_to_type" + +(** [type_of_handle tyh] resolves the type handle [tyh]. + See the method [llvm::PATypeHolder::get()]. *) +external type_of_handle : lltypehandle -> lltype = "llvm_type_of_handle" + +(** [refine_type opaque_ty ty] replaces the abstract type [opaque_ty] with the + concrete type [ty] in all users. Warning: This may invalidate {!lltype} + values! Use {!lltypehandle} to manipulate potentially abstract types. See + the method [llvm::Type::refineAbstractType]. *) +external refine_type : lltype -> lltype -> unit = "llvm_refine_type" + + +(* {6 Values} *) + +(** [type_of v] returns the type of the value [v]. + See the method [llvm::Value::getType]. *) +external type_of : llvalue -> lltype = "llvm_type_of" + +(** [value_name v] returns the name of the value [v]. For global values, this is + the symbol name. For instructions and basic blocks, it is the SSA register + name. It is meaningless for constants. + See the method [llvm::Value::getName]. *) +external value_name : llvalue -> string = "llvm_value_name" + +(** [set_value_name n v] sets the name of the value [v] to [n]. See the method + [llvm::Value::setName]. *) +external set_value_name : string -> llvalue -> unit = "llvm_set_value_name" + +(** [dump_value v] prints the .ll representation of the value [v] to standard + error. See the method [llvm::Value::dump]. *) +external dump_value : llvalue -> unit = "llvm_dump_value" + +(** [replace_all_uses_with old new] replaces all uses of the value [old] + * with the value [new]. See the method [llvm::Value::replaceAllUsesWith]. *) +external replace_all_uses_with : llvalue -> llvalue -> unit + = "LLVMReplaceAllUsesWith" + + +(* {6 Uses} *) + +(** [use_begin v] returns the first position in the use list for the value [v]. + [use_begin] and [use_succ] can e used to iterate over the use list in order. + See the method [llvm::Value::use_begin]. *) +external use_begin : llvalue -> lluse option = "llvm_use_begin" + +(** [use_succ u] returns the use list position succeeding [u]. + See the method [llvm::use_value_iterator::operator++]. *) +external use_succ : lluse -> lluse option = "llvm_use_succ" + +(** [user u] returns the user of the use [u]. + See the method [llvm::Use::getUser]. *) +external user : lluse -> llvalue = "llvm_user" + +(** [used_value u] returns the usee of the use [u]. + See the method [llvm::Use::getUsedValue]. *) +external used_value : lluse -> llvalue = "llvm_used_value" + +(** [iter_uses f v] applies function [f] to each of the users of the value [v] + in order. Tail recursive. *) +val iter_uses : (lluse -> unit) -> llvalue -> unit + +(** [fold_left_uses f init v] is [f (... (f init u1) ...) uN] where + [u1,...,uN] are the users of the value [v]. Tail recursive. *) +val fold_left_uses : ('a -> lluse -> 'a) -> 'a -> llvalue -> 'a + +(** [fold_right_uses f v init] is [f u1 (... (f uN init) ...)] where + [u1,...,uN] are the users of the value [v]. Not tail recursive. *) +val fold_right_uses : (lluse -> 'a -> 'a) -> llvalue -> 'a -> 'a + + +(* {6 Users} *) + +(** [operand v i] returns the operand at index [i] for the value [v]. See the + method [llvm::User::getOperand]. *) +external operand : llvalue -> int -> llvalue = "llvm_operand" + + +(** {7 Operations on constants of (mostly) any type} *) + +(** [is_constant v] returns [true] if the value [v] is a constant, [false] + otherwise. Similar to [llvm::isa<Constant>]. *) +external is_constant : llvalue -> bool = "llvm_is_constant" + +(** [const_null ty] returns the constant null (zero) of the type [ty]. + See the method [llvm::Constant::getNullValue]. *) +external const_null : lltype -> llvalue = "LLVMConstNull" + +(** [const_all_ones ty] returns the constant '-1' of the integer or vector type + [ty]. See the method [llvm::Constant::getAllOnesValue]. *) +external const_all_ones : (*int|vec*)lltype -> llvalue = "LLVMConstAllOnes" + +(** [const_pointer_null ty] returns the constant null (zero) pointer of the type + [ty]. See the method [llvm::ConstantPointerNull::get]. *) +external const_pointer_null : lltype -> llvalue = "LLVMConstPointerNull" + +(** [undef ty] returns the undefined value of the type [ty]. + See the method [llvm::UndefValue::get]. *) +external undef : lltype -> llvalue = "LLVMGetUndef" + +(** [is_null v] returns [true] if the value [v] is the null (zero) value. + See the method [llvm::Constant::isNullValue]. *) +external is_null : llvalue -> bool = "llvm_is_null" + +(** [is_undef v] returns [true] if the value [v] is an undefined value, [false] + otherwise. Similar to [llvm::isa<UndefValue>]. *) +external is_undef : llvalue -> bool = "llvm_is_undef" + + +(** {7 Operations on instructions} *) + +(** [has_metadata i] returns whether or not the instruction [i] has any + metadata attached to it. See the function + [llvm::Instruction::hasMetadata]. *) +external has_metadata : llvalue -> bool = "llvm_has_metadata" + +(** [metadata i kind] optionally returns the metadata associated with the + kind [kind] in the instruction [i] See the function + [llvm::Instruction::getMetadata]. *) +external metadata : llvalue -> int -> llvalue option = "llvm_metadata" + +(** [set_metadata i kind md] sets the metadata [md] of kind [kind] in the + instruction [i]. See the function [llvm::Instruction::setMetadata]. *) +external set_metadata : llvalue -> int -> llvalue -> unit = "llvm_set_metadata" + +(** [clear_metadata i kind] clears the metadata of kind [kind] in the + instruction [i]. See the function [llvm::Instruction::setMetadata]. *) +external clear_metadata : llvalue -> int -> unit = "llvm_clear_metadata" + + +(** {7 Operations on metadata} *) + +(** [mdstring c s] returns the MDString of the string [s] in the context [c]. + See the method [llvm::MDNode::get]. *) +external mdstring : llcontext -> string -> llvalue = "llvm_mdstring" + +(** [mdnode c elts] returns the MDNode containing the values [elts] in the + context [c]. + See the method [llvm::MDNode::get]. *) +external mdnode : llcontext -> llvalue array -> llvalue = "llvm_mdnode" + + +(** {7 Operations on scalar constants} *) + +(** [const_int ty i] returns the integer constant of type [ty] and value [i]. + See the method [llvm::ConstantInt::get]. *) +external const_int : lltype -> int -> llvalue = "llvm_const_int" + +(** [const_of_int64 ty i] returns the integer constant of type [ty] and value + [i]. See the method [llvm::ConstantInt::get]. *) +external const_of_int64 : lltype -> Int64.t -> bool -> llvalue + = "llvm_const_of_int64" + +(** [const_int_of_string ty s r] returns the integer constant of type [ty] and + * value [s], with the radix [r]. See the method [llvm::ConstantInt::get]. *) +external const_int_of_string : lltype -> string -> int -> llvalue + = "llvm_const_int_of_string" + +(** [const_float ty n] returns the floating point constant of type [ty] and + value [n]. See the method [llvm::ConstantFP::get]. *) +external const_float : lltype -> float -> llvalue = "llvm_const_float" + +(** [const_float_of_string ty s] returns the floating point constant of type + [ty] and value [n]. See the method [llvm::ConstantFP::get]. *) +external const_float_of_string : lltype -> string -> llvalue + = "llvm_const_float_of_string" + + +(** {7 Operations on composite constants} *) + +(** [const_string c s] returns the constant [i8] array with the values of the + characters in the string [s] in the context [c]. The array is not + null-terminated (but see {!const_stringz}). This value can in turn be used + as the initializer for a global variable. See the method + [llvm::ConstantArray::get]. *) +external const_string : llcontext -> string -> llvalue = "llvm_const_string" + +(** [const_stringz c s] returns the constant [i8] array with the values of the + characters in the string [s] and a null terminator in the context [c]. This + value can in turn be used as the initializer for a global variable. + See the method [llvm::ConstantArray::get]. *) +external const_stringz : llcontext -> string -> llvalue = "llvm_const_stringz" + +(** [const_array ty elts] returns the constant array of type + [array_type ty (Array.length elts)] and containing the values [elts]. + This value can in turn be used as the initializer for a global variable. + See the method [llvm::ConstantArray::get]. *) +external const_array : lltype -> llvalue array -> llvalue = "llvm_const_array" + +(** [const_struct context elts] returns the structured constant of type + [struct_type (Array.map type_of elts)] and containing the values [elts] + in the context [context]. This value can in turn be used as the initializer + for a global variable. See the method [llvm::ConstantStruct::get]. *) +external const_struct : llcontext -> llvalue array -> llvalue + = "llvm_const_struct" + +(** [const_packed_struct context elts] returns the structured constant of + type {!packed_struct_type} [(Array.map type_of elts)] and containing the + values [elts] in the context [context]. This value can in turn be used as + the initializer for a global variable. See the method + [llvm::ConstantStruct::get]. *) +external const_packed_struct : llcontext -> llvalue array -> llvalue + = "llvm_const_packed_struct" + +(** [const_vector elts] returns the vector constant of type + [vector_type (type_of elts.(0)) (Array.length elts)] and containing the + values [elts]. See the method [llvm::ConstantVector::get]. *) +external const_vector : llvalue array -> llvalue = "llvm_const_vector" + +(** [const_union ty v] returns the union constant of type [union_type tys] and + containing the value [v]. See the method [llvm::ConstantUnion::get]. *) +external const_union : lltype -> llvalue -> llvalue = "LLVMConstUnion" + + +(** {7 Constant expressions} *) + +(** [align_of ty] returns the alignof constant for the type [ty]. This is + equivalent to [const_ptrtoint (const_gep (const_null (pointer_type {i8,ty})) + (const_int i32_type 0) (const_int i32_type 1)) i32_type], but considerably + more readable. See the method [llvm::ConstantExpr::getAlignOf]. *) +external align_of : lltype -> llvalue = "LLVMAlignOf" + +(** [size_of ty] returns the sizeof constant for the type [ty]. This is + equivalent to [const_ptrtoint (const_gep (const_null (pointer_type ty)) + (const_int i32_type 1)) i64_type], but considerably more readable. + See the method [llvm::ConstantExpr::getSizeOf]. *) +external size_of : lltype -> llvalue = "LLVMSizeOf" + +(** [const_neg c] returns the arithmetic negation of the constant [c]. + See the method [llvm::ConstantExpr::getNeg]. *) +external const_neg : llvalue -> llvalue = "LLVMConstNeg" + +(** [const_nsw_neg c] returns the arithmetic negation of the constant [c] with + no signed wrapping. The result is undefined if the negation overflows. + See the method [llvm::ConstantExpr::getNSWNeg]. *) +external const_nsw_neg : llvalue -> llvalue = "LLVMConstNSWNeg" + +(** [const_nuw_neg c] returns the arithmetic negation of the constant [c] with + no unsigned wrapping. The result is undefined if the negation overflows. + See the method [llvm::ConstantExpr::getNUWNeg]. *) +external const_nuw_neg : llvalue -> llvalue = "LLVMConstNUWNeg" + +(** [const_fneg c] returns the arithmetic negation of the constant float [c]. + See the method [llvm::ConstantExpr::getFNeg]. *) +external const_fneg : llvalue -> llvalue = "LLVMConstFNeg" + +(** [const_not c] returns the bitwise inverse of the constant [c]. + See the method [llvm::ConstantExpr::getNot]. *) +external const_not : llvalue -> llvalue = "LLVMConstNot" + +(** [const_add c1 c2] returns the constant sum of two constants. + See the method [llvm::ConstantExpr::getAdd]. *) +external const_add : llvalue -> llvalue -> llvalue = "LLVMConstAdd" + +(** [const_nsw_add c1 c2] returns the constant sum of two constants with no + signed wrapping. The result is undefined if the sum overflows. + See the method [llvm::ConstantExpr::getNSWAdd]. *) +external const_nsw_add : llvalue -> llvalue -> llvalue = "LLVMConstNSWAdd" + +(** [const_nuw_add c1 c2] returns the constant sum of two constants with no + unsigned wrapping. The result is undefined if the sum overflows. + See the method [llvm::ConstantExpr::getNSWAdd]. *) +external const_nuw_add : llvalue -> llvalue -> llvalue = "LLVMConstNUWAdd" + +(** [const_fadd c1 c2] returns the constant sum of two constant floats. + See the method [llvm::ConstantExpr::getFAdd]. *) +external const_fadd : llvalue -> llvalue -> llvalue = "LLVMConstFAdd" + +(** [const_sub c1 c2] returns the constant difference, [c1 - c2], of two + constants. See the method [llvm::ConstantExpr::getSub]. *) +external const_sub : llvalue -> llvalue -> llvalue = "LLVMConstSub" + +(** [const_nsw_sub c1 c2] returns the constant difference of two constants with + no signed wrapping. The result is undefined if the sum overflows. + See the method [llvm::ConstantExpr::getNSWSub]. *) +external const_nsw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNSWSub" + +(** [const_nuw_sub c1 c2] returns the constant difference of two constants with + no unsigned wrapping. The result is undefined if the sum overflows. + See the method [llvm::ConstantExpr::getNSWSub]. *) +external const_nuw_sub : llvalue -> llvalue -> llvalue = "LLVMConstNUWSub" + +(** [const_fsub c1 c2] returns the constant difference, [c1 - c2], of two + constant floats. See the method [llvm::ConstantExpr::getFSub]. *) +external const_fsub : llvalue -> llvalue -> llvalue = "LLVMConstFSub" + +(** [const_mul c1 c2] returns the constant product of two constants. + See the method [llvm::ConstantExpr::getMul]. *) +external const_mul : llvalue -> llvalue -> llvalue = "LLVMConstMul" + +(** [const_nsw_mul c1 c2] returns the constant product of two constants with + no signed wrapping. The result is undefined if the sum overflows. + See the method [llvm::ConstantExpr::getNSWMul]. *) +external const_nsw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNSWMul" + +(** [const_nuw_mul c1 c2] returns the constant product of two constants with + no unsigned wrapping. The result is undefined if the sum overflows. + See the method [llvm::ConstantExpr::getNSWMul]. *) +external const_nuw_mul : llvalue -> llvalue -> llvalue = "LLVMConstNUWMul" + +(** [const_fmul c1 c2] returns the constant product of two constants floats. + See the method [llvm::ConstantExpr::getFMul]. *) +external const_fmul : llvalue -> llvalue -> llvalue = "LLVMConstFMul" + +(** [const_udiv c1 c2] returns the constant quotient [c1 / c2] of two unsigned + integer constants. + See the method [llvm::ConstantExpr::getUDiv]. *) +external const_udiv : llvalue -> llvalue -> llvalue = "LLVMConstUDiv" + +(** [const_sdiv c1 c2] returns the constant quotient [c1 / c2] of two signed + integer constants. + See the method [llvm::ConstantExpr::getSDiv]. *) +external const_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstSDiv" + +(** [const_exact_sdiv c1 c2] returns the constant quotient [c1 / c2] of two + signed integer constants. The result is undefined if the result is rounded + or overflows. See the method [llvm::ConstantExpr::getExactSDiv]. *) +external const_exact_sdiv : llvalue -> llvalue -> llvalue = "LLVMConstExactSDiv" + +(** [const_fdiv c1 c2] returns the constant quotient [c1 / c2] of two floating + point constants. + See the method [llvm::ConstantExpr::getFDiv]. *) +external const_fdiv : llvalue -> llvalue -> llvalue = "LLVMConstFDiv" + +(** [const_urem c1 c2] returns the constant remainder [c1 MOD c2] of two + unsigned integer constants. + See the method [llvm::ConstantExpr::getURem]. *) +external const_urem : llvalue -> llvalue -> llvalue = "LLVMConstURem" + +(** [const_srem c1 c2] returns the constant remainder [c1 MOD c2] of two + signed integer constants. + See the method [llvm::ConstantExpr::getSRem]. *) +external const_srem : llvalue -> llvalue -> llvalue = "LLVMConstSRem" + +(** [const_frem c1 c2] returns the constant remainder [c1 MOD c2] of two + signed floating point constants. + See the method [llvm::ConstantExpr::getFRem]. *) +external const_frem : llvalue -> llvalue -> llvalue = "LLVMConstFRem" + +(** [const_and c1 c2] returns the constant bitwise [AND] of two integer + constants. + See the method [llvm::ConstantExpr::getAnd]. *) +external const_and : llvalue -> llvalue -> llvalue = "LLVMConstAnd" + +(** [const_or c1 c2] returns the constant bitwise [OR] of two integer + constants. + See the method [llvm::ConstantExpr::getOr]. *) +external const_or : llvalue -> llvalue -> llvalue = "LLVMConstOr" + +(** [const_xor c1 c2] returns the constant bitwise [XOR] of two integer + constants. + See the method [llvm::ConstantExpr::getXor]. *) +external const_xor : llvalue -> llvalue -> llvalue = "LLVMConstXor" + +(** [const_icmp pred c1 c2] returns the constant comparison of two integer + constants, [c1 pred c2]. + See the method [llvm::ConstantExpr::getICmp]. *) +external const_icmp : Icmp.t -> llvalue -> llvalue -> llvalue + = "llvm_const_icmp" + +(** [const_fcmp pred c1 c2] returns the constant comparison of two floating + point constants, [c1 pred c2]. + See the method [llvm::ConstantExpr::getFCmp]. *) +external const_fcmp : Fcmp.t -> llvalue -> llvalue -> llvalue + = "llvm_const_fcmp" + +(** [const_shl c1 c2] returns the constant integer [c1] left-shifted by the + constant integer [c2]. + See the method [llvm::ConstantExpr::getShl]. *) +external const_shl : llvalue -> llvalue -> llvalue = "LLVMConstShl" + +(** [const_lshr c1 c2] returns the constant integer [c1] right-shifted by the + constant integer [c2] with zero extension. + See the method [llvm::ConstantExpr::getLShr]. *) +external const_lshr : llvalue -> llvalue -> llvalue = "LLVMConstLShr" + +(** [const_ashr c1 c2] returns the constant integer [c1] right-shifted by the + constant integer [c2] with sign extension. + See the method [llvm::ConstantExpr::getAShr]. *) +external const_ashr : llvalue -> llvalue -> llvalue = "LLVMConstAShr" + +(** [const_gep pc indices] returns the constant [getElementPtr] of [p1] with the + constant integers indices from the array [indices]. + See the method [llvm::ConstantExpr::getGetElementPtr]. *) +external const_gep : llvalue -> llvalue array -> llvalue = "llvm_const_gep" + +(** [const_in_bounds_gep pc indices] returns the constant [getElementPtr] of [p1] + with the constant integers indices from the array [indices]. + See the method [llvm::ConstantExpr::getInBoundsGetElementPtr]. *) +external const_in_bounds_gep : llvalue -> llvalue array -> llvalue + = "llvm_const_in_bounds_gep" + +(** [const_trunc c ty] returns the constant truncation of integer constant [c] + to the smaller integer type [ty]. + See the method [llvm::ConstantExpr::getTrunc]. *) +external const_trunc : llvalue -> lltype -> llvalue = "LLVMConstTrunc" + +(** [const_sext c ty] returns the constant sign extension of integer constant + [c] to the larger integer type [ty]. + See the method [llvm::ConstantExpr::getSExt]. *) +external const_sext : llvalue -> lltype -> llvalue = "LLVMConstSExt" + +(** [const_zext c ty] returns the constant zero extension of integer constant + [c] to the larger integer type [ty]. + See the method [llvm::ConstantExpr::getZExt]. *) +external const_zext : llvalue -> lltype -> llvalue = "LLVMConstZExt" + +(** [const_fptrunc c ty] returns the constant truncation of floating point + constant [c] to the smaller floating point type [ty]. + See the method [llvm::ConstantExpr::getFPTrunc]. *) +external const_fptrunc : llvalue -> lltype -> llvalue = "LLVMConstFPTrunc" + +(** [const_fpext c ty] returns the constant extension of floating point constant + [c] to the larger floating point type [ty]. + See the method [llvm::ConstantExpr::getFPExt]. *) +external const_fpext : llvalue -> lltype -> llvalue = "LLVMConstFPExt" + +(** [const_uitofp c ty] returns the constant floating point conversion of + unsigned integer constant [c] to the floating point type [ty]. + See the method [llvm::ConstantExpr::getUIToFP]. *) +external const_uitofp : llvalue -> lltype -> llvalue = "LLVMConstUIToFP" + +(** [const_sitofp c ty] returns the constant floating point conversion of + signed integer constant [c] to the floating point type [ty]. + See the method [llvm::ConstantExpr::getSIToFP]. *) +external const_sitofp : llvalue -> lltype -> llvalue = "LLVMConstSIToFP" + +(** [const_fptoui c ty] returns the constant unsigned integer conversion of + floating point constant [c] to integer type [ty]. + See the method [llvm::ConstantExpr::getFPToUI]. *) +external const_fptoui : llvalue -> lltype -> llvalue = "LLVMConstFPToUI" + +(** [const_fptoui c ty] returns the constant unsigned integer conversion of + floating point constant [c] to integer type [ty]. + See the method [llvm::ConstantExpr::getFPToSI]. *) +external const_fptosi : llvalue -> lltype -> llvalue = "LLVMConstFPToSI" + +(** [const_ptrtoint c ty] returns the constant integer conversion of + pointer constant [c] to integer type [ty]. + See the method [llvm::ConstantExpr::getPtrToInt]. *) +external const_ptrtoint : llvalue -> lltype -> llvalue = "LLVMConstPtrToInt" + +(** [const_inttoptr c ty] returns the constant pointer conversion of + integer constant [c] to pointer type [ty]. + See the method [llvm::ConstantExpr::getIntToPtr]. *) +external const_inttoptr : llvalue -> lltype -> llvalue = "LLVMConstIntToPtr" + +(** [const_bitcast c ty] returns the constant bitwise conversion of constant [c] + to type [ty] of equal size. + See the method [llvm::ConstantExpr::getBitCast]. *) +external const_bitcast : llvalue -> lltype -> llvalue = "LLVMConstBitCast" + +(** [const_zext_or_bitcast c ty] returns a constant zext or bitwise cast + conversion of constant [c] to type [ty]. + See the method [llvm::ConstantExpr::getZExtOrBitCast]. *) +external const_zext_or_bitcast : llvalue -> lltype -> llvalue + = "LLVMConstZExtOrBitCast" + +(** [const_sext_or_bitcast c ty] returns a constant sext or bitwise cast + conversion of constant [c] to type [ty]. + See the method [llvm::ConstantExpr::getSExtOrBitCast]. *) +external const_sext_or_bitcast : llvalue -> lltype -> llvalue + = "LLVMConstSExtOrBitCast" + +(** [const_trunc_or_bitcast c ty] returns a constant trunc or bitwise cast + conversion of constant [c] to type [ty]. + See the method [llvm::ConstantExpr::getTruncOrBitCast]. *) +external const_trunc_or_bitcast : llvalue -> lltype -> llvalue + = "LLVMConstTruncOrBitCast" + +(** [const_pointercast c ty] returns a constant bitcast or a pointer-to-int + cast conversion of constant [c] to type [ty] of equal size. + See the method [llvm::ConstantExpr::getPointerCast]. *) +external const_pointercast : llvalue -> lltype -> llvalue + = "LLVMConstPointerCast" + +(** [const_intcast c ty] returns a constant zext, bitcast, or trunc for integer + -> integer casts of constant [c] to type [ty]. + See the method [llvm::ConstantExpr::getIntCast]. *) +external const_intcast : llvalue -> lltype -> llvalue + = "LLVMConstIntCast" + +(** [const_fpcast c ty] returns a constant fpext, bitcast, or fptrunc for fp -> + fp casts of constant [c] to type [ty]. + See the method [llvm::ConstantExpr::getFPCast]. *) +external const_fpcast : llvalue -> lltype -> llvalue + = "LLVMConstFPCast" + +(** [const_select cond t f] returns the constant conditional which returns value + [t] if the boolean constant [cond] is true and the value [f] otherwise. + See the method [llvm::ConstantExpr::getSelect]. *) +external const_select : llvalue -> llvalue -> llvalue -> llvalue + = "LLVMConstSelect" + +(** [const_extractelement vec i] returns the constant [i]th element of + constant vector [vec]. [i] must be a constant [i32] value unsigned less than + the size of the vector. + See the method [llvm::ConstantExpr::getExtractElement]. *) +external const_extractelement : llvalue -> llvalue -> llvalue + = "LLVMConstExtractElement" + +(** [const_insertelement vec v i] returns the constant vector with the same + elements as constant vector [v] but the [i]th element replaced by the + constant [v]. [v] must be a constant value with the type of the vector + elements. [i] must be a constant [i32] value unsigned less than the size + of the vector. + See the method [llvm::ConstantExpr::getInsertElement]. *) +external const_insertelement : llvalue -> llvalue -> llvalue -> llvalue + = "LLVMConstInsertElement" + +(** [const_shufflevector a b mask] returns a constant [shufflevector]. + See the LLVM Language Reference for details on the [sufflevector] + instruction. + See the method [llvm::ConstantExpr::getShuffleVector]. *) +external const_shufflevector : llvalue -> llvalue -> llvalue -> llvalue + = "LLVMConstShuffleVector" + +(** [const_extractvalue agg idxs] returns the constant [idxs]th value of + constant aggregate [agg]. Each [idxs] must be less than the size of the + aggregate. See the method [llvm::ConstantExpr::getExtractValue]. *) +external const_extractvalue : llvalue -> int array -> llvalue + = "llvm_const_extractvalue" + +(** [const_insertvalue agg val idxs] inserts the value [val] in the specified + indexs [idxs] in the aggegate [agg]. Each [idxs] must be less than the size + of the aggregate. See the method [llvm::ConstantExpr::getInsertValue]. *) +external const_insertvalue : llvalue -> llvalue -> int array -> llvalue + = "llvm_const_insertvalue" + +(** [const_inline_asm ty asm con side align] inserts a inline assembly string. + See the method [llvm::InlineAsm::get]. *) +external const_inline_asm : lltype -> string -> string -> bool -> bool -> + llvalue + = "llvm_const_inline_asm" + +(** [block_address f bb] returns the address of the basic block [bb] in the + function [f]. See the method [llvm::BasicBlock::get]. *) +external block_address : llvalue -> llbasicblock -> llvalue = "LLVMBlockAddress" + + +(** {7 Operations on global variables, functions, and aliases (globals)} *) + +(** [global_parent g] is the enclosing module of the global value [g]. + See the method [llvm::GlobalValue::getParent]. *) +external global_parent : llvalue -> llmodule = "LLVMGetGlobalParent" + +(** [is_declaration g] returns [true] if the global value [g] is a declaration + only. Returns [false] otherwise. + See the method [llvm::GlobalValue::isDeclaration]. *) +external is_declaration : llvalue -> bool = "llvm_is_declaration" + +(** [linkage g] returns the linkage of the global value [g]. + See the method [llvm::GlobalValue::getLinkage]. *) +external linkage : llvalue -> Linkage.t = "llvm_linkage" + +(** [set_linkage l g] sets the linkage of the global value [g] to [l]. + See the method [llvm::GlobalValue::setLinkage]. *) +external set_linkage : Linkage.t -> llvalue -> unit = "llvm_set_linkage" + +(** [section g] returns the linker section of the global value [g]. + See the method [llvm::GlobalValue::getSection]. *) +external section : llvalue -> string = "llvm_section" + +(** [set_section s g] sets the linker section of the global value [g] to [s]. + See the method [llvm::GlobalValue::setSection]. *) +external set_section : string -> llvalue -> unit = "llvm_set_section" + +(** [visibility g] returns the linker visibility of the global value [g]. + See the method [llvm::GlobalValue::getVisibility]. *) +external visibility : llvalue -> Visibility.t = "llvm_visibility" + +(** [set_visibility v g] sets the linker visibility of the global value [g] to + [v]. See the method [llvm::GlobalValue::setVisibility]. *) +external set_visibility : Visibility.t -> llvalue -> unit + = "llvm_set_visibility" + +(** [alignment g] returns the required alignment of the global value [g]. + See the method [llvm::GlobalValue::getAlignment]. *) +external alignment : llvalue -> int = "llvm_alignment" + +(** [set_alignment n g] sets the required alignment of the global value [g] to + [n] bytes. See the method [llvm::GlobalValue::setAlignment]. *) +external set_alignment : int -> llvalue -> unit = "llvm_set_alignment" + + +(** {7 Operations on global variables} *) + +(** [declare_global ty name m] returns a new global variable of type [ty] and + with name [name] in module [m] in the default address space (0). If such a + global variable already exists, it is returned. If the type of the existing + global differs, then a bitcast to [ty] is returned. *) +external declare_global : lltype -> string -> llmodule -> llvalue + = "llvm_declare_global" + +(** [declare_qualified_global ty name addrspace m] returns a new global variable + of type [ty] and with name [name] in module [m] in the address space + [addrspace]. If such a global variable already exists, it is returned. If + the type of the existing global differs, then a bitcast to [ty] is + returned. *) +external declare_qualified_global : lltype -> string -> int -> llmodule -> + llvalue + = "llvm_declare_qualified_global" + +(** [define_global name init m] returns a new global with name [name] and + initializer [init] in module [m] in the default address space (0). If the + named global already exists, it is renamed. + See the constructor of [llvm::GlobalVariable]. *) +external define_global : string -> llvalue -> llmodule -> llvalue + = "llvm_define_global" + +(** [define_qualified_global name init addrspace m] returns a new global with + name [name] and initializer [init] in module [m] in the address space + [addrspace]. If the named global already exists, it is renamed. + See the constructor of [llvm::GlobalVariable]. *) +external define_qualified_global : string -> llvalue -> int -> llmodule -> + llvalue + = "llvm_define_qualified_global" + +(** [lookup_global name m] returns [Some g] if a global variable with name + [name] exists in module [m]. If no such global exists, returns [None]. + See the [llvm::GlobalVariable] constructor. *) +external lookup_global : string -> llmodule -> llvalue option + = "llvm_lookup_global" + +(** [delete_global gv] destroys the global variable [gv]. + See the method [llvm::GlobalVariable::eraseFromParent]. *) +external delete_global : llvalue -> unit = "llvm_delete_global" + +(** [global_begin m] returns the first position in the global variable list of + the module [m]. [global_begin] and [global_succ] can be used to iterate + over the global list in order. + See the method [llvm::Module::global_begin]. *) +external global_begin : llmodule -> (llmodule, llvalue) llpos + = "llvm_global_begin" + +(** [global_succ gv] returns the global variable list position succeeding + [Before gv]. + See the method [llvm::Module::global_iterator::operator++]. *) +external global_succ : llvalue -> (llmodule, llvalue) llpos + = "llvm_global_succ" + +(** [iter_globals f m] applies function [f] to each of the global variables of + module [m] in order. Tail recursive. *) +val iter_globals : (llvalue -> unit) -> llmodule -> unit + +(** [fold_left_globals f init m] is [f (... (f init g1) ...) gN] where + [g1,...,gN] are the global variables of module [m]. Tail recursive. *) +val fold_left_globals : ('a -> llvalue -> 'a) -> 'a -> llmodule -> 'a + +(** [global_end m] returns the last position in the global variable list of the + module [m]. [global_end] and [global_pred] can be used to iterate over the + global list in reverse. + See the method [llvm::Module::global_end]. *) +external global_end : llmodule -> (llmodule, llvalue) llrev_pos + = "llvm_global_end" + +(** [global_pred gv] returns the global variable list position preceding + [After gv]. + See the method [llvm::Module::global_iterator::operator--]. *) +external global_pred : llvalue -> (llmodule, llvalue) llrev_pos + = "llvm_global_pred" + +(** [rev_iter_globals f m] applies function [f] to each of the global variables + of module [m] in reverse order. Tail recursive. *) +val rev_iter_globals : (llvalue -> unit) -> llmodule -> unit + +(** [fold_right_globals f m init] is [f g1 (... (f gN init) ...)] where + [g1,...,gN] are the global variables of module [m]. Tail recursive. *) +val fold_right_globals : (llvalue -> 'a -> 'a) -> llmodule -> 'a -> 'a + +(** [is_global_constant gv] returns [true] if the global variabile [gv] is a + constant. Returns [false] otherwise. + See the method [llvm::GlobalVariable::isConstant]. *) +external is_global_constant : llvalue -> bool = "llvm_is_global_constant" + +(** [set_global_constant c gv] sets the global variable [gv] to be a constant if + [c] is [true] and not if [c] is [false]. + See the method [llvm::GlobalVariable::setConstant]. *) +external set_global_constant : bool -> llvalue -> unit + = "llvm_set_global_constant" + +(** [global_initializer gv] returns the initializer for the global variable + [gv]. See the method [llvm::GlobalVariable::getInitializer]. *) +external global_initializer : llvalue -> llvalue = "LLVMGetInitializer" + +(** [set_initializer c gv] sets the initializer for the global variable + [gv] to the constant [c]. + See the method [llvm::GlobalVariable::setInitializer]. *) +external set_initializer : llvalue -> llvalue -> unit = "llvm_set_initializer" + +(** [remove_initializer gv] unsets the initializer for the global variable + [gv]. + See the method [llvm::GlobalVariable::setInitializer]. *) +external remove_initializer : llvalue -> unit = "llvm_remove_initializer" + +(** [is_thread_local gv] returns [true] if the global variable [gv] is + thread-local and [false] otherwise. + See the method [llvm::GlobalVariable::isThreadLocal]. *) +external is_thread_local : llvalue -> bool = "llvm_is_thread_local" + +(** [set_thread_local c gv] sets the global variable [gv] to be thread local if + [c] is [true] and not otherwise. + See the method [llvm::GlobalVariable::setThreadLocal]. *) +external set_thread_local : bool -> llvalue -> unit = "llvm_set_thread_local" + + +(** {7 Operations on aliases} *) + +(** [add_alias m t a n] inserts an alias in the module [m] with the type [t] and + the aliasee [a] with the name [n]. + See the constructor for [llvm::GlobalAlias]. *) +external add_alias : llmodule -> lltype -> llvalue -> string -> llvalue + = "llvm_add_alias" + + +(** {7 Operations on functions} *) + +(** [declare_function name ty m] returns a new function of type [ty] and + with name [name] in module [m]. If such a function already exists, + it is returned. If the type of the existing function differs, then a bitcast + to [ty] is returned. *) +external declare_function : string -> lltype -> llmodule -> llvalue + = "llvm_declare_function" + +(** [define_function name ty m] creates a new function with name [name] and + type [ty] in module [m]. If the named function already exists, it is + renamed. An entry basic block is created in the function. + See the constructor of [llvm::GlobalVariable]. *) +external define_function : string -> lltype -> llmodule -> llvalue + = "llvm_define_function" + +(** [lookup_function name m] returns [Some f] if a function with name + [name] exists in module [m]. If no such function exists, returns [None]. + See the method [llvm::Module] constructor. *) +external lookup_function : string -> llmodule -> llvalue option + = "llvm_lookup_function" + +(** [delete_function f] destroys the function [f]. + See the method [llvm::Function::eraseFromParent]. *) +external delete_function : llvalue -> unit = "llvm_delete_function" + +(** [function_begin m] returns the first position in the function list of the + module [m]. [function_begin] and [function_succ] can be used to iterate over + the function list in order. + See the method [llvm::Module::begin]. *) +external function_begin : llmodule -> (llmodule, llvalue) llpos + = "llvm_function_begin" + +(** [function_succ gv] returns the function list position succeeding + [Before gv]. + See the method [llvm::Module::iterator::operator++]. *) +external function_succ : llvalue -> (llmodule, llvalue) llpos + = "llvm_function_succ" + +(** [iter_functions f m] applies function [f] to each of the functions of module + [m] in order. Tail recursive. *) +val iter_functions : (llvalue -> unit) -> llmodule -> unit + +(** [fold_left_function f init m] is [f (... (f init f1) ...) fN] where + [f1,...,fN] are the functions of module [m]. Tail recursive. *) +val fold_left_functions : ('a -> llvalue -> 'a) -> 'a -> llmodule -> 'a + +(** [function_end m] returns the last position in the function list of + the module [m]. [function_end] and [function_pred] can be used to iterate + over the function list in reverse. + See the method [llvm::Module::end]. *) +external function_end : llmodule -> (llmodule, llvalue) llrev_pos + = "llvm_function_end" + +(** [function_pred gv] returns the function list position preceding [After gv]. + See the method [llvm::Module::iterator::operator--]. *) +external function_pred : llvalue -> (llmodule, llvalue) llrev_pos + = "llvm_function_pred" + +(** [rev_iter_functions f fn] applies function [f] to each of the functions of + module [m] in reverse order. Tail recursive. *) +val rev_iter_functions : (llvalue -> unit) -> llmodule -> unit + +(** [fold_right_functions f m init] is [f (... (f init fN) ...) f1] where + [f1,...,fN] are the functions of module [m]. Tail recursive. *) +val fold_right_functions : (llvalue -> 'a -> 'a) -> llmodule -> 'a -> 'a + +(** [is_intrinsic f] returns true if the function [f] is an intrinsic. + See the method [llvm::Function::isIntrinsic]. *) +external is_intrinsic : llvalue -> bool = "llvm_is_intrinsic" + +(** [function_call_conv f] returns the calling convention of the function [f]. + See the method [llvm::Function::getCallingConv]. *) +external function_call_conv : llvalue -> int = "llvm_function_call_conv" + +(** [set_function_call_conv cc f] sets the calling convention of the function + [f] to the calling convention numbered [cc]. + See the method [llvm::Function::setCallingConv]. *) +external set_function_call_conv : int -> llvalue -> unit + = "llvm_set_function_call_conv" + +(** [gc f] returns [Some name] if the function [f] has a garbage + collection algorithm specified and [None] otherwise. + See the method [llvm::Function::getGC]. *) +external gc : llvalue -> string option = "llvm_gc" + +(** [set_gc gc f] sets the collection algorithm for the function [f] to + [gc]. See the method [llvm::Function::setGC]. *) +external set_gc : string option -> llvalue -> unit = "llvm_set_gc" + +(** [add_function_attr f a] adds attribute [a] to the return type of function + [f]. *) +val add_function_attr : llvalue -> Attribute.t -> unit + +(** [remove_function_attr f a] removes attribute [a] from the return type of + function [f]. *) +val remove_function_attr : llvalue -> Attribute.t -> unit + +(** {7 Operations on params} *) + +(** [params f] returns the parameters of function [f]. + See the method [llvm::Function::getArgumentList]. *) +external params : llvalue -> llvalue array = "llvm_params" + +(** [param f n] returns the [n]th parameter of function [f]. + See the method [llvm::Function::getArgumentList]. *) +external param : llvalue -> int -> llvalue = "llvm_param" + +(** [param_parent p] returns the parent function that owns the parameter. + See the method [llvm::Argument::getParent]. *) +external param_parent : llvalue -> llvalue = "LLVMGetParamParent" + +(** [param_begin f] returns the first position in the parameter list of the + function [f]. [param_begin] and [param_succ] can be used to iterate over + the parameter list in order. + See the method [llvm::Function::arg_begin]. *) +external param_begin : llvalue -> (llvalue, llvalue) llpos = "llvm_param_begin" + +(** [param_succ bb] returns the parameter list position succeeding + [Before bb]. + See the method [llvm::Function::arg_iterator::operator++]. *) +external param_succ : llvalue -> (llvalue, llvalue) llpos = "llvm_param_succ" + +(** [iter_params f fn] applies function [f] to each of the parameters + of function [fn] in order. Tail recursive. *) +val iter_params : (llvalue -> unit) -> llvalue -> unit + +(** [fold_left_params f init fn] is [f (... (f init b1) ...) bN] where + [b1,...,bN] are the parameters of function [fn]. Tail recursive. *) +val fold_left_params : ('a -> llvalue -> 'a) -> 'a -> llvalue -> 'a + +(** [param_end f] returns the last position in the parameter list of + the function [f]. [param_end] and [param_pred] can be used to iterate + over the parameter list in reverse. + See the method [llvm::Function::arg_end]. *) +external param_end : llvalue -> (llvalue, llvalue) llrev_pos = "llvm_param_end" + +(** [param_pred gv] returns the function list position preceding [After gv]. + See the method [llvm::Function::arg_iterator::operator--]. *) +external param_pred : llvalue -> (llvalue, llvalue) llrev_pos + = "llvm_param_pred" + +(** [rev_iter_params f fn] applies function [f] to each of the parameters + of function [fn] in reverse order. Tail recursive. *) +val rev_iter_params : (llvalue -> unit) -> llvalue -> unit + +(** [fold_right_params f fn init] is [f (... (f init bN) ...) b1] where + [b1,...,bN] are the parameters of function [fn]. Tail recursive. *) +val fold_right_params : (llvalue -> 'a -> 'a) -> llvalue -> 'a -> 'a + +(** [add_param p a] adds attribute [a] to parameter [p]. *) +val add_param_attr : llvalue -> Attribute.t -> unit + +(** [remove_param_attr p a] removes attribute [a] from parameter [p]. *) +val remove_param_attr : llvalue -> Attribute.t -> unit + +(** [set_param_alignment p a] set the alignment of parameter [p] to [a]. *) +external set_param_alignment : llvalue -> int -> unit + = "llvm_set_param_alignment" + +(** {7 Operations on basic blocks} *) + +(** [basic_blocks fn] returns the basic blocks of the function [f]. + See the method [llvm::Function::getBasicBlockList]. *) +external basic_blocks : llvalue -> llbasicblock array = "llvm_basic_blocks" + +(** [entry_block fn] returns the entry basic block of the function [f]. + See the method [llvm::Function::getEntryBlock]. *) +external entry_block : llvalue -> llbasicblock = "LLVMGetEntryBasicBlock" + +(** [delete_block bb] deletes the basic block [bb]. + See the method [llvm::BasicBlock::eraseFromParent]. *) +external delete_block : llbasicblock -> unit = "llvm_delete_block" + +(** [append_block c name f] creates a new basic block named [name] at the end of + function [f] in the context [c]. + See the constructor of [llvm::BasicBlock]. *) +external append_block : llcontext -> string -> llvalue -> llbasicblock + = "llvm_append_block" + +(** [insert_block c name bb] creates a new basic block named [name] before the + basic block [bb] in the context [c]. + See the constructor of [llvm::BasicBlock]. *) +external insert_block : llcontext -> string -> llbasicblock -> llbasicblock + = "llvm_insert_block" + +(** [block_parent bb] returns the parent function that owns the basic block. + See the method [llvm::BasicBlock::getParent]. *) +external block_parent : llbasicblock -> llvalue = "LLVMGetBasicBlockParent" + +(** [block_begin f] returns the first position in the basic block list of the + function [f]. [block_begin] and [block_succ] can be used to iterate over + the basic block list in order. + See the method [llvm::Function::begin]. *) +external block_begin : llvalue -> (llvalue, llbasicblock) llpos + = "llvm_block_begin" + +(** [block_succ bb] returns the basic block list position succeeding + [Before bb]. + See the method [llvm::Function::iterator::operator++]. *) +external block_succ : llbasicblock -> (llvalue, llbasicblock) llpos + = "llvm_block_succ" + +(** [iter_blocks f fn] applies function [f] to each of the basic blocks + of function [fn] in order. Tail recursive. *) +val iter_blocks : (llbasicblock -> unit) -> llvalue -> unit + +(** [fold_left_blocks f init fn] is [f (... (f init b1) ...) bN] where + [b1,...,bN] are the basic blocks of function [fn]. Tail recursive. *) +val fold_left_blocks : ('a -> llbasicblock -> 'a) -> 'a -> llvalue -> 'a + +(** [block_end f] returns the last position in the basic block list of + the function [f]. [block_end] and [block_pred] can be used to iterate + over the basic block list in reverse. + See the method [llvm::Function::end]. *) +external block_end : llvalue -> (llvalue, llbasicblock) llrev_pos + = "llvm_block_end" + +(** [block_pred gv] returns the function list position preceding [After gv]. + See the method [llvm::Function::iterator::operator--]. *) +external block_pred : llbasicblock -> (llvalue, llbasicblock) llrev_pos + = "llvm_block_pred" + +(** [rev_iter_blocks f fn] applies function [f] to each of the basic blocks + of function [fn] in reverse order. Tail recursive. *) +val rev_iter_blocks : (llbasicblock -> unit) -> llvalue -> unit + +(** [fold_right_blocks f fn init] is [f (... (f init bN) ...) b1] where + [b1,...,bN] are the basic blocks of function [fn]. Tail recursive. *) +val fold_right_blocks : (llbasicblock -> 'a -> 'a) -> llvalue -> 'a -> 'a + +(** [value_of_block bb] losslessly casts [bb] to an [llvalue]. *) +external value_of_block : llbasicblock -> llvalue = "LLVMBasicBlockAsValue" + +(** [value_is_block v] returns [true] if the value [v] is a basic block and + [false] otherwise. + Similar to [llvm::isa<BasicBlock>]. *) +external value_is_block : llvalue -> bool = "llvm_value_is_block" + +(** [block_of_value v] losslessly casts [v] to an [llbasicblock]. *) +external block_of_value : llvalue -> llbasicblock = "LLVMValueAsBasicBlock" + + +(** {7 Operations on instructions} *) + +(** [instr_parent i] is the enclosing basic block of the instruction [i]. + See the method [llvm::Instruction::getParent]. *) +external instr_parent : llvalue -> llbasicblock = "LLVMGetInstructionParent" + +(** [instr_begin bb] returns the first position in the instruction list of the + basic block [bb]. [instr_begin] and [instr_succ] can be used to iterate over + the instruction list in order. + See the method [llvm::BasicBlock::begin]. *) +external instr_begin : llbasicblock -> (llbasicblock, llvalue) llpos + = "llvm_instr_begin" + +(** [instr_succ i] returns the instruction list position succeeding [Before i]. + See the method [llvm::BasicBlock::iterator::operator++]. *) +external instr_succ : llvalue -> (llbasicblock, llvalue) llpos + = "llvm_instr_succ" + +(** [iter_instrs f bb] applies function [f] to each of the instructions of basic + block [bb] in order. Tail recursive. *) +val iter_instrs: (llvalue -> unit) -> llbasicblock -> unit + +(** [fold_left_instrs f init bb] is [f (... (f init g1) ...) gN] where + [g1,...,gN] are the instructions of basic block [bb]. Tail recursive. *) +val fold_left_instrs: ('a -> llvalue -> 'a) -> 'a -> llbasicblock -> 'a + +(** [instr_end bb] returns the last position in the instruction list of the + basic block [bb]. [instr_end] and [instr_pred] can be used to iterate over + the instruction list in reverse. + See the method [llvm::BasicBlock::end]. *) +external instr_end : llbasicblock -> (llbasicblock, llvalue) llrev_pos + = "llvm_instr_end" + +(** [instr_pred i] returns the instruction list position preceding [After i]. + See the method [llvm::BasicBlock::iterator::operator--]. *) +external instr_pred : llvalue -> (llbasicblock, llvalue) llrev_pos + = "llvm_instr_pred" + +(** [fold_right_instrs f bb init] is [f (... (f init fN) ...) f1] where + [f1,...,fN] are the instructions of basic block [bb]. Tail recursive. *) +val fold_right_instrs: (llvalue -> 'a -> 'a) -> llbasicblock -> 'a -> 'a + + +(** {7 Operations on call sites} *) + +(** [instruction_call_conv ci] is the calling convention for the call or invoke + instruction [ci], which may be one of the values from the module + {!CallConv}. See the method [llvm::CallInst::getCallingConv] and + [llvm::InvokeInst::getCallingConv]. *) +external instruction_call_conv: llvalue -> int + = "llvm_instruction_call_conv" + +(** [set_instruction_call_conv cc ci] sets the calling convention for the call + or invoke instruction [ci] to the integer [cc], which can be one of the + values from the module {!CallConv}. + See the method [llvm::CallInst::setCallingConv] + and [llvm::InvokeInst::setCallingConv]. *) +external set_instruction_call_conv: int -> llvalue -> unit + = "llvm_set_instruction_call_conv" + +(** [add_instruction_param_attr ci i a] adds attribute [a] to the [i]th + parameter of the call or invoke instruction [ci]. [i]=0 denotes the return + value. *) +val add_instruction_param_attr : llvalue -> int -> Attribute.t -> unit + +(** [remove_instruction_param_attr ci i a] removes attribute [a] from the + [i]th parameter of the call or invoke instruction [ci]. [i]=0 denotes the + return value. *) +val remove_instruction_param_attr : llvalue -> int -> Attribute.t -> unit + +(** {Operations on call instructions (only)} *) + +(** [is_tail_call ci] is [true] if the call instruction [ci] is flagged as + eligible for tail call optimization, [false] otherwise. + See the method [llvm::CallInst::isTailCall]. *) +external is_tail_call : llvalue -> bool = "llvm_is_tail_call" + +(** [set_tail_call tc ci] flags the call instruction [ci] as eligible for tail + call optimization if [tc] is [true], clears otherwise. + See the method [llvm::CallInst::setTailCall]. *) +external set_tail_call : bool -> llvalue -> unit = "llvm_set_tail_call" + +(** {7 Operations on phi nodes} *) + +(** [add_incoming (v, bb) pn] adds the value [v] to the phi node [pn] for use + with branches from [bb]. See the method [llvm::PHINode::addIncoming]. *) +external add_incoming : (llvalue * llbasicblock) -> llvalue -> unit + = "llvm_add_incoming" + +(** [incoming pn] returns the list of value-block pairs for phi node [pn]. + See the method [llvm::PHINode::getIncomingValue]. *) +external incoming : llvalue -> (llvalue * llbasicblock) list = "llvm_incoming" + + + +(** {6 Instruction builders} *) + +(** [builder context] creates an instruction builder with no position in + the context [context]. It is invalid to use this builder until its position + is set with {!position_before} or {!position_at_end}. See the constructor + for [llvm::LLVMBuilder]. *) +external builder : llcontext -> llbuilder = "llvm_builder" + +(** [builder_at ip] creates an instruction builder positioned at [ip]. + See the constructor for [llvm::LLVMBuilder]. *) +val builder_at : llcontext -> (llbasicblock, llvalue) llpos -> llbuilder + +(** [builder_before ins] creates an instruction builder positioned before the + instruction [isn]. See the constructor for [llvm::LLVMBuilder]. *) +val builder_before : llcontext -> llvalue -> llbuilder + +(** [builder_at_end bb] creates an instruction builder positioned at the end of + the basic block [bb]. See the constructor for [llvm::LLVMBuilder]. *) +val builder_at_end : llcontext -> llbasicblock -> llbuilder + +(** [position_builder ip bb] moves the instruction builder [bb] to the position + [ip]. + See the constructor for [llvm::LLVMBuilder]. *) +external position_builder : (llbasicblock, llvalue) llpos -> llbuilder -> unit + = "llvm_position_builder" + +(** [position_before ins b] moves the instruction builder [b] to before the + instruction [isn]. See the method [llvm::LLVMBuilder::SetInsertPoint]. *) +val position_before : llvalue -> llbuilder -> unit + +(** [position_at_end bb b] moves the instruction builder [b] to the end of the + basic block [bb]. See the method [llvm::LLVMBuilder::SetInsertPoint]. *) +val position_at_end : llbasicblock -> llbuilder -> unit + +(** [insertion_block b] returns the basic block that the builder [b] is + positioned to insert into. Raises [Not_Found] if the instruction builder is + uninitialized. + See the method [llvm::LLVMBuilder::GetInsertBlock]. *) +external insertion_block : llbuilder -> llbasicblock = "llvm_insertion_block" + +(** [insert_into_builder i name b] inserts the specified instruction [i] at the + position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::Insert]. *) +external insert_into_builder : llvalue -> string -> llbuilder -> unit + = "llvm_insert_into_builder" + +(** {7 Metadata} *) + +(** [set_current_debug_location b md] sets the current debug location [md] in + the builder [b]. + See the method [llvm::IRBuilder::SetDebugLocation]. *) +external set_current_debug_location : llbuilder -> llvalue -> unit + = "llvm_set_current_debug_location" + +(** [clear_current_debug_location b] clears the current debug location in the + builder [b]. *) +external clear_current_debug_location : llbuilder -> unit + = "llvm_clear_current_debug_location" + +(** [current_debug_location b] returns the current debug location, or None + if none is currently set. + See the method [llvm::IRBuilder::GetDebugLocation]. *) +external current_debug_location : llbuilder -> llvalue option + = "llvm_current_debug_location" + +(** [set_inst_debug_location b i] sets the current debug location of the builder + [b] to the instruction [i]. + See the method [llvm::IRBuilder::SetInstDebugLocation]. *) +external set_inst_debug_location : llbuilder -> llvalue -> unit + = "llvm_set_inst_debug_location" + +(** {7 Terminators} *) + +(** [build_ret_void b] creates a + [ret void] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateRetVoid]. *) +external build_ret_void : llbuilder -> llvalue = "llvm_build_ret_void" + +(** [build_ret v b] creates a + [ret %v] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateRet]. *) +external build_ret : llvalue -> llbuilder -> llvalue = "llvm_build_ret" + +(** [build_aggregate_ret vs b] creates a + [ret {...} { %v1, %v2, ... } ] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateAggregateRet]. *) +external build_aggregate_ret : llvalue array -> llbuilder -> llvalue + = "llvm_build_aggregate_ret" + +(** [build_br bb b] creates a + [br %bb] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateBr]. *) +external build_br : llbasicblock -> llbuilder -> llvalue = "llvm_build_br" + +(** [build_cond_br cond tbb fbb b] creates a + [br %cond, %tbb, %fbb] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateCondBr]. *) +external build_cond_br : llvalue -> llbasicblock -> llbasicblock -> llbuilder -> + llvalue = "llvm_build_cond_br" + +(** [build_switch case elsebb count b] creates an empty + [switch %case, %elsebb] + instruction at the position specified by the instruction builder [b] with + space reserved for [count] cases. + See the method [llvm::LLVMBuilder::CreateSwitch]. *) +external build_switch : llvalue -> llbasicblock -> int -> llbuilder -> llvalue + = "llvm_build_switch" + +(** [add_case sw onval bb] causes switch instruction [sw] to branch to [bb] + when its input matches the constant [onval]. + See the method [llvm::SwitchInst::addCase]. **) +external add_case : llvalue -> llvalue -> llbasicblock -> unit + = "llvm_add_case" + +(** [build_indirect_br addr count b] creates a + [indirectbr %addr] + instruction at the position specified by the instruction builder [b] with + space reserved for [count] destinations. + See the method [llvm::LLVMBuilder::CreateIndirectBr]. *) +external build_indirect_br : llvalue -> int -> llbuilder -> llvalue + = "llvm_build_indirect_br" + +(** [add_destination br bb] adds the basic block [bb] as a possible branch + location for the indirectbr instruction [br]. + See the method [llvm::IndirectBrInst::addDestination]. **) +external add_destination : llvalue -> llbasicblock -> unit + = "llvm_add_destination" + +(** [build_invoke fn args tobb unwindbb name b] creates an + [%name = invoke %fn(args) to %tobb unwind %unwindbb] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateInvoke]. *) +external build_invoke : llvalue -> llvalue array -> llbasicblock -> + llbasicblock -> string -> llbuilder -> llvalue + = "llvm_build_invoke_bc" "llvm_build_invoke_nat" + +(** [build_unwind b] creates an + [unwind] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateUnwind]. *) +external build_unwind : llbuilder -> llvalue = "llvm_build_unwind" + +(** [build_unreachable b] creates an + [unreachable] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateUnwind]. *) +external build_unreachable : llbuilder -> llvalue = "llvm_build_unreachable" + + +(** {7 Arithmetic} *) + +(** [build_add x y name b] creates a + [%name = add %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateAdd]. *) +external build_add : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_add" + +(** [build_nsw_add x y name b] creates a + [%name = nsw add %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateNSWAdd]. *) +external build_nsw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_add" + +(** [build_nuw_add x y name b] creates a + [%name = nuw add %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateNUWAdd]. *) +external build_nuw_add : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_add" + +(** [build_fadd x y name b] creates a + [%name = fadd %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFAdd]. *) +external build_fadd : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fadd" + +(** [build_sub x y name b] creates a + [%name = sub %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateSub]. *) +external build_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_sub" + +(** [build_nsw_sub x y name b] creates a + [%name = nsw sub %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateNSWSub]. *) +external build_nsw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_sub" + +(** [build_nuw_sub x y name b] creates a + [%name = nuw sub %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateNUWSub]. *) +external build_nuw_sub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_sub" + +(** [build_fsub x y name b] creates a + [%name = fsub %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFSub]. *) +external build_fsub : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fsub" + +(** [build_mul x y name b] creates a + [%name = mul %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateMul]. *) +external build_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_mul" + +(** [build_nsw_mul x y name b] creates a + [%name = nsw mul %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateNSWMul]. *) +external build_nsw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_mul" + +(** [build_nuw_mul x y name b] creates a + [%name = nuw mul %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateNUWMul]. *) +external build_nuw_mul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_mul" + +(** [build_fmul x y name b] creates a + [%name = fmul %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFMul]. *) +external build_fmul : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fmul" + +(** [build_udiv x y name b] creates a + [%name = udiv %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateUDiv]. *) +external build_udiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_udiv" + +(** [build_sdiv x y name b] creates a + [%name = sdiv %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateSDiv]. *) +external build_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_sdiv" + +(** [build_exact_sdiv x y name b] creates a + [%name = exact sdiv %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateExactSDiv]. *) +external build_exact_sdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_exact_sdiv" + +(** [build_fdiv x y name b] creates a + [%name = fdiv %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFDiv]. *) +external build_fdiv : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fdiv" + +(** [build_urem x y name b] creates a + [%name = urem %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateURem]. *) +external build_urem : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_urem" + +(** [build_SRem x y name b] creates a + [%name = srem %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateSRem]. *) +external build_srem : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_srem" + +(** [build_frem x y name b] creates a + [%name = frem %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFRem]. *) +external build_frem : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_frem" + +(** [build_shl x y name b] creates a + [%name = shl %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateShl]. *) +external build_shl : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_shl" + +(** [build_lshr x y name b] creates a + [%name = lshr %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateLShr]. *) +external build_lshr : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_lshr" + +(** [build_ashr x y name b] creates a + [%name = ashr %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateAShr]. *) +external build_ashr : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_ashr" + +(** [build_and x y name b] creates a + [%name = and %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateAnd]. *) +external build_and : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_and" + +(** [build_or x y name b] creates a + [%name = or %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateOr]. *) +external build_or : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_or" + +(** [build_xor x y name b] creates a + [%name = xor %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateXor]. *) +external build_xor : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_xor" + +(** [build_neg x name b] creates a + [%name = sub 0, %x] + instruction at the position specified by the instruction builder [b]. + [-0.0] is used for floating point types to compute the correct sign. + See the method [llvm::LLVMBuilder::CreateNeg]. *) +external build_neg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_neg" + +(** [build_nsw_neg x name b] creates a + [%name = nsw sub 0, %x] + instruction at the position specified by the instruction builder [b]. + [-0.0] is used for floating point types to compute the correct sign. + See the method [llvm::LLVMBuilder::CreateNeg]. *) +external build_nsw_neg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nsw_neg" + +(** [build_nuw_neg x name b] creates a + [%name = nuw sub 0, %x] + instruction at the position specified by the instruction builder [b]. + [-0.0] is used for floating point types to compute the correct sign. + See the method [llvm::LLVMBuilder::CreateNeg]. *) +external build_nuw_neg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_nuw_neg" + +(** [build_fneg x name b] creates a + [%name = fsub 0, %x] + instruction at the position specified by the instruction builder [b]. + [-0.0] is used for floating point types to compute the correct sign. + See the method [llvm::LLVMBuilder::CreateFNeg]. *) +external build_fneg : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_fneg" + +(** [build_xor x name b] creates a + [%name = xor %x, -1] + instruction at the position specified by the instruction builder [b]. + [-1] is the correct "all ones" value for the type of [x]. + See the method [llvm::LLVMBuilder::CreateXor]. *) +external build_not : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_not" + + +(** {7 Memory} *) + +(** [build_alloca ty name b] creates a + [%name = alloca %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateAlloca]. *) +external build_alloca : lltype -> string -> llbuilder -> llvalue + = "llvm_build_alloca" + +(** [build_array_alloca ty n name b] creates a + [%name = alloca %ty, %n] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateAlloca]. *) +external build_array_alloca : lltype -> llvalue -> string -> llbuilder -> + llvalue = "llvm_build_array_alloca" + +(** [build_load v name b] creates a + [%name = load %v] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateLoad]. *) +external build_load : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_load" + +(** [build_store v p b] creates a + [store %v, %p] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateStore]. *) +external build_store : llvalue -> llvalue -> llbuilder -> llvalue + = "llvm_build_store" + +(** [build_gep p indices name b] creates a + [%name = getelementptr %p, indices...] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateGetElementPtr]. *) +external build_gep : llvalue -> llvalue array -> string -> llbuilder -> llvalue + = "llvm_build_gep" + +(** [build_in_bounds_gep p indices name b] creates a + [%name = gelementptr inbounds %p, indices...] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateInBoundsGetElementPtr]. *) +external build_in_bounds_gep : llvalue -> llvalue array -> string -> llbuilder -> + llvalue = "llvm_build_in_bounds_gep" + +(** [build_struct_gep p idx name b] creates a + [%name = getelementptr %p, 0, idx] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateStructGetElementPtr]. *) +external build_struct_gep : llvalue -> int -> string -> llbuilder -> + llvalue = "llvm_build_struct_gep" + +(** [build_global_string str name b] creates a series of instructions that adds + a global string at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateGlobalString]. *) +external build_global_string : string -> string -> llbuilder -> llvalue + = "llvm_build_global_string" + +(** [build_global_stringptr str name b] creates a series of instructions that + adds a global string pointer at the position specified by the instruction + builder [b]. + See the method [llvm::LLVMBuilder::CreateGlobalStringPtr]. *) +external build_global_stringptr : string -> string -> llbuilder -> llvalue + = "llvm_build_global_stringptr" + + +(** {7 Casts} *) + +(** [build_trunc v ty name b] creates a + [%name = trunc %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateTrunc]. *) +external build_trunc : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_trunc" + +(** [build_zext v ty name b] creates a + [%name = zext %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateZExt]. *) +external build_zext : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_zext" + +(** [build_sext v ty name b] creates a + [%name = sext %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateSExt]. *) +external build_sext : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_sext" + +(** [build_fptoui v ty name b] creates a + [%name = fptoui %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFPToUI]. *) +external build_fptoui : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fptoui" + +(** [build_fptosi v ty name b] creates a + [%name = fptosi %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFPToSI]. *) +external build_fptosi : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fptosi" + +(** [build_uitofp v ty name b] creates a + [%name = uitofp %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateUIToFP]. *) +external build_uitofp : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_uitofp" + +(** [build_sitofp v ty name b] creates a + [%name = sitofp %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateSIToFP]. *) +external build_sitofp : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_sitofp" + +(** [build_fptrunc v ty name b] creates a + [%name = fptrunc %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFPTrunc]. *) +external build_fptrunc : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fptrunc" + +(** [build_fpext v ty name b] creates a + [%name = fpext %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFPExt]. *) +external build_fpext : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fpext" + +(** [build_ptrtoint v ty name b] creates a + [%name = prtotint %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreatePtrToInt]. *) +external build_ptrtoint : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_prttoint" + +(** [build_inttoptr v ty name b] creates a + [%name = inttoptr %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateIntToPtr]. *) +external build_inttoptr : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_inttoptr" + +(** [build_bitcast v ty name b] creates a + [%name = bitcast %p to %ty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateBitCast]. *) +external build_bitcast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_bitcast" + +(** [build_zext_or_bitcast v ty name b] creates a zext or bitcast + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateZExtOrBitCast]. *) +external build_zext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> + llvalue = "llvm_build_zext_or_bitcast" + +(** [build_sext_or_bitcast v ty name b] creates a sext or bitcast + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateSExtOrBitCast]. *) +external build_sext_or_bitcast : llvalue -> lltype -> string -> llbuilder -> + llvalue = "llvm_build_sext_or_bitcast" + +(** [build_trunc_or_bitcast v ty name b] creates a trunc or bitcast + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateZExtOrBitCast]. *) +external build_trunc_or_bitcast : llvalue -> lltype -> string -> llbuilder -> + llvalue = "llvm_build_trunc_or_bitcast" + +(** [build_pointercast v ty name b] creates a bitcast or pointer-to-int + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreatePointerCast]. *) +external build_pointercast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_pointercast" + +(** [build_intcast v ty name b] creates a zext, bitcast, or trunc + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateIntCast]. *) +external build_intcast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_intcast" + +(** [build_fpcast v ty name b] creates a fpext, bitcast, or fptrunc + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFPCast]. *) +external build_fpcast : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_fpcast" + + +(** {7 Comparisons} *) + +(** [build_icmp pred x y name b] creates a + [%name = icmp %pred %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateICmp]. *) +external build_icmp : Icmp.t -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_icmp" + +(** [build_fcmp pred x y name b] creates a + [%name = fcmp %pred %x, %y] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateFCmp]. *) +external build_fcmp : Fcmp.t -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_fcmp" + + +(** {7 Miscellaneous instructions} *) + +(** [build_phi incoming name b] creates a + [%name = phi %incoming] + instruction at the position specified by the instruction builder [b]. + [incoming] is a list of [(llvalue, llbasicblock)] tuples. + See the method [llvm::LLVMBuilder::CreatePHI]. *) +external build_phi : (llvalue * llbasicblock) list -> string -> llbuilder -> + llvalue = "llvm_build_phi" + +(** [build_call fn args name b] creates a + [%name = call %fn(args...)] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateCall]. *) +external build_call : llvalue -> llvalue array -> string -> llbuilder -> llvalue + = "llvm_build_call" + +(** [build_select cond thenv elsev name b] creates a + [%name = select %cond, %thenv, %elsev] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateSelect]. *) +external build_select : llvalue -> llvalue -> llvalue -> string -> llbuilder -> + llvalue = "llvm_build_select" + +(** [build_va_arg valist argty name b] creates a + [%name = va_arg %valist, %argty] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateVAArg]. *) +external build_va_arg : llvalue -> lltype -> string -> llbuilder -> llvalue + = "llvm_build_va_arg" + +(** [build_extractelement vec i name b] creates a + [%name = extractelement %vec, %i] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateExtractElement]. *) +external build_extractelement : llvalue -> llvalue -> string -> llbuilder -> + llvalue = "llvm_build_extractelement" + +(** [build_insertelement vec elt i name b] creates a + [%name = insertelement %vec, %elt, %i] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateInsertElement]. *) +external build_insertelement : llvalue -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_insertelement" + +(** [build_shufflevector veca vecb mask name b] creates a + [%name = shufflevector %veca, %vecb, %mask] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateShuffleVector]. *) +external build_shufflevector : llvalue -> llvalue -> llvalue -> string -> + llbuilder -> llvalue = "llvm_build_shufflevector" + +(** [build_insertvalue agg idx name b] creates a + [%name = extractvalue %agg, %idx] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateExtractValue]. *) +external build_extractvalue : llvalue -> int -> string -> llbuilder -> llvalue + = "llvm_build_extractvalue" + +(** [build_insertvalue agg val idx name b] creates a + [%name = insertvalue %agg, %val, %idx] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateInsertValue]. *) +external build_insertvalue : llvalue -> llvalue -> int -> string -> llbuilder -> + llvalue = "llvm_build_insertvalue" + +(** [build_is_null val name b] creates a + [%name = icmp eq %val, null] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateIsNull]. *) +external build_is_null : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_is_null" + +(** [build_is_not_null val name b] creates a + [%name = icmp ne %val, null] + instruction at the position specified by the instruction builder [b]. + See the method [llvm::LLVMBuilder::CreateIsNotNull]. *) +external build_is_not_null : llvalue -> string -> llbuilder -> llvalue + = "llvm_build_is_not_null" + +(** [build_ptrdiff lhs rhs name b] creates a series of instructions that measure + the difference between two pointer values at the position specified by the + instruction builder [b]. + See the method [llvm::LLVMBuilder::CreatePtrDiff]. *) +external build_ptrdiff : llvalue -> llvalue -> string -> llbuilder -> llvalue + = "llvm_build_ptrdiff" + + +(** {6 Memory buffers} *) + +module MemoryBuffer : sig + (** [of_file p] is the memory buffer containing the contents of the file at + path [p]. If the file could not be read, then [IoError msg] is + raised. *) + external of_file : string -> llmemorybuffer = "llvm_memorybuffer_of_file" + + (** [stdin ()] is the memory buffer containing the contents of standard input. + If standard input is empty, then [IoError msg] is raised. *) + external of_stdin : unit -> llmemorybuffer = "llvm_memorybuffer_of_stdin" + + (** Disposes of a memory buffer. *) + external dispose : llmemorybuffer -> unit = "llvm_memorybuffer_dispose" +end + + +(** {6 Pass Managers} *) + +module PassManager : sig + (** *) + type 'a t + type any = [ `Module | `Function ] + + (** [PassManager.create ()] constructs a new whole-module pass pipeline. This + type of pipeline is suitable for link-time optimization and whole-module + transformations. + See the constructor of [llvm::PassManager]. *) + external create : unit -> [ `Module ] t = "llvm_passmanager_create" + + (** [PassManager.create_function m] constructs a new function-by-function + pass pipeline over the module [m]. It does not take ownership of [m]. + This type of pipeline is suitable for code generation and JIT compilation + tasks. + See the constructor of [llvm::FunctionPassManager]. *) + external create_function : llmodule -> [ `Function ] t + = "LLVMCreateFunctionPassManager" + + (** [run_module m pm] initializes, executes on the module [m], and finalizes + all of the passes scheduled in the pass manager [pm]. Returns [true] if + any of the passes modified the module, [false] otherwise. + See the [llvm::PassManager::run] method. *) + external run_module : llmodule -> [ `Module ] t -> bool + = "llvm_passmanager_run_module" + + (** [initialize fpm] initializes all of the function passes scheduled in the + function pass manager [fpm]. Returns [true] if any of the passes modified + the module, [false] otherwise. + See the [llvm::FunctionPassManager::doInitialization] method. *) + external initialize : [ `Function ] t -> bool = "llvm_passmanager_initialize" + + (** [run_function f fpm] executes all of the function passes scheduled in the + function pass manager [fpm] over the function [f]. Returns [true] if any + of the passes modified [f], [false] otherwise. + See the [llvm::FunctionPassManager::run] method. *) + external run_function : llvalue -> [ `Function ] t -> bool + = "llvm_passmanager_run_function" + + (** [finalize fpm] finalizes all of the function passes scheduled in in the + function pass manager [fpm]. Returns [true] if any of the passes + modified the module, [false] otherwise. + See the [llvm::FunctionPassManager::doFinalization] method. *) + external finalize : [ `Function ] t -> bool = "llvm_passmanager_finalize" + + (** Frees the memory of a pass pipeline. For function pipelines, does not free + the module. + See the destructor of [llvm::BasePassManager]. *) + external dispose : [< any ] t -> unit = "llvm_passmanager_dispose" +end diff --git a/contrib/llvm/bindings/ocaml/llvm/llvm_ocaml.c b/contrib/llvm/bindings/ocaml/llvm/llvm_ocaml.c new file mode 100644 index 0000000..c4355ba --- /dev/null +++ b/contrib/llvm/bindings/ocaml/llvm/llvm_ocaml.c @@ -0,0 +1,1828 @@ +/*===-- llvm_ocaml.c - LLVM Ocaml Glue --------------------------*- C++ -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file glues LLVM's ocaml interface to its C interface. These functions *| +|* are by and large transparent wrappers to the corresponding C functions. *| +|* *| +|* Note that these functions intentionally take liberties with the CAMLparamX *| +|* macros, since most of the parameters are not GC heap objects. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#include "llvm-c/Core.h" +#include "caml/alloc.h" +#include "caml/custom.h" +#include "caml/memory.h" +#include "caml/fail.h" +#include "caml/callback.h" +#include "llvm/Config/config.h" +#include <assert.h> +#include <stdlib.h> + + +/* Can't use the recommended caml_named_value mechanism for backwards + compatibility reasons. This is largely equivalent. */ +static value llvm_ioerror_exn; + +CAMLprim value llvm_register_core_exns(value IoError) { + llvm_ioerror_exn = Field(IoError, 0); + register_global_root(&llvm_ioerror_exn); + return Val_unit; +} + +static void llvm_raise(value Prototype, char *Message) { + CAMLparam1(Prototype); + CAMLlocal1(CamlMessage); + + CamlMessage = copy_string(Message); + LLVMDisposeMessage(Message); + + raise_with_arg(Prototype, CamlMessage); + abort(); /* NOTREACHED */ +#ifdef CAMLnoreturn + CAMLnoreturn; /* Silences warnings, but is missing in some versions. */ +#endif +} + +static value alloc_variant(int tag, void *Value) { + value Iter = alloc_small(1, tag); + Field(Iter, 0) = Val_op(Value); + return Iter; +} + +/* Macro to convert the C first/next/last/prev idiom to the Ocaml llpos/ + llrev_pos idiom. */ +#define DEFINE_ITERATORS(camlname, cname, pty, cty, pfun) \ + /* llmodule -> ('a, 'b) llpos */ \ + CAMLprim value llvm_##camlname##_begin(pty Mom) { \ + cty First = LLVMGetFirst##cname(Mom); \ + if (First) \ + return alloc_variant(1, First); \ + return alloc_variant(0, Mom); \ + } \ + \ + /* llvalue -> ('a, 'b) llpos */ \ + CAMLprim value llvm_##camlname##_succ(cty Kid) { \ + cty Next = LLVMGetNext##cname(Kid); \ + if (Next) \ + return alloc_variant(1, Next); \ + return alloc_variant(0, pfun(Kid)); \ + } \ + \ + /* llmodule -> ('a, 'b) llrev_pos */ \ + CAMLprim value llvm_##camlname##_end(pty Mom) { \ + cty Last = LLVMGetLast##cname(Mom); \ + if (Last) \ + return alloc_variant(1, Last); \ + return alloc_variant(0, Mom); \ + } \ + \ + /* llvalue -> ('a, 'b) llrev_pos */ \ + CAMLprim value llvm_##camlname##_pred(cty Kid) { \ + cty Prev = LLVMGetPrevious##cname(Kid); \ + if (Prev) \ + return alloc_variant(1, Prev); \ + return alloc_variant(0, pfun(Kid)); \ + } + + +/*===-- Contexts ----------------------------------------------------------===*/ + +/* unit -> llcontext */ +CAMLprim LLVMContextRef llvm_create_context(value Unit) { + return LLVMContextCreate(); +} + +/* llcontext -> unit */ +CAMLprim value llvm_dispose_context(LLVMContextRef C) { + LLVMContextDispose(C); + return Val_unit; +} + +/* unit -> llcontext */ +CAMLprim LLVMContextRef llvm_global_context(value Unit) { + return LLVMGetGlobalContext(); +} + +/* llcontext -> string -> int */ +CAMLprim value llvm_mdkind_id(LLVMContextRef C, value Name) { + unsigned MDKindID = LLVMGetMDKindIDInContext(C, String_val(Name), + caml_string_length(Name)); + return Val_int(MDKindID); +} + +/*===-- Modules -----------------------------------------------------------===*/ + +/* llcontext -> string -> llmodule */ +CAMLprim LLVMModuleRef llvm_create_module(LLVMContextRef C, value ModuleID) { + return LLVMModuleCreateWithNameInContext(String_val(ModuleID), C); +} + +/* llmodule -> unit */ +CAMLprim value llvm_dispose_module(LLVMModuleRef M) { + LLVMDisposeModule(M); + return Val_unit; +} + +/* llmodule -> string */ +CAMLprim value llvm_target_triple(LLVMModuleRef M) { + return copy_string(LLVMGetTarget(M)); +} + +/* string -> llmodule -> unit */ +CAMLprim value llvm_set_target_triple(value Trip, LLVMModuleRef M) { + LLVMSetTarget(M, String_val(Trip)); + return Val_unit; +} + +/* llmodule -> string */ +CAMLprim value llvm_data_layout(LLVMModuleRef M) { + return copy_string(LLVMGetDataLayout(M)); +} + +/* string -> llmodule -> unit */ +CAMLprim value llvm_set_data_layout(value Layout, LLVMModuleRef M) { + LLVMSetDataLayout(M, String_val(Layout)); + return Val_unit; +} + +/* string -> lltype -> llmodule -> bool */ +CAMLprim value llvm_add_type_name(value Name, LLVMTypeRef Ty, LLVMModuleRef M) { + int res = LLVMAddTypeName(M, String_val(Name), Ty); + return Val_bool(res == 0); +} + +/* string -> llmodule -> unit */ +CAMLprim value llvm_delete_type_name(value Name, LLVMModuleRef M) { + LLVMDeleteTypeName(M, String_val(Name)); + return Val_unit; +} + +/* llmodule -> string -> lltype option */ +CAMLprim value llvm_type_by_name(LLVMModuleRef M, value Name) { + CAMLparam1(Name); + LLVMTypeRef T; + if ((T = LLVMGetTypeByName(M, String_val(Name)))) { + value Option = alloc(1, 0); + Field(Option, 0) = (value) T; + CAMLreturn(Option); + } + CAMLreturn(Val_int(0)); +} + +/* llmodule -> unit */ +CAMLprim value llvm_dump_module(LLVMModuleRef M) { + LLVMDumpModule(M); + return Val_unit; +} + +/* llmodule -> string -> unit */ +CAMLprim value llvm_set_module_inline_asm(LLVMModuleRef M, value Asm) { + LLVMSetModuleInlineAsm(M, String_val(Asm)); + return Val_unit; +} + +/*===-- Types -------------------------------------------------------------===*/ + +/* lltype -> TypeKind.t */ +CAMLprim value llvm_classify_type(LLVMTypeRef Ty) { + return Val_int(LLVMGetTypeKind(Ty)); +} + +/* lltype -> llcontext */ +CAMLprim LLVMContextRef llvm_type_context(LLVMTypeRef Ty) { + return LLVMGetTypeContext(Ty); +} + +/*--... Operations on integer types ........................................--*/ + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_i1_type (LLVMContextRef Context) { + return LLVMInt1TypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_i8_type (LLVMContextRef Context) { + return LLVMInt8TypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_i16_type (LLVMContextRef Context) { + return LLVMInt16TypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_i32_type (LLVMContextRef Context) { + return LLVMInt32TypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_i64_type (LLVMContextRef Context) { + return LLVMInt64TypeInContext(Context); +} + +/* llcontext -> int -> lltype */ +CAMLprim LLVMTypeRef llvm_integer_type(LLVMContextRef Context, value Width) { + return LLVMIntTypeInContext(Context, Int_val(Width)); +} + +/* lltype -> int */ +CAMLprim value llvm_integer_bitwidth(LLVMTypeRef IntegerTy) { + return Val_int(LLVMGetIntTypeWidth(IntegerTy)); +} + +/*--... Operations on real types ...........................................--*/ + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_float_type(LLVMContextRef Context) { + return LLVMFloatTypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_double_type(LLVMContextRef Context) { + return LLVMDoubleTypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_x86fp80_type(LLVMContextRef Context) { + return LLVMX86FP80TypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_fp128_type(LLVMContextRef Context) { + return LLVMFP128TypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_ppc_fp128_type(LLVMContextRef Context) { + return LLVMPPCFP128TypeInContext(Context); +} + +/*--... Operations on function types .......................................--*/ + +/* lltype -> lltype array -> lltype */ +CAMLprim LLVMTypeRef llvm_function_type(LLVMTypeRef RetTy, value ParamTys) { + return LLVMFunctionType(RetTy, (LLVMTypeRef *) ParamTys, + Wosize_val(ParamTys), 0); +} + +/* lltype -> lltype array -> lltype */ +CAMLprim LLVMTypeRef llvm_var_arg_function_type(LLVMTypeRef RetTy, + value ParamTys) { + return LLVMFunctionType(RetTy, (LLVMTypeRef *) ParamTys, + Wosize_val(ParamTys), 1); +} + +/* lltype -> bool */ +CAMLprim value llvm_is_var_arg(LLVMTypeRef FunTy) { + return Val_bool(LLVMIsFunctionVarArg(FunTy)); +} + +/* lltype -> lltype array */ +CAMLprim value llvm_param_types(LLVMTypeRef FunTy) { + value Tys = alloc(LLVMCountParamTypes(FunTy), 0); + LLVMGetParamTypes(FunTy, (LLVMTypeRef *) Tys); + return Tys; +} + +/*--... Operations on struct types .........................................--*/ + +/* llcontext -> lltype array -> lltype */ +CAMLprim LLVMTypeRef llvm_struct_type(LLVMContextRef C, value ElementTypes) { + return LLVMStructTypeInContext(C, (LLVMTypeRef *) ElementTypes, + Wosize_val(ElementTypes), 0); +} + +/* llcontext -> lltype array -> lltype */ +CAMLprim LLVMTypeRef llvm_packed_struct_type(LLVMContextRef C, + value ElementTypes) { + return LLVMStructTypeInContext(C, (LLVMTypeRef *) ElementTypes, + Wosize_val(ElementTypes), 1); +} + +/* lltype -> lltype array */ +CAMLprim value llvm_struct_element_types(LLVMTypeRef StructTy) { + value Tys = alloc(LLVMCountStructElementTypes(StructTy), 0); + LLVMGetStructElementTypes(StructTy, (LLVMTypeRef *) Tys); + return Tys; +} + +/* lltype -> bool */ +CAMLprim value llvm_is_packed(LLVMTypeRef StructTy) { + return Val_bool(LLVMIsPackedStruct(StructTy)); +} + +/*--... Operations on union types ..........................................--*/ + +/* llcontext -> lltype array -> lltype */ +CAMLprim LLVMTypeRef llvm_union_type(LLVMContextRef C, value ElementTypes) { + return LLVMUnionTypeInContext(C, (LLVMTypeRef *) ElementTypes, + Wosize_val(ElementTypes)); +} + +/* lltype -> lltype array */ +CAMLprim value llvm_union_element_types(LLVMTypeRef UnionTy) { + value Tys = alloc(LLVMCountUnionElementTypes(UnionTy), 0); + LLVMGetUnionElementTypes(UnionTy, (LLVMTypeRef *) Tys); + return Tys; +} + +/*--... Operations on array, pointer, and vector types .....................--*/ + +/* lltype -> int -> lltype */ +CAMLprim LLVMTypeRef llvm_array_type(LLVMTypeRef ElementTy, value Count) { + return LLVMArrayType(ElementTy, Int_val(Count)); +} + +/* lltype -> lltype */ +CAMLprim LLVMTypeRef llvm_pointer_type(LLVMTypeRef ElementTy) { + return LLVMPointerType(ElementTy, 0); +} + +/* lltype -> int -> lltype */ +CAMLprim LLVMTypeRef llvm_qualified_pointer_type(LLVMTypeRef ElementTy, + value AddressSpace) { + return LLVMPointerType(ElementTy, Int_val(AddressSpace)); +} + +/* lltype -> int -> lltype */ +CAMLprim LLVMTypeRef llvm_vector_type(LLVMTypeRef ElementTy, value Count) { + return LLVMVectorType(ElementTy, Int_val(Count)); +} + +/* lltype -> int */ +CAMLprim value llvm_array_length(LLVMTypeRef ArrayTy) { + return Val_int(LLVMGetArrayLength(ArrayTy)); +} + +/* lltype -> int */ +CAMLprim value llvm_address_space(LLVMTypeRef PtrTy) { + return Val_int(LLVMGetPointerAddressSpace(PtrTy)); +} + +/* lltype -> int */ +CAMLprim value llvm_vector_size(LLVMTypeRef VectorTy) { + return Val_int(LLVMGetVectorSize(VectorTy)); +} + +/*--... Operations on other types ..........................................--*/ + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_void_type (LLVMContextRef Context) { + return LLVMVoidTypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_label_type(LLVMContextRef Context) { + return LLVMLabelTypeInContext(Context); +} + +/* llcontext -> lltype */ +CAMLprim LLVMTypeRef llvm_opaque_type(LLVMContextRef Context) { + return LLVMOpaqueTypeInContext(Context); +} + +/*--... Operations on type handles .........................................--*/ + +#define Typehandle_val(v) (*(LLVMTypeHandleRef *)(Data_custom_val(v))) + +static void llvm_finalize_handle(value TH) { + LLVMDisposeTypeHandle(Typehandle_val(TH)); +} + +static struct custom_operations typehandle_ops = { + (char *) "LLVMTypeHandle", + llvm_finalize_handle, + custom_compare_default, + custom_hash_default, + custom_serialize_default, + custom_deserialize_default +}; + +CAMLprim value llvm_handle_to_type(LLVMTypeRef PATy) { + value TH = alloc_custom(&typehandle_ops, sizeof(LLVMBuilderRef), 0, 1); + Typehandle_val(TH) = LLVMCreateTypeHandle(PATy); + return TH; +} + +CAMLprim LLVMTypeRef llvm_type_of_handle(value TH) { + return LLVMResolveTypeHandle(Typehandle_val(TH)); +} + +CAMLprim value llvm_refine_type(LLVMTypeRef AbstractTy, LLVMTypeRef ConcreteTy){ + LLVMRefineType(AbstractTy, ConcreteTy); + return Val_unit; +} + + +/*===-- VALUES ------------------------------------------------------------===*/ + +/* llvalue -> lltype */ +CAMLprim LLVMTypeRef llvm_type_of(LLVMValueRef Val) { + return LLVMTypeOf(Val); +} + +/* llvalue -> string */ +CAMLprim value llvm_value_name(LLVMValueRef Val) { + return copy_string(LLVMGetValueName(Val)); +} + +/* string -> llvalue -> unit */ +CAMLprim value llvm_set_value_name(value Name, LLVMValueRef Val) { + LLVMSetValueName(Val, String_val(Name)); + return Val_unit; +} + +/* llvalue -> unit */ +CAMLprim value llvm_dump_value(LLVMValueRef Val) { + LLVMDumpValue(Val); + return Val_unit; +} + +/*--... Operations on users ................................................--*/ + +/* llvalue -> int -> llvalue */ +CAMLprim LLVMValueRef llvm_operand(LLVMValueRef V, value I) { + return LLVMGetOperand(V, Int_val(I)); +} + +/*--... Operations on constants of (mostly) any type .......................--*/ + +/* llvalue -> bool */ +CAMLprim value llvm_is_constant(LLVMValueRef Val) { + return Val_bool(LLVMIsConstant(Val)); +} + +/* llvalue -> bool */ +CAMLprim value llvm_is_null(LLVMValueRef Val) { + return Val_bool(LLVMIsNull(Val)); +} + +/* llvalue -> bool */ +CAMLprim value llvm_is_undef(LLVMValueRef Val) { + return Val_bool(LLVMIsUndef(Val)); +} + +/*--... Operations on instructions .........................................--*/ + +/* llvalue -> bool */ +CAMLprim value llvm_has_metadata(LLVMValueRef Val) { + return Val_bool(LLVMHasMetadata(Val)); +} + +/* llvalue -> int -> llvalue option */ +CAMLprim value llvm_metadata(LLVMValueRef Val, value MDKindID) { + CAMLparam1(MDKindID); + LLVMValueRef MD; + if ((MD = LLVMGetMetadata(Val, Int_val(MDKindID)))) { + value Option = alloc(1, 0); + Field(Option, 0) = (value) MD; + CAMLreturn(Option); + } + CAMLreturn(Val_int(0)); +} + +/* llvalue -> int -> llvalue -> unit */ +CAMLprim value llvm_set_metadata(LLVMValueRef Val, value MDKindID, + LLVMValueRef MD) { + LLVMSetMetadata(Val, Int_val(MDKindID), MD); + return Val_unit; +} + +/* llvalue -> int -> unit */ +CAMLprim value llvm_clear_metadata(LLVMValueRef Val, value MDKindID) { + LLVMSetMetadata(Val, Int_val(MDKindID), NULL); + return Val_unit; +} + + +/*--... Operations on metadata .............................................--*/ + +/* llcontext -> string -> llvalue */ +CAMLprim LLVMValueRef llvm_mdstring(LLVMContextRef C, value S) { + return LLVMMDStringInContext(C, String_val(S), caml_string_length(S)); +} + +/* llcontext -> llvalue array -> llvalue */ +CAMLprim LLVMValueRef llvm_mdnode(LLVMContextRef C, value ElementVals) { + return LLVMMDNodeInContext(C, (LLVMValueRef*) Op_val(ElementVals), + Wosize_val(ElementVals)); +} + +/*--... Operations on scalar constants .....................................--*/ + +/* lltype -> int -> llvalue */ +CAMLprim LLVMValueRef llvm_const_int(LLVMTypeRef IntTy, value N) { + return LLVMConstInt(IntTy, (long long) Int_val(N), 1); +} + +/* lltype -> Int64.t -> bool -> llvalue */ +CAMLprim LLVMValueRef llvm_const_of_int64(LLVMTypeRef IntTy, value N, + value SExt) { + return LLVMConstInt(IntTy, Int64_val(N), Bool_val(SExt)); +} + +/* lltype -> string -> int -> llvalue */ +CAMLprim LLVMValueRef llvm_const_int_of_string(LLVMTypeRef IntTy, value S, + value Radix) { + return LLVMConstIntOfStringAndSize(IntTy, String_val(S), caml_string_length(S), + Int_val(Radix)); +} + +/* lltype -> float -> llvalue */ +CAMLprim LLVMValueRef llvm_const_float(LLVMTypeRef RealTy, value N) { + return LLVMConstReal(RealTy, Double_val(N)); +} + +/* lltype -> string -> llvalue */ +CAMLprim LLVMValueRef llvm_const_float_of_string(LLVMTypeRef RealTy, value S) { + return LLVMConstRealOfStringAndSize(RealTy, String_val(S), + caml_string_length(S)); +} + +/*--... Operations on composite constants ..................................--*/ + +/* llcontext -> string -> llvalue */ +CAMLprim LLVMValueRef llvm_const_string(LLVMContextRef Context, value Str, + value NullTerminate) { + return LLVMConstStringInContext(Context, String_val(Str), string_length(Str), + 1); +} + +/* llcontext -> string -> llvalue */ +CAMLprim LLVMValueRef llvm_const_stringz(LLVMContextRef Context, value Str, + value NullTerminate) { + return LLVMConstStringInContext(Context, String_val(Str), string_length(Str), + 0); +} + +/* lltype -> llvalue array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_array(LLVMTypeRef ElementTy, + value ElementVals) { + return LLVMConstArray(ElementTy, (LLVMValueRef*) Op_val(ElementVals), + Wosize_val(ElementVals)); +} + +/* llcontext -> llvalue array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_struct(LLVMContextRef C, value ElementVals) { + return LLVMConstStructInContext(C, (LLVMValueRef *) Op_val(ElementVals), + Wosize_val(ElementVals), 0); +} + +/* llcontext -> llvalue array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_packed_struct(LLVMContextRef C, + value ElementVals) { + return LLVMConstStructInContext(C, (LLVMValueRef *) Op_val(ElementVals), + Wosize_val(ElementVals), 1); +} + +/* llvalue array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_vector(value ElementVals) { + return LLVMConstVector((LLVMValueRef*) Op_val(ElementVals), + Wosize_val(ElementVals)); +} + +/*--... Constant expressions ...............................................--*/ + +/* Icmp.t -> llvalue -> llvalue -> llvalue */ +CAMLprim LLVMValueRef llvm_const_icmp(value Pred, + LLVMValueRef LHSConstant, + LLVMValueRef RHSConstant) { + return LLVMConstICmp(Int_val(Pred) + LLVMIntEQ, LHSConstant, RHSConstant); +} + +/* Fcmp.t -> llvalue -> llvalue -> llvalue */ +CAMLprim LLVMValueRef llvm_const_fcmp(value Pred, + LLVMValueRef LHSConstant, + LLVMValueRef RHSConstant) { + return LLVMConstFCmp(Int_val(Pred), LHSConstant, RHSConstant); +} + +/* llvalue -> llvalue array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_gep(LLVMValueRef ConstantVal, value Indices) { + return LLVMConstGEP(ConstantVal, (LLVMValueRef*) Op_val(Indices), + Wosize_val(Indices)); +} + +/* llvalue -> llvalue array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_in_bounds_gep(LLVMValueRef ConstantVal, + value Indices) { + return LLVMConstInBoundsGEP(ConstantVal, (LLVMValueRef*) Op_val(Indices), + Wosize_val(Indices)); +} + +/* llvalue -> int array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_extractvalue(LLVMValueRef Aggregate, + value Indices) { + CAMLparam1(Indices); + int size = Wosize_val(Indices); + int i; + LLVMValueRef result; + + unsigned* idxs = (unsigned*)malloc(size * sizeof(unsigned)); + for (i = 0; i < size; i++) { + idxs[i] = Int_val(Field(Indices, i)); + } + + result = LLVMConstExtractValue(Aggregate, idxs, size); + free(idxs); + CAMLreturnT(LLVMValueRef, result); +} + +/* llvalue -> llvalue -> int array -> llvalue */ +CAMLprim LLVMValueRef llvm_const_insertvalue(LLVMValueRef Aggregate, + LLVMValueRef Val, value Indices) { + CAMLparam1(Indices); + int size = Wosize_val(Indices); + int i; + LLVMValueRef result; + + unsigned* idxs = (unsigned*)malloc(size * sizeof(unsigned)); + for (i = 0; i < size; i++) { + idxs[i] = Int_val(Field(Indices, i)); + } + + result = LLVMConstInsertValue(Aggregate, Val, idxs, size); + free(idxs); + CAMLreturnT(LLVMValueRef, result); +} + +/* lltype -> string -> string -> bool -> bool -> llvalue */ +CAMLprim LLVMValueRef llvm_const_inline_asm(LLVMTypeRef Ty, value Asm, + value Constraints, value HasSideEffects, + value IsAlignStack) { + return LLVMConstInlineAsm(Ty, String_val(Asm), String_val(Constraints), + Bool_val(HasSideEffects), Bool_val(IsAlignStack)); +} + +/*--... Operations on global variables, functions, and aliases (globals) ...--*/ + +/* llvalue -> bool */ +CAMLprim value llvm_is_declaration(LLVMValueRef Global) { + return Val_bool(LLVMIsDeclaration(Global)); +} + +/* llvalue -> Linkage.t */ +CAMLprim value llvm_linkage(LLVMValueRef Global) { + return Val_int(LLVMGetLinkage(Global)); +} + +/* Linkage.t -> llvalue -> unit */ +CAMLprim value llvm_set_linkage(value Linkage, LLVMValueRef Global) { + LLVMSetLinkage(Global, Int_val(Linkage)); + return Val_unit; +} + +/* llvalue -> string */ +CAMLprim value llvm_section(LLVMValueRef Global) { + return copy_string(LLVMGetSection(Global)); +} + +/* string -> llvalue -> unit */ +CAMLprim value llvm_set_section(value Section, LLVMValueRef Global) { + LLVMSetSection(Global, String_val(Section)); + return Val_unit; +} + +/* llvalue -> Visibility.t */ +CAMLprim value llvm_visibility(LLVMValueRef Global) { + return Val_int(LLVMGetVisibility(Global)); +} + +/* Visibility.t -> llvalue -> unit */ +CAMLprim value llvm_set_visibility(value Viz, LLVMValueRef Global) { + LLVMSetVisibility(Global, Int_val(Viz)); + return Val_unit; +} + +/* llvalue -> int */ +CAMLprim value llvm_alignment(LLVMValueRef Global) { + return Val_int(LLVMGetAlignment(Global)); +} + +/* int -> llvalue -> unit */ +CAMLprim value llvm_set_alignment(value Bytes, LLVMValueRef Global) { + LLVMSetAlignment(Global, Int_val(Bytes)); + return Val_unit; +} + +/*--... Operations on uses .................................................--*/ + +/* llvalue -> lluse option */ +CAMLprim value llvm_use_begin(LLVMValueRef Val) { + CAMLparam0(); + LLVMUseRef First; + if ((First = LLVMGetFirstUse(Val))) { + value Option = alloc(1, 0); + Field(Option, 0) = (value) First; + CAMLreturn(Option); + } + CAMLreturn(Val_int(0)); +} + +/* lluse -> lluse option */ +CAMLprim value llvm_use_succ(LLVMUseRef U) { + CAMLparam0(); + LLVMUseRef Next; + if ((Next = LLVMGetNextUse(U))) { + value Option = alloc(1, 0); + Field(Option, 0) = (value) Next; + CAMLreturn(Option); + } + CAMLreturn(Val_int(0)); +} + +/* lluse -> llvalue */ +CAMLprim LLVMValueRef llvm_user(LLVMUseRef UR) { + return LLVMGetUser(UR); +} + +/* lluse -> llvalue */ +CAMLprim LLVMValueRef llvm_used_value(LLVMUseRef UR) { + return LLVMGetUsedValue(UR); +} + +/*--... Operations on global variables .....................................--*/ + +DEFINE_ITERATORS(global, Global, LLVMModuleRef, LLVMValueRef, + LLVMGetGlobalParent) + +/* lltype -> string -> llmodule -> llvalue */ +CAMLprim LLVMValueRef llvm_declare_global(LLVMTypeRef Ty, value Name, + LLVMModuleRef M) { + LLVMValueRef GlobalVar; + if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) { + if (LLVMGetElementType(LLVMTypeOf(GlobalVar)) != Ty) + return LLVMConstBitCast(GlobalVar, LLVMPointerType(Ty, 0)); + return GlobalVar; + } + return LLVMAddGlobal(M, Ty, String_val(Name)); +} + +/* lltype -> string -> int -> llmodule -> llvalue */ +CAMLprim LLVMValueRef llvm_declare_qualified_global(LLVMTypeRef Ty, value Name, + value AddressSpace, + LLVMModuleRef M) { + LLVMValueRef GlobalVar; + if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) { + if (LLVMGetElementType(LLVMTypeOf(GlobalVar)) != Ty) + return LLVMConstBitCast(GlobalVar, + LLVMPointerType(Ty, Int_val(AddressSpace))); + return GlobalVar; + } + return LLVMAddGlobal(M, Ty, String_val(Name)); +} + +/* string -> llmodule -> llvalue option */ +CAMLprim value llvm_lookup_global(value Name, LLVMModuleRef M) { + CAMLparam1(Name); + LLVMValueRef GlobalVar; + if ((GlobalVar = LLVMGetNamedGlobal(M, String_val(Name)))) { + value Option = alloc(1, 0); + Field(Option, 0) = (value) GlobalVar; + CAMLreturn(Option); + } + CAMLreturn(Val_int(0)); +} + +/* string -> llvalue -> llmodule -> llvalue */ +CAMLprim LLVMValueRef llvm_define_global(value Name, LLVMValueRef Initializer, + LLVMModuleRef M) { + LLVMValueRef GlobalVar = LLVMAddGlobal(M, LLVMTypeOf(Initializer), + String_val(Name)); + LLVMSetInitializer(GlobalVar, Initializer); + return GlobalVar; +} + +/* string -> llvalue -> int -> llmodule -> llvalue */ +CAMLprim LLVMValueRef llvm_define_qualified_global(value Name, + LLVMValueRef Initializer, + value AddressSpace, + LLVMModuleRef M) { + LLVMValueRef GlobalVar = LLVMAddGlobalInAddressSpace(M, + LLVMTypeOf(Initializer), + String_val(Name), + Int_val(AddressSpace)); + LLVMSetInitializer(GlobalVar, Initializer); + return GlobalVar; +} + +/* llvalue -> unit */ +CAMLprim value llvm_delete_global(LLVMValueRef GlobalVar) { + LLVMDeleteGlobal(GlobalVar); + return Val_unit; +} + +/* llvalue -> llvalue -> unit */ +CAMLprim value llvm_set_initializer(LLVMValueRef ConstantVal, + LLVMValueRef GlobalVar) { + LLVMSetInitializer(GlobalVar, ConstantVal); + return Val_unit; +} + +/* llvalue -> unit */ +CAMLprim value llvm_remove_initializer(LLVMValueRef GlobalVar) { + LLVMSetInitializer(GlobalVar, NULL); + return Val_unit; +} + +/* llvalue -> bool */ +CAMLprim value llvm_is_thread_local(LLVMValueRef GlobalVar) { + return Val_bool(LLVMIsThreadLocal(GlobalVar)); +} + +/* bool -> llvalue -> unit */ +CAMLprim value llvm_set_thread_local(value IsThreadLocal, + LLVMValueRef GlobalVar) { + LLVMSetThreadLocal(GlobalVar, Bool_val(IsThreadLocal)); + return Val_unit; +} + +/* llvalue -> bool */ +CAMLprim value llvm_is_global_constant(LLVMValueRef GlobalVar) { + return Val_bool(LLVMIsGlobalConstant(GlobalVar)); +} + +/* bool -> llvalue -> unit */ +CAMLprim value llvm_set_global_constant(value Flag, LLVMValueRef GlobalVar) { + LLVMSetGlobalConstant(GlobalVar, Bool_val(Flag)); + return Val_unit; +} + +/*--... Operations on aliases ..............................................--*/ + +CAMLprim LLVMValueRef llvm_add_alias(LLVMModuleRef M, LLVMTypeRef Ty, + LLVMValueRef Aliasee, value Name) { + return LLVMAddAlias(M, Ty, Aliasee, String_val(Name)); +} + +/*--... Operations on functions ............................................--*/ + +DEFINE_ITERATORS(function, Function, LLVMModuleRef, LLVMValueRef, + LLVMGetGlobalParent) + +/* string -> lltype -> llmodule -> llvalue */ +CAMLprim LLVMValueRef llvm_declare_function(value Name, LLVMTypeRef Ty, + LLVMModuleRef M) { + LLVMValueRef Fn; + if ((Fn = LLVMGetNamedFunction(M, String_val(Name)))) { + if (LLVMGetElementType(LLVMTypeOf(Fn)) != Ty) + return LLVMConstBitCast(Fn, LLVMPointerType(Ty, 0)); + return Fn; + } + return LLVMAddFunction(M, String_val(Name), Ty); +} + +/* string -> llmodule -> llvalue option */ +CAMLprim value llvm_lookup_function(value Name, LLVMModuleRef M) { + CAMLparam1(Name); + LLVMValueRef Fn; + if ((Fn = LLVMGetNamedFunction(M, String_val(Name)))) { + value Option = alloc(1, 0); + Field(Option, 0) = (value) Fn; + CAMLreturn(Option); + } + CAMLreturn(Val_int(0)); +} + +/* string -> lltype -> llmodule -> llvalue */ +CAMLprim LLVMValueRef llvm_define_function(value Name, LLVMTypeRef Ty, + LLVMModuleRef M) { + LLVMValueRef Fn = LLVMAddFunction(M, String_val(Name), Ty); + LLVMAppendBasicBlockInContext(LLVMGetTypeContext(Ty), Fn, "entry"); + return Fn; +} + +/* llvalue -> unit */ +CAMLprim value llvm_delete_function(LLVMValueRef Fn) { + LLVMDeleteFunction(Fn); + return Val_unit; +} + +/* llvalue -> bool */ +CAMLprim value llvm_is_intrinsic(LLVMValueRef Fn) { + return Val_bool(LLVMGetIntrinsicID(Fn)); +} + +/* llvalue -> int */ +CAMLprim value llvm_function_call_conv(LLVMValueRef Fn) { + return Val_int(LLVMGetFunctionCallConv(Fn)); +} + +/* int -> llvalue -> unit */ +CAMLprim value llvm_set_function_call_conv(value Id, LLVMValueRef Fn) { + LLVMSetFunctionCallConv(Fn, Int_val(Id)); + return Val_unit; +} + +/* llvalue -> string option */ +CAMLprim value llvm_gc(LLVMValueRef Fn) { + const char *GC; + CAMLparam0(); + CAMLlocal2(Name, Option); + + if ((GC = LLVMGetGC(Fn))) { + Name = copy_string(GC); + + Option = alloc(1, 0); + Field(Option, 0) = Name; + CAMLreturn(Option); + } else { + CAMLreturn(Val_int(0)); + } +} + +/* string option -> llvalue -> unit */ +CAMLprim value llvm_set_gc(value GC, LLVMValueRef Fn) { + LLVMSetGC(Fn, GC == Val_int(0)? 0 : String_val(Field(GC, 0))); + return Val_unit; +} + +/* llvalue -> Attribute.t -> unit */ +CAMLprim value llvm_add_function_attr(LLVMValueRef Arg, value PA) { + LLVMAddFunctionAttr(Arg, Int_val(PA)); + return Val_unit; +} + +/* llvalue -> Attribute.t -> unit */ +CAMLprim value llvm_remove_function_attr(LLVMValueRef Arg, value PA) { + LLVMRemoveFunctionAttr(Arg, Int_val(PA)); + return Val_unit; +} +/*--... Operations on parameters ...........................................--*/ + +DEFINE_ITERATORS(param, Param, LLVMValueRef, LLVMValueRef, LLVMGetParamParent) + +/* llvalue -> int -> llvalue */ +CAMLprim LLVMValueRef llvm_param(LLVMValueRef Fn, value Index) { + return LLVMGetParam(Fn, Int_val(Index)); +} + +/* llvalue -> int -> llvalue */ +CAMLprim value llvm_params(LLVMValueRef Fn, value Index) { + value Params = alloc(LLVMCountParams(Fn), 0); + LLVMGetParams(Fn, (LLVMValueRef *) Op_val(Params)); + return Params; +} + +/* llvalue -> Attribute.t -> unit */ +CAMLprim value llvm_add_param_attr(LLVMValueRef Arg, value PA) { + LLVMAddAttribute(Arg, Int_val(PA)); + return Val_unit; +} + +/* llvalue -> Attribute.t -> unit */ +CAMLprim value llvm_remove_param_attr(LLVMValueRef Arg, value PA) { + LLVMRemoveAttribute(Arg, Int_val(PA)); + return Val_unit; +} + +/* llvalue -> int -> unit */ +CAMLprim value llvm_set_param_alignment(LLVMValueRef Arg, value align) { + LLVMSetParamAlignment(Arg, Int_val(align)); + return Val_unit; +} + +/*--... Operations on basic blocks .........................................--*/ + +DEFINE_ITERATORS( + block, BasicBlock, LLVMValueRef, LLVMBasicBlockRef, LLVMGetBasicBlockParent) + +/* llvalue -> llbasicblock array */ +CAMLprim value llvm_basic_blocks(LLVMValueRef Fn) { + value MLArray = alloc(LLVMCountBasicBlocks(Fn), 0); + LLVMGetBasicBlocks(Fn, (LLVMBasicBlockRef *) Op_val(MLArray)); + return MLArray; +} + +/* llbasicblock -> unit */ +CAMLprim value llvm_delete_block(LLVMBasicBlockRef BB) { + LLVMDeleteBasicBlock(BB); + return Val_unit; +} + +/* string -> llvalue -> llbasicblock */ +CAMLprim LLVMBasicBlockRef llvm_append_block(LLVMContextRef Context, value Name, + LLVMValueRef Fn) { + return LLVMAppendBasicBlockInContext(Context, Fn, String_val(Name)); +} + +/* string -> llbasicblock -> llbasicblock */ +CAMLprim LLVMBasicBlockRef llvm_insert_block(LLVMContextRef Context, value Name, + LLVMBasicBlockRef BB) { + return LLVMInsertBasicBlockInContext(Context, BB, String_val(Name)); +} + +/* llvalue -> bool */ +CAMLprim value llvm_value_is_block(LLVMValueRef Val) { + return Val_bool(LLVMValueIsBasicBlock(Val)); +} + +/*--... Operations on instructions .........................................--*/ + +DEFINE_ITERATORS(instr, Instruction, LLVMBasicBlockRef, LLVMValueRef, + LLVMGetInstructionParent) + + +/*--... Operations on call sites ...........................................--*/ + +/* llvalue -> int */ +CAMLprim value llvm_instruction_call_conv(LLVMValueRef Inst) { + return Val_int(LLVMGetInstructionCallConv(Inst)); +} + +/* int -> llvalue -> unit */ +CAMLprim value llvm_set_instruction_call_conv(value CC, LLVMValueRef Inst) { + LLVMSetInstructionCallConv(Inst, Int_val(CC)); + return Val_unit; +} + +/* llvalue -> int -> Attribute.t -> unit */ +CAMLprim value llvm_add_instruction_param_attr(LLVMValueRef Instr, + value index, + value PA) { + LLVMAddInstrAttribute(Instr, Int_val(index), Int_val(PA)); + return Val_unit; +} + +/* llvalue -> int -> Attribute.t -> unit */ +CAMLprim value llvm_remove_instruction_param_attr(LLVMValueRef Instr, + value index, + value PA) { + LLVMRemoveInstrAttribute(Instr, Int_val(index), Int_val(PA)); + return Val_unit; +} + +/*--... Operations on call instructions (only) .............................--*/ + +/* llvalue -> bool */ +CAMLprim value llvm_is_tail_call(LLVMValueRef CallInst) { + return Val_bool(LLVMIsTailCall(CallInst)); +} + +/* bool -> llvalue -> unit */ +CAMLprim value llvm_set_tail_call(value IsTailCall, + LLVMValueRef CallInst) { + LLVMSetTailCall(CallInst, Bool_val(IsTailCall)); + return Val_unit; +} + +/*--... Operations on phi nodes ............................................--*/ + +/* (llvalue * llbasicblock) -> llvalue -> unit */ +CAMLprim value llvm_add_incoming(value Incoming, LLVMValueRef PhiNode) { + LLVMAddIncoming(PhiNode, + (LLVMValueRef*) &Field(Incoming, 0), + (LLVMBasicBlockRef*) &Field(Incoming, 1), + 1); + return Val_unit; +} + +/* llvalue -> (llvalue * llbasicblock) list */ +CAMLprim value llvm_incoming(LLVMValueRef PhiNode) { + unsigned I; + CAMLparam0(); + CAMLlocal3(Hd, Tl, Tmp); + + /* Build a tuple list of them. */ + Tl = Val_int(0); + for (I = LLVMCountIncoming(PhiNode); I != 0; ) { + Hd = alloc(2, 0); + Store_field(Hd, 0, (value) LLVMGetIncomingValue(PhiNode, --I)); + Store_field(Hd, 1, (value) LLVMGetIncomingBlock(PhiNode, I)); + + Tmp = alloc(2, 0); + Store_field(Tmp, 0, Hd); + Store_field(Tmp, 1, Tl); + Tl = Tmp; + } + + CAMLreturn(Tl); +} + + +/*===-- Instruction builders ----------------------------------------------===*/ + +#define Builder_val(v) (*(LLVMBuilderRef *)(Data_custom_val(v))) + +static void llvm_finalize_builder(value B) { + LLVMDisposeBuilder(Builder_val(B)); +} + +static struct custom_operations builder_ops = { + (char *) "IRBuilder", + llvm_finalize_builder, + custom_compare_default, + custom_hash_default, + custom_serialize_default, + custom_deserialize_default +}; + +static value alloc_builder(LLVMBuilderRef B) { + value V = alloc_custom(&builder_ops, sizeof(LLVMBuilderRef), 0, 1); + Builder_val(V) = B; + return V; +} + +/* llcontext -> llbuilder */ +CAMLprim value llvm_builder(LLVMContextRef C) { + return alloc_builder(LLVMCreateBuilderInContext(C)); +} + +/* (llbasicblock, llvalue) llpos -> llbuilder -> unit */ +CAMLprim value llvm_position_builder(value Pos, value B) { + if (Tag_val(Pos) == 0) { + LLVMBasicBlockRef BB = (LLVMBasicBlockRef) Op_val(Field(Pos, 0)); + LLVMPositionBuilderAtEnd(Builder_val(B), BB); + } else { + LLVMValueRef I = (LLVMValueRef) Op_val(Field(Pos, 0)); + LLVMPositionBuilderBefore(Builder_val(B), I); + } + return Val_unit; +} + +/* llbuilder -> llbasicblock */ +CAMLprim LLVMBasicBlockRef llvm_insertion_block(value B) { + LLVMBasicBlockRef InsertBlock = LLVMGetInsertBlock(Builder_val(B)); + if (!InsertBlock) + raise_not_found(); + return InsertBlock; +} + +/* llvalue -> string -> llbuilder -> unit */ +CAMLprim value llvm_insert_into_builder(LLVMValueRef I, value Name, value B) { + LLVMInsertIntoBuilderWithName(Builder_val(B), I, String_val(Name)); + return Val_unit; +} + +/*--... Metadata ...........................................................--*/ + +/* llbuilder -> llvalue -> unit */ +CAMLprim value llvm_set_current_debug_location(value B, LLVMValueRef V) { + LLVMSetCurrentDebugLocation(Builder_val(B), V); + return Val_unit; +} + +/* llbuilder -> unit */ +CAMLprim value llvm_clear_current_debug_location(value B) { + LLVMSetCurrentDebugLocation(Builder_val(B), NULL); + return Val_unit; +} + +/* llbuilder -> llvalue option */ +CAMLprim value llvm_current_debug_location(value B) { + CAMLparam0(); + LLVMValueRef L; + if ((L = LLVMGetCurrentDebugLocation(Builder_val(B)))) { + value Option = alloc(1, 0); + Field(Option, 0) = (value) L; + CAMLreturn(Option); + } + CAMLreturn(Val_int(0)); +} + +/* llbuilder -> llvalue -> unit */ +CAMLprim value llvm_set_inst_debug_location(value B, LLVMValueRef V) { + LLVMSetInstDebugLocation(Builder_val(B), V); + return Val_unit; +} + + +/*--... Terminators ........................................................--*/ + +/* llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_ret_void(value B) { + return LLVMBuildRetVoid(Builder_val(B)); +} + +/* llvalue -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_ret(LLVMValueRef Val, value B) { + return LLVMBuildRet(Builder_val(B), Val); +} + +/* llvalue array -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_aggregate_ret(value RetVals, value B) { + return LLVMBuildAggregateRet(Builder_val(B), (LLVMValueRef *) Op_val(RetVals), + Wosize_val(RetVals)); +} + +/* llbasicblock -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_br(LLVMBasicBlockRef BB, value B) { + return LLVMBuildBr(Builder_val(B), BB); +} + +/* llvalue -> llbasicblock -> llbasicblock -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_cond_br(LLVMValueRef If, + LLVMBasicBlockRef Then, + LLVMBasicBlockRef Else, + value B) { + return LLVMBuildCondBr(Builder_val(B), If, Then, Else); +} + +/* llvalue -> llbasicblock -> int -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_switch(LLVMValueRef Of, + LLVMBasicBlockRef Else, + value EstimatedCount, + value B) { + return LLVMBuildSwitch(Builder_val(B), Of, Else, Int_val(EstimatedCount)); +} + +/* llvalue -> llvalue -> llbasicblock -> unit */ +CAMLprim value llvm_add_case(LLVMValueRef Switch, LLVMValueRef OnVal, + LLVMBasicBlockRef Dest) { + LLVMAddCase(Switch, OnVal, Dest); + return Val_unit; +} + +/* llvalue -> llbasicblock -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_indirect_br(LLVMValueRef Addr, + value EstimatedDests, + value B) { + return LLVMBuildIndirectBr(Builder_val(B), Addr, EstimatedDests); +} + +/* llvalue -> llvalue -> llbasicblock -> unit */ +CAMLprim value llvm_add_destination(LLVMValueRef IndirectBr, + LLVMBasicBlockRef Dest) { + LLVMAddDestination(IndirectBr, Dest); + return Val_unit; +} + +/* llvalue -> llvalue array -> llbasicblock -> llbasicblock -> string -> + llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_invoke_nat(LLVMValueRef Fn, value Args, + LLVMBasicBlockRef Then, + LLVMBasicBlockRef Catch, + value Name, value B) { + return LLVMBuildInvoke(Builder_val(B), Fn, (LLVMValueRef *) Op_val(Args), + Wosize_val(Args), Then, Catch, String_val(Name)); +} + +/* llvalue -> llvalue array -> llbasicblock -> llbasicblock -> string -> + llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_invoke_bc(value Args[], int NumArgs) { + return llvm_build_invoke_nat((LLVMValueRef) Args[0], Args[1], + (LLVMBasicBlockRef) Args[2], + (LLVMBasicBlockRef) Args[3], + Args[4], Args[5]); +} + +/* llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_unwind(value B) { + return LLVMBuildUnwind(Builder_val(B)); +} + +/* llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_unreachable(value B) { + return LLVMBuildUnreachable(Builder_val(B)); +} + +/*--... Arithmetic .........................................................--*/ + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_add(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildAdd(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nsw_add(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildNSWAdd(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nuw_add(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildNUWAdd(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fadd(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildFAdd(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_sub(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildSub(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nsw_sub(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildNSWSub(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nuw_sub(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildNUWSub(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fsub(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildFSub(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_mul(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildMul(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nsw_mul(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildNSWMul(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nuw_mul(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildNUWMul(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fmul(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildFMul(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_udiv(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildUDiv(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_sdiv(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildSDiv(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_exact_sdiv(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildExactSDiv(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fdiv(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildFDiv(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_urem(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildURem(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_srem(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildSRem(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_frem(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildFRem(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_shl(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildShl(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_lshr(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildLShr(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_ashr(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildAShr(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_and(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildAnd(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_or(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildOr(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_xor(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildXor(Builder_val(B), LHS, RHS, String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_neg(LLVMValueRef X, + value Name, value B) { + return LLVMBuildNeg(Builder_val(B), X, String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nsw_neg(LLVMValueRef X, + value Name, value B) { + return LLVMBuildNSWNeg(Builder_val(B), X, String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_nuw_neg(LLVMValueRef X, + value Name, value B) { + return LLVMBuildNUWNeg(Builder_val(B), X, String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fneg(LLVMValueRef X, + value Name, value B) { + return LLVMBuildFNeg(Builder_val(B), X, String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_not(LLVMValueRef X, + value Name, value B) { + return LLVMBuildNot(Builder_val(B), X, String_val(Name)); +} + +/*--... Memory .............................................................--*/ + +/* lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_alloca(LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildAlloca(Builder_val(B), Ty, String_val(Name)); +} + +/* lltype -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_array_alloca(LLVMTypeRef Ty, LLVMValueRef Size, + value Name, value B) { + return LLVMBuildArrayAlloca(Builder_val(B), Ty, Size, String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_load(LLVMValueRef Pointer, + value Name, value B) { + return LLVMBuildLoad(Builder_val(B), Pointer, String_val(Name)); +} + +/* llvalue -> llvalue -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_store(LLVMValueRef Value, LLVMValueRef Pointer, + value B) { + return LLVMBuildStore(Builder_val(B), Value, Pointer); +} + +/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_gep(LLVMValueRef Pointer, value Indices, + value Name, value B) { + return LLVMBuildGEP(Builder_val(B), Pointer, + (LLVMValueRef *) Op_val(Indices), Wosize_val(Indices), + String_val(Name)); +} + +/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_in_bounds_gep(LLVMValueRef Pointer, + value Indices, value Name, + value B) { + return LLVMBuildInBoundsGEP(Builder_val(B), Pointer, + (LLVMValueRef *) Op_val(Indices), + Wosize_val(Indices), String_val(Name)); +} + +/* llvalue -> int -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_struct_gep(LLVMValueRef Pointer, + value Index, value Name, + value B) { + return LLVMBuildStructGEP(Builder_val(B), Pointer, + Int_val(Index), String_val(Name)); +} + +/* string -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_global_string(value Str, value Name, value B) { + return LLVMBuildGlobalString(Builder_val(B), String_val(Str), + String_val(Name)); +} + +/* string -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_global_stringptr(value Str, value Name, + value B) { + return LLVMBuildGlobalStringPtr(Builder_val(B), String_val(Str), + String_val(Name)); +} + +/*--... Casts ..............................................................--*/ + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_trunc(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildTrunc(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_zext(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildZExt(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_sext(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildSExt(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fptoui(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildFPToUI(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fptosi(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildFPToSI(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_uitofp(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildUIToFP(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_sitofp(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildSIToFP(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fptrunc(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildFPTrunc(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fpext(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildFPExt(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_prttoint(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildPtrToInt(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_inttoptr(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildIntToPtr(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_bitcast(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildBitCast(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_zext_or_bitcast(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildZExtOrBitCast(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_sext_or_bitcast(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildSExtOrBitCast(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_trunc_or_bitcast(LLVMValueRef X, + LLVMTypeRef Ty, value Name, + value B) { + return LLVMBuildTruncOrBitCast(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_pointercast(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildPointerCast(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_intcast(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildIntCast(Builder_val(B), X, Ty, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fpcast(LLVMValueRef X, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildFPCast(Builder_val(B), X, Ty, String_val(Name)); +} + +/*--... Comparisons ........................................................--*/ + +/* Icmp.t -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_icmp(value Pred, + LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildICmp(Builder_val(B), Int_val(Pred) + LLVMIntEQ, LHS, RHS, + String_val(Name)); +} + +/* Fcmp.t -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_fcmp(value Pred, + LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildFCmp(Builder_val(B), Int_val(Pred), LHS, RHS, + String_val(Name)); +} + +/*--... Miscellaneous instructions .........................................--*/ + +/* (llvalue * llbasicblock) list -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_phi(value Incoming, value Name, value B) { + value Hd, Tl; + LLVMValueRef FirstValue, PhiNode; + + assert(Incoming != Val_int(0) && "Empty list passed to Llvm.build_phi!"); + + Hd = Field(Incoming, 0); + FirstValue = (LLVMValueRef) Field(Hd, 0); + PhiNode = LLVMBuildPhi(Builder_val(B), LLVMTypeOf(FirstValue), + String_val(Name)); + + for (Tl = Incoming; Tl != Val_int(0); Tl = Field(Tl, 1)) { + value Hd = Field(Tl, 0); + LLVMAddIncoming(PhiNode, (LLVMValueRef*) &Field(Hd, 0), + (LLVMBasicBlockRef*) &Field(Hd, 1), 1); + } + + return PhiNode; +} + +/* llvalue -> llvalue array -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_call(LLVMValueRef Fn, value Params, + value Name, value B) { + return LLVMBuildCall(Builder_val(B), Fn, (LLVMValueRef *) Op_val(Params), + Wosize_val(Params), String_val(Name)); +} + +/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_select(LLVMValueRef If, + LLVMValueRef Then, LLVMValueRef Else, + value Name, value B) { + return LLVMBuildSelect(Builder_val(B), If, Then, Else, String_val(Name)); +} + +/* llvalue -> lltype -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_va_arg(LLVMValueRef List, LLVMTypeRef Ty, + value Name, value B) { + return LLVMBuildVAArg(Builder_val(B), List, Ty, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_extractelement(LLVMValueRef Vec, + LLVMValueRef Idx, + value Name, value B) { + return LLVMBuildExtractElement(Builder_val(B), Vec, Idx, String_val(Name)); +} + +/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_insertelement(LLVMValueRef Vec, + LLVMValueRef Element, + LLVMValueRef Idx, + value Name, value B) { + return LLVMBuildInsertElement(Builder_val(B), Vec, Element, Idx, + String_val(Name)); +} + +/* llvalue -> llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_shufflevector(LLVMValueRef V1, LLVMValueRef V2, + LLVMValueRef Mask, + value Name, value B) { + return LLVMBuildShuffleVector(Builder_val(B), V1, V2, Mask, String_val(Name)); +} + +/* llvalue -> int -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_extractvalue(LLVMValueRef Aggregate, + value Idx, value Name, value B) { + return LLVMBuildExtractValue(Builder_val(B), Aggregate, Int_val(Idx), + String_val(Name)); +} + +/* llvalue -> llvalue -> int -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_insertvalue(LLVMValueRef Aggregate, + LLVMValueRef Val, value Idx, + value Name, value B) { + return LLVMBuildInsertValue(Builder_val(B), Aggregate, Val, Int_val(Idx), + String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_is_null(LLVMValueRef Val, value Name, + value B) { + return LLVMBuildIsNull(Builder_val(B), Val, String_val(Name)); +} + +/* llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_is_not_null(LLVMValueRef Val, value Name, + value B) { + return LLVMBuildIsNotNull(Builder_val(B), Val, String_val(Name)); +} + +/* llvalue -> llvalue -> string -> llbuilder -> llvalue */ +CAMLprim LLVMValueRef llvm_build_ptrdiff(LLVMValueRef LHS, LLVMValueRef RHS, + value Name, value B) { + return LLVMBuildPtrDiff(Builder_val(B), LHS, RHS, String_val(Name)); +} + + +/*===-- Memory buffers ----------------------------------------------------===*/ + +/* string -> llmemorybuffer + raises IoError msg on error */ +CAMLprim value llvm_memorybuffer_of_file(value Path) { + CAMLparam1(Path); + char *Message; + LLVMMemoryBufferRef MemBuf; + + if (LLVMCreateMemoryBufferWithContentsOfFile(String_val(Path), + &MemBuf, &Message)) + llvm_raise(llvm_ioerror_exn, Message); + + CAMLreturn((value) MemBuf); +} + +/* unit -> llmemorybuffer + raises IoError msg on error */ +CAMLprim LLVMMemoryBufferRef llvm_memorybuffer_of_stdin(value Unit) { + char *Message; + LLVMMemoryBufferRef MemBuf; + + if (LLVMCreateMemoryBufferWithSTDIN(&MemBuf, &Message)) + llvm_raise(llvm_ioerror_exn, Message); + + return MemBuf; +} + +/* llmemorybuffer -> unit */ +CAMLprim value llvm_memorybuffer_dispose(LLVMMemoryBufferRef MemBuf) { + LLVMDisposeMemoryBuffer(MemBuf); + return Val_unit; +} + +/*===-- Pass Managers -----------------------------------------------------===*/ + +/* unit -> [ `Module ] PassManager.t */ +CAMLprim LLVMPassManagerRef llvm_passmanager_create(value Unit) { + return LLVMCreatePassManager(); +} + +/* llmodule -> [ `Function ] PassManager.t -> bool */ +CAMLprim value llvm_passmanager_run_module(LLVMModuleRef M, + LLVMPassManagerRef PM) { + return Val_bool(LLVMRunPassManager(PM, M)); +} + +/* [ `Function ] PassManager.t -> bool */ +CAMLprim value llvm_passmanager_initialize(LLVMPassManagerRef FPM) { + return Val_bool(LLVMInitializeFunctionPassManager(FPM)); +} + +/* llvalue -> [ `Function ] PassManager.t -> bool */ +CAMLprim value llvm_passmanager_run_function(LLVMValueRef F, + LLVMPassManagerRef FPM) { + return Val_bool(LLVMRunFunctionPassManager(FPM, F)); +} + +/* [ `Function ] PassManager.t -> bool */ +CAMLprim value llvm_passmanager_finalize(LLVMPassManagerRef FPM) { + return Val_bool(LLVMFinalizeFunctionPassManager(FPM)); +} + +/* PassManager.any PassManager.t -> unit */ +CAMLprim value llvm_passmanager_dispose(LLVMPassManagerRef PM) { + LLVMDisposePassManager(PM); + return Val_unit; +} diff --git a/contrib/llvm/bindings/ocaml/target/Makefile b/contrib/llvm/bindings/ocaml/target/Makefile new file mode 100644 index 0000000..3c48cd8 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/target/Makefile @@ -0,0 +1,19 @@ +##===- bindings/ocaml/target/Makefile ----------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_target interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +LIBRARYNAME := llvm_target +UsedComponents := target +UsedOcamlInterfaces := llvm + +include ../Makefile.ocaml diff --git a/contrib/llvm/bindings/ocaml/target/llvm_target.ml b/contrib/llvm/bindings/ocaml/target/llvm_target.ml new file mode 100644 index 0000000..ea5341d --- /dev/null +++ b/contrib/llvm/bindings/ocaml/target/llvm_target.ml @@ -0,0 +1,44 @@ +(*===-- llvm_target.ml - LLVM Ocaml Interface ------------------*- OCaml -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +module Endian = struct + type t = + | Big + | Little +end + +module TargetData = struct + type t + + external create : string -> t = "llvm_targetdata_create" + external add : t -> [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_targetdata_add" + external as_string : t -> string = "llvm_targetdata_as_string" + external invalidate_struct_layout : t -> Llvm.lltype -> unit + = "llvm_targetdata_invalidate_struct_layout" + external dispose : t -> unit = "llvm_targetdata_dispose" +end + +external byte_order : TargetData.t -> Endian.t = "llvm_byte_order" +external pointer_size : TargetData.t -> int = "llvm_pointer_size" +external intptr_type : TargetData.t -> Llvm.lltype = "LLVMIntPtrType" +external size_in_bits : TargetData.t -> Llvm.lltype -> Int64.t + = "llvm_size_in_bits" +external store_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_store_size" +external abi_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_abi_size" +external abi_align : TargetData.t -> Llvm.lltype -> int = "llvm_abi_align" +external stack_align : TargetData.t -> Llvm.lltype -> int = "llvm_stack_align" +external preferred_align : TargetData.t -> Llvm.lltype -> int + = "llvm_preferred_align" +external preferred_align_of_global : TargetData.t -> Llvm.llvalue -> int + = "llvm_preferred_align_of_global" +external element_at_offset : TargetData.t -> Llvm.lltype -> Int64.t -> int + = "llvm_element_at_offset" +external offset_of_element : TargetData.t -> Llvm.lltype -> int -> Int64.t + = "llvm_offset_of_element" diff --git a/contrib/llvm/bindings/ocaml/target/llvm_target.mli b/contrib/llvm/bindings/ocaml/target/llvm_target.mli new file mode 100644 index 0000000..a82e1b6 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/target/llvm_target.mli @@ -0,0 +1,102 @@ +(*===-- llvm_target.mli - LLVM Ocaml Interface -----------------*- OCaml -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +(** Target Information. + + This interface provides an ocaml API for LLVM target information, + the classes in the Target library. *) + +module Endian : sig + type t = + | Big + | Little +end + +module TargetData : sig + type t + + (** [TargetData.create rep] parses the target data string representation [rep]. + See the constructor llvm::TargetData::TargetData. *) + external create : string -> t = "llvm_targetdata_create" + + (** [add_target_data td pm] adds the target data [td] to the pass manager [pm]. + Does not take ownership of the target data. + See the method llvm::PassManagerBase::add. *) + external add : t -> [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_targetdata_add" + + (** [as_string td] is the string representation of the target data [td]. + See the constructor llvm::TargetData::TargetData. *) + external as_string : t -> string = "llvm_targetdata_as_string" + + (** Struct layouts are speculatively cached. If a TargetDataRef is alive when + types are being refined and removed, this method must be called whenever a + struct type is removed to avoid a dangling pointer in this cache. + See the method llvm::TargetData::InvalidateStructLayoutInfo. *) + external invalidate_struct_layout : t -> Llvm.lltype -> unit + = "llvm_targetdata_invalidate_struct_layout" + + (** Deallocates a TargetData. + See the destructor llvm::TargetData::~TargetData. *) + external dispose : t -> unit = "llvm_targetdata_dispose" +end + +(** Returns the byte order of a target, either LLVMBigEndian or + LLVMLittleEndian. + See the method llvm::TargetData::isLittleEndian. *) +external byte_order : TargetData.t -> Endian.t = "llvm_byte_order" + +(** Returns the pointer size in bytes for a target. + See the method llvm::TargetData::getPointerSize. *) +external pointer_size : TargetData.t -> int = "llvm_pointer_size" + +(** Returns the integer type that is the same size as a pointer on a target. + See the method llvm::TargetData::getIntPtrType. *) +external intptr_type : TargetData.t -> Llvm.lltype = "LLVMIntPtrType" + +(** Computes the size of a type in bytes for a target. + See the method llvm::TargetData::getTypeSizeInBits. *) +external size_in_bits : TargetData.t -> Llvm.lltype -> Int64.t + = "llvm_size_in_bits" + +(** Computes the storage size of a type in bytes for a target. + See the method llvm::TargetData::getTypeStoreSize. *) +external store_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_store_size" + +(** Computes the ABI size of a type in bytes for a target. + See the method llvm::TargetData::getTypeAllocSize. *) +external abi_size : TargetData.t -> Llvm.lltype -> Int64.t = "llvm_abi_size" + +(** Computes the ABI alignment of a type in bytes for a target. + See the method llvm::TargetData::getTypeABISize. *) +external abi_align : TargetData.t -> Llvm.lltype -> int = "llvm_abi_align" + +(** Computes the call frame alignment of a type in bytes for a target. + See the method llvm::TargetData::getTypeABISize. *) +external stack_align : TargetData.t -> Llvm.lltype -> int = "llvm_stack_align" + +(** Computes the preferred alignment of a type in bytes for a target. + See the method llvm::TargetData::getTypeABISize. *) +external preferred_align : TargetData.t -> Llvm.lltype -> int + = "llvm_preferred_align" + +(** Computes the preferred alignment of a global variable in bytes for a target. + See the method llvm::TargetData::getPreferredAlignment. *) +external preferred_align_of_global : TargetData.t -> Llvm.llvalue -> int + = "llvm_preferred_align_of_global" + +(** Computes the structure element that contains the byte offset for a target. + See the method llvm::StructLayout::getElementContainingOffset. *) +external element_at_offset : TargetData.t -> Llvm.lltype -> Int64.t -> int + = "llvm_element_at_offset" + +(** Computes the byte offset of the indexed struct element for a target. + See the method llvm::StructLayout::getElementContainingOffset. *) +external offset_of_element : TargetData.t -> Llvm.lltype -> int -> Int64.t + = "llvm_offset_of_element" diff --git a/contrib/llvm/bindings/ocaml/target/target_ocaml.c b/contrib/llvm/bindings/ocaml/target/target_ocaml.c new file mode 100644 index 0000000..cc20e81 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/target/target_ocaml.c @@ -0,0 +1,109 @@ +/*===-- target_ocaml.c - LLVM Ocaml Glue ------------------------*- C++ -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file glues LLVM's ocaml interface to its C interface. These functions *| +|* are by and large transparent wrappers to the corresponding C functions. *| +|* *| +|* Note that these functions intentionally take liberties with the CAMLparamX *| +|* macros, since most of the parameters are not GC heap objects. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#include "llvm-c/Target.h" +#include "caml/alloc.h" + +/* string -> TargetData.t */ +CAMLprim LLVMTargetDataRef llvm_targetdata_create(value StringRep) { + return LLVMCreateTargetData(String_val(StringRep)); +} + +/* TargetData.t -> [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_targetdata_add(LLVMTargetDataRef TD, LLVMPassManagerRef PM){ + LLVMAddTargetData(TD, PM); + return Val_unit; +} + +/* TargetData.t -> string */ +CAMLprim value llvm_targetdata_as_string(LLVMTargetDataRef TD) { + char *StringRep = LLVMCopyStringRepOfTargetData(TD); + value Copy = copy_string(StringRep); + LLVMDisposeMessage(StringRep); + return Copy; +} + +/* TargetData.t -> Llvm.lltype -> unit */ +CAMLprim value llvm_targetdata_invalidate_struct_layout(LLVMTargetDataRef TD, + LLVMTypeRef Ty) { + LLVMInvalidateStructLayout(TD, Ty); + return Val_unit; +} + +/* TargetData.t -> unit */ +CAMLprim value llvm_targetdata_dispose(LLVMTargetDataRef TD) { + LLVMDisposeTargetData(TD); + return Val_unit; +} + +/* TargetData.t -> Endian.t */ +CAMLprim value llvm_byte_order(LLVMTargetDataRef TD) { + return Val_int(LLVMByteOrder(TD)); +} + +/* TargetData.t -> int */ +CAMLprim value llvm_pointer_size(LLVMTargetDataRef TD) { + return Val_int(LLVMPointerSize(TD)); +} + +/* TargetData.t -> Llvm.lltype -> Int64.t */ +CAMLprim value llvm_size_in_bits(LLVMTargetDataRef TD, LLVMTypeRef Ty) { + return caml_copy_int64(LLVMSizeOfTypeInBits(TD, Ty)); +} + +/* TargetData.t -> Llvm.lltype -> Int64.t */ +CAMLprim value llvm_store_size(LLVMTargetDataRef TD, LLVMTypeRef Ty) { + return caml_copy_int64(LLVMStoreSizeOfType(TD, Ty)); +} + +/* TargetData.t -> Llvm.lltype -> Int64.t */ +CAMLprim value llvm_abi_size(LLVMTargetDataRef TD, LLVMTypeRef Ty) { + return caml_copy_int64(LLVMABISizeOfType(TD, Ty)); +} + +/* TargetData.t -> Llvm.lltype -> int */ +CAMLprim value llvm_abi_align(LLVMTargetDataRef TD, LLVMTypeRef Ty) { + return Val_int(LLVMABIAlignmentOfType(TD, Ty)); +} + +/* TargetData.t -> Llvm.lltype -> int */ +CAMLprim value llvm_stack_align(LLVMTargetDataRef TD, LLVMTypeRef Ty) { + return Val_int(LLVMCallFrameAlignmentOfType(TD, Ty)); +} + +/* TargetData.t -> Llvm.lltype -> int */ +CAMLprim value llvm_preferred_align(LLVMTargetDataRef TD, LLVMTypeRef Ty) { + return Val_int(LLVMPreferredAlignmentOfType(TD, Ty)); +} + +/* TargetData.t -> Llvm.llvalue -> int */ +CAMLprim value llvm_preferred_align_of_global(LLVMTargetDataRef TD, + LLVMValueRef GlobalVar) { + return Val_int(LLVMPreferredAlignmentOfGlobal(TD, GlobalVar)); +} + +/* TargetData.t -> Llvm.lltype -> Int64.t -> int */ +CAMLprim value llvm_element_at_offset(LLVMTargetDataRef TD, LLVMTypeRef Ty, + value Offset) { + return Val_int(LLVMElementAtOffset(TD, Ty, Int_val(Offset))); +} + +/* TargetData.t -> Llvm.lltype -> int -> Int64.t */ +CAMLprim value llvm_offset_of_element(LLVMTargetDataRef TD, LLVMTypeRef Ty, + value Index) { + return caml_copy_int64(LLVMOffsetOfElement(TD, Ty, Int_val(Index))); +} diff --git a/contrib/llvm/bindings/ocaml/transforms/Makefile b/contrib/llvm/bindings/ocaml/transforms/Makefile new file mode 100644 index 0000000..95b00c8 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/transforms/Makefile @@ -0,0 +1,18 @@ +##===- bindings/ocaml/transforms/Makefile ------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../.. +DIRS = scalar + +ocamldoc: + $(Verb) for i in $(DIRS) ; do \ + $(MAKE) -C $$i ocamldoc; \ + done + +include $(LEVEL)/Makefile.common diff --git a/contrib/llvm/bindings/ocaml/transforms/scalar/Makefile b/contrib/llvm/bindings/ocaml/transforms/scalar/Makefile new file mode 100644 index 0000000..cbaffa4 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/transforms/scalar/Makefile @@ -0,0 +1,20 @@ +##===- bindings/ocaml/transforms/scalar/Makefile -----------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## +# +# This is the makefile for the Objective Caml Llvm_scalar_opts interface. +# +##===----------------------------------------------------------------------===## + +LEVEL := ../../../.. +LIBRARYNAME := llvm_scalar_opts +DONT_BUILD_RELINKED := 1 +UsedComponents := scalaropts +UsedOcamlInterfaces := llvm + +include ../../Makefile.ocaml diff --git a/contrib/llvm/bindings/ocaml/transforms/scalar/llvm_scalar_opts.ml b/contrib/llvm/bindings/ocaml/transforms/scalar/llvm_scalar_opts.ml new file mode 100644 index 0000000..5699152 --- /dev/null +++ b/contrib/llvm/bindings/ocaml/transforms/scalar/llvm_scalar_opts.ml @@ -0,0 +1,75 @@ +(*===-- llvm_scalar_opts.ml - LLVM Ocaml Interface -------------*- OCaml -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +external add_constant_propagation : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_constant_propagation" +external add_sccp : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_sccp" +external add_dead_store_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_dead_store_elimination" +external add_aggressive_dce : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_aggressive_dce" +external +add_scalar_repl_aggregation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_scalar_repl_aggregation" +external add_ind_var_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_ind_var_simplification" +external +add_instruction_combination : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_instruction_combination" +external add_licm : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_licm" +external add_loop_unswitch : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_unswitch" +external add_loop_unroll : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_unroll" +external add_loop_rotation : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_rotation" +external add_loop_index_split : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_index_split" +external +add_memory_to_register_promotion : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_memory_to_register_promotion" +external +add_memory_to_register_demotion : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_memory_to_register_demotion" +external add_reassociation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_reassociation" +external add_jump_threading : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_jump_threading" +external add_cfg_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_cfg_simplification" +external +add_tail_call_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_tail_call_elimination" +external add_gvn : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_gvn" +external add_memcpy_opt : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_memcpy_opt" +external add_loop_deletion : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_deletion" +external +add_lib_call_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_lib_call_simplification" diff --git a/contrib/llvm/bindings/ocaml/transforms/scalar/llvm_scalar_opts.mli b/contrib/llvm/bindings/ocaml/transforms/scalar/llvm_scalar_opts.mli new file mode 100644 index 0000000..9f95fbc --- /dev/null +++ b/contrib/llvm/bindings/ocaml/transforms/scalar/llvm_scalar_opts.mli @@ -0,0 +1,123 @@ +(*===-- llvm_scalar_opts.mli - LLVM Ocaml Interface ------------*- OCaml -*-===* + * + * The LLVM Compiler Infrastructure + * + * This file is distributed under the University of Illinois Open Source + * License. See LICENSE.TXT for details. + * + *===----------------------------------------------------------------------===*) + +(** Scalar Transforms. + + This interface provides an ocaml API for LLVM scalar transforms, the + classes in the [LLVMScalarOpts] library. *) + +(** See the [llvm::createConstantPropogationPass] function. *) +external add_constant_propagation : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_constant_propagation" + +(** See the [llvm::createSCCPPass] function. *) +external add_sccp : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_sccp" + +(** See [llvm::createDeadStoreEliminationPass] function. *) +external add_dead_store_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_dead_store_elimination" + +(** See The [llvm::createAggressiveDCEPass] function. *) +external add_aggressive_dce : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_aggressive_dce" + +(** See the [llvm::createScalarReplAggregatesPass] function. *) +external +add_scalar_repl_aggregation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_scalar_repl_aggregation" + +(** See the [llvm::createIndVarSimplifyPass] function. *) +external add_ind_var_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_ind_var_simplification" + +(** See the [llvm::createInstructionCombiningPass] function. *) +external +add_instruction_combination : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_instruction_combination" + +(** See the [llvm::createLICMPass] function. *) +external add_licm : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_licm" + +(** See the [llvm::createLoopUnswitchPass] function. *) +external add_loop_unswitch : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_unswitch" + +(** See the [llvm::createLoopUnrollPass] function. *) +external add_loop_unroll : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_unroll" + +(** See the [llvm::createLoopRotatePass] function. *) +external add_loop_rotation : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_rotation" + +(** See the [llvm::createLoopIndexSplitPass] function. *) +external add_loop_index_split : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_index_split" + +(** See the [llvm::createPromoteMemoryToRegisterPass] function. *) +external +add_memory_to_register_promotion : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_memory_to_register_promotion" + +(** See the [llvm::createDemoteMemoryToRegisterPass] function. *) +external +add_memory_to_register_demotion : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_memory_to_register_demotion" + +(** See the [llvm::createReassociatePass] function. *) +external add_reassociation : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_reassociation" + +(** See the [llvm::createJumpThreadingPass] function. *) +external add_jump_threading : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_jump_threading" + +(** See the [llvm::createCFGSimplificationPass] function. *) +external add_cfg_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_cfg_simplification" + +(** See the [llvm::createTailCallEliminationPass] function. *) +external +add_tail_call_elimination : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_tail_call_elimination" + +(** See the [llvm::createGVNPass] function. *) +external add_gvn : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_gvn" + +(** See the [llvm::createMemCpyOptPass] function. *) +external add_memcpy_opt : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_memcpy_opt" + +(** See the [llvm::createLoopDeletionPass] function. *) +external add_loop_deletion : [<Llvm.PassManager.any] Llvm.PassManager.t + -> unit + = "llvm_add_loop_deletion" + +(** See the [llvm::createSimplifyLibCallsPass] function. *) +external +add_lib_call_simplification : [<Llvm.PassManager.any] Llvm.PassManager.t -> unit + = "llvm_add_lib_call_simplification" diff --git a/contrib/llvm/bindings/ocaml/transforms/scalar/scalar_opts_ocaml.c b/contrib/llvm/bindings/ocaml/transforms/scalar/scalar_opts_ocaml.c new file mode 100644 index 0000000..c20bdde --- /dev/null +++ b/contrib/llvm/bindings/ocaml/transforms/scalar/scalar_opts_ocaml.c @@ -0,0 +1,152 @@ +/*===-- scalar_opts_ocaml.c - LLVM Ocaml Glue -------------------*- C++ -*-===*\ +|* *| +|* The LLVM Compiler Infrastructure *| +|* *| +|* This file is distributed under the University of Illinois Open Source *| +|* License. See LICENSE.TXT for details. *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file glues LLVM's ocaml interface to its C interface. These functions *| +|* are by and large transparent wrappers to the corresponding C functions. *| +|* *| +|* Note that these functions intentionally take liberties with the CAMLparamX *| +|* macros, since most of the parameters are not GC heap objects. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#include "llvm-c/Transforms/Scalar.h" +#include "caml/mlvalues.h" +#include "caml/misc.h" + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_constant_propagation(LLVMPassManagerRef PM) { + LLVMAddConstantPropagationPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_sccp(LLVMPassManagerRef PM) { + LLVMAddSCCPPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_dead_store_elimination(LLVMPassManagerRef PM) { + LLVMAddDeadStoreEliminationPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_aggressive_dce(LLVMPassManagerRef PM) { + LLVMAddAggressiveDCEPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_scalar_repl_aggregation(LLVMPassManagerRef PM) { + LLVMAddScalarReplAggregatesPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_ind_var_simplification(LLVMPassManagerRef PM) { + LLVMAddIndVarSimplifyPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_instruction_combination(LLVMPassManagerRef PM) { + LLVMAddInstructionCombiningPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_licm(LLVMPassManagerRef PM) { + LLVMAddLICMPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_loop_unswitch(LLVMPassManagerRef PM) { + LLVMAddLoopUnrollPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_loop_unroll(LLVMPassManagerRef PM) { + LLVMAddLoopUnrollPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_loop_rotation(LLVMPassManagerRef PM) { + LLVMAddLoopRotatePass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_loop_index_split(LLVMPassManagerRef PM) { + LLVMAddLoopIndexSplitPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_memory_to_register_promotion(LLVMPassManagerRef PM) { + LLVMAddPromoteMemoryToRegisterPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_memory_to_register_demotion(LLVMPassManagerRef PM) { + LLVMAddDemoteMemoryToRegisterPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_reassociation(LLVMPassManagerRef PM) { + LLVMAddReassociatePass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_jump_threading(LLVMPassManagerRef PM) { + LLVMAddJumpThreadingPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_cfg_simplification(LLVMPassManagerRef PM) { + LLVMAddCFGSimplificationPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_tail_call_elimination(LLVMPassManagerRef PM) { + LLVMAddTailCallEliminationPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_gvn(LLVMPassManagerRef PM) { + LLVMAddGVNPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_memcpy_opt(LLVMPassManagerRef PM) { + LLVMAddMemCpyOptPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_loop_deletion(LLVMPassManagerRef PM) { + LLVMAddLoopDeletionPass(PM); + return Val_unit; +} + +/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */ +CAMLprim value llvm_add_lib_call_simplification(LLVMPassManagerRef PM) { + LLVMAddSimplifyLibCallsPass(PM); + return Val_unit; +} |