licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
docs
107
```@meta CurrentModule = Charts ``` ```@docs plot PlotConfig PlotData PlotDataMarker PlotlyLine Trace ```
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
docs
226
```@meta CurrentModule = Layouts ``` ```@docs ColorBar Font ErrorBar GeoProjection MCenter PlotLayout PlotAnnotation PlotLayoutAxis PlotLayoutGeo PlotLayoutGrid PlotLayoutLegend PlotLayoutMapbox PlotLayoutTitle PRotation ```
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.14.3
9aee830051af43009b3c97651f124246fdabb86a
docs
62
```@meta CurrentModule = StipplePlotly ``` ```@docs deps ```
StipplePlotly
https://github.com/GenieFramework/StipplePlotly.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
349
push!(LOAD_PATH,"../src/") using Documenter, TravelingSalesmanHeuristics makedocs( format = Documenter.HTML(), sitename = "Traveling Salesman Heuristics", pages = [ "Home" => "index.md", "Heuristics" => "heuristics.md", "Examples" => "examples.md" ] ) deploydocs( repo = "github.com/evanfields/TravelingSalesmanHeuristics.jl.git", )
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
14094
module TravelingSalesmanHeuristics using Random, LinearAlgebra include("helpers.jl") include("simulated_annealing.jl") include("lowerbounds.jl") export solve_tsp, lowerbound, repetitive_heuristic, two_opt, nearest_neighbor, cheapest_insertion, simulated_annealing, farthest_insertion """ solve_tsp(distmat; quality_factor = 40) Approximately solve a TSP by specifying a distance matrix. Return a tuple `(path, cost)`. The optional keyword `quality_factor` (real number in [0,100]; defaults to 40) specifies the tradeoff between computation time and quality of solution returned. Higher values tend to lead to better solutions found at the cost of more computation time. !!! note It is not guaranteed that a call with a high `quality_factor` will always run slower or return a better solution than a call with a lower `quality_factor`, though this is typically the case. A `quality_factor` of 100 neither guarantees an optimal solution nor the best solution that can be found via extensive use of the methods in this package. !!! danger TravelingSalesmanHeuristics does not support distance matrices with arbitrary indexing; indices must be `1:n` in both dimensions for `n` cities. See also: individual heuristic methods such as [`farthest_insertion`](@ref) """ function solve_tsp(distmat::AbstractMatrix{T}; quality_factor::Real = 40.0) where {T<:Real} if quality_factor < 0 || quality_factor > 100 @warn "quality_factor keyword passed to solve_tsp must be in [0,100]" quality_factor = clamp(quality_factor, 0, 100) end lowest_threshold = 5 # begin adding heuristics as dictated by the quality_factor, # starting with the very fastest answers = Vector{Tuple{Vector{Int}, T}}() push!(answers, farthest_insertion(distmat; do2opt = false)) if quality_factor < lowest_threshold # fastest heuristic and out return answers[1] end # otherwise, we'll try several heuristics and return the best # add any nearest neighbor heuristics as dictated by quality_factor if quality_factor >= 60 # repetitive-NN, 2-opt on each iter push!(answers, repetitive_heuristic(distmat, nearest_neighbor; do2opt = true)) elseif quality_factor >= 25 # repetitive-NN, 2-opt on final rnnpath, _ = repetitive_heuristic(distmat, nearest_neighbor; do2opt = false) push!(answers, two_opt(distmat, rnnpath)) elseif quality_factor >= 15 # NN w/ 2-opt push!(answers, nearest_neighbor(distmat; do2opt = true)) end # farthest insertions as needed if quality_factor >= 70 # repetitive-FI, 2-opt on each push!(answers, repetitive_heuristic(distmat, farthest_insertion; do2opt = true)) elseif quality_factor >= 5 # FI w/ 2-opt push!(answers, farthest_insertion(distmat; do2opt = true)) end # cheapest insertions if quality_factor >= 90 # repetitive-CI w/ 2-opt on each push!(answers, repetitive_heuristic(distmat, cheapest_insertion; do2opt = true)) elseif quality_factor >= 35 push!(answers, cheapest_insertion(distmat; do2opt = true)) end # simulated annealing refinement, seeded with best so far if quality_factor >= 80 _, bestind = findmin([pc[2] for pc in answers]) bestpath, bestcost = answers[bestind] nstart = ceil(Int, (quality_factor - 79)/5) push!(answers, simulated_annealing(distmat; num_starts = nstart, init_path = bestpath) ) end # pick best _, bestind = findmin([pc[2] for pc in answers]) return answers[bestind] end ### # path generation heuristics ### """ nearest_neighbor(distmat) Approximately solve a TSP using the nearest neighbor heuristic. `distmat` is a square real matrix where distmat[i,j] represents the distance from city `i` to city `j`. The matrix needn't be symmetric and can contain negative values. Return a tuple `(path, pathcost)`. # Optional keyword arguments: - `firstcity::Union{Int, Nothing}`: specifies the city to begin the path on. Passing `nothing` or not specifying a value corresponds to random selection. - `closepath::Bool = true`: whether to include the arc from the last city visited back to the first city in cost calculations. If true, the first city appears first and last in the path. - `do2opt::Bool = true`: whether to refine the path found by 2-opt switches (corresponds to removing path crossings in the planar Euclidean case). """ function nearest_neighbor(distmat::AbstractMatrix{T} where {T<:Real}; firstcity::Union{Int, Nothing} = rand(1:size(distmat, 1)), repetitive::Bool = false, closepath::Bool = true, do2opt::Bool = true) # must have a square matrix num_cities = check_square(distmat, "Must pass a square distance matrix to nearest_neighbor") # extract a safe int value for firstcity if firstcity == nothing # random first city firstcityint = rand(1:num_cities) else # an int was passed firstcityint = firstcity if !(1 <= firstcityint <= num_cities) error("firstcity of $(firstcity) passed to `nearest_neighbor`" * " out of range [1, $(num_cities)]") end end # calling with KW repetitive is deprecated; pass the call to repetitive_heuristic if repetitive @warn ("Calling `nearest_neighbor` with keyword `repetitive` is deprecated;'" * " instead call `repetitive_heuristic(distmat, nearest_neighbor; kwargs...)`") return repetitive_heuristic(distmat, nearest_neighbor; closepath = closepath, do2opt = do2opt) end # put first city on path path = Vector{Int}() push!(path, firstcityint) # cities to visit citiesToVisit = collect(1:(firstcityint - 1)) append!(citiesToVisit, collect((firstcityint + 1):num_cities)) # nearest neighbor loop while !isempty(citiesToVisit) curCity = path[end] dists = distmat[curCity, citiesToVisit] _, nextInd = findmin(dists) nextCity = citiesToVisit[nextInd] push!(path, nextCity) deleteat!(citiesToVisit, nextInd) end # complete cycle? (duplicates first city) if closepath push!(path, firstcityint) end # do swaps? if do2opt path, _ = two_opt(distmat, path) end return (path, pathcost(distmat, path)) end """ cheapest_insertion(distmat::Matrix, initpath::AbstractArray{Int}) Given a distance matrix and an initial path, complete the tour by repeatedly doing the cheapest insertion. Return a tuple `(path, cost)`. The initial path must have length at least 2, but can be simply `[i, i]` for some city index `i` which corresponds to starting with a loop at city `i`. !!! note Insertions are always in the interior of the current path so this heuristic can also be used for non-closed TSP paths. Currently the implementation is a naive ``n^3`` algorithm. """ function cheapest_insertion(distmat::AbstractMatrix{T}, initpath::AbstractVector{S}) where {T<:Real, S<:Integer} check_square(distmat, "Distance matrix passed to cheapest_insertion must be square.") n = size(distmat, 1) path = Vector{Int}(initpath) # collect cities to visited visitus = setdiff(collect(1:n), initpath) while !isempty(visitus) bestCost = Inf bestInsertion = (-1, -1) for k in visitus for after in 1:(length(path) - 1) # can't insert after end of path c = inscost(k, after, path, distmat) if c < bestCost bestCost = c bestInsertion = (k, after) end end end # bestInsertion now holds (k, after) # insert into path, remove from to-do list k, after = bestInsertion insert!(path, after + 1, k) visitus = setdiff(visitus, k) end return (path, pathcost(distmat, path)) end """ cheapest_insertion(distmat; ...) Complete a tour using cheapest insertion with a single-city loop as the initial path. Return a tuple `(path, cost)`. ### Optional keyword arguments: - `firstcity::Union{Int, Nothing}`: specifies the city to begin the path on. Passing `nothing` or not specifying a value corresponds to random selection. - `do2opt::Bool = true`: whether to improve the path found by 2-opt swaps. """ function cheapest_insertion(distmat::AbstractMatrix{T} where{T<:Real}; firstcity::Union{Int, Nothing} = rand(1:size(distmat, 1)), repetitive::Bool = false, do2opt::Bool = true) #infer size num_cities = size(distmat, 1) # calling with KW repetitive is deprecated; pass the call to repetitive_heuristic if repetitive @warn "Calling `cheapest_insertionr` with keyword `repetitive` is deprecated;'" * " instead call `repetitive_heuristic(distmat, cheapest_insertion; kwargs...)`" return repetitive_heuristic(distmat, cheapest_insertion; do2opt = do2opt) end # extract a safe int value for firstcity if firstcity == nothing # random first city firstcityint = rand(1:num_cities) else # an int was passed firstcityint = firstcity if !(1 <= firstcityint <= num_cities) error("firstcity of $(firstcity) passed to `cheapest_insertion`" * " out of range [1, $(num_cities)]") end end # okay, we're not repetitive, put a loop on the first city path, cost = cheapest_insertion(distmat, [firstcityint, firstcityint]) # user may have asked for 2-opt refinement if do2opt path, cost = two_opt(distmat, path) end return path, cost end """ farthest_insertion(distmat; ...) Generate a TSP path using the farthest insertion strategy. `distmat` must be a square real matrix. Return a tuple `(path, cost)`. ### Optional arguments: - `firstCity::Int`: specifies the city to begin the path on. Not specifying a value corresponds to random selection. - `do2opt::Bool = true`: whether to improve the path by 2-opt swaps. """ function farthest_insertion(distmat::AbstractMatrix{T}; firstcity::Int = rand(1:size(distmat, 1)), do2opt::Bool = true) where {T<:Real} n = check_square(distmat, "Must pass square distance matrix to farthest_insertion.") if firstcity < 1 || firstcity > n error("First city for farthest_insertion must be in [1,...,n]") end smallval = minimum(distmat) - one(T) # will never be the max path = Int[firstcity, firstcity] sizehint!(path, n + 1) dists_to_tour = (distmat[firstcity, :] + distmat[:, firstcity]) / 2 dists_to_tour[firstcity] = smallval while length(path) < n + 1 # city farthest from tour _, nextcity = findmax(dists_to_tour) # find where to add it bestcost = inscost(nextcity, 1, path, distmat) bestind = 1 for ind in 2:(length(path) - 1) altcost = inscost(nextcity, ind, path, distmat) if altcost < bestcost bestcost = altcost bestind = ind end end # and add the next city at the best spot found insert!(path, bestind + 1, nextcity) # +1 since arg to insert! is where nextcity ends up # update distances to tour dists_to_tour[nextcity] = smallval for i in 1:n c = dists_to_tour[i] if c == zero(T) # i already in tour continue end altc = (distmat[i, nextcity] + distmat[nextcity, i]) / 2 # cost i--nextcity if altc < c @inbounds dists_to_tour[i] = altc end end end if do2opt path, _ = two_opt(distmat, path) end return path, pathcost(distmat, path) end ### # path improvement heuristics ### """ two_opt(distmat, path) Improve `path` by doing 2-opt switches (i.e. reversing part of the path) until doing so no longer reduces the cost. Return a tuple `(improved_path, improved_cost)`. On large problem instances this heuristic can be slow, but it is highly recommended on small and medium problem instances. See also [`simulated_annealing`](@ref) for another path generation heuristic. """ function two_opt(distmat::AbstractMatrix{T}, path::AbstractVector{S}) where {T<:Real, S<:Integer} # We can accelerate if the instance is symmetric issymmetric(distmat) && (distmat = Symmetric(distmat)) return _two_opt_logic(distmat, path) end function _two_opt_logic(distmat::AbstractMatrix{T}, path::AbstractVector{S}) where {T<:Real, S<:Integer} # size checks n = length(path) if size(distmat, 1) != size(distmat, 2) error("Distance matrix passed to two_opt must be square.") end # don't modify input path = copy(path) # Int is a bitstype # how much must each swap improve the cost? thresh = improvement_threshold(T) # main loop # check every possible switch until no 2-swaps reduce objective # if the path passed in is a loop (first/last nodes are the same) # then we must keep these the endpoints of the path the same # ie just keep it a loop, and therefore it doesn't matter which node is at the end # if the path is not a cycle, we should respect the endpoints switchLow = 2 switchHigh = n - 1 need_to_loop = true # always look for swaps at least once while need_to_loop need_to_loop = false # we can't change the first for i in switchLow:(switchHigh-1) for j in switchHigh:-1:(i+1) cost_change = pathcost_rev_delta(distmat, path, i, j) if cost_change + thresh <= 0 need_to_loop = true reverse!(path, i, j) end end end end return path, pathcost(distmat, path) end end # module
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
6709
### # helpers ### # make sure a passed distance matrix is a square function check_square(m, msg) n = size(m, 1) if n != size(m, 2) error(msg) end return n end """ rotate_circuit(circuit::AbstractArray{<:Integer}, desired_start::Integer) "Rotate" a closed circuit so that it starts (and ends) at `desired_start`. E.g. `rotate_circuit([1,2,3,1], 2) == [2,3,1,2]`. `circuit` must be a closed path. """ function rotate_circuit(circuit, desired_start) if first(circuit) != last(circuit) throw(DomainError(circuit, "Circuit passed to rotate_circuit is not closed.")) end first(circuit) == desired_start && return copy(circuit) start_ind = findfirst(circuit .== desired_start) return vcat( circuit[start_ind:end], circuit[2:start_ind] ) end """ legal_circuit(circuit::AbstractArray{<:Integer}) Check that an array of integers is a valid circuit. A valid circuit over `n` locations has length `n+1`. The first `n` entries are a permutation of `1, ..., n`, and the `(n+1)`-st entry is equal to the first entry. """ function legal_circuit(circuit) n = length(circuit) - 1 return circuit[1] == circuit[end] && sort(circuit[1:(end-1)]) == 1:n end """ repetitive_heuristic(distmat::Matrix, heuristic::Function, repetitive_kw::Symbol; keywords...) For each `i` in `1:n`, run `heuristic` with keyword `repetitive_kw` set to `i`. Return the tuple `(bestpath, bestcost)`. By default, `repetitive_kw` is `:firstcity`, which is appropriate for the `farthest_insertion`, `cheapest_insertion`, and `nearest_neighbor` heuristics. Any keywords passed to `repetitive_heuristic` are passed along to each call of `heuristic`. For example, `repetitive_heuristic(dm, nearest_neighbor; do2opt = true)` will perform 2-opt for each of the `n` nearest neighbor paths. !!! note The repetitive heuristic calls are parallelized with threads. For optimum speed make sure Julia is running with multiple threads. """ function repetitive_heuristic(dm::AbstractMatrix{T}, heuristic::Function, repetitive_kw = :firstcity; kwargs...) where {T<:Real} # call the heuristic with varying starting cities n = size(dm, 1) results_list = Vector{Tuple{Vector{Int}, T}}(undef, n) Threads.@threads for i in 1:n results_list[i] = heuristic(dm; kwargs..., repetitive_kw => i) end bestind, bestcost = 1, results_list[1][2] for i in 2:n if results_list[i][2] < bestcost bestind, bestcost = i, results_list[i][2] end end return results_list[bestind] end # helper for readable one-line path costs # optionally specify the bounds for the subpath we want the cost of # defaults to the whole path # but when calculating reversed path costs can help to have subpath costs function pathcost(distmat::AbstractMatrix{T}, path::AbstractArray{S}, lb::Int = 1, ub::Int = length(path)) where {T<:Real, S<:Integer} cost = zero(T) for i in lb:(ub - 1) @inbounds cost += distmat[path[i], path[i+1]] end return cost end "Compute the change in cost from reversing the subset of the path from indices `revLow` to `revHigh`, inclusive." function pathcost_rev_delta(distmat::AbstractMatrix{T}, path::AbstractArray{S}, revLow::Int, revHigh::Int) where {T<:Real, S<:Integer} cost_delta = zero(T) # if there's an initial unreversed section if revLow > 1 # new step onto the reversed section @inbounds cost_delta += distmat[path[revLow - 1], path[revHigh]] # no longer pay the cost of old step onto the reversed section @inbounds cost_delta -= distmat[path[revLow - 1], path[revLow]] end # new cost of the reversed section for i in revHigh:-1:(revLow + 1) @inbounds cost_delta += distmat[path[i], path[i-1]] end # no longer pay the forward cost of the reversed section for i in revLow:(revHigh - 1) @inbounds cost_delta -= distmat[path[i], path[i+1]] end # if there's an unreversed section after the reversed bit if revHigh < length(path) # new step out of the reversed section @inbounds cost_delta += distmat[path[revLow], path[revHigh + 1]] # no longer pay the old cost of stepping out of the reversed section @inbounds cost_delta -= distmat[path[revHigh], path[revHigh + 1]] end return cost_delta end "Specialized for symmetric matrices: compute the change in cost from reversing the subset of the path from indices `revLow` to `revHigh`, inclusive." function pathcost_rev_delta(distmat::Symmetric, path::AbstractArray{S}, revLow::Int, revHigh::Int) where {S<:Integer} cost_delta = zero(eltype(distmat)) # if there's an initial unreversed section if revLow > 1 # new step onto the reversed section @inbounds cost_delta += distmat[path[revLow - 1], path[revHigh]] # no longer pay the cost of old step onto the reversed section @inbounds cost_delta -= distmat[path[revLow - 1], path[revLow]] end # The actual cost of walking along the reversed section doesn't change # because the distance matrix is symmetric. # if there's an unreversed section after the reversed bit if revHigh < length(path) # new step out of the reversed section @inbounds cost_delta += distmat[path[revLow], path[revHigh + 1]] # no longer pay the old cost of stepping out of the reversed section @inbounds cost_delta -= distmat[path[revHigh], path[revHigh + 1]] end return cost_delta end "Due to floating point imprecision, various path refinement heuristics may get stuck in infinite loops as both doing and un-doing a particular change apparently improves the path cost. For example, floating point error may suggest that both reversing and un-reversing a path for a symmetric TSP instance improves the cost slightly. To avoid such false-improvement infinite loops, limit refinement heuristics to improvements with some minimum magnitude defined by the element type of the distance matrix." improvement_threshold(T::Type{<:Integer}) = one(T) improvement_threshold(T::Type{<:AbstractFloat}) = sqrt(eps(one(T))) improvement_threshold(::Type{<:Real}) = sqrt(eps(1.0)) "Cost of inserting city `k` after index `after` in path `path` with costs `distmat`." function inscost( k::Int, after::Int, path::AbstractArray{<:Integer}, distmat::AbstractMatrix{<:Real} ) return distmat[path[after], k] + distmat[k, path[after + 1]] - distmat[path[after], path[after + 1]] end
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
5070
# I implement several simple but super loose bounds # These only apply to closed tours # the cost of a tour must be >= the sum over all vertices of # the cost of the cheapest edge leaving that vertex # likewise for the cheapest edge entering that vertex # since we must go to and leave each vertex function vertwise_bound(distmat::AbstractMatrix{T}) where {T<:Real} # the simple code below would tend to pick out the 0 costs on the diagonal # so make a doctored copy of the distance matrix with high costs on the diagonal m = maximum(distmat) distmat_nodiag = distmat + m * I leaving = sum(minimum(distmat_nodiag, dims = 2)) entering = sum(minimum(distmat_nodiag, dims = 1)) return maximum([leaving, entering]) end # helper to get min spanning trees # returns a (n-1) long Vector of Tuple{Int, Int} where each tuple is an edge in the MST # and the total weight of the tree # the matrix passed in must be symmetric or you won't get out the minimum spanning tree function minspantree(dm::AbstractMatrix{T}) where {T<:Real} # accepts views mst_edges = Vector{Tuple{Int, Int}}() mst_cost = zero(T) n = size(dm, 1) # we keep a running list of the distance from each vertex to the partly formed tree # rather than using 0 for vertices already in the tree, we use a large value so that we # can find the closest non-tree vertex via call to Julia's `findmin`. bigval = maximum(dm) + one(T) tree_dists = dm[1,:] # distance to tree closest_tree_verts = ones(Int, n) tree_dists[1] = bigval # vert 1 is in tree now for _ in 1:(n-1) # need to add n - 1 other verts to tree cost, newvert = findmin(tree_dists) treevert = closest_tree_verts[newvert] # add costs and edges mst_cost += cost if treevert < newvert push!(mst_edges, (treevert, newvert)) else push!(mst_edges, (newvert, treevert)) end # update distances to tree tree_dists[newvert] = bigval for i in 1:n c = tree_dists[i] if c >= bigval # already in tree continue end # maybe this vertex is closer to the new vertex than the prior iteration's tree if c > dm[i, newvert] tree_dists[i] = dm[i, newvert] closest_tree_verts[i] = newvert end end end return mst_edges, mst_cost end # a simplified/looser version of Held-Karp bounds # any tour is a spanning tree on (n-1) verts plus two edges # from the left out vert # so the maximum over all verts (as the left out vert) of # MST cost on remaining vertices plus 2 cheapest edges from # the left out vert is a lower bound # for extra simplicity, the distance matrix is modified to be symmetric so we can treat # the underlying graph as undirected. This also doesn't help the bound! function hkinspired_bound(distmat::AbstractMatrix{T}) where {T<:Real} n = size(distmat, 1) if size(distmat, 2) != n error("Must pass square distance matrix to hkinspired_bound") end # make a symmetric copy of the distance matrix distmat = copy(distmat) for i in 1:n, j in 1:n if i == j continue end d = min(distmat[i,j], distmat[j,i]) distmat[i,j] = d distmat[j,i] = d end # get a view of the distmat with one vertex deleted function del_vert(v) keep = [1:(v-1) ; (v+1):n] return view(distmat, keep, keep) end # make sure min(distmat[v,:]) doesn't pick diagonal elements m = maximum(distmat) distmat_nodiag = distmat + m * I # lower bound the optimal cost by leaving a single vertex out # forming spanning tree on the rest # connecting the left-out vertex function cost_leave_out(v) dmprime = del_vert(v) _, c = minspantree(dmprime) c += minimum(distmat_nodiag[v,:]) c += minimum(distmat_nodiag[:,v]) return c end return maximum(map(cost_leave_out, 1:n)) end # best lower bound we have """ lowerbound(distmat) Lower bound the cost of the optimal TSP tour. At present, the bounds considered are a simple bound based on the minimum cost of entering and exiting each city and a slightly better bound inspired by the Held-Karp bounds; note that the implementation here is simpler and less tight than proper HK bounds. The Held-Karp-inspired bound requires computing many spanning trees. For a faster but typically looser bound, use `TravelingSalesmanHeuristics.vertwise_bound(distmat)`. !!! note The spanning tree bounds are only correct on symmetric problem instances and will not be used if the passed `distmat` is not symmetric. If you wish to use these bounds anyway, (e.g. for near-symmetric instances), use `TravelingSalesmanHeuristics.hkinspired_bound`. """ function lowerbound(distmat::AbstractMatrix{T} where {T<:Real}) vb = vertwise_bound(distmat) if !issymmetric(distmat) return vb end return max(vb, hkinspired_bound(distmat)) end
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
3204
# this file contains code for the simulated annealing TSP heuristic """ simulated_annealing(distmat; ...) Use a simulated annealing strategy to return a closed tour. The temperature decays exponentially from `init_temp` to `final_temp`. Return a tuple `(path, cost)`. ### Optional keyword arguments: - `steps::Int = 50n^2`: number of steps to take; defaults to 50n^2 where n is number of cities - `num_starts::Int = 1`: number of times to run the simulated annealing algorithm, each time starting with a random path, or `init_path` if non-null. Defaults to 1. - `init_temp::Real = exp(8)`: initial temperature which controls initial chance of accepting an inferior tour. - `final_temp::Real = exp(-6.5)` final temperature which controls final chance of accepting an inferior tour; lower values roughly correspond to a longer period of 2-opt. - `init_path::Union{Vector{Int}, Nothing} = nothing`: path to start the annealing from. Either a `Vector{Int}` or `nothing`. If a `Vector{Int}` is given, it will be used as the initial path; otherwise a random initial path is used. """ function simulated_annealing(distmat::Matrix{T} where {T<:Real}; steps = 50*length(distmat), num_starts = 1, init_temp = exp(8), final_temp = exp(-6.5), init_path::Union{Vector{Int}, Nothing} = nothing) # check inputs n = check_square(distmat, "Must pass a square distance matrix to simulated_annealing.") # cooling rate: we multiply by a constant mult each step cool_rate = (final_temp / init_temp)^(1 / (steps - 1)) # do SA with a single starting path function sahelper!(path) temp = init_temp / cool_rate # divide by cool_rate so when we first multiply we get init_temp n = size(distmat, 1) for i in 1:steps temp *= cool_rate # take a step # keep first and last cities fixed first, last = rand(2:n), rand(2:n) if first > last first, last = last, first end cost_delta = pathcost_rev_delta(distmat, path, first, last) @fastmath accept = cost_delta < 0 ? true : rand() < exp(-cost_delta / temp) # should we accept? if accept reverse!(path, first, last) end end return path, pathcost(distmat, path) end # unpack the initial path if init_path == nothing randstart = true path = randpath(n) else if !legal_circuit(init_path) error("The init_path passed to simulated_annealing must be a legal circuit.") end randstart = false path = init_path end cost = pathcost(distmat, path) for _ in 1:num_starts path_this_start = randstart ? randpath(n) : deepcopy(init_path) otherpath, othercost = sahelper!(path_this_start) if othercost < cost cost = othercost path = otherpath end end return path, cost end function randpath(n::Int) path = shuffle(1:n) push!(path, path[1]) # loop return path end
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
2361
# This file contains "tests for humans:" functions you might use to reassure # yourself that the heuristics are working properly or chose a heuristic for your # particular problem. The functions in this file are not run by Travis and this file # requires several packages (such as Gadfly) not listed in the REQUIRE. using Gadfly using TravelingSalesmanHeuristics using Distances # use Gadfly to plot a TSP visualization # pts must be a 2 x n matrix and path the vector of column indices function visTSP(pts, path) pts = pts[:,path] plot(x = pts[1,:], y = pts[2,:], Geom.path, Geom.point) end # visualize a planar TSP in the unit square # specify number of points and solution method function visPlanarTSP(n = 10, heuristic = nearest_neighbor; extraArgs...) pts = rand(2, n) distMat = pairwise(Euclidean(), pts, pts) path, _ = heuristic(distMat; extraArgs...) visTSP(pts, path) end # compare some heuristics function compareHeuristics(n = 20) pts = rand(2, n) dm = pairwise(Euclidean(), pts, pts) println("Simple lower bound: $(lowerbound(dm))") singlenn_no2opt = nearest_neighbor(dm, do2opt = false) println("Single start nearest neighbor without 2-opt has cost $(singlenn_no2opt[2])") singlenn_2opt = nearest_neighbor(dm, do2opt = true) println("Single start nearest neighbor with 2-opt has cost $(singlenn_2opt[2])") repnn_no2opt = repetitive_heuristic(dm, nearest_neighbor, do2opt = false) println("Multi start nearest neighbor without 2-opt has cost $(repnn_no2opt[2])") repnn_2opt = repetitive_heuristic(dm, nearest_neighbor, do2opt = true) println("Multi start nearest neighbor with 2-opt has cost $(repnn_2opt[2])") singleci_no2opt = cheapest_insertion(dm, do2opt = false) println("Single start cheapest insert without 2-opt has cost $(singleci_no2opt[2])") singleci_2opt = cheapest_insertion(dm, do2opt = true) println("Single start cheapest insert with 2-opt has cost $(singleci_2opt[2])") multici_no2opt = repetitive_heuristic(dm, cheapest_insertion, do2opt = false) println("Multi start cheapest insert without 2-opt has cost $(multici_no2opt[2])") multici_2opt = repetitive_heuristic(dm, cheapest_insertion, do2opt = true) println("Multi start cheapest insert with 2-opt has cost $(multici_2opt[2])") simanneal = simulated_annealing(dm) println("Simulated annealing with default arguments has cost $(simanneal[2])") end
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
3178
#= This file contains a set of synthetic TSP test cases, plus some small helper functions for running the test cases. It's mostly intended for comparing algorithms in development and probably isn't of much use to end users. Note the dependence on DataFrames and Distributions as well, which aren't part of the TravelingSalesmanHeuristics environment. =# using Random using LinearAlgebra: norm using DataFrames using Distributions using TravelingSalesmanHeuristics TSP = TravelingSalesmanHeuristics struct TestCase distmat description::String end """ runcase(alg, case) Test an algorithm on a TestCase. `alg` must be a function `distmat -> (path, cost)`. Return a NamedTuple describing the result. The `bound` and `excess` keys in the resulting tuple are respectively the vertwise bound and a simple scale-adjusted cost (lower is still better).""" function runcase(alg, case::TestCase) time = @elapsed path, cost = alg(case.distmat) path = TSP.rotate_circuit(path, 1) bound = TSP.vertwise_bound(case.distmat) excess = (cost - bound) / abs(bound) return (;time, path, cost, bound, excess, description = case.description) end """Run multiple test cases and return the result as a DataFrame. `alg` should be a function `distmat -> (path, cost)`.""" function runcases(alg, cases) return DataFrame(runcase.(alg, cases)) end "Euclidean distance matrix from a matrix of points, one col per point, one row per dim" function _distmat_from_pts(pts) n = size(pts, 2) return [norm(pts[:,i] - pts[:,j]) for i in 1:n, j in 1:n] end """Generate a list of Euclidean test cases. For each dimension and number of points, generate a test case in a unit square, a squashed rectangle, and a spherical shell.""" function generate_cases_euclidean(; seed = 47, dimensions = [2, 5, 15], ns = [5, 25, 100, 500], ) Random.seed!(seed) cases = TestCase[] for d in dimensions, n in ns # hypercube pts = rand(d, n) dm = _distmat_from_pts(pts) push!(cases, TestCase(dm, "euclidean_hypercube_$(d)d_$(n)n")) # squashed hypercube pts = rand(d, n) pts[1:(d ÷ 2), :] ./= 10 dm = _distmat_from_pts(pts) push!(cases, TestCase(dm, "euclidean_squashedhypercube_$(d)d_$(n)n")) # hypersphere shell pts = randn(d, n) for i in 1:n pts[:,i] ./= norm(pts[:,i]) end dm = _distmat_from_pts(pts) push!(cases, TestCase(dm, "euclidean_sphereshell_$(d)d_$(n)n")) end return cases end """Generate non-Euclidean test cases by starting with the Eculidean cases and adding IID noise to each distance measurement, producing cases which are nonsymmetric and may have negative travel costs.""" function generate_cases_euclidean_plus_noise(; dists = [ Normal(), Exponential(1), ], euclidean_args... ) euclidean_cases = generate_cases_euclidean(euclidean_args...) return [ TestCase( case.distmat .+ rand(dist, size(case.distmat)), case.description * "_plus_" * string(dist) ) for case in euclidean_cases for dist in dists ] end
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
code
5969
using TravelingSalesmanHeuristics const TSP = TravelingSalesmanHeuristics using Test using Random using LinearAlgebra ### # helpers ### # generate a Euclidean distance matrix for n points in the unit square function generate_planar_distmat(n) pts = rand(2, n) return [norm(pts[:,i] - pts[:,j]) for i in 1:n, j in 1:n] end # test that a path is acceptable: # - at most one city appears twice, and if so must be first and last # - all values 1:n are present where n is the maximum city index, and no other values function testpathvalidity(path, iscycle) if iscycle @test path[1] == path[end] end n = iscycle ? length(path) - 1 : length(path) @test sort(unique(path)) == collect(1:n) end # tests that a path-cost pair is consistent with the distance matrix # basically a reimplementation of `pathcost`, but hey...less likely to double a mistake? function testpathcost(path, cost, dm) c = zero(eltype(dm)) for i in 1:(length(path) - 1) c += dm[path[i], path[i+1]] end @test isapprox(c, cost) end ### # main tests ### function test_nearest_neighbor() distmats = [generate_planar_distmat(10), generate_planar_distmat(2)] for dm in distmats n = size(dm, 1) randstartcity = rand(1:n) # standard path, cost = nearest_neighbor(dm) @test cost > 0 testpathvalidity(path, true) # repetitive path, cost = repetitive_heuristic(dm, nearest_neighbor) @test cost > 0 testpathvalidity(path, true) # no loop, 2 opt path, cost = nearest_neighbor(dm, closepath = false) @test cost > 0 testpathvalidity(path, false) # no loop, no 2 opt path, cost = nearest_neighbor(dm, closepath = false, do2opt = false) @test cost > 0 testpathvalidity(path, false) # fixed start, no loop path, cost = nearest_neighbor(dm, closepath = false, firstcity = randstartcity) @test cost > 0 testpathvalidity(path, false) end dm_bad = rand(3,2) @test_throws ErrorException nearest_neighbor(dm_bad) end function test_cheapest_insertion() # default random start dm = generate_planar_distmat(8) path, cost = cheapest_insertion(dm) @test cost > 0 testpathvalidity(path, true) # should be a closed path # repetitive start path, cost = repetitive_heuristic(dm, cheapest_insertion) @test cost > 0 testpathvalidity(path, true) # bad input dmbad = rand(2,3) @test_throws ErrorException cheapest_insertion(dmbad) end function test_farthest_insertion() # standard symmetric case dm = generate_planar_distmat(8) path, cost = farthest_insertion(dm) testpathvalidity(path, true) testpathcost(path, cost, dm) # invalid argument @test_throws ErrorException farthest_insertion(dm; firstcity = 0) # asymmetric matrix dm = rand(20, 20) path, cost = farthest_insertion(dm; firstcity = 1, do2opt = true) testpathvalidity(path, true) testpathcost(path, cost, dm) end function test_simulated_annealing() dm = generate_planar_distmat(14) # single start path, cost = simulated_annealing(dm) @test cost > 0 testpathvalidity(path, true) # closed path # multi-start dm = generate_planar_distmat(8) path, cost = simulated_annealing(dm, num_starts = 3) @test cost > 0 testpathvalidity(path, true) # also closed # given init path init_path = collect(1:8) push!(init_path, 1) reverse!(init_path, 2, 6) path, cost = simulated_annealing(dm; init_path = init_path) @test cost > lowerbound(dm) testpathvalidity(path, true) # still closed end function test_bounds() dm = generate_planar_distmat(2) path, cost = solve_tsp(dm) lb = lowerbound(dm) @test lb <= cost dm = generate_planar_distmat(30) path, cost = solve_tsp(dm) lb = lowerbound(dm) @test lb <= cost end function test_path_costs() dm = [1 2 3; 4 5 6; 7 8 9] p1 = [1, 2, 3, 1] orig_cost = 2 + 6 + 7 @test TSP.pathcost(dm, p1) == orig_cost # various reverse indices to test revs = [(1,4), (2,3), (2,4), (3,3)] for rev in revs path_rev = reverse(p1, rev[1], rev[2]) @test TSP.pathcost(dm, path_rev) ≈ orig_cost + TSP.pathcost_rev_delta(dm, p1, rev[1], rev[2]) end end function test_rotate() # rotate a circuit @test TSP.rotate_circuit([11,12,13,11], 12) == [12,13,11,12] # not a circuit @test_throws DomainError TSP.rotate_circuit([1,2,3,4], 2) end function test_solve_tsp() dm = rand(10,10) quality_factors = [-1, 0, 1.1, 35, 101] for qf in quality_factors path, cost = solve_tsp(dm; quality_factor = qf) testpathvalidity(path, true) end end function test_two_opt() n = 50 dm = generate_planar_distmat(n) path = collect(1:n) path_2opt, _ = two_opt(dm, path) testpathvalidity(path_2opt, false) # shouldn't affect endpoints @test path_2opt[1] == 1 @test path_2opt[end] == n cycle = vcat(path, 1) cycle_2opt, _ = two_opt(dm, cycle) testpathvalidity(cycle_2opt, true) # same endpoints @test cycle_2opt[1] == 1 == cycle_2opt[n+1] end function test_atypical_types() # rational distance matrix dm = [rationalize(rand(); tol = .01) for i in 1:10, j in 1:10] initpath = 1:2:9 # not a Vector, but <:AbstractVector{<:Int} p, c = cheapest_insertion(dm, initpath) testpathvalidity(p, false) # Symmetric matrix type. <: AbstractMatrix, not a matrix. dm = Symmetric(rand(15,15)) p, c = solve_tsp(dm; quality_factor = 60) testpathvalidity(p, true) end ### # run ### println("Hello tester") Random.seed!(47) test_nearest_neighbor() test_cheapest_insertion() test_farthest_insertion() test_simulated_annealing() test_bounds() test_path_costs() test_rotate() test_solve_tsp() test_two_opt() test_atypical_types() println("Done testing.")
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
docs
1873
## 2020-5-28 ## - Various bugfixes and housekeeping over the last almost 2 years. - Some heuristics will now run much faster on symmetric problems. - Only Julia versions >= 1.0 are supported. ## 2018-7-11 ## - New version with support for Julia 0.7; dropped support for previous Julia versions. ## 2018-1-25 ## - The package now has proper documentation (built with Documenter). - A wider variety of types should be supported; e.g. your distance matrix can have `Rational` arguments, initial paths can be `AbstractVectors`, etc. - `simulated_annealing` will no longer sometimes return a worse path than you pass it. - `lowerbound` checks that your problem instance is symmetric before using spanning tree bounds. ## 2017-7-14 ## - `solve_tsp` accepts an optional `quality_factor` keyword specifying (without units or guarantees) the trade-off between computation time and solution quality. ## 2017-7-13 ## - Julia version 0.4 is no longer supported. - Introduced helper function `repetitive_heuristic(distmat, heuristic; keywords...)` for repeating a heuristic with many starting cities. The repetitition is parallelized with a `@threads` loop. - Using the `repetitive` keyword for `nearest_neighbor` or `cheapest_insertion` is deprecated. Instead, use `repetitive_heuristic(distmat, heuristic; ...)`. - The `firstcity` keyword should now be an `Int`, not a `Nullable{Int}`. (For now, backwards compatibility is maintained). If the first city is not specified, a random city is chosen. - The available path generation heuristics now include farthest insertion. Small experiments suggest farthest insertion is the fastest of the generation heuristics and performs decently well on Euclidean instances. ## 2017-1-26 ## The previous update broke Julia 0.4 compatibility. Thanks to tkelman for the find and fix. I expect to drop 0.4 support when Julia 0.6 is released.
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
docs
1080
# TravelingSalesmanHeuristics [![codecov.io](https://codecov.io/github/evanfields/TravelingSalesmanHeuristics.jl/coverage.svg?branch=master)](https://codecov.io/github/evanfields/TravelingSalesmanHeuristics.jl?branch=master) [![Project Status: Active – The project has reached a stable, usable state and is receiving occasional updates.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://evanfields.github.io/TravelingSalesmanHeuristics.jl/stable) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://evanfields.github.io/TravelingSalesmanHeuristics.jl/dev) `TravelingSalesmanHeuristics` is a Julia package containing simple heuristics for the [traveling salesman problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem). I welcome any contributions, suggestions, feature requests, pull requests, criticisms, etc. The package has reached a stable usable state, and while ongoing development is sporadic, I attempt to keep the package well-maintained.
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
docs
5249
This page gives some examples of using TravelingSalesmanHeuristics. For convenience and so we can easily visualize the problems, we'll use planar Euclidean instances generated as follows: ``` using TravelingSalesmanHeuristics using LinearAlgebra using Random function generate_instance(n) Random.seed!(47) pts = rand(2, n) distmat = [norm(pts[:,i] - pts[:,j]) for i in 1:n, j in 1:n] return pts, distmat end ``` In this function and throughout the examples, I routinely reseed the global random number generator (with value 47, which is a [great number](http://magazine.pomona.edu/pomoniana/2015/02/13/the-mystery-of-47/)) so that (hopefully) the examples can be reproduced, at least if you're using the same Julia version. Some handy visualization functions: ``` using Gadfly plot_instance(pts) = plot(x = pts[1,:], y = pts[2,:], Geom.point, Guide.xlabel(nothing), Guide.ylabel(nothing)) function plot_solution(pts, path, extras = []) ptspath = pts[:,path] plot(x = ptspath[1,:], y = ptspath[2,:], Geom.point, Geom.path, Guide.xlabel(nothing), Guide.ylabel(nothing), extras...) end ``` ## Basic usage First, generate and plot a small instance: ``` pts, distmat = generate_instance(20) plot_instance(pts) ``` ![small instance](images/examples/small_instance.png) A quick solution (run it twice to avoid measuring precompilation): ``` Random.seed!(47) @time path, cost = solve_tsp(distmat; quality_factor = 5) 0.000050 seconds (34 allocations: 3.797 KiB) ([4, 19, 17, 14, 5, 1, 20, 9, 16, 2 … 6, 10, 15, 11, 18, 8, 12, 13, 3, 4], 3.8300484331007696) plot_solution(pts, path) ``` ![small instance solved](images/examples/small_instance_solved.png) It looks like we've found the optimum path, and a higher `quality_factor` doens't give a better objective: ``` Random.seed!(47) @time path, cost = solve_tsp(distmat; quality_factor = 80) 0.006352 seconds (92.43 k allocations: 1.551 MiB) ([2, 16, 9, 20, 1, 5, 14, 17, 19, 4 … 13, 12, 8, 18, 11, 15, 10, 6, 7, 2], 3.830048433100769) ``` On a bigger instance, the `quality_factor` makes more of a difference: ``` pts, distmat = generate_instance(200) @time path, cost = solve_tsp(distmat; quality_factor = 5) 0.008352 seconds (34 allocations: 21.031 KiB) ([53, 93, 60, 29, 159, 135, 187, 8, 127, 178 … 11, 10, 154, 59, 80, 6, 108, 188, 57, 53], 10.942110669021305) @time path, cost = solve_tsp(distmat; quality_factor = 80) 2.066067 seconds (9.00 M allocations: 177.469 MiB, 2.61% gc time) ([20, 27, 76, 23, 92, 146, 161, 194, 152, 171 … 66, 36, 147, 124, 32, 70, 34, 120, 47, 20], 10.552544594904079) plot_solution(pts, path) ``` ![big instance solved](images/examples/big_instance_solved.png) Note that increasing `quality_factor` greatly increases the runtime but only slightly improves the objective. This pattern is common. ## Using a specific heuristic ```julia pts, distmat = generate_instance(100) path_nn, cost_nn = nearest_neighbor(distmat; firstcity = 1, do2opt = false) # cost is 9.93 path_nn2opt, cost_nn2opt = nearest_neighbor(distmat; firstcity = 1, do2opt = true) # cost is 8.15 path_fi, cost_fi = farthest_insertion(distmat; firstcity = 1, do2opt = false) # cost is 8.12 path_fi2opt, cost_fi2opt = farthest_insertion(distmat; firstcity = 1, do2opt = true) # cost is 8.06 ``` ![path nearest neighbor](images/examples/path_nn.png)![path nearest neighbor 2-opt](images/examples/path_nn2opt.png) ![path farthest insertion](images/examples/path_fi.png)![path farthest insertion 2-opt](images/examples/path_fi2opt.png) ## Simulated annealing refinements The current simulated annealing implementation is very simple (pull requests most welcome!), but it can nonetheless be useful for path refinement. Here's a quick example: ```julia pts, distmat = generate_instance(300) path_quick, cost_quick = solve_tsp(distmat) ([104, 185, 290, 91, 294, 269, 40, 205, 121, 271 … 156, 237, 97, 288, 137, 63, 257, 168, 14, 104], 13.568672416542647) path_sa, cost_sa = simulated_annealing(distmat; init_path = Nullable(path_quick), num_starts = 10) ([104, 14, 168, 257, 63, 137, 46, 101, 44, 193 … 220, 269, 40, 121, 205, 294, 91, 290, 185, 104], 13.298439981448235) ``` ## Lower bounds In the previous section, we generated a 300 point TSP in the unit square. Is the above solution with cost about `13.3` any good? We can get a rough lower bound: ``` lowerbound(distmat) 11.5998918075456 ``` Let's see where that bound came from: ``` TravelingSalesmanHeuristics.vertwise_bound(distmat) 8.666013688087942 TravelingSalesmanHeuristics.hkinspired_bound(distmat) 11.5998918075456 ``` Because our problem is symmetric, the latter bound based on spanning trees applies, and this bound is typically tighter. If we use an integer program to solve the TSP to certified optimality (beyond the scope of this package), we find that the optimal solution has cost about `12.82`. So the final path found by simulated annealing is about `3.7%` worse than the optimal path, and the lower bound reported is about `9.5%` lower than the optimal cost. These values are quite typical for mid-sized Euclidean instances. ![300 point optimal path](images/examples/300_optimal.png)![300 point simulated annealing path](images/examples/300_sa.png)
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
docs
1365
This page describes the heuristics currently implemented by this package. The heuristics are split into *path generation* heuristics, which create an initial path from a problem instance (specified by a distance matrix) and *path refinement* heuristics which take an input path and attempt to improve it. ## Path generation heuristics ```@docs nearest_neighbor ``` ```@docs farthest_insertion ``` ```@docs cheapest_insertion ``` ## Path refinement heuristics ```@docs two_opt ``` ```@docs simulated_annealing ``` ## Repetitive heuristics Many of the heuristics in this package require some starting state. For example, the nearest neighbor heuristic begins at a first city and then iteratively continues to whichever unvisited city is closest to the current city. Therefore, running the heuristic with different choices for the first city may produce different final paths. At the cost of increased computation time, a better path can often be found by starting the heuristic method at each city. The convenience method `repetitive_heuristic` is provided to help with this use case: ```@docs repetitive_heuristic ``` ## Lower bounds A simple lower bound on the cost of the optimal tour is provided. This bound uses no problem-specific structure; if you know some details of your problem instance, you can probably find a tighter bound. ```@docs lowerbound ```
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.3.4
723b16cbc89f37986f09a374cc35efca3ff89a23
docs
3545
## Overview `TravelingSalesmanHeuristics` implements basic heuristics for the [traveling salesman problem](https://en.wikipedia.org/wiki/Travelling_salesman_problem). `TravelingSalesmanHeuristics` implements the nearest neighbor, farthest insertion, and cheapest insertion strategies for path generation, the 2-opt strategy for path refinement, and a simulated annealing heuristic which can be used for path generation or refinement. A simple spanning tree type lower bound is also implemented. ## When to use Though the traveling salesman problem is the canonical NP-hard problem, in practice heuristic methods are often unnecessary. Modern integer programming solvers such as CPLEX and Gurobi can quickly provide excellent (even certifiably optimal) solutions. If you are interested in solving TSP instances to optimality, I highly recommend the [JuMP](https://github.com/JuliaOpt/JuMP.jl) package. The very slick [TravelingSalesmanExact](https://github.com/ericphanson/TravelingSalesmanExact.jl) package implements the problem formulation and provides some nifty visualization utilities. Even if you are not concerned with obtaining truly optimal solutions, using a mixed integer programming solver is a promising strategy for finding high quality TSP solutions. If you would like to use an integer programming solver along with JuMP or TravelingSalesmanExact but don't have access to commercial software, [HiGHS](https://github.com/jump-dev/HiGHS.jl) can work well. Use of this package is most appropriate when you want decent solutions to small or moderate sized TSP instances with a minimum of hassle: one-off personal projects, if you can't install a mixed integer linear programming solver, prototyping, etc. A word of warning: the heuristics implemented are * heuristics, meaning you won't get any optimality guarantees and, except on very small instances, are unlikely to find the optimal tour; * general purpose, meaning they do not take advantage of any problem specific structure; * simple and (hopefully) readable but not terribly high performance, meaning you may have trouble with large instances. In particular the two-opt path refinement strategy slows down noticeably when there are >400 cities. ## Installation `TravelingSalesmanHeuristics` is a registered package, so you can install it with the REPL's `Pkg` mode: `]add TravelingSalesmanHeuristics`. Load it with `using TravelingSalesmanHeuristics`. ## Usage All problems are specified through a square distance matrix `D` where `D[i,j]` represents the cost of traveling from the `i`-th to the `j`-th city. Your distance matrix need not be symmetric or non-negative. !!! note Because problems are specified by dense distance matrices, this package is not well suited to problem instances with sparse distance matrix structure, i.e. problems with large numbers of cities where each city is connected to few other cities. !!! tip TravelingSalesmanHeuristics supports distance matrices with arbitrary real element types: integers, floats, rationals, etc. However, mixing element types in your distance matrix is not recommended for performance reasons. !!! danger TravelingSalesmanHeuristics does _not_ support distance matrices with arbitrary indexing; indices must be `1:n` in both dimensions for `n` cities. The simplest way to use this package is with the `solve_tsp` function: ```@docs solve_tsp ``` See [here](https://github.com/ericphanson/TravelingSalesmanBenchmarks.jl) for some benchmarks of different `quality_factor`s on various instances.
TravelingSalesmanHeuristics
https://github.com/evanfields/TravelingSalesmanHeuristics.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
927
# Hide example blocks with "#hideall". # Also, use "#hideon" and "#hideoff" to toggle hiding for the current document. function hideall(input) lines = split(input, "\n") inexample = false shouldhide = false hideon = false for (i,s) in enumerate(lines) if occursin(r"^````@example", s) inexample = true continue end if inexample && occursin(r"\#hideall", s) shouldhide = true end if inexample && occursin(r"\#hideon", s) hideon = true end if inexample && occursin(r"\#hideoff", s) hideon = false end if occursin(r"^````", s) && !occursin("@", s) inexample = false shouldhide = false continue end if inexample && (hideon || shouldhide) lines[i] *= " #hide" end end return join(lines, "\n") end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
1894
push!(LOAD_PATH,"../src/") using Documenter using WebAssemblyCompiler if haskey(ENV, "GITHUB_ACTIONS") ENV["JULIA_DEBUG"] = "Documenter" end deployconfig = Documenter.auto_detect_deploy_system() Documenter.post_status(deployconfig; type="pending", repo="github.com/tshort/WebAssemblyCompiler.jl.git") using Literate include("hideall.jl") # Literate.markdown(joinpath(@__DIR__, "../examples/basics/basics.jl"), # joinpath(@__DIR__, "src/examples"), credit = false, postprocess = hideall) Literate.markdown(joinpath(@__DIR__, "../examples/lorenz/lorenz.jl"), joinpath(@__DIR__, "src/examples"), credit = false, postprocess = hideall) Literate.markdown(joinpath(@__DIR__, "../examples/observables/observables.jl"), joinpath(@__DIR__, "src/examples"), credit = false, postprocess = hideall) makedocs( sitename = "WebAssemblyCompiler", # modules = [WebAssemblyCompiler], repo = Remotes.GitHub("tshort", "WebAssemblyCompiler.jl"), remotes = nothing, # linkcheck = true, format = Documenter.HTML( assets = ["assets/custom.css", "assets/favicon.ico"], prettyurls = true, # haskey(ENV, "GITHUB_ACTIONS"), canonical = "https://tshort.github.io/WebAssemblyCompiler.jl/", # format = HTML(repolink = "https://github.com/tshort/WebAssemblyCompiler.jl"), ), pages = Any[ "Introduction" => "index.md", "Examples" => Any[ # "JS interop" => "examples/basics.md", "Lorenz model" => "examples/lorenz.md", "Observables" => "examples/observables.md", "Makie" => "examples/makie.md", ], "api.md", "notes.md" ]) deploydocs( repo = "github.com/tshort/WebAssemblyCompiler.jl", target = "build", branch = "gh-pages", devbranch = "main", versions = ["stable" => "v^", "v#.#" ], )
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
1452
#= # Basic JavaScript interop This example generates HTML from Julia and inserts the contents here: --- ```@raw html <div id="myid"></div> ``` --- Here is the Julia code to be compiled to WebAssembly. In addition to the use of [`JS.h`](@ref), this example also shows the use of [`JS.sethtml`](@ref), [`JS.eval`](@ref), and [`JS.console_log`](@ref). =# using WebAssemblyCompiler const h = JS.h function basics(x) n = h("p", h("strong", " This is strong text with a class."), class = "myclass") n = h("div", "This is some text generated by `JS.h`. ", "This is a number: ", x, n, class = "myclass2") JS.sethtml("myid", string(n)) ## JS.eval("alert('Generated by Julia')") # It works, but it's too annoying. JS.console_log((arr = [1., 2., 3.], str = "hello", num = 2.0, tp = (3, 3.))) return x end nothing #hide # Compile it using: compile((basics, Float64); filepath = "basics/basics.wasm", validate = true, optimize = false) #= ```@raw html <script src="basics.wasm.js"></script> <script type="module"> export async function load_wasm() { const response = await fetch('basics.wasm'); const bytes = await response.arrayBuffer(); const { instance } = await WebAssembly.instantiate(bytes, jsexports); const { basics } = instance.exports; return instance.exports; } var wasm = await load_wasm(); console.log(wasm.basics(3.0)); </script> ``` =#
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
4885
#= # Lorenz model using OrdinaryDiffEq =# using WebAssemblyCompiler # prep some input #hideall using WebAssemblyCompiler.JS: h const W = WebAssemblyCompiler W.setdebug(:offline) numform(name; mdpad = "name", step = 1, value = 1, args...) = h.div."field has-addons"( h.p."control"( h.a."button is-static"( name ) ), h.p."control"( h.input."input"(;type = "number", mdpad, step, value, args...) ), ) h.div( h.div."columns is-vcentered"( h.div."column"( h.form( numform("σ", mdpad = "p1", step = 0.2, value = 10.0), numform("ρ", mdpad = "p2", step = 1.0, value = 28.0), numform("β", mdpad = "p3", step = 0.1, value = 8 / 3), ) ), h.div."column"( h.div(id = "xyplot") ) ), h.div(id = "timeplot") ) #= ## Making the app Here is the model that we'll compile. =# using OrdinaryDiffEq using WebAssemblyCompiler function lorenz!(du,u,p,t) σ,ρ,β = p du[1] = σ*(u[2]-u[1]) du[2] = u[1]*(ρ-u[3]) - u[2] du[3] = u[1]*u[2] - β*u[3] end u0 = [1.0,0.0,0.0] tspan = (0.0,100.0) p = (10.0,28.0,8/3) prob = ODEProblem{true, SciMLBase.FullSpecialize}(lorenz!,u0,tspan,p) # try to avoid FunctionWrappers with FullSpecialize const integ = init(prob, Tsit5(), dense = true) nothing #hide #= Here's a simple solver function. It references `integ`, a predefined integrator. WebAssembly stores that as a global variable. =# function update() OrdinaryDiffEq.reinit!(integ) integ.p = update_params() sol = solve!(integ) t = collect(0:0.001:100) u1 = Float64[sol(tt)[1] for tt in t] u2 = Float64[sol(tt)[2] for tt in t] u3 = Float64[sol(tt)[3] for tt in t] update_output(t, u1, u2, u3) nothing end nothing #hide # These utilities update the page inputs. mdpadnum(x) = @jscall("x => mdpad[x]", Float64, Tuple{Externref}, JS.object(x)) update_params() = (mdpadnum("p1"), mdpadnum("p2"), mdpadnum("p3")) nothing #hide # This function plots the results. @inline function update_output(t, u1, u2, u3) xydata = ((x = u1, y = u2, type = "line", name = "x"),) xylayout = (width = 400.0, height = 400.0, margin = (t = 20., b = 20., l = 20., r = 20.)) config = (responsive = true,) plotly("xyplot", xydata, xylayout, config) tdata = ((x = t, y = u1, type = "line", name = "x"), (x = t, y = u2, type = "line", name = "y"), (x = t, y = u3, type = "line", name = "z")) tlayout = (width = 900.0, height = 300.0, margin = (t = 20., b = 20.)) plotly("timeplot", tdata, tlayout, config) nothing end plotly(id, data, layout, config) = @jscall("(id, data, layout, config) => Plotly.newPlot(id, data, layout, config)", Nothing, Tuple{Externref, Externref, Externref, Externref}, JS.object(id), data, layout, config) nothing #hide # Before compiling, we need to override some error checks that caused failures. using Base.Experimental: @overlay @overlay WebAssemblyCompiler.MT @inline SciMLBase.check_error(integrator::SciMLBase.DEIntegrator) = SciMLBase.ReturnCode.Success ## The following function includes a try/catch, so bypass it. @overlay WebAssemblyCompiler.MT @inline OrdinaryDiffEq.ode_determine_initdt(args...; kw...) = 0.001 nothing #hide # Compile `update` to WebAssembly: compile((update,); filepath = "lorenz/lorenz.wasm", validate = true) nothing #hide #= `update()` runs automatically whenever inputs are changed. [`examples/lorenz/lorenz.jl`](https://github.com/tshort/WebAssemblyCompiler.jl/blob/main/examples/lorenz/lorenz.jl) also includes some raw HTML to load Plotly and mdpad and to load the WebAssembly file. ```@raw html <script> // Weird hack to load Plotly: https://stackoverflow.com/a/3363588 // https://github.com/JuliaDocs/Documenter.jl/issues/12471 window.__define = window.define; window.__require = window.require; window.define = undefined; window.require = undefined; </script> <script src="https://cdn.plot.ly/plotly-2.26.0.min.js" charset="utf-8"></script> <script> window.define = window.__define; window.require = window.__require; window.__define = undefined; window.__require = undefined; </script> <script src="../../js/mdpad.js" ></script> <script src="lorenz.wasm.js"></script> <script> setTimeout(function() { var x = document.getElementById("xyplot") if (x.innerHTML === "") { x.innerHTML = "<strong>Unsupported browser.</strong> Chrome v119 or Firefox v120 or better should work." } }, 1000) async function mdpad_init() { const fetchPromise = fetch('lorenz.wasm'); const { instance } = await WebAssembly.instantiateStreaming(fetchPromise, jsexports); wasm = instance.exports; } function mdpad_update() { wasm.update() } </script> ``` =#
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
165
using Literate include("../../docs/hideall.jl") Literate.markdown(joinpath("makie.jl"), joinpath("."), credit = false, postprocess = hideall)
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
8915
#= # Makie Plot with Makie in the browser with interactivity. =# using WebAssemblyCompiler # prep some input #hideall using WebAssemblyCompiler.JS: h const W = WebAssemblyCompiler W.setdebug(:offline) W.unsetdebug(:inline) using Observables using Makie using Colors const names = [] const os = [] function numform(description; jl = description, step = 1, value = 1) push!(names, jl) push!(os, Observable(value)) h.div."field"( h.label."label"( description ), h.div."control"( h.input."input"(;type = "number", step, value, onchange = "document.wasm.$jl(this.value)") ), ) end html = h.div( h.div."columns is-vcentered"( h.div."column is-2"( h.form( numform("k1", step = 0.2, value = 1.0), numform("k2", step = 0.2, value = 1.0), numform("k3", step = 0.2, value = 1.0), numform("k4", step = 0.2, value = 1.0), numform("k5", step = 0.2, value = 1.0), numform("k6", step = 0.2, value = 1.0), ) ), h.div."column"( h.div(id = "plot") ) ), ) nothing #hide #= !!! warning "Technology demo" This code does not compile out of the box. It uses dev'd versions of Observables and Makie. ## A basic Makie plot =# const x = 0:0.02:8π sine(x, a, ω, ϕ) = a * cos((ω * x + ϕ) * π) const y1 = lift((a, ω, ϕ) -> [sine(x, a, ω, ϕ) for x in x], os[1], os[2], os[3]) const y2 = lift((a, ω, ϕ) -> [sine(x, a, ω, ϕ) for x in x], os[4], os[5], os[6]) const y3 = lift((y1, y2) -> Float64[y1[i] + y2[i] for i in eachindex(y1)], y1, y2) fig = Figure() color1 = :steelblue3 color1a = :midnightblue color2 = :orange color2a = :firebrick4 ax1 = Axis(fig[1, 1], title = "Independent sine waves", xlabel = "t", ylabel = "y") l1 = lines!(x, y1, label = L"f_1", color = color1) l2 = lines!(x, y2, label = L"f_2", color = color2) ylims!(-3.1, 3.1) ax2 = Axis(fig[2, 1], title = "Sum of sines", xlabel = "t", ylabel = L"f_1 + f_2") lines!(x, y3, color = :orange) ylims!(-5.2, 5.2) nothing #hide #= ## A super basic Makie backend It uses a rather kludgy approach of eval'ing a bunch of expressions to create a compilable function. Not the best way, but it's an easy way to unroll things. =# function project_position(transform_func::T, space, point, model::Makie.Mat4, res, projectionview) where T ## use transform func point = Makie.apply_transform(transform_func, point, space) yflip = true p4d = Makie.to_ndim(Vec4f, Makie.to_ndim(Vec3f, point, 0f0), 1f0) clip = projectionview * model * p4d ## @show point p4d clip model space camera @inbounds begin ## between -1 and 1 p = (clip ./ clip[4])[Vec(1, 2)] ## flip y to match cairo p_yflip = Vec2f(p[1], (1f0 - 2f0 * yflip) * p[2]) ## normalize to between 0 and 1 p_0_to_1 = (p_yflip .+ 1f0) ./ 2f0 end ## multiply with scene resolution for final position return p_0_to_1 .* res end _allplots = Makie.collect_atomic_plots(fig.scene) zvals = Makie.zvalue2d.(_allplots) permute!(_allplots, sortperm(zvals)) const allplots = tuple(filter(x -> x isa Lines || x isa LineSegments, _allplots)...) function make_svg_function(nargs) ## color = to_color(primitive.calculated_colors[]) dummyargs = gensym.(string.(1:nargs)) e = quote function $(gensym())($(dummyargs...)) svg = Any["<svg width=800 height=600>"] end end ea = e.args[end].args[end].args for i in eachindex(allplots) push!(ea, primitive_svg_expr(allplots[i], i)) end push!(ea, :(push!(svg, "</svg>"))) push!(ea, :(JS.sethtml("plot", JS.join(JS.object(svg))))) return eval(e) end function primitive_svg_expr(primitive::Union{Lines, LineSegments}, i) scene = Makie.parent_scene(primitive) if primitive isa Lines scene = primitive.parent end root_area = Makie.root(scene).px_area[] root_area_height = widths(root_area)[2] scene_area = pixelarea(scene)[] scene_height = widths(scene_area)[2] scene_x_origin, scene_y_origin = scene_area.origin top_offset = root_area_height - scene_height - scene_y_origin transform_expr = " transform='translate($scene_x_origin,$top_offset)'" model = primitive[:model][] positions = primitive[1] length(to_value(positions)) < 1 && return nothing @get_attribute(primitive, (color, linewidth, linestyle)) transform = Makie.transform_func(primitive) space = QuoteNode(to_value(get(primitive, :space, :data))) res = scene.camera.resolution[] camera = scene.camera projectionview = camera.projectionview[] hexcolor = hex(RGB(color isa Vector ? color[1] : color)) opacity = alpha(color isa Vector ? color[1] : color) draw_expr = primitive isa Lines ? draw_lines(hexcolor, opacity, transform_expr) : draw_linesegments(hexcolor, opacity, transform_expr) return quote primitive = allplots[$i] positions = primitive[1] ## model = primitive[:model][] projected_positions = [project_position($transform, $space, p, $model, $res, $projectionview) for p in to_value(positions)] $draw_expr push!(svg, "'/>") end end function draw_lines(hexcolor, alpha, transform) return quote push!(svg, "<polyline fill='none' stroke='#") push!(svg, $hexcolor) push!(svg, "' stroke-opacity=") push!(svg, $alpha) push!(svg, $transform) push!(svg, " points='") for pt in projected_positions push!(svg, pt[1]) push!(svg, ",") push!(svg, pt[2]) push!(svg, " ") end end end function draw_linesegments(hexcolor, alpha, transform) return quote push!(svg, "<path fill='none' stroke='#") push!(svg, $hexcolor) push!(svg, "' stroke-opacity=") push!(svg, $alpha) push!(svg, $transform) push!(svg, " d='") @inbounds for i in 1:2:length(projected_positions)-1 p1 = projected_positions[i] p2 = projected_positions[i+1] push!(svg, " M ") push!(svg, p1[1]) push!(svg, ",") push!(svg, p1[2]) push!(svg, " L ") push!(svg, p2[1]) push!(svg, ",") push!(svg, p2[2]) end end end function primitive_svg_expr(x, i) end using CairoMakie save("ss.png", fig) fsvg = make_svg_function(6) onany(fsvg, os...) nothing #hide #= We also need to patch up some internals in WebAssemblyCompiler. WebAssembly doesn't handle circular references. As a kludge, we assign defaults to circular references. We're okay with that here because these circular references are never used. =# W.default(o::Observable{T}) where T = Observable(o[]) nothing #hide #= The last part is pretty simple. We'll call `onany` to connect our set of input Observables `os` to the `set_svg` method. `fix!` returns a named tuple with a `setfuns` component that can be passed to `compile`. Each `setfuns` method is passed a value appropriate for that Observable. This triggers propagation of updates to the listeners. =# include("observable-utils.jl") setfuns = fix!(os...) nothing #hide #= Kludge Makie some to try to make it amenable to compilation. =# W.default(o::Observable) = Observable(o[]) ## Fix up a type issue in Base using Base.Experimental: @overlay @overlay W.MT Base.merge(::NamedTuple{(), Tuple{}}, ::Tuple{}) = NamedTuple() ## Don't store the abstract parts of Observables W.fieldskept(::Type{T}) where T <: Observable = (:ignore_equal_values, :val) W.fieldskept(::Type{T}) where T <: Observables.MapCallback = () W.fieldskept(::Type{T}) where T <: OnAnyHolder = (:f, :args) W.fieldskept(::Type{T}) where T <: MapCallbackHolder = (:args, :result, :listeners, :f) W.fieldskept(::Type{T}) where T <: LineSegments = (:converted,) W.fieldskept(::Type{T}) where T <: Lines = (:converted,) W.fieldskept(::Type{T}) where T <: Makie.Text = (:converted,) W.fieldskept(::Type{T}) where T <: Mesh = (:converted,) compile(setfuns...; names = names, filepath = "makie/makie.wasm", validate = true) nothing #hide #= ```@raw html <script src="observables.wasm.js"></script> <script type="module"> setTimeout(function() { var x = document.getElementById("plot") if (x.innerHTML === "") { x.innerHTML = "<strong>Unsupported browser.</strong> Chrome v119 or Firefox v120 or better should work." } }, 1000) export async function load_wasm() { const response = await fetch('observables.wasm'); const bytes = await response.arrayBuffer(); const { instance } = await WebAssembly.instantiate(bytes, jsexports); const { basics } = instance.exports; return instance.exports; } document.wasm = await load_wasm(); document.wasm.k4(1.5); </script> ``` =#
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
2614
#= The `fix!` methods take a set of Observables, walk their connections, and return a set of methods that will update the Observables provided. These methods unroll calls to the listeners of each Observable to make it easier to statically compile. =# using Observables fix!(os::AbstractObservable...) = fix!(Set{AbstractObservable}(), os...) function fix!(ctx::Set{AbstractObservable}, x...) end function fix!(ctx::Set{AbstractObservable}, observables::Observable...) setfuns = [] notifies = [] for observable in observables observable in ctx && continue push!(ctx, observable) push!(setfuns, (makeset(ctx, observable), typeof(observable.val))) end return setfuns end function makeset(ctx::Set{AbstractObservable}, o::Observable) listeners = tuple((fix!(ctx, l[2]) for l in o.listeners)...) return val -> begin o.val = Observables.to_value(val) nnotify(o, listeners...) end end function fix!(ctx::Set{AbstractObservable}, oa::Observables.OnAny) return OnAnyHolder(oa.f, tuple(oa.args...)) return val -> begin f(valargs(args...)...) return Consume(false) end end mutable struct OnAnyHolder{F,A} f::F args::A end function (x::OnAnyHolder)(val) x.f(valargs(x.args...)...) return Consume(false) end function fix!(ctx::Set{AbstractObservable}, mc::Observables.MapCallback) set! = makeset(ctx, mc.result) result = mc.result resultlisteners = tuple((fix!(ctx, l[2]) for l in result.listeners)...) return MapCallbackHolder(mc.result, mc.f, tuple(mc.args...), resultlisteners) end mutable struct MapCallbackHolder{O,F,A,L} result::O f::F args::A listeners::L end function (x::MapCallbackHolder)(val) x.result.val = x.f(valargs(x.args...)...) nnotify(x.result, x.listeners...) return Consume(false) end @inline valargs() = () @inline valargs(x) = (Observables.to_value(x),) @inline valargs(x, xs...) = (Observables.to_value(x), valargs(xs...)...) @inline nnotify(o::Observable) = nothing @inline nnotify(::Nothing) = nothing @inline function nnotify(o::Observable, f) result = f(o.val) result.x && return true return false end @inline function nnotify(o::Observable, f, fs...) nnotify(o, f) nnotify(o, fs...) return false end # a = Observable(2) # b = map(x -> 2x, a) # c = map(x -> 2x, b) # d = map((x,y) -> x + y, a, b) # x = Observable(3) # y = map((b,x) -> b * x, b, x) # onany((a,b) -> display(a+b), a, b) # fs = fix!(a, x) # @show fs[1][1](5) # @show a # @show b # @show c # @show d # @show fs[2][1](10) # @show x # @show y
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
7137
#= # Making an SVG using Observables This app mimics [this JSServe app](https://simondanisch.github.io/JSServe.jl/stable/animation.html) but with interactivity provided by Julia code compiled to WebAssembly. =# using WebAssemblyCompiler # prep some input #hideall using WebAssemblyCompiler.JS: h const W = WebAssemblyCompiler W.setdebug(:offline) W.unsetdebug(:inline) using Observables const names = [] const os = [] function numform(description; jl = description, step = 1, value = 1, args...) push!(names, jl) push!(os, Observable(value)) h.div."field"( h.label."label"( description ), h.div."control"( h.input."input"(;type = "number", step, value, onchange = "document.wasm.$jl(this.value)", args...) ), ) end html = h.div( h.div."columns is-vcentered"( h.div."column is-2"( h.form( numform("nsamples", step = 5, value = Int32(100), min = 5, max = 1000), numform("steps", jl = "sample_step", step = 0.02, value = 0.1, min = 0.02, max = 1.0), numform("phase", step = 0.25, value = 0.0, min = 0.0, max = 3.0), numform("radii", step = 5.0, value = 10.0, min = 1.0, max = 40.0), ) ), h.div."column"( h.div(id = "plot") ) ), ) #= ## Making the app [Observables](https://github.com/JuliaGizmos/Observables.jl) are used widely by Julia packages to provide interactivity. For static compilation, they are problematic, though. The `Observable` type is not strongly typed, and it's challenging to compile statically. What we can do is define some Observables and some interactivity and compile the results. First, we'll create the basics for the updating SVG. =# const colors = ["black", "gray", "silver", "maroon", "red", "olive", "yellow", "green", "lime", "teal", "aqua", "navy", "blue", "purple", "fuchsia"] function circ(cx, cy, r, icol) ["<circle cx='", cx, "' cy='", cy, "' r='", r, "' fill='", colors[icol % length(colors) + 1], "'></circle>"] end function set_svg(nsamples, sample_step, phase, radii) width, height = 900.0, 300.0 cxs_unscaled = [i*sample_step + phase for i in 1:nsamples] cys = [sin(cxs_unscaled[i]) * height/3 + height/2 for i in 1:nsamples] cxs = [cxs_unscaled[i] * width/4pi for i in 1:nsamples] rr = radii ## make an array of strings and numbers to join in JavaScript geom = Any["<svg width=", width, " height=", height, " ><g>"] for i in 1:nsamples append!(geom, circ(cxs[i], cys[i], rr, i)) end push!(geom, "</g></svg>") obj = JS.object(geom) geom = JS.join(obj) JS.sethtml("plot", geom) end nothing #hide #= The method `set_svg` is what we'll ultimately want to compile. To get there, we need the code that'll compile the Observables. The `fix!` methods take a set of Observables, walk their connections, and return a set of methods that will update the Observables provided. These methods unroll calls to the listeners of each Observable to make it easier to statically compile. =# using Observables fix!(os::AbstractObservable...) = fix!(Set{AbstractObservable}(), os...) function fix!(ctx::Set{AbstractObservable}, x...) end function fix!(ctx::Set{AbstractObservable}, observables::Observable...) setfuns = [] notifies = [] for observable in observables observable in ctx && continue push!(ctx, observable) push!(setfuns, (makeset(ctx, observable), typeof(observable.val))) end return setfuns end function makeset(ctx::Set{AbstractObservable}, o::Observable) listeners = tuple((fix!(ctx, l[2]) for l in o.listeners)...) return val -> begin o.val = Observables.to_value(val) nnotify(o, listeners...) end end function fix!(ctx::Set{AbstractObservable}, oa::Observables.OnAny) return OnAnyHolder(oa.f, tuple(oa.args...)) return val -> begin f(valargs(args...)...) return Consume(false) end end mutable struct OnAnyHolder{F,A} f::F args::A end function (x::OnAnyHolder)(val) x.f(valargs(x.args...)...) return Consume(false) end function fix!(ctx::Set{AbstractObservable}, mc::Observables.MapCallback) set! = makeset(ctx, mc.result) result = mc.result resultlisteners = tuple((fix!(ctx, l[2]) for l in result.listeners)...) return MapCallbackHolder(mc.result, mc.f, tuple(mc.args...), resultlisteners) end mutable struct MapCallbackHolder{O,F,A,L} result::O f::F args::A listeners::L end function (x::MapCallbackHolder)(val) x.result.val = x.f(valargs(x.args...)...) nnotify(x.result, x.listeners...) return Consume(false) end @inline valargs() = () @inline valargs(x) = (Observables.to_value(x),) @inline valargs(x, xs...) = (Observables.to_value(x), valargs(xs...)...) @inline nnotify(o::Observable) = nothing @inline nnotify(::Nothing) = nothing @inline function nnotify(o::Observable, f) result = f(o.val) result.x && return true return false end @inline function nnotify(o::Observable, f, fs...) nnotify(o, f) nnotify(o, fs...) return false end nothing #hide #= We also need to patch up some internals in WebAssemblyCompiler. WebAssembly doesn't handle circular references. As a kludge, we assign defaults to circular references. We're okay with that here because these circular references are never used. =# W.default(o::Observable{T}) where T = Observable(o.val) nothing #hide #= The last part is pretty simple. We'll call `onany` to connect our set of input Observables `os` to the `set_svg` method. `fix!` returns a named tuple with a `setfuns` component that can be passed to `compile`. Each `setfuns` method is passed a value appropriate for that Observable. This triggers propagation of updates to the listeners. =# onany(set_svg, os...) setfuns! = fix!(os...) compile(setfuns!...; names = names, filepath = "observables/observables.wasm") nothing #hide #= With this interactivity provided by Observables, we've eliminated almost all of the JavaScript. `JS.h` methods are used to define the inputs, including an `onupdate` trigger that calls the appropriate WebAssembly function. These also define Observables and collect names for the WebAssembly functions. See [`examples/observables/observables.jl`](https://github.com/tshort/WebAssemblyCompiler.jl/blob/main/examples/observables/observables.jl) for the complete source for this example. =# #= ```@raw html <script src="observables.wasm.js"></script> <script type="module"> setTimeout(function() { var x = document.getElementById("plot") if (x.innerHTML === "") { x.innerHTML = "<strong>Unsupported browser.</strong> Chrome v119 or Firefox v120 or better should work." } }, 1000) export async function load_wasm() { const response = await fetch('observables.wasm'); const bytes = await response.arrayBuffer(); const { instance } = await WebAssembly.instantiate(bytes, jsexports); const { basics } = instance.exports; return instance.exports; } document.wasm = await load_wasm(); document.wasm.radii(10.); </script> ``` =#
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
569
using Clang.Generators using Binaryen_jll # replace this with your jll package cd(@__DIR__) include_dir = normpath(Binaryen_jll.artifact_dir, "include") options = load_options(joinpath(@__DIR__, "generator.toml")) # add compiler flags, e.g. "-DXXXXXXXXX" args = get_default_args() # Note you must call this function firstly and then append your own flags push!(args, "-I$include_dir") push!(args, "-fparse-all-comments") headers = [joinpath(include_dir, "binaryen-c.h")] # create context ctx = create_context(headers, args, options) # run generator build!(ctx)
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
269429
module LibBinaryen using Binaryen_jll export Binaryen_jll using CEnum """ Expression ids (call to get the value of each; you can cache them) """ const BinaryenExpressionId = UInt32 """ BinaryenIndex Used for internal indexes and list sizes. """ const BinaryenIndex = UInt32 """ Core types (call to get the value of each; you can cache them, they never change) """ const BinaryenType = Csize_t function BinaryenTypeNone() ccall((:BinaryenTypeNone, libbinaryen), BinaryenType, ()) end function BinaryenTypeInt32() ccall((:BinaryenTypeInt32, libbinaryen), BinaryenType, ()) end function BinaryenTypeInt64() ccall((:BinaryenTypeInt64, libbinaryen), BinaryenType, ()) end function BinaryenTypeFloat32() ccall((:BinaryenTypeFloat32, libbinaryen), BinaryenType, ()) end function BinaryenTypeFloat64() ccall((:BinaryenTypeFloat64, libbinaryen), BinaryenType, ()) end function BinaryenTypeVec128() ccall((:BinaryenTypeVec128, libbinaryen), BinaryenType, ()) end function BinaryenTypeFuncref() ccall((:BinaryenTypeFuncref, libbinaryen), BinaryenType, ()) end function BinaryenTypeExternref() ccall((:BinaryenTypeExternref, libbinaryen), BinaryenType, ()) end function BinaryenTypeAnyref() ccall((:BinaryenTypeAnyref, libbinaryen), BinaryenType, ()) end function BinaryenTypeEqref() ccall((:BinaryenTypeEqref, libbinaryen), BinaryenType, ()) end function BinaryenTypeI31ref() ccall((:BinaryenTypeI31ref, libbinaryen), BinaryenType, ()) end function BinaryenTypeStructref() ccall((:BinaryenTypeStructref, libbinaryen), BinaryenType, ()) end function BinaryenTypeArrayref() ccall((:BinaryenTypeArrayref, libbinaryen), BinaryenType, ()) end function BinaryenTypeStringref() ccall((:BinaryenTypeStringref, libbinaryen), BinaryenType, ()) end function BinaryenTypeStringviewWTF8() ccall((:BinaryenTypeStringviewWTF8, libbinaryen), BinaryenType, ()) end function BinaryenTypeStringviewWTF16() ccall((:BinaryenTypeStringviewWTF16, libbinaryen), BinaryenType, ()) end function BinaryenTypeStringviewIter() ccall((:BinaryenTypeStringviewIter, libbinaryen), BinaryenType, ()) end function BinaryenTypeNullref() ccall((:BinaryenTypeNullref, libbinaryen), BinaryenType, ()) end function BinaryenTypeNullExternref() ccall((:BinaryenTypeNullExternref, libbinaryen), BinaryenType, ()) end function BinaryenTypeNullFuncref() ccall((:BinaryenTypeNullFuncref, libbinaryen), BinaryenType, ()) end function BinaryenTypeUnreachable() ccall((:BinaryenTypeUnreachable, libbinaryen), BinaryenType, ()) end """ BinaryenTypeAuto() Not a real type. Used as the last parameter to BinaryenBlock to let the API figure out the type instead of providing one. """ function BinaryenTypeAuto() ccall((:BinaryenTypeAuto, libbinaryen), BinaryenType, ()) end function BinaryenTypeCreate(valueTypes, numTypes) ccall((:BinaryenTypeCreate, libbinaryen), BinaryenType, (Ptr{BinaryenType}, BinaryenIndex), valueTypes, numTypes) end function BinaryenTypeArity(t) ccall((:BinaryenTypeArity, libbinaryen), UInt32, (BinaryenType,), t) end function BinaryenTypeExpand(t, buf) ccall((:BinaryenTypeExpand, libbinaryen), Cvoid, (BinaryenType, Ptr{BinaryenType}), t, buf) end function BinaryenNone() ccall((:BinaryenNone, libbinaryen), BinaryenType, ()) end function BinaryenInt32() ccall((:BinaryenInt32, libbinaryen), BinaryenType, ()) end function BinaryenInt64() ccall((:BinaryenInt64, libbinaryen), BinaryenType, ()) end function BinaryenFloat32() ccall((:BinaryenFloat32, libbinaryen), BinaryenType, ()) end function BinaryenFloat64() ccall((:BinaryenFloat64, libbinaryen), BinaryenType, ()) end function BinaryenUndefined() ccall((:BinaryenUndefined, libbinaryen), BinaryenType, ()) end """ Packed types (call to get the value of each; you can cache them) """ const BinaryenPackedType = UInt32 function BinaryenPackedTypeNotPacked() ccall((:BinaryenPackedTypeNotPacked, libbinaryen), BinaryenPackedType, ()) end function BinaryenPackedTypeInt8() ccall((:BinaryenPackedTypeInt8, libbinaryen), BinaryenPackedType, ()) end function BinaryenPackedTypeInt16() ccall((:BinaryenPackedTypeInt16, libbinaryen), BinaryenPackedType, ()) end """ Heap types """ const BinaryenHeapType = Csize_t function BinaryenHeapTypeExt() ccall((:BinaryenHeapTypeExt, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeFunc() ccall((:BinaryenHeapTypeFunc, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeAny() ccall((:BinaryenHeapTypeAny, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeEq() ccall((:BinaryenHeapTypeEq, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeI31() ccall((:BinaryenHeapTypeI31, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeStruct() ccall((:BinaryenHeapTypeStruct, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeArray() ccall((:BinaryenHeapTypeArray, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeString() ccall((:BinaryenHeapTypeString, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeStringviewWTF8() ccall((:BinaryenHeapTypeStringviewWTF8, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeStringviewWTF16() ccall((:BinaryenHeapTypeStringviewWTF16, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeStringviewIter() ccall((:BinaryenHeapTypeStringviewIter, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeNone() ccall((:BinaryenHeapTypeNone, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeNoext() ccall((:BinaryenHeapTypeNoext, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeNofunc() ccall((:BinaryenHeapTypeNofunc, libbinaryen), BinaryenHeapType, ()) end function BinaryenHeapTypeIsBasic(heapType) ccall((:BinaryenHeapTypeIsBasic, libbinaryen), Bool, (BinaryenHeapType,), heapType) end function BinaryenHeapTypeIsSignature(heapType) ccall((:BinaryenHeapTypeIsSignature, libbinaryen), Bool, (BinaryenHeapType,), heapType) end function BinaryenHeapTypeIsStruct(heapType) ccall((:BinaryenHeapTypeIsStruct, libbinaryen), Bool, (BinaryenHeapType,), heapType) end function BinaryenHeapTypeIsArray(heapType) ccall((:BinaryenHeapTypeIsArray, libbinaryen), Bool, (BinaryenHeapType,), heapType) end function BinaryenHeapTypeIsBottom(heapType) ccall((:BinaryenHeapTypeIsBottom, libbinaryen), Bool, (BinaryenHeapType,), heapType) end function BinaryenHeapTypeGetBottom(heapType) ccall((:BinaryenHeapTypeGetBottom, libbinaryen), BinaryenHeapType, (BinaryenHeapType,), heapType) end function BinaryenHeapTypeIsSubType(left, right) ccall((:BinaryenHeapTypeIsSubType, libbinaryen), Bool, (BinaryenHeapType, BinaryenHeapType), left, right) end function BinaryenStructTypeGetNumFields(heapType) ccall((:BinaryenStructTypeGetNumFields, libbinaryen), BinaryenIndex, (BinaryenHeapType,), heapType) end function BinaryenStructTypeGetFieldType(heapType, index) ccall((:BinaryenStructTypeGetFieldType, libbinaryen), BinaryenType, (BinaryenHeapType, BinaryenIndex), heapType, index) end function BinaryenStructTypeGetFieldPackedType(heapType, index) ccall((:BinaryenStructTypeGetFieldPackedType, libbinaryen), BinaryenPackedType, (BinaryenHeapType, BinaryenIndex), heapType, index) end function BinaryenStructTypeIsFieldMutable(heapType, index) ccall((:BinaryenStructTypeIsFieldMutable, libbinaryen), Bool, (BinaryenHeapType, BinaryenIndex), heapType, index) end function BinaryenArrayTypeGetElementType(heapType) ccall((:BinaryenArrayTypeGetElementType, libbinaryen), BinaryenType, (BinaryenHeapType,), heapType) end function BinaryenArrayTypeGetElementPackedType(heapType) ccall((:BinaryenArrayTypeGetElementPackedType, libbinaryen), BinaryenPackedType, (BinaryenHeapType,), heapType) end function BinaryenArrayTypeIsElementMutable(heapType) ccall((:BinaryenArrayTypeIsElementMutable, libbinaryen), Bool, (BinaryenHeapType,), heapType) end function BinaryenSignatureTypeGetParams(heapType) ccall((:BinaryenSignatureTypeGetParams, libbinaryen), BinaryenType, (BinaryenHeapType,), heapType) end function BinaryenSignatureTypeGetResults(heapType) ccall((:BinaryenSignatureTypeGetResults, libbinaryen), BinaryenType, (BinaryenHeapType,), heapType) end function BinaryenTypeGetHeapType(type) ccall((:BinaryenTypeGetHeapType, libbinaryen), BinaryenHeapType, (BinaryenType,), type) end function BinaryenTypeIsNullable(type) ccall((:BinaryenTypeIsNullable, libbinaryen), Bool, (BinaryenType,), type) end function BinaryenTypeFromHeapType(heapType, nullable) ccall((:BinaryenTypeFromHeapType, libbinaryen), BinaryenType, (BinaryenHeapType, Bool), heapType, nullable) end function BinaryenInvalidId() ccall((:BinaryenInvalidId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenNopId() ccall((:BinaryenNopId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenBlockId() ccall((:BinaryenBlockId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenIfId() ccall((:BinaryenIfId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenLoopId() ccall((:BinaryenLoopId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenBreakId() ccall((:BinaryenBreakId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSwitchId() ccall((:BinaryenSwitchId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenCallId() ccall((:BinaryenCallId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenCallIndirectId() ccall((:BinaryenCallIndirectId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenLocalGetId() ccall((:BinaryenLocalGetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenLocalSetId() ccall((:BinaryenLocalSetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenGlobalGetId() ccall((:BinaryenGlobalGetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenGlobalSetId() ccall((:BinaryenGlobalSetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenLoadId() ccall((:BinaryenLoadId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStoreId() ccall((:BinaryenStoreId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenAtomicRMWId() ccall((:BinaryenAtomicRMWId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenAtomicCmpxchgId() ccall((:BinaryenAtomicCmpxchgId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenAtomicWaitId() ccall((:BinaryenAtomicWaitId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenAtomicNotifyId() ccall((:BinaryenAtomicNotifyId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenAtomicFenceId() ccall((:BinaryenAtomicFenceId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSIMDExtractId() ccall((:BinaryenSIMDExtractId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSIMDReplaceId() ccall((:BinaryenSIMDReplaceId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSIMDShuffleId() ccall((:BinaryenSIMDShuffleId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSIMDTernaryId() ccall((:BinaryenSIMDTernaryId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSIMDShiftId() ccall((:BinaryenSIMDShiftId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSIMDLoadId() ccall((:BinaryenSIMDLoadId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSIMDLoadStoreLaneId() ccall((:BinaryenSIMDLoadStoreLaneId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenMemoryInitId() ccall((:BinaryenMemoryInitId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenDataDropId() ccall((:BinaryenDataDropId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenMemoryCopyId() ccall((:BinaryenMemoryCopyId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenMemoryFillId() ccall((:BinaryenMemoryFillId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenConstId() ccall((:BinaryenConstId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenUnaryId() ccall((:BinaryenUnaryId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenBinaryId() ccall((:BinaryenBinaryId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenSelectId() ccall((:BinaryenSelectId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenDropId() ccall((:BinaryenDropId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenReturnId() ccall((:BinaryenReturnId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenMemorySizeId() ccall((:BinaryenMemorySizeId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenMemoryGrowId() ccall((:BinaryenMemoryGrowId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenUnreachableId() ccall((:BinaryenUnreachableId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenPopId() ccall((:BinaryenPopId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRefNullId() ccall((:BinaryenRefNullId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRefIsNullId() ccall((:BinaryenRefIsNullId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRefFuncId() ccall((:BinaryenRefFuncId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRefEqId() ccall((:BinaryenRefEqId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenTableGetId() ccall((:BinaryenTableGetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenTableSetId() ccall((:BinaryenTableSetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenTableSizeId() ccall((:BinaryenTableSizeId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenTableGrowId() ccall((:BinaryenTableGrowId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenTryId() ccall((:BinaryenTryId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenThrowId() ccall((:BinaryenThrowId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRethrowId() ccall((:BinaryenRethrowId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenTupleMakeId() ccall((:BinaryenTupleMakeId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenTupleExtractId() ccall((:BinaryenTupleExtractId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenI31NewId() ccall((:BinaryenI31NewId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenI31GetId() ccall((:BinaryenI31GetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenCallRefId() ccall((:BinaryenCallRefId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRefTestId() ccall((:BinaryenRefTestId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRefCastId() ccall((:BinaryenRefCastId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenBrOnId() ccall((:BinaryenBrOnId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStructNewId() ccall((:BinaryenStructNewId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStructGetId() ccall((:BinaryenStructGetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStructSetId() ccall((:BinaryenStructSetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayNewId() ccall((:BinaryenArrayNewId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayNewDataId() ccall((:BinaryenArrayNewDataId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayNewElemId() ccall((:BinaryenArrayNewElemId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayNewFixedId() ccall((:BinaryenArrayNewFixedId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayGetId() ccall((:BinaryenArrayGetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArraySetId() ccall((:BinaryenArraySetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayLenId() ccall((:BinaryenArrayLenId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayCopyId() ccall((:BinaryenArrayCopyId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayFillId() ccall((:BinaryenArrayFillId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayInitDataId() ccall((:BinaryenArrayInitDataId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenArrayInitElemId() ccall((:BinaryenArrayInitElemId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenRefAsId() ccall((:BinaryenRefAsId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringNewId() ccall((:BinaryenStringNewId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringConstId() ccall((:BinaryenStringConstId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringMeasureId() ccall((:BinaryenStringMeasureId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringEncodeId() ccall((:BinaryenStringEncodeId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringConcatId() ccall((:BinaryenStringConcatId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringEqId() ccall((:BinaryenStringEqId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringAsId() ccall((:BinaryenStringAsId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringWTF8AdvanceId() ccall((:BinaryenStringWTF8AdvanceId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringWTF16GetId() ccall((:BinaryenStringWTF16GetId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringIterNextId() ccall((:BinaryenStringIterNextId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringIterMoveId() ccall((:BinaryenStringIterMoveId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringSliceWTFId() ccall((:BinaryenStringSliceWTFId, libbinaryen), BinaryenExpressionId, ()) end function BinaryenStringSliceIterId() ccall((:BinaryenStringSliceIterId, libbinaryen), BinaryenExpressionId, ()) end """ External kinds (call to get the value of each; you can cache them) """ const BinaryenExternalKind = UInt32 function BinaryenExternalFunction() ccall((:BinaryenExternalFunction, libbinaryen), BinaryenExternalKind, ()) end function BinaryenExternalTable() ccall((:BinaryenExternalTable, libbinaryen), BinaryenExternalKind, ()) end function BinaryenExternalMemory() ccall((:BinaryenExternalMemory, libbinaryen), BinaryenExternalKind, ()) end function BinaryenExternalGlobal() ccall((:BinaryenExternalGlobal, libbinaryen), BinaryenExternalKind, ()) end function BinaryenExternalTag() ccall((:BinaryenExternalTag, libbinaryen), BinaryenExternalKind, ()) end """ Features. Call to get the value of each; you can cache them. Use bitwise operators to combine and test particular features. """ const BinaryenFeatures = UInt32 function BinaryenFeatureMVP() ccall((:BinaryenFeatureMVP, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureAtomics() ccall((:BinaryenFeatureAtomics, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureBulkMemory() ccall((:BinaryenFeatureBulkMemory, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureMutableGlobals() ccall((:BinaryenFeatureMutableGlobals, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureNontrappingFPToInt() ccall((:BinaryenFeatureNontrappingFPToInt, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureSignExt() ccall((:BinaryenFeatureSignExt, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureSIMD128() ccall((:BinaryenFeatureSIMD128, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureExceptionHandling() ccall((:BinaryenFeatureExceptionHandling, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureTailCall() ccall((:BinaryenFeatureTailCall, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureReferenceTypes() ccall((:BinaryenFeatureReferenceTypes, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureMultivalue() ccall((:BinaryenFeatureMultivalue, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureGC() ccall((:BinaryenFeatureGC, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureMemory64() ccall((:BinaryenFeatureMemory64, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureRelaxedSIMD() ccall((:BinaryenFeatureRelaxedSIMD, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureExtendedConst() ccall((:BinaryenFeatureExtendedConst, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureStrings() ccall((:BinaryenFeatureStrings, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureMultiMemories() ccall((:BinaryenFeatureMultiMemories, libbinaryen), BinaryenFeatures, ()) end function BinaryenFeatureAll() ccall((:BinaryenFeatureAll, libbinaryen), BinaryenFeatures, ()) end mutable struct BinaryenModule end const BinaryenModuleRef = Ptr{BinaryenModule} function BinaryenModuleCreate() ccall((:BinaryenModuleCreate, libbinaryen), BinaryenModuleRef, ()) end function BinaryenModuleDispose(_module) ccall((:BinaryenModuleDispose, libbinaryen), Cvoid, (BinaryenModuleRef,), _module) end """ BinaryenLiteral Literals. These are passed by value. """ struct BinaryenLiteral data::NTuple{24, UInt8} end function Base.getproperty(x::Ptr{BinaryenLiteral}, f::Symbol) f === :type && return Ptr{Csize_t}(x + 0) f === :i32 && return Ptr{Int32}(x + 8) f === :i64 && return Ptr{Int64}(x + 8) f === :f32 && return Ptr{Cfloat}(x + 8) f === :f64 && return Ptr{Cdouble}(x + 8) f === :v128 && return Ptr{NTuple{16, UInt8}}(x + 8) f === :func && return Ptr{Ptr{Cchar}}(x + 8) return getfield(x, f) end function Base.getproperty(x::BinaryenLiteral, f::Symbol) r = Ref{BinaryenLiteral}(x) ptr = Base.unsafe_convert(Ptr{BinaryenLiteral}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{BinaryenLiteral}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end function BinaryenLiteralInt32(x) ccall((:BinaryenLiteralInt32, libbinaryen), BinaryenLiteral, (Int32,), x) end function BinaryenLiteralInt64(x) ccall((:BinaryenLiteralInt64, libbinaryen), BinaryenLiteral, (Int64,), x) end function BinaryenLiteralFloat32(x) ccall((:BinaryenLiteralFloat32, libbinaryen), BinaryenLiteral, (Cfloat,), x) end function BinaryenLiteralFloat64(x) ccall((:BinaryenLiteralFloat64, libbinaryen), BinaryenLiteral, (Cdouble,), x) end function BinaryenLiteralVec128(x) ccall((:BinaryenLiteralVec128, libbinaryen), BinaryenLiteral, (Ptr{UInt8},), x) end function BinaryenLiteralFloat32Bits(x) ccall((:BinaryenLiteralFloat32Bits, libbinaryen), BinaryenLiteral, (Int32,), x) end function BinaryenLiteralFloat64Bits(x) ccall((:BinaryenLiteralFloat64Bits, libbinaryen), BinaryenLiteral, (Int64,), x) end """ Expressions Some expressions have a BinaryenOp, which is the more specific operation/opcode. Some expressions have optional parameters, like Return may not return a value. You can supply a NULL pointer in those cases. For more information, see wasm.h """ const BinaryenOp = Int32 function BinaryenClzInt32() ccall((:BinaryenClzInt32, libbinaryen), BinaryenOp, ()) end function BinaryenCtzInt32() ccall((:BinaryenCtzInt32, libbinaryen), BinaryenOp, ()) end function BinaryenPopcntInt32() ccall((:BinaryenPopcntInt32, libbinaryen), BinaryenOp, ()) end function BinaryenNegFloat32() ccall((:BinaryenNegFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenAbsFloat32() ccall((:BinaryenAbsFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenCeilFloat32() ccall((:BinaryenCeilFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenFloorFloat32() ccall((:BinaryenFloorFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncFloat32() ccall((:BinaryenTruncFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenNearestFloat32() ccall((:BinaryenNearestFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenSqrtFloat32() ccall((:BinaryenSqrtFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenEqZInt32() ccall((:BinaryenEqZInt32, libbinaryen), BinaryenOp, ()) end function BinaryenClzInt64() ccall((:BinaryenClzInt64, libbinaryen), BinaryenOp, ()) end function BinaryenCtzInt64() ccall((:BinaryenCtzInt64, libbinaryen), BinaryenOp, ()) end function BinaryenPopcntInt64() ccall((:BinaryenPopcntInt64, libbinaryen), BinaryenOp, ()) end function BinaryenNegFloat64() ccall((:BinaryenNegFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenAbsFloat64() ccall((:BinaryenAbsFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenCeilFloat64() ccall((:BinaryenCeilFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenFloorFloat64() ccall((:BinaryenFloorFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncFloat64() ccall((:BinaryenTruncFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenNearestFloat64() ccall((:BinaryenNearestFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenSqrtFloat64() ccall((:BinaryenSqrtFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenEqZInt64() ccall((:BinaryenEqZInt64, libbinaryen), BinaryenOp, ()) end function BinaryenExtendSInt32() ccall((:BinaryenExtendSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenExtendUInt32() ccall((:BinaryenExtendUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenWrapInt64() ccall((:BinaryenWrapInt64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSFloat32ToInt32() ccall((:BinaryenTruncSFloat32ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSFloat32ToInt64() ccall((:BinaryenTruncSFloat32ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncUFloat32ToInt32() ccall((:BinaryenTruncUFloat32ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncUFloat32ToInt64() ccall((:BinaryenTruncUFloat32ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSFloat64ToInt32() ccall((:BinaryenTruncSFloat64ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSFloat64ToInt64() ccall((:BinaryenTruncSFloat64ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncUFloat64ToInt32() ccall((:BinaryenTruncUFloat64ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncUFloat64ToInt64() ccall((:BinaryenTruncUFloat64ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenReinterpretFloat32() ccall((:BinaryenReinterpretFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenReinterpretFloat64() ccall((:BinaryenReinterpretFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenConvertSInt32ToFloat32() ccall((:BinaryenConvertSInt32ToFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenConvertSInt32ToFloat64() ccall((:BinaryenConvertSInt32ToFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenConvertUInt32ToFloat32() ccall((:BinaryenConvertUInt32ToFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenConvertUInt32ToFloat64() ccall((:BinaryenConvertUInt32ToFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenConvertSInt64ToFloat32() ccall((:BinaryenConvertSInt64ToFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenConvertSInt64ToFloat64() ccall((:BinaryenConvertSInt64ToFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenConvertUInt64ToFloat32() ccall((:BinaryenConvertUInt64ToFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenConvertUInt64ToFloat64() ccall((:BinaryenConvertUInt64ToFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenPromoteFloat32() ccall((:BinaryenPromoteFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenDemoteFloat64() ccall((:BinaryenDemoteFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenReinterpretInt32() ccall((:BinaryenReinterpretInt32, libbinaryen), BinaryenOp, ()) end function BinaryenReinterpretInt64() ccall((:BinaryenReinterpretInt64, libbinaryen), BinaryenOp, ()) end function BinaryenExtendS8Int32() ccall((:BinaryenExtendS8Int32, libbinaryen), BinaryenOp, ()) end function BinaryenExtendS16Int32() ccall((:BinaryenExtendS16Int32, libbinaryen), BinaryenOp, ()) end function BinaryenExtendS8Int64() ccall((:BinaryenExtendS8Int64, libbinaryen), BinaryenOp, ()) end function BinaryenExtendS16Int64() ccall((:BinaryenExtendS16Int64, libbinaryen), BinaryenOp, ()) end function BinaryenExtendS32Int64() ccall((:BinaryenExtendS32Int64, libbinaryen), BinaryenOp, ()) end function BinaryenAddInt32() ccall((:BinaryenAddInt32, libbinaryen), BinaryenOp, ()) end function BinaryenSubInt32() ccall((:BinaryenSubInt32, libbinaryen), BinaryenOp, ()) end function BinaryenMulInt32() ccall((:BinaryenMulInt32, libbinaryen), BinaryenOp, ()) end function BinaryenDivSInt32() ccall((:BinaryenDivSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenDivUInt32() ccall((:BinaryenDivUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenRemSInt32() ccall((:BinaryenRemSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenRemUInt32() ccall((:BinaryenRemUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenAndInt32() ccall((:BinaryenAndInt32, libbinaryen), BinaryenOp, ()) end function BinaryenOrInt32() ccall((:BinaryenOrInt32, libbinaryen), BinaryenOp, ()) end function BinaryenXorInt32() ccall((:BinaryenXorInt32, libbinaryen), BinaryenOp, ()) end function BinaryenShlInt32() ccall((:BinaryenShlInt32, libbinaryen), BinaryenOp, ()) end function BinaryenShrUInt32() ccall((:BinaryenShrUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenShrSInt32() ccall((:BinaryenShrSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenRotLInt32() ccall((:BinaryenRotLInt32, libbinaryen), BinaryenOp, ()) end function BinaryenRotRInt32() ccall((:BinaryenRotRInt32, libbinaryen), BinaryenOp, ()) end function BinaryenEqInt32() ccall((:BinaryenEqInt32, libbinaryen), BinaryenOp, ()) end function BinaryenNeInt32() ccall((:BinaryenNeInt32, libbinaryen), BinaryenOp, ()) end function BinaryenLtSInt32() ccall((:BinaryenLtSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenLtUInt32() ccall((:BinaryenLtUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenLeSInt32() ccall((:BinaryenLeSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenLeUInt32() ccall((:BinaryenLeUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenGtSInt32() ccall((:BinaryenGtSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenGtUInt32() ccall((:BinaryenGtUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenGeSInt32() ccall((:BinaryenGeSInt32, libbinaryen), BinaryenOp, ()) end function BinaryenGeUInt32() ccall((:BinaryenGeUInt32, libbinaryen), BinaryenOp, ()) end function BinaryenAddInt64() ccall((:BinaryenAddInt64, libbinaryen), BinaryenOp, ()) end function BinaryenSubInt64() ccall((:BinaryenSubInt64, libbinaryen), BinaryenOp, ()) end function BinaryenMulInt64() ccall((:BinaryenMulInt64, libbinaryen), BinaryenOp, ()) end function BinaryenDivSInt64() ccall((:BinaryenDivSInt64, libbinaryen), BinaryenOp, ()) end function BinaryenDivUInt64() ccall((:BinaryenDivUInt64, libbinaryen), BinaryenOp, ()) end function BinaryenRemSInt64() ccall((:BinaryenRemSInt64, libbinaryen), BinaryenOp, ()) end function BinaryenRemUInt64() ccall((:BinaryenRemUInt64, libbinaryen), BinaryenOp, ()) end function BinaryenAndInt64() ccall((:BinaryenAndInt64, libbinaryen), BinaryenOp, ()) end function BinaryenOrInt64() ccall((:BinaryenOrInt64, libbinaryen), BinaryenOp, ()) end function BinaryenXorInt64() ccall((:BinaryenXorInt64, libbinaryen), BinaryenOp, ()) end function BinaryenShlInt64() ccall((:BinaryenShlInt64, libbinaryen), BinaryenOp, ()) end function BinaryenShrUInt64() ccall((:BinaryenShrUInt64, libbinaryen), BinaryenOp, ()) end function BinaryenShrSInt64() ccall((:BinaryenShrSInt64, libbinaryen), BinaryenOp, ()) end function BinaryenRotLInt64() ccall((:BinaryenRotLInt64, libbinaryen), BinaryenOp, ()) end function BinaryenRotRInt64() ccall((:BinaryenRotRInt64, libbinaryen), BinaryenOp, ()) end function BinaryenEqInt64() ccall((:BinaryenEqInt64, libbinaryen), BinaryenOp, ()) end function BinaryenNeInt64() ccall((:BinaryenNeInt64, libbinaryen), BinaryenOp, ()) end function BinaryenLtSInt64() ccall((:BinaryenLtSInt64, libbinaryen), BinaryenOp, ()) end function BinaryenLtUInt64() ccall((:BinaryenLtUInt64, libbinaryen), BinaryenOp, ()) end function BinaryenLeSInt64() ccall((:BinaryenLeSInt64, libbinaryen), BinaryenOp, ()) end function BinaryenLeUInt64() ccall((:BinaryenLeUInt64, libbinaryen), BinaryenOp, ()) end function BinaryenGtSInt64() ccall((:BinaryenGtSInt64, libbinaryen), BinaryenOp, ()) end function BinaryenGtUInt64() ccall((:BinaryenGtUInt64, libbinaryen), BinaryenOp, ()) end function BinaryenGeSInt64() ccall((:BinaryenGeSInt64, libbinaryen), BinaryenOp, ()) end function BinaryenGeUInt64() ccall((:BinaryenGeUInt64, libbinaryen), BinaryenOp, ()) end function BinaryenAddFloat32() ccall((:BinaryenAddFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenSubFloat32() ccall((:BinaryenSubFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenMulFloat32() ccall((:BinaryenMulFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenDivFloat32() ccall((:BinaryenDivFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenCopySignFloat32() ccall((:BinaryenCopySignFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenMinFloat32() ccall((:BinaryenMinFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenMaxFloat32() ccall((:BinaryenMaxFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenEqFloat32() ccall((:BinaryenEqFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenNeFloat32() ccall((:BinaryenNeFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenLtFloat32() ccall((:BinaryenLtFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenLeFloat32() ccall((:BinaryenLeFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenGtFloat32() ccall((:BinaryenGtFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenGeFloat32() ccall((:BinaryenGeFloat32, libbinaryen), BinaryenOp, ()) end function BinaryenAddFloat64() ccall((:BinaryenAddFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenSubFloat64() ccall((:BinaryenSubFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenMulFloat64() ccall((:BinaryenMulFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenDivFloat64() ccall((:BinaryenDivFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenCopySignFloat64() ccall((:BinaryenCopySignFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenMinFloat64() ccall((:BinaryenMinFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenMaxFloat64() ccall((:BinaryenMaxFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenEqFloat64() ccall((:BinaryenEqFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenNeFloat64() ccall((:BinaryenNeFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenLtFloat64() ccall((:BinaryenLtFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenLeFloat64() ccall((:BinaryenLeFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenGtFloat64() ccall((:BinaryenGtFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenGeFloat64() ccall((:BinaryenGeFloat64, libbinaryen), BinaryenOp, ()) end function BinaryenAtomicRMWAdd() ccall((:BinaryenAtomicRMWAdd, libbinaryen), BinaryenOp, ()) end function BinaryenAtomicRMWSub() ccall((:BinaryenAtomicRMWSub, libbinaryen), BinaryenOp, ()) end function BinaryenAtomicRMWAnd() ccall((:BinaryenAtomicRMWAnd, libbinaryen), BinaryenOp, ()) end function BinaryenAtomicRMWOr() ccall((:BinaryenAtomicRMWOr, libbinaryen), BinaryenOp, ()) end function BinaryenAtomicRMWXor() ccall((:BinaryenAtomicRMWXor, libbinaryen), BinaryenOp, ()) end function BinaryenAtomicRMWXchg() ccall((:BinaryenAtomicRMWXchg, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatSFloat32ToInt32() ccall((:BinaryenTruncSatSFloat32ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatSFloat32ToInt64() ccall((:BinaryenTruncSatSFloat32ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatUFloat32ToInt32() ccall((:BinaryenTruncSatUFloat32ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatUFloat32ToInt64() ccall((:BinaryenTruncSatUFloat32ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatSFloat64ToInt32() ccall((:BinaryenTruncSatSFloat64ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatSFloat64ToInt64() ccall((:BinaryenTruncSatSFloat64ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatUFloat64ToInt32() ccall((:BinaryenTruncSatUFloat64ToInt32, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatUFloat64ToInt64() ccall((:BinaryenTruncSatUFloat64ToInt64, libbinaryen), BinaryenOp, ()) end function BinaryenSplatVecI8x16() ccall((:BinaryenSplatVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneSVecI8x16() ccall((:BinaryenExtractLaneSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneUVecI8x16() ccall((:BinaryenExtractLaneUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenReplaceLaneVecI8x16() ccall((:BinaryenReplaceLaneVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenSplatVecI16x8() ccall((:BinaryenSplatVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneSVecI16x8() ccall((:BinaryenExtractLaneSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneUVecI16x8() ccall((:BinaryenExtractLaneUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenReplaceLaneVecI16x8() ccall((:BinaryenReplaceLaneVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenSplatVecI32x4() ccall((:BinaryenSplatVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneVecI32x4() ccall((:BinaryenExtractLaneVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenReplaceLaneVecI32x4() ccall((:BinaryenReplaceLaneVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenSplatVecI64x2() ccall((:BinaryenSplatVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneVecI64x2() ccall((:BinaryenExtractLaneVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenReplaceLaneVecI64x2() ccall((:BinaryenReplaceLaneVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenSplatVecF32x4() ccall((:BinaryenSplatVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneVecF32x4() ccall((:BinaryenExtractLaneVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenReplaceLaneVecF32x4() ccall((:BinaryenReplaceLaneVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenSplatVecF64x2() ccall((:BinaryenSplatVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtractLaneVecF64x2() ccall((:BinaryenExtractLaneVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenReplaceLaneVecF64x2() ccall((:BinaryenReplaceLaneVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenEqVecI8x16() ccall((:BinaryenEqVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenNeVecI8x16() ccall((:BinaryenNeVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenLtSVecI8x16() ccall((:BinaryenLtSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenLtUVecI8x16() ccall((:BinaryenLtUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenGtSVecI8x16() ccall((:BinaryenGtSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenGtUVecI8x16() ccall((:BinaryenGtUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenLeSVecI8x16() ccall((:BinaryenLeSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenLeUVecI8x16() ccall((:BinaryenLeUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenGeSVecI8x16() ccall((:BinaryenGeSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenGeUVecI8x16() ccall((:BinaryenGeUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenEqVecI16x8() ccall((:BinaryenEqVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenNeVecI16x8() ccall((:BinaryenNeVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenLtSVecI16x8() ccall((:BinaryenLtSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenLtUVecI16x8() ccall((:BinaryenLtUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenGtSVecI16x8() ccall((:BinaryenGtSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenGtUVecI16x8() ccall((:BinaryenGtUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenLeSVecI16x8() ccall((:BinaryenLeSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenLeUVecI16x8() ccall((:BinaryenLeUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenGeSVecI16x8() ccall((:BinaryenGeSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenGeUVecI16x8() ccall((:BinaryenGeUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenEqVecI32x4() ccall((:BinaryenEqVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenNeVecI32x4() ccall((:BinaryenNeVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLtSVecI32x4() ccall((:BinaryenLtSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLtUVecI32x4() ccall((:BinaryenLtUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenGtSVecI32x4() ccall((:BinaryenGtSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenGtUVecI32x4() ccall((:BinaryenGtUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLeSVecI32x4() ccall((:BinaryenLeSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLeUVecI32x4() ccall((:BinaryenLeUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenGeSVecI32x4() ccall((:BinaryenGeSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenGeUVecI32x4() ccall((:BinaryenGeUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenEqVecI64x2() ccall((:BinaryenEqVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenNeVecI64x2() ccall((:BinaryenNeVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenLtSVecI64x2() ccall((:BinaryenLtSVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenGtSVecI64x2() ccall((:BinaryenGtSVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenLeSVecI64x2() ccall((:BinaryenLeSVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenGeSVecI64x2() ccall((:BinaryenGeSVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenEqVecF32x4() ccall((:BinaryenEqVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenNeVecF32x4() ccall((:BinaryenNeVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLtVecF32x4() ccall((:BinaryenLtVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenGtVecF32x4() ccall((:BinaryenGtVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLeVecF32x4() ccall((:BinaryenLeVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenGeVecF32x4() ccall((:BinaryenGeVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenEqVecF64x2() ccall((:BinaryenEqVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenNeVecF64x2() ccall((:BinaryenNeVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenLtVecF64x2() ccall((:BinaryenLtVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenGtVecF64x2() ccall((:BinaryenGtVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenLeVecF64x2() ccall((:BinaryenLeVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenGeVecF64x2() ccall((:BinaryenGeVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenNotVec128() ccall((:BinaryenNotVec128, libbinaryen), BinaryenOp, ()) end function BinaryenAndVec128() ccall((:BinaryenAndVec128, libbinaryen), BinaryenOp, ()) end function BinaryenOrVec128() ccall((:BinaryenOrVec128, libbinaryen), BinaryenOp, ()) end function BinaryenXorVec128() ccall((:BinaryenXorVec128, libbinaryen), BinaryenOp, ()) end function BinaryenAndNotVec128() ccall((:BinaryenAndNotVec128, libbinaryen), BinaryenOp, ()) end function BinaryenBitselectVec128() ccall((:BinaryenBitselectVec128, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedFmaVecF32x4() ccall((:BinaryenRelaxedFmaVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedFmsVecF32x4() ccall((:BinaryenRelaxedFmsVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedFmaVecF64x2() ccall((:BinaryenRelaxedFmaVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedFmsVecF64x2() ccall((:BinaryenRelaxedFmsVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenLaneselectI8x16() ccall((:BinaryenLaneselectI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenLaneselectI16x8() ccall((:BinaryenLaneselectI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenLaneselectI32x4() ccall((:BinaryenLaneselectI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLaneselectI64x2() ccall((:BinaryenLaneselectI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenDotI8x16I7x16AddSToVecI32x4() ccall((:BinaryenDotI8x16I7x16AddSToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenAnyTrueVec128() ccall((:BinaryenAnyTrueVec128, libbinaryen), BinaryenOp, ()) end function BinaryenPopcntVecI8x16() ccall((:BinaryenPopcntVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenAbsVecI8x16() ccall((:BinaryenAbsVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenNegVecI8x16() ccall((:BinaryenNegVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenAllTrueVecI8x16() ccall((:BinaryenAllTrueVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenBitmaskVecI8x16() ccall((:BinaryenBitmaskVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenShlVecI8x16() ccall((:BinaryenShlVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenShrSVecI8x16() ccall((:BinaryenShrSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenShrUVecI8x16() ccall((:BinaryenShrUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenAddVecI8x16() ccall((:BinaryenAddVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenAddSatSVecI8x16() ccall((:BinaryenAddSatSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenAddSatUVecI8x16() ccall((:BinaryenAddSatUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenSubVecI8x16() ccall((:BinaryenSubVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenSubSatSVecI8x16() ccall((:BinaryenSubSatSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenSubSatUVecI8x16() ccall((:BinaryenSubSatUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenMinSVecI8x16() ccall((:BinaryenMinSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenMinUVecI8x16() ccall((:BinaryenMinUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenMaxSVecI8x16() ccall((:BinaryenMaxSVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenMaxUVecI8x16() ccall((:BinaryenMaxUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenAvgrUVecI8x16() ccall((:BinaryenAvgrUVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenAbsVecI16x8() ccall((:BinaryenAbsVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenNegVecI16x8() ccall((:BinaryenNegVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenAllTrueVecI16x8() ccall((:BinaryenAllTrueVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenBitmaskVecI16x8() ccall((:BinaryenBitmaskVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenShlVecI16x8() ccall((:BinaryenShlVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenShrSVecI16x8() ccall((:BinaryenShrSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenShrUVecI16x8() ccall((:BinaryenShrUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenAddVecI16x8() ccall((:BinaryenAddVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenAddSatSVecI16x8() ccall((:BinaryenAddSatSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenAddSatUVecI16x8() ccall((:BinaryenAddSatUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenSubVecI16x8() ccall((:BinaryenSubVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenSubSatSVecI16x8() ccall((:BinaryenSubSatSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenSubSatUVecI16x8() ccall((:BinaryenSubSatUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenMulVecI16x8() ccall((:BinaryenMulVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenMinSVecI16x8() ccall((:BinaryenMinSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenMinUVecI16x8() ccall((:BinaryenMinUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenMaxSVecI16x8() ccall((:BinaryenMaxSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenMaxUVecI16x8() ccall((:BinaryenMaxUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenAvgrUVecI16x8() ccall((:BinaryenAvgrUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenQ15MulrSatSVecI16x8() ccall((:BinaryenQ15MulrSatSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulLowSVecI16x8() ccall((:BinaryenExtMulLowSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulHighSVecI16x8() ccall((:BinaryenExtMulHighSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulLowUVecI16x8() ccall((:BinaryenExtMulLowUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulHighUVecI16x8() ccall((:BinaryenExtMulHighUVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenAbsVecI32x4() ccall((:BinaryenAbsVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenNegVecI32x4() ccall((:BinaryenNegVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenAllTrueVecI32x4() ccall((:BinaryenAllTrueVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenBitmaskVecI32x4() ccall((:BinaryenBitmaskVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenShlVecI32x4() ccall((:BinaryenShlVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenShrSVecI32x4() ccall((:BinaryenShrSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenShrUVecI32x4() ccall((:BinaryenShrUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenAddVecI32x4() ccall((:BinaryenAddVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenSubVecI32x4() ccall((:BinaryenSubVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMulVecI32x4() ccall((:BinaryenMulVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMinSVecI32x4() ccall((:BinaryenMinSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMinUVecI32x4() ccall((:BinaryenMinUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMaxSVecI32x4() ccall((:BinaryenMaxSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMaxUVecI32x4() ccall((:BinaryenMaxUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenDotSVecI16x8ToVecI32x4() ccall((:BinaryenDotSVecI16x8ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulLowSVecI32x4() ccall((:BinaryenExtMulLowSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulHighSVecI32x4() ccall((:BinaryenExtMulHighSVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulLowUVecI32x4() ccall((:BinaryenExtMulLowUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulHighUVecI32x4() ccall((:BinaryenExtMulHighUVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenAbsVecI64x2() ccall((:BinaryenAbsVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenNegVecI64x2() ccall((:BinaryenNegVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenAllTrueVecI64x2() ccall((:BinaryenAllTrueVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenBitmaskVecI64x2() ccall((:BinaryenBitmaskVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenShlVecI64x2() ccall((:BinaryenShlVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenShrSVecI64x2() ccall((:BinaryenShrSVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenShrUVecI64x2() ccall((:BinaryenShrUVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenAddVecI64x2() ccall((:BinaryenAddVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenSubVecI64x2() ccall((:BinaryenSubVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenMulVecI64x2() ccall((:BinaryenMulVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulLowSVecI64x2() ccall((:BinaryenExtMulLowSVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulHighSVecI64x2() ccall((:BinaryenExtMulHighSVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulLowUVecI64x2() ccall((:BinaryenExtMulLowUVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtMulHighUVecI64x2() ccall((:BinaryenExtMulHighUVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenAbsVecF32x4() ccall((:BinaryenAbsVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenNegVecF32x4() ccall((:BinaryenNegVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenSqrtVecF32x4() ccall((:BinaryenSqrtVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenAddVecF32x4() ccall((:BinaryenAddVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenSubVecF32x4() ccall((:BinaryenSubVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMulVecF32x4() ccall((:BinaryenMulVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenDivVecF32x4() ccall((:BinaryenDivVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMinVecF32x4() ccall((:BinaryenMinVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenMaxVecF32x4() ccall((:BinaryenMaxVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenPMinVecF32x4() ccall((:BinaryenPMinVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenPMaxVecF32x4() ccall((:BinaryenPMaxVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenCeilVecF32x4() ccall((:BinaryenCeilVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenFloorVecF32x4() ccall((:BinaryenFloorVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenTruncVecF32x4() ccall((:BinaryenTruncVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenNearestVecF32x4() ccall((:BinaryenNearestVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenAbsVecF64x2() ccall((:BinaryenAbsVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenNegVecF64x2() ccall((:BinaryenNegVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenSqrtVecF64x2() ccall((:BinaryenSqrtVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenAddVecF64x2() ccall((:BinaryenAddVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenSubVecF64x2() ccall((:BinaryenSubVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenMulVecF64x2() ccall((:BinaryenMulVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenDivVecF64x2() ccall((:BinaryenDivVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenMinVecF64x2() ccall((:BinaryenMinVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenMaxVecF64x2() ccall((:BinaryenMaxVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenPMinVecF64x2() ccall((:BinaryenPMinVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenPMaxVecF64x2() ccall((:BinaryenPMaxVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenCeilVecF64x2() ccall((:BinaryenCeilVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenFloorVecF64x2() ccall((:BinaryenFloorVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenTruncVecF64x2() ccall((:BinaryenTruncVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenNearestVecF64x2() ccall((:BinaryenNearestVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtAddPairwiseSVecI8x16ToI16x8() ccall((:BinaryenExtAddPairwiseSVecI8x16ToI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtAddPairwiseUVecI8x16ToI16x8() ccall((:BinaryenExtAddPairwiseUVecI8x16ToI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtAddPairwiseSVecI16x8ToI32x4() ccall((:BinaryenExtAddPairwiseSVecI16x8ToI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtAddPairwiseUVecI16x8ToI32x4() ccall((:BinaryenExtAddPairwiseUVecI16x8ToI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatSVecF32x4ToVecI32x4() ccall((:BinaryenTruncSatSVecF32x4ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatUVecF32x4ToVecI32x4() ccall((:BinaryenTruncSatUVecF32x4ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenConvertSVecI32x4ToVecF32x4() ccall((:BinaryenConvertSVecI32x4ToVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenConvertUVecI32x4ToVecF32x4() ccall((:BinaryenConvertUVecI32x4ToVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenLoad8SplatVec128() ccall((:BinaryenLoad8SplatVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad16SplatVec128() ccall((:BinaryenLoad16SplatVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad32SplatVec128() ccall((:BinaryenLoad32SplatVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad64SplatVec128() ccall((:BinaryenLoad64SplatVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad8x8SVec128() ccall((:BinaryenLoad8x8SVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad8x8UVec128() ccall((:BinaryenLoad8x8UVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad16x4SVec128() ccall((:BinaryenLoad16x4SVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad16x4UVec128() ccall((:BinaryenLoad16x4UVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad32x2SVec128() ccall((:BinaryenLoad32x2SVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad32x2UVec128() ccall((:BinaryenLoad32x2UVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad32ZeroVec128() ccall((:BinaryenLoad32ZeroVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad64ZeroVec128() ccall((:BinaryenLoad64ZeroVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad8LaneVec128() ccall((:BinaryenLoad8LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad16LaneVec128() ccall((:BinaryenLoad16LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad32LaneVec128() ccall((:BinaryenLoad32LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenLoad64LaneVec128() ccall((:BinaryenLoad64LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenStore8LaneVec128() ccall((:BinaryenStore8LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenStore16LaneVec128() ccall((:BinaryenStore16LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenStore32LaneVec128() ccall((:BinaryenStore32LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenStore64LaneVec128() ccall((:BinaryenStore64LaneVec128, libbinaryen), BinaryenOp, ()) end function BinaryenNarrowSVecI16x8ToVecI8x16() ccall((:BinaryenNarrowSVecI16x8ToVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenNarrowUVecI16x8ToVecI8x16() ccall((:BinaryenNarrowUVecI16x8ToVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenNarrowSVecI32x4ToVecI16x8() ccall((:BinaryenNarrowSVecI32x4ToVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenNarrowUVecI32x4ToVecI16x8() ccall((:BinaryenNarrowUVecI32x4ToVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtendLowSVecI8x16ToVecI16x8() ccall((:BinaryenExtendLowSVecI8x16ToVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtendHighSVecI8x16ToVecI16x8() ccall((:BinaryenExtendHighSVecI8x16ToVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtendLowUVecI8x16ToVecI16x8() ccall((:BinaryenExtendLowUVecI8x16ToVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtendHighUVecI8x16ToVecI16x8() ccall((:BinaryenExtendHighUVecI8x16ToVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenExtendLowSVecI16x8ToVecI32x4() ccall((:BinaryenExtendLowSVecI16x8ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtendHighSVecI16x8ToVecI32x4() ccall((:BinaryenExtendHighSVecI16x8ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtendLowUVecI16x8ToVecI32x4() ccall((:BinaryenExtendLowUVecI16x8ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtendHighUVecI16x8ToVecI32x4() ccall((:BinaryenExtendHighUVecI16x8ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenExtendLowSVecI32x4ToVecI64x2() ccall((:BinaryenExtendLowSVecI32x4ToVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtendHighSVecI32x4ToVecI64x2() ccall((:BinaryenExtendHighSVecI32x4ToVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtendLowUVecI32x4ToVecI64x2() ccall((:BinaryenExtendLowUVecI32x4ToVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenExtendHighUVecI32x4ToVecI64x2() ccall((:BinaryenExtendHighUVecI32x4ToVecI64x2, libbinaryen), BinaryenOp, ()) end function BinaryenConvertLowSVecI32x4ToVecF64x2() ccall((:BinaryenConvertLowSVecI32x4ToVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenConvertLowUVecI32x4ToVecF64x2() ccall((:BinaryenConvertLowUVecI32x4ToVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatZeroSVecF64x2ToVecI32x4() ccall((:BinaryenTruncSatZeroSVecF64x2ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenTruncSatZeroUVecF64x2ToVecI32x4() ccall((:BinaryenTruncSatZeroUVecF64x2ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenDemoteZeroVecF64x2ToVecF32x4() ccall((:BinaryenDemoteZeroVecF64x2ToVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenPromoteLowVecF32x4ToVecF64x2() ccall((:BinaryenPromoteLowVecF32x4ToVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedTruncSVecF32x4ToVecI32x4() ccall((:BinaryenRelaxedTruncSVecF32x4ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedTruncUVecF32x4ToVecI32x4() ccall((:BinaryenRelaxedTruncUVecF32x4ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedTruncZeroSVecF64x2ToVecI32x4() ccall((:BinaryenRelaxedTruncZeroSVecF64x2ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedTruncZeroUVecF64x2ToVecI32x4() ccall((:BinaryenRelaxedTruncZeroUVecF64x2ToVecI32x4, libbinaryen), BinaryenOp, ()) end function BinaryenSwizzleVecI8x16() ccall((:BinaryenSwizzleVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedSwizzleVecI8x16() ccall((:BinaryenRelaxedSwizzleVecI8x16, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedMinVecF32x4() ccall((:BinaryenRelaxedMinVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedMaxVecF32x4() ccall((:BinaryenRelaxedMaxVecF32x4, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedMinVecF64x2() ccall((:BinaryenRelaxedMinVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedMaxVecF64x2() ccall((:BinaryenRelaxedMaxVecF64x2, libbinaryen), BinaryenOp, ()) end function BinaryenRelaxedQ15MulrSVecI16x8() ccall((:BinaryenRelaxedQ15MulrSVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenDotI8x16I7x16SToVecI16x8() ccall((:BinaryenDotI8x16I7x16SToVecI16x8, libbinaryen), BinaryenOp, ()) end function BinaryenRefAsNonNull() ccall((:BinaryenRefAsNonNull, libbinaryen), BinaryenOp, ()) end function BinaryenRefAsExternInternalize() ccall((:BinaryenRefAsExternInternalize, libbinaryen), BinaryenOp, ()) end function BinaryenRefAsExternExternalize() ccall((:BinaryenRefAsExternExternalize, libbinaryen), BinaryenOp, ()) end function BinaryenBrOnNull() ccall((:BinaryenBrOnNull, libbinaryen), BinaryenOp, ()) end function BinaryenBrOnNonNull() ccall((:BinaryenBrOnNonNull, libbinaryen), BinaryenOp, ()) end function BinaryenBrOnCast() ccall((:BinaryenBrOnCast, libbinaryen), BinaryenOp, ()) end function BinaryenBrOnCastFail() ccall((:BinaryenBrOnCastFail, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewUTF8() ccall((:BinaryenStringNewUTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewWTF8() ccall((:BinaryenStringNewWTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewLossyUTF8() ccall((:BinaryenStringNewLossyUTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewWTF16() ccall((:BinaryenStringNewWTF16, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewUTF8Array() ccall((:BinaryenStringNewUTF8Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewWTF8Array() ccall((:BinaryenStringNewWTF8Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewLossyUTF8Array() ccall((:BinaryenStringNewLossyUTF8Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewWTF16Array() ccall((:BinaryenStringNewWTF16Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringNewFromCodePoint() ccall((:BinaryenStringNewFromCodePoint, libbinaryen), BinaryenOp, ()) end function BinaryenStringMeasureUTF8() ccall((:BinaryenStringMeasureUTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringMeasureWTF8() ccall((:BinaryenStringMeasureWTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringMeasureWTF16() ccall((:BinaryenStringMeasureWTF16, libbinaryen), BinaryenOp, ()) end function BinaryenStringMeasureIsUSV() ccall((:BinaryenStringMeasureIsUSV, libbinaryen), BinaryenOp, ()) end function BinaryenStringMeasureWTF16View() ccall((:BinaryenStringMeasureWTF16View, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeUTF8() ccall((:BinaryenStringEncodeUTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeLossyUTF8() ccall((:BinaryenStringEncodeLossyUTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeWTF8() ccall((:BinaryenStringEncodeWTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeWTF16() ccall((:BinaryenStringEncodeWTF16, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeUTF8Array() ccall((:BinaryenStringEncodeUTF8Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeLossyUTF8Array() ccall((:BinaryenStringEncodeLossyUTF8Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeWTF8Array() ccall((:BinaryenStringEncodeWTF8Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringEncodeWTF16Array() ccall((:BinaryenStringEncodeWTF16Array, libbinaryen), BinaryenOp, ()) end function BinaryenStringAsWTF8() ccall((:BinaryenStringAsWTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringAsWTF16() ccall((:BinaryenStringAsWTF16, libbinaryen), BinaryenOp, ()) end function BinaryenStringAsIter() ccall((:BinaryenStringAsIter, libbinaryen), BinaryenOp, ()) end function BinaryenStringIterMoveAdvance() ccall((:BinaryenStringIterMoveAdvance, libbinaryen), BinaryenOp, ()) end function BinaryenStringIterMoveRewind() ccall((:BinaryenStringIterMoveRewind, libbinaryen), BinaryenOp, ()) end function BinaryenStringSliceWTF8() ccall((:BinaryenStringSliceWTF8, libbinaryen), BinaryenOp, ()) end function BinaryenStringSliceWTF16() ccall((:BinaryenStringSliceWTF16, libbinaryen), BinaryenOp, ()) end function BinaryenStringEqEqual() ccall((:BinaryenStringEqEqual, libbinaryen), BinaryenOp, ()) end function BinaryenStringEqCompare() ccall((:BinaryenStringEqCompare, libbinaryen), BinaryenOp, ()) end mutable struct BinaryenExpression end const BinaryenExpressionRef = Ptr{BinaryenExpression} """ BinaryenBlock(_module, name, children, numChildren, type) Block: name can be NULL. Specifying BinaryenUndefined() as the 'type' parameter indicates that the block's type shall be figured out automatically instead of explicitly providing it. This conforms to the behavior before the 'type' parameter has been introduced. """ function BinaryenBlock(_module, name, children, numChildren, type) ccall((:BinaryenBlock, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{BinaryenExpressionRef}, BinaryenIndex, BinaryenType), _module, name, children, numChildren, type) end """ BinaryenIf(_module, condition, ifTrue, ifFalse) If: ifFalse can be NULL """ function BinaryenIf(_module, condition, ifTrue, ifFalse) ccall((:BinaryenIf, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, condition, ifTrue, ifFalse) end function BinaryenLoop(_module, in, body) ccall((:BinaryenLoop, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef), _module, in, body) end """ BinaryenBreak(_module, name, condition, value) Break: value and condition can be NULL """ function BinaryenBreak(_module, name, condition, value) ccall((:BinaryenBreak, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, BinaryenExpressionRef), _module, name, condition, value) end """ BinaryenSwitch(_module, names, numNames, defaultName, condition, value) Switch: value can be NULL """ function BinaryenSwitch(_module, names, numNames, defaultName, condition, value) ccall((:BinaryenSwitch, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Ptr{Cchar}}, BinaryenIndex, Ptr{Cchar}, BinaryenExpressionRef, BinaryenExpressionRef), _module, names, numNames, defaultName, condition, value) end """ BinaryenCall(_module, target, operands, numOperands, returnType) Call: Note the 'returnType' parameter. You must declare the type returned by the function being called, as that function might not have been created yet, so we don't know what it is. """ function BinaryenCall(_module, target, operands, numOperands, returnType) ccall((:BinaryenCall, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{BinaryenExpressionRef}, BinaryenIndex, BinaryenType), _module, target, operands, numOperands, returnType) end function BinaryenCallIndirect(_module, table, target, operands, numOperands, params, results) ccall((:BinaryenCallIndirect, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, Ptr{BinaryenExpressionRef}, BinaryenIndex, BinaryenType, BinaryenType), _module, table, target, operands, numOperands, params, results) end function BinaryenReturnCall(_module, target, operands, numOperands, returnType) ccall((:BinaryenReturnCall, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{BinaryenExpressionRef}, BinaryenIndex, BinaryenType), _module, target, operands, numOperands, returnType) end function BinaryenReturnCallIndirect(_module, table, target, operands, numOperands, params, results) ccall((:BinaryenReturnCallIndirect, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, Ptr{BinaryenExpressionRef}, BinaryenIndex, BinaryenType, BinaryenType), _module, table, target, operands, numOperands, params, results) end """ BinaryenLocalGet(_module, index, type) LocalGet: Note the 'type' parameter. It might seem redundant, since the local at that index must have a type. However, this API lets you build code "top-down": create a node, then its parents, and so on, and finally create the function at the end. (Note that in fact you do not mention a function when creating ExpressionRefs, only a module.) And since LocalGet is a leaf node, we need to be told its type. (Other nodes detect their type either from their type or their opcode, or failing that, their children. But LocalGet has no children, it is where a "stream" of type info begins.) Note also that the index of a local can refer to a param or a var, that is, either a parameter to the function or a variable declared when you call BinaryenAddFunction. See BinaryenAddFunction for more details. """ function BinaryenLocalGet(_module, index, type) ccall((:BinaryenLocalGet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenIndex, BinaryenType), _module, index, type) end function BinaryenLocalSet(_module, index, value) ccall((:BinaryenLocalSet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenIndex, BinaryenExpressionRef), _module, index, value) end function BinaryenLocalTee(_module, index, value, type) ccall((:BinaryenLocalTee, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenIndex, BinaryenExpressionRef, BinaryenType), _module, index, value, type) end function BinaryenGlobalGet(_module, name, type) ccall((:BinaryenGlobalGet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenType), _module, name, type) end function BinaryenGlobalSet(_module, name, value) ccall((:BinaryenGlobalSet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef), _module, name, value) end """ BinaryenLoad(_module, bytes, signed_, offset, align, type, ptr, memoryName) Load: align can be 0, in which case it will be the natural alignment (equal to bytes) """ function BinaryenLoad(_module, bytes, signed_, offset, align, type, ptr, memoryName) ccall((:BinaryenLoad, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, UInt32, Bool, UInt32, UInt32, BinaryenType, BinaryenExpressionRef, Ptr{Cchar}), _module, bytes, signed_, offset, align, type, ptr, memoryName) end """ BinaryenStore(_module, bytes, offset, align, ptr, value, type, memoryName) Store: align can be 0, in which case it will be the natural alignment (equal to bytes) """ function BinaryenStore(_module, bytes, offset, align, ptr, value, type, memoryName) ccall((:BinaryenStore, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, UInt32, UInt32, UInt32, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenType, Ptr{Cchar}), _module, bytes, offset, align, ptr, value, type, memoryName) end function BinaryenConst(_module, value) ccall((:BinaryenConst, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenLiteral), _module, value) end function BinaryenUnary(_module, op, value) ccall((:BinaryenUnary, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef), _module, op, value) end function BinaryenBinary(_module, op, left, right) ccall((:BinaryenBinary, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef), _module, op, left, right) end function BinaryenSelect(_module, condition, ifTrue, ifFalse, type) ccall((:BinaryenSelect, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenType), _module, condition, ifTrue, ifFalse, type) end function BinaryenDrop(_module, value) ccall((:BinaryenDrop, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef), _module, value) end """ BinaryenReturn(_module, value) Return: value can be NULL """ function BinaryenReturn(_module, value) ccall((:BinaryenReturn, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef), _module, value) end function BinaryenMemorySize(_module, memoryName, memoryIs64) ccall((:BinaryenMemorySize, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, Bool), _module, memoryName, memoryIs64) end function BinaryenMemoryGrow(_module, delta, memoryName, memoryIs64) ccall((:BinaryenMemoryGrow, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, Ptr{Cchar}, Bool), _module, delta, memoryName, memoryIs64) end function BinaryenNop(_module) ccall((:BinaryenNop, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef,), _module) end function BinaryenUnreachable(_module) ccall((:BinaryenUnreachable, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef,), _module) end function BinaryenAtomicLoad(_module, bytes, offset, type, ptr, memoryName) ccall((:BinaryenAtomicLoad, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, UInt32, UInt32, BinaryenType, BinaryenExpressionRef, Ptr{Cchar}), _module, bytes, offset, type, ptr, memoryName) end function BinaryenAtomicStore(_module, bytes, offset, ptr, value, type, memoryName) ccall((:BinaryenAtomicStore, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, UInt32, UInt32, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenType, Ptr{Cchar}), _module, bytes, offset, ptr, value, type, memoryName) end function BinaryenAtomicRMW(_module, op, bytes, offset, ptr, value, type, memoryName) ccall((:BinaryenAtomicRMW, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenIndex, BinaryenIndex, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenType, Ptr{Cchar}), _module, op, bytes, offset, ptr, value, type, memoryName) end function BinaryenAtomicCmpxchg(_module, bytes, offset, ptr, expected, replacement, type, memoryName) ccall((:BinaryenAtomicCmpxchg, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenIndex, BinaryenIndex, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenType, Ptr{Cchar}), _module, bytes, offset, ptr, expected, replacement, type, memoryName) end function BinaryenAtomicWait(_module, ptr, expected, timeout, type, memoryName) ccall((:BinaryenAtomicWait, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenType, Ptr{Cchar}), _module, ptr, expected, timeout, type, memoryName) end function BinaryenAtomicNotify(_module, ptr, notifyCount, memoryName) ccall((:BinaryenAtomicNotify, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, Ptr{Cchar}), _module, ptr, notifyCount, memoryName) end function BinaryenAtomicFence(_module) ccall((:BinaryenAtomicFence, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef,), _module) end function BinaryenSIMDExtract(_module, op, vec, index) ccall((:BinaryenSIMDExtract, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, UInt8), _module, op, vec, index) end function BinaryenSIMDReplace(_module, op, vec, index, value) ccall((:BinaryenSIMDReplace, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, UInt8, BinaryenExpressionRef), _module, op, vec, index, value) end function BinaryenSIMDShuffle(_module, left, right, mask) ccall((:BinaryenSIMDShuffle, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, Ptr{UInt8}), _module, left, right, mask) end function BinaryenSIMDTernary(_module, op, a, b, c) ccall((:BinaryenSIMDTernary, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, op, a, b, c) end function BinaryenSIMDShift(_module, op, vec, shift) ccall((:BinaryenSIMDShift, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef), _module, op, vec, shift) end function BinaryenSIMDLoad(_module, op, offset, align, ptr, name) ccall((:BinaryenSIMDLoad, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, UInt32, UInt32, BinaryenExpressionRef, Ptr{Cchar}), _module, op, offset, align, ptr, name) end function BinaryenSIMDLoadStoreLane(_module, op, offset, align, index, ptr, vec, memoryName) ccall((:BinaryenSIMDLoadStoreLane, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, UInt32, UInt32, UInt8, BinaryenExpressionRef, BinaryenExpressionRef, Ptr{Cchar}), _module, op, offset, align, index, ptr, vec, memoryName) end function BinaryenMemoryInit(_module, segment, dest, offset, size, memoryName) ccall((:BinaryenMemoryInit, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, Ptr{Cchar}), _module, segment, dest, offset, size, memoryName) end function BinaryenDataDrop(_module, segment) ccall((:BinaryenDataDrop, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}), _module, segment) end function BinaryenMemoryCopy(_module, dest, source, size, destMemory, sourceMemory) ccall((:BinaryenMemoryCopy, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, Ptr{Cchar}, Ptr{Cchar}), _module, dest, source, size, destMemory, sourceMemory) end function BinaryenMemoryFill(_module, dest, value, size, memoryName) ccall((:BinaryenMemoryFill, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, Ptr{Cchar}), _module, dest, value, size, memoryName) end function BinaryenRefNull(_module, type) ccall((:BinaryenRefNull, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenType), _module, type) end function BinaryenRefIsNull(_module, value) ccall((:BinaryenRefIsNull, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef), _module, value) end function BinaryenRefAs(_module, op, value) ccall((:BinaryenRefAs, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef), _module, op, value) end function BinaryenRefFunc(_module, func, type) ccall((:BinaryenRefFunc, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenType), _module, func, type) end function BinaryenRefEq(_module, left, right) ccall((:BinaryenRefEq, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, left, right) end function BinaryenTableGet(_module, name, index, type) ccall((:BinaryenTableGet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, BinaryenType), _module, name, index, type) end function BinaryenTableSet(_module, name, index, value) ccall((:BinaryenTableSet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, BinaryenExpressionRef), _module, name, index, value) end function BinaryenTableSize(_module, name) ccall((:BinaryenTableSize, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenTableGrow(_module, name, value, delta) ccall((:BinaryenTableGrow, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, BinaryenExpressionRef), _module, name, value, delta) end """ BinaryenTry(_module, name, body, catchTags, numCatchTags, catchBodies, numCatchBodies, delegateTarget) Try: name can be NULL. delegateTarget should be NULL in try-catch. """ function BinaryenTry(_module, name, body, catchTags, numCatchTags, catchBodies, numCatchBodies, delegateTarget) ccall((:BinaryenTry, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenExpressionRef, Ptr{Ptr{Cchar}}, BinaryenIndex, Ptr{BinaryenExpressionRef}, BinaryenIndex, Ptr{Cchar}), _module, name, body, catchTags, numCatchTags, catchBodies, numCatchBodies, delegateTarget) end function BinaryenThrow(_module, tag, operands, numOperands) ccall((:BinaryenThrow, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{BinaryenExpressionRef}, BinaryenIndex), _module, tag, operands, numOperands) end function BinaryenRethrow(_module, target) ccall((:BinaryenRethrow, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}), _module, target) end function BinaryenTupleMake(_module, operands, numOperands) ccall((:BinaryenTupleMake, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{BinaryenExpressionRef}, BinaryenIndex), _module, operands, numOperands) end function BinaryenTupleExtract(_module, tuple, index) ccall((:BinaryenTupleExtract, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenIndex), _module, tuple, index) end function BinaryenPop(_module, type) ccall((:BinaryenPop, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenType), _module, type) end function BinaryenI31New(_module, value) ccall((:BinaryenI31New, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef), _module, value) end function BinaryenI31Get(_module, i31, signed_) ccall((:BinaryenI31Get, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, Bool), _module, i31, signed_) end function BinaryenCallRef(_module, target, operands, numOperands, type, isReturn) ccall((:BinaryenCallRef, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, Ptr{BinaryenExpressionRef}, BinaryenIndex, BinaryenType, Bool), _module, target, operands, numOperands, type, isReturn) end function BinaryenRefTest(_module, ref, castType) ccall((:BinaryenRefTest, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenType), _module, ref, castType) end function BinaryenRefCast(_module, ref, type) ccall((:BinaryenRefCast, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenType), _module, ref, type) end function BinaryenBrOn(_module, op, name, ref, castType) ccall((:BinaryenBrOn, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, Ptr{Cchar}, BinaryenExpressionRef, BinaryenType), _module, op, name, ref, castType) end function BinaryenStructNew(_module, operands, numOperands, type) ccall((:BinaryenStructNew, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{BinaryenExpressionRef}, BinaryenIndex, BinaryenHeapType), _module, operands, numOperands, type) end function BinaryenStructGet(_module, index, ref, type, signed_) ccall((:BinaryenStructGet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenIndex, BinaryenExpressionRef, BinaryenType, Bool), _module, index, ref, type, signed_) end function BinaryenStructSet(_module, index, ref, value) ccall((:BinaryenStructSet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenIndex, BinaryenExpressionRef, BinaryenExpressionRef), _module, index, ref, value) end function BinaryenArrayNew(_module, type, size, init) ccall((:BinaryenArrayNew, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenHeapType, BinaryenExpressionRef, BinaryenExpressionRef), _module, type, size, init) end """ BinaryenArrayNewFixed(_module, type, values, numValues) TODO: BinaryenArrayNewSeg """ function BinaryenArrayNewFixed(_module, type, values, numValues) ccall((:BinaryenArrayNewFixed, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenHeapType, Ptr{BinaryenExpressionRef}, BinaryenIndex), _module, type, values, numValues) end function BinaryenArrayGet(_module, ref, index, type, signed_) ccall((:BinaryenArrayGet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenType, Bool), _module, ref, index, type, signed_) end function BinaryenArraySet(_module, ref, index, value) ccall((:BinaryenArraySet, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, ref, index, value) end function BinaryenArrayLen(_module, ref) ccall((:BinaryenArrayLen, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef), _module, ref) end function BinaryenArrayCopy(_module, destRef, destIndex, srcRef, srcIndex, length) ccall((:BinaryenArrayCopy, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, destRef, destIndex, srcRef, srcIndex, length) end function BinaryenStringNew(_module, op, ptr, length, start, _end, try_) ccall((:BinaryenStringNew, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef, Bool), _module, op, ptr, length, start, _end, try_) end function BinaryenStringConst(_module, name) ccall((:BinaryenStringConst, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenStringMeasure(_module, op, ref) ccall((:BinaryenStringMeasure, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef), _module, op, ref) end function BinaryenStringEncode(_module, op, ref, ptr, start) ccall((:BinaryenStringEncode, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, op, ref, ptr, start) end function BinaryenStringConcat(_module, left, right) ccall((:BinaryenStringConcat, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, left, right) end function BinaryenStringEq(_module, op, left, right) ccall((:BinaryenStringEq, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef), _module, op, left, right) end function BinaryenStringAs(_module, op, ref) ccall((:BinaryenStringAs, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef), _module, op, ref) end function BinaryenStringWTF8Advance(_module, ref, pos, bytes) ccall((:BinaryenStringWTF8Advance, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, ref, pos, bytes) end function BinaryenStringWTF16Get(_module, ref, pos) ccall((:BinaryenStringWTF16Get, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, ref, pos) end function BinaryenStringIterNext(_module, ref) ccall((:BinaryenStringIterNext, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef), _module, ref) end function BinaryenStringIterMove(_module, op, ref, num) ccall((:BinaryenStringIterMove, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef), _module, op, ref, num) end function BinaryenStringSliceWTF(_module, op, ref, start, _end) ccall((:BinaryenStringSliceWTF, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenOp, BinaryenExpressionRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, op, ref, start, _end) end function BinaryenStringSliceIter(_module, ref, num) ccall((:BinaryenStringSliceIter, libbinaryen), BinaryenExpressionRef, (BinaryenModuleRef, BinaryenExpressionRef, BinaryenExpressionRef), _module, ref, num) end """ BinaryenExpressionGetId(expr) Gets the id (kind) of the given expression. """ function BinaryenExpressionGetId(expr) ccall((:BinaryenExpressionGetId, libbinaryen), BinaryenExpressionId, (BinaryenExpressionRef,), expr) end """ BinaryenExpressionGetType(expr) Gets the type of the given expression. """ function BinaryenExpressionGetType(expr) ccall((:BinaryenExpressionGetType, libbinaryen), BinaryenType, (BinaryenExpressionRef,), expr) end """ BinaryenExpressionSetType(expr, type) Sets the type of the given expression. """ function BinaryenExpressionSetType(expr, type) ccall((:BinaryenExpressionSetType, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenType), expr, type) end """ BinaryenExpressionPrint(expr) Prints text format of the given expression to stdout. """ function BinaryenExpressionPrint(expr) ccall((:BinaryenExpressionPrint, libbinaryen), Cvoid, (BinaryenExpressionRef,), expr) end """ BinaryenExpressionFinalize(expr) Re-finalizes an expression after it has been modified. """ function BinaryenExpressionFinalize(expr) ccall((:BinaryenExpressionFinalize, libbinaryen), Cvoid, (BinaryenExpressionRef,), expr) end """ BinaryenExpressionCopy(expr, _module) Makes a deep copy of the given expression. """ function BinaryenExpressionCopy(expr, _module) ccall((:BinaryenExpressionCopy, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenModuleRef), expr, _module) end """ BinaryenBlockGetName(expr) Gets the name (label) of a `block` expression. """ function BinaryenBlockGetName(expr) ccall((:BinaryenBlockGetName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenBlockSetName(expr, name) Sets the name (label) of a `block` expression. """ function BinaryenBlockSetName(expr, name) ccall((:BinaryenBlockSetName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenBlockGetNumChildren(expr) Gets the number of child expressions of a `block` expression. """ function BinaryenBlockGetNumChildren(expr) ccall((:BinaryenBlockGetNumChildren, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenBlockGetChildAt(expr, index) Gets the child expression at the specified index of a `block` expression. """ function BinaryenBlockGetChildAt(expr, index) ccall((:BinaryenBlockGetChildAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenBlockSetChildAt(expr, index, childExpr) Sets (replaces) the child expression at the specified index of a `block` expression. """ function BinaryenBlockSetChildAt(expr, index, childExpr) ccall((:BinaryenBlockSetChildAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, childExpr) end """ BinaryenBlockAppendChild(expr, childExpr) Appends a child expression to a `block` expression, returning its insertion index. """ function BinaryenBlockAppendChild(expr, childExpr) ccall((:BinaryenBlockAppendChild, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, childExpr) end """ BinaryenBlockInsertChildAt(expr, index, childExpr) Inserts a child expression at the specified index of a `block` expression, moving existing children including the one previously at that index one index up. """ function BinaryenBlockInsertChildAt(expr, index, childExpr) ccall((:BinaryenBlockInsertChildAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, childExpr) end """ BinaryenBlockRemoveChildAt(expr, index) Removes the child expression at the specified index of a `block` expression, moving all subsequent children one index down. Returns the child expression. """ function BinaryenBlockRemoveChildAt(expr, index) ccall((:BinaryenBlockRemoveChildAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenIfGetCondition(expr) Gets the condition expression of an `if` expression. """ function BinaryenIfGetCondition(expr) ccall((:BinaryenIfGetCondition, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenIfSetCondition(expr, condExpr) Sets the condition expression of an `if` expression. """ function BinaryenIfSetCondition(expr, condExpr) ccall((:BinaryenIfSetCondition, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, condExpr) end """ BinaryenIfGetIfTrue(expr) Gets the ifTrue (then) expression of an `if` expression. """ function BinaryenIfGetIfTrue(expr) ccall((:BinaryenIfGetIfTrue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenIfSetIfTrue(expr, ifTrueExpr) Sets the ifTrue (then) expression of an `if` expression. """ function BinaryenIfSetIfTrue(expr, ifTrueExpr) ccall((:BinaryenIfSetIfTrue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ifTrueExpr) end """ BinaryenIfGetIfFalse(expr) Gets the ifFalse (else) expression, if any, of an `if` expression. """ function BinaryenIfGetIfFalse(expr) ccall((:BinaryenIfGetIfFalse, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenIfSetIfFalse(expr, ifFalseExpr) Sets the ifFalse (else) expression, if any, of an `if` expression. """ function BinaryenIfSetIfFalse(expr, ifFalseExpr) ccall((:BinaryenIfSetIfFalse, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ifFalseExpr) end """ BinaryenLoopGetName(expr) Gets the name (label) of a `loop` expression. """ function BinaryenLoopGetName(expr) ccall((:BinaryenLoopGetName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenLoopSetName(expr, name) Sets the name (label) of a `loop` expression. """ function BinaryenLoopSetName(expr, name) ccall((:BinaryenLoopSetName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenLoopGetBody(expr) Gets the body expression of a `loop` expression. """ function BinaryenLoopGetBody(expr) ccall((:BinaryenLoopGetBody, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenLoopSetBody(expr, bodyExpr) Sets the body expression of a `loop` expression. """ function BinaryenLoopSetBody(expr, bodyExpr) ccall((:BinaryenLoopSetBody, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, bodyExpr) end """ BinaryenBreakGetName(expr) Gets the name (target label) of a `br` or `br_if` expression. """ function BinaryenBreakGetName(expr) ccall((:BinaryenBreakGetName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenBreakSetName(expr, name) Sets the name (target label) of a `br` or `br_if` expression. """ function BinaryenBreakSetName(expr, name) ccall((:BinaryenBreakSetName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenBreakGetCondition(expr) Gets the condition expression, if any, of a `br_if` expression. No condition indicates a `br` expression. """ function BinaryenBreakGetCondition(expr) ccall((:BinaryenBreakGetCondition, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenBreakSetCondition(expr, condExpr) Sets the condition expression, if any, of a `br_if` expression. No condition makes it a `br` expression. """ function BinaryenBreakSetCondition(expr, condExpr) ccall((:BinaryenBreakSetCondition, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, condExpr) end """ BinaryenBreakGetValue(expr) Gets the value expression, if any, of a `br` or `br_if` expression. """ function BinaryenBreakGetValue(expr) ccall((:BinaryenBreakGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenBreakSetValue(expr, valueExpr) Sets the value expression, if any, of a `br` or `br_if` expression. """ function BinaryenBreakSetValue(expr, valueExpr) ccall((:BinaryenBreakSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenSwitchGetNumNames(expr) Gets the number of names (target labels) of a `br_table` expression. """ function BinaryenSwitchGetNumNames(expr) ccall((:BinaryenSwitchGetNumNames, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenSwitchGetNameAt(expr, index) Gets the name (target label) at the specified index of a `br_table` expression. """ function BinaryenSwitchGetNameAt(expr, index) ccall((:BinaryenSwitchGetNameAt, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenSwitchSetNameAt(expr, index, name) Sets the name (target label) at the specified index of a `br_table` expression. """ function BinaryenSwitchSetNameAt(expr, index, name) ccall((:BinaryenSwitchSetNameAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, Ptr{Cchar}), expr, index, name) end """ BinaryenSwitchAppendName(expr, name) Appends a name to a `br_table` expression, returning its insertion index. """ function BinaryenSwitchAppendName(expr, name) ccall((:BinaryenSwitchAppendName, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenSwitchInsertNameAt(expr, index, name) Inserts a name at the specified index of a `br_table` expression, moving existing names including the one previously at that index one index up. """ function BinaryenSwitchInsertNameAt(expr, index, name) ccall((:BinaryenSwitchInsertNameAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, Ptr{Cchar}), expr, index, name) end """ BinaryenSwitchRemoveNameAt(expr, index) Removes the name at the specified index of a `br_table` expression, moving all subsequent names one index down. Returns the name. """ function BinaryenSwitchRemoveNameAt(expr, index) ccall((:BinaryenSwitchRemoveNameAt, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenSwitchGetDefaultName(expr) Gets the default name (target label), if any, of a `br_table` expression. """ function BinaryenSwitchGetDefaultName(expr) ccall((:BinaryenSwitchGetDefaultName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenSwitchSetDefaultName(expr, name) Sets the default name (target label), if any, of a `br_table` expression. """ function BinaryenSwitchSetDefaultName(expr, name) ccall((:BinaryenSwitchSetDefaultName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenSwitchGetCondition(expr) Gets the condition expression of a `br_table` expression. """ function BinaryenSwitchGetCondition(expr) ccall((:BinaryenSwitchGetCondition, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSwitchSetCondition(expr, condExpr) Sets the condition expression of a `br_table` expression. """ function BinaryenSwitchSetCondition(expr, condExpr) ccall((:BinaryenSwitchSetCondition, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, condExpr) end """ BinaryenSwitchGetValue(expr) Gets the value expression, if any, of a `br_table` expression. """ function BinaryenSwitchGetValue(expr) ccall((:BinaryenSwitchGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSwitchSetValue(expr, valueExpr) Sets the value expression, if any, of a `br_table` expression. """ function BinaryenSwitchSetValue(expr, valueExpr) ccall((:BinaryenSwitchSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenCallGetTarget(expr) Gets the target function name of a `call` expression. """ function BinaryenCallGetTarget(expr) ccall((:BinaryenCallGetTarget, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenCallSetTarget(expr, target) Sets the target function name of a `call` expression. """ function BinaryenCallSetTarget(expr, target) ccall((:BinaryenCallSetTarget, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, target) end """ BinaryenCallGetNumOperands(expr) Gets the number of operands of a `call` expression. """ function BinaryenCallGetNumOperands(expr) ccall((:BinaryenCallGetNumOperands, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenCallGetOperandAt(expr, index) Gets the operand expression at the specified index of a `call` expression. """ function BinaryenCallGetOperandAt(expr, index) ccall((:BinaryenCallGetOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenCallSetOperandAt(expr, index, operandExpr) Sets the operand expression at the specified index of a `call` expression. """ function BinaryenCallSetOperandAt(expr, index, operandExpr) ccall((:BinaryenCallSetOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenCallAppendOperand(expr, operandExpr) Appends an operand expression to a `call` expression, returning its insertion index. """ function BinaryenCallAppendOperand(expr, operandExpr) ccall((:BinaryenCallAppendOperand, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, operandExpr) end """ BinaryenCallInsertOperandAt(expr, index, operandExpr) Inserts an operand expression at the specified index of a `call` expression, moving existing operands including the one previously at that index one index up. """ function BinaryenCallInsertOperandAt(expr, index, operandExpr) ccall((:BinaryenCallInsertOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenCallRemoveOperandAt(expr, index) Removes the operand expression at the specified index of a `call` expression, moving all subsequent operands one index down. Returns the operand expression. """ function BinaryenCallRemoveOperandAt(expr, index) ccall((:BinaryenCallRemoveOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenCallIsReturn(expr) Gets whether the specified `call` expression is a tail call. """ function BinaryenCallIsReturn(expr) ccall((:BinaryenCallIsReturn, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenCallSetReturn(expr, isReturn) Sets whether the specified `call` expression is a tail call. """ function BinaryenCallSetReturn(expr, isReturn) ccall((:BinaryenCallSetReturn, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, isReturn) end """ BinaryenCallIndirectGetTarget(expr) Gets the target expression of a `call_indirect` expression. """ function BinaryenCallIndirectGetTarget(expr) ccall((:BinaryenCallIndirectGetTarget, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenCallIndirectSetTarget(expr, targetExpr) Sets the target expression of a `call_indirect` expression. """ function BinaryenCallIndirectSetTarget(expr, targetExpr) ccall((:BinaryenCallIndirectSetTarget, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, targetExpr) end """ BinaryenCallIndirectGetTable(expr) Gets the table name of a `call_indirect` expression. """ function BinaryenCallIndirectGetTable(expr) ccall((:BinaryenCallIndirectGetTable, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenCallIndirectSetTable(expr, table) Sets the table name of a `call_indirect` expression. """ function BinaryenCallIndirectSetTable(expr, table) ccall((:BinaryenCallIndirectSetTable, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, table) end """ BinaryenCallIndirectGetNumOperands(expr) Gets the number of operands of a `call_indirect` expression. """ function BinaryenCallIndirectGetNumOperands(expr) ccall((:BinaryenCallIndirectGetNumOperands, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenCallIndirectGetOperandAt(expr, index) Gets the operand expression at the specified index of a `call_indirect` expression. """ function BinaryenCallIndirectGetOperandAt(expr, index) ccall((:BinaryenCallIndirectGetOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenCallIndirectSetOperandAt(expr, index, operandExpr) Sets the operand expression at the specified index of a `call_indirect` expression. """ function BinaryenCallIndirectSetOperandAt(expr, index, operandExpr) ccall((:BinaryenCallIndirectSetOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenCallIndirectAppendOperand(expr, operandExpr) Appends an operand expression to a `call_indirect` expression, returning its insertion index. """ function BinaryenCallIndirectAppendOperand(expr, operandExpr) ccall((:BinaryenCallIndirectAppendOperand, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, operandExpr) end """ BinaryenCallIndirectInsertOperandAt(expr, index, operandExpr) Inserts an operand expression at the specified index of a `call_indirect` expression, moving existing operands including the one previously at that index one index up. """ function BinaryenCallIndirectInsertOperandAt(expr, index, operandExpr) ccall((:BinaryenCallIndirectInsertOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenCallIndirectRemoveOperandAt(expr, index) Removes the operand expression at the specified index of a `call_indirect` expression, moving all subsequent operands one index down. Returns the operand expression. """ function BinaryenCallIndirectRemoveOperandAt(expr, index) ccall((:BinaryenCallIndirectRemoveOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenCallIndirectIsReturn(expr) Gets whether the specified `call_indirect` expression is a tail call. """ function BinaryenCallIndirectIsReturn(expr) ccall((:BinaryenCallIndirectIsReturn, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenCallIndirectSetReturn(expr, isReturn) Sets whether the specified `call_indirect` expression is a tail call. """ function BinaryenCallIndirectSetReturn(expr, isReturn) ccall((:BinaryenCallIndirectSetReturn, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, isReturn) end """ BinaryenCallIndirectGetParams(expr) Gets the parameter types of the specified `call_indirect` expression. """ function BinaryenCallIndirectGetParams(expr) ccall((:BinaryenCallIndirectGetParams, libbinaryen), BinaryenType, (BinaryenExpressionRef,), expr) end """ BinaryenCallIndirectSetParams(expr, params) Sets the parameter types of the specified `call_indirect` expression. """ function BinaryenCallIndirectSetParams(expr, params) ccall((:BinaryenCallIndirectSetParams, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenType), expr, params) end """ BinaryenCallIndirectGetResults(expr) Gets the result types of the specified `call_indirect` expression. """ function BinaryenCallIndirectGetResults(expr) ccall((:BinaryenCallIndirectGetResults, libbinaryen), BinaryenType, (BinaryenExpressionRef,), expr) end """ BinaryenCallIndirectSetResults(expr, params) Sets the result types of the specified `call_indirect` expression. """ function BinaryenCallIndirectSetResults(expr, params) ccall((:BinaryenCallIndirectSetResults, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenType), expr, params) end """ BinaryenLocalGetGetIndex(expr) Gets the local index of a `local.get` expression. """ function BinaryenLocalGetGetIndex(expr) ccall((:BinaryenLocalGetGetIndex, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenLocalGetSetIndex(expr, index) Sets the local index of a `local.get` expression. """ function BinaryenLocalGetSetIndex(expr, index) ccall((:BinaryenLocalGetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenLocalSetIsTee(expr) Gets whether a `local.set` tees its value (is a `local.tee`). True if the expression has a type other than `none`. """ function BinaryenLocalSetIsTee(expr) ccall((:BinaryenLocalSetIsTee, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenLocalSetGetIndex(expr) Gets the local index of a `local.set` or `local.tee` expression. """ function BinaryenLocalSetGetIndex(expr) ccall((:BinaryenLocalSetGetIndex, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenLocalSetSetIndex(expr, index) Sets the local index of a `local.set` or `local.tee` expression. """ function BinaryenLocalSetSetIndex(expr, index) ccall((:BinaryenLocalSetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenLocalSetGetValue(expr) Gets the value expression of a `local.set` or `local.tee` expression. """ function BinaryenLocalSetGetValue(expr) ccall((:BinaryenLocalSetGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenLocalSetSetValue(expr, valueExpr) Sets the value expression of a `local.set` or `local.tee` expression. """ function BinaryenLocalSetSetValue(expr, valueExpr) ccall((:BinaryenLocalSetSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenGlobalGetGetName(expr) Gets the name of the global being accessed by a `global.get` expression. """ function BinaryenGlobalGetGetName(expr) ccall((:BinaryenGlobalGetGetName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenGlobalGetSetName(expr, name) Sets the name of the global being accessed by a `global.get` expression. """ function BinaryenGlobalGetSetName(expr, name) ccall((:BinaryenGlobalGetSetName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenGlobalSetGetName(expr) Gets the name of the global being accessed by a `global.set` expression. """ function BinaryenGlobalSetGetName(expr) ccall((:BinaryenGlobalSetGetName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenGlobalSetSetName(expr, name) Sets the name of the global being accessed by a `global.set` expression. """ function BinaryenGlobalSetSetName(expr, name) ccall((:BinaryenGlobalSetSetName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenGlobalSetGetValue(expr) Gets the value expression of a `global.set` expression. """ function BinaryenGlobalSetGetValue(expr) ccall((:BinaryenGlobalSetGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenGlobalSetSetValue(expr, valueExpr) Sets the value expression of a `global.set` expression. """ function BinaryenGlobalSetSetValue(expr, valueExpr) ccall((:BinaryenGlobalSetSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenTableGetGetTable(expr) Gets the name of the table being accessed by a `table.get` expression. """ function BinaryenTableGetGetTable(expr) ccall((:BinaryenTableGetGetTable, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenTableGetSetTable(expr, table) Sets the name of the table being accessed by a `table.get` expression. """ function BinaryenTableGetSetTable(expr, table) ccall((:BinaryenTableGetSetTable, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, table) end """ BinaryenTableGetGetIndex(expr) Gets the index expression of a `table.get` expression. """ function BinaryenTableGetGetIndex(expr) ccall((:BinaryenTableGetGetIndex, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenTableGetSetIndex(expr, indexExpr) Sets the index expression of a `table.get` expression. """ function BinaryenTableGetSetIndex(expr, indexExpr) ccall((:BinaryenTableGetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, indexExpr) end """ BinaryenTableSetGetTable(expr) Gets the name of the table being accessed by a `table.set` expression. """ function BinaryenTableSetGetTable(expr) ccall((:BinaryenTableSetGetTable, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenTableSetSetTable(expr, table) Sets the name of the table being accessed by a `table.set` expression. """ function BinaryenTableSetSetTable(expr, table) ccall((:BinaryenTableSetSetTable, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, table) end """ BinaryenTableSetGetIndex(expr) Gets the index expression of a `table.set` expression. """ function BinaryenTableSetGetIndex(expr) ccall((:BinaryenTableSetGetIndex, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenTableSetSetIndex(expr, indexExpr) Sets the index expression of a `table.set` expression. """ function BinaryenTableSetSetIndex(expr, indexExpr) ccall((:BinaryenTableSetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, indexExpr) end """ BinaryenTableSetGetValue(expr) Gets the value expression of a `table.set` expression. """ function BinaryenTableSetGetValue(expr) ccall((:BinaryenTableSetGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenTableSetSetValue(expr, valueExpr) Sets the value expression of a `table.set` expression. """ function BinaryenTableSetSetValue(expr, valueExpr) ccall((:BinaryenTableSetSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenTableSizeGetTable(expr) Gets the name of the table being accessed by a `table.size` expression. """ function BinaryenTableSizeGetTable(expr) ccall((:BinaryenTableSizeGetTable, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenTableSizeSetTable(expr, table) Sets the name of the table being accessed by a `table.size` expression. """ function BinaryenTableSizeSetTable(expr, table) ccall((:BinaryenTableSizeSetTable, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, table) end """ BinaryenTableGrowGetTable(expr) Gets the name of the table being accessed by a `table.grow` expression. """ function BinaryenTableGrowGetTable(expr) ccall((:BinaryenTableGrowGetTable, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenTableGrowSetTable(expr, table) Sets the name of the table being accessed by a `table.grow` expression. """ function BinaryenTableGrowSetTable(expr, table) ccall((:BinaryenTableGrowSetTable, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, table) end """ BinaryenTableGrowGetValue(expr) Gets the value expression of a `table.grow` expression. """ function BinaryenTableGrowGetValue(expr) ccall((:BinaryenTableGrowGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenTableGrowSetValue(expr, valueExpr) Sets the value expression of a `table.grow` expression. """ function BinaryenTableGrowSetValue(expr, valueExpr) ccall((:BinaryenTableGrowSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenTableGrowGetDelta(expr) Gets the delta of a `table.grow` expression. """ function BinaryenTableGrowGetDelta(expr) ccall((:BinaryenTableGrowGetDelta, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenTableGrowSetDelta(expr, deltaExpr) Sets the delta of a `table.grow` expression. """ function BinaryenTableGrowSetDelta(expr, deltaExpr) ccall((:BinaryenTableGrowSetDelta, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, deltaExpr) end """ BinaryenMemoryGrowGetDelta(expr) Gets the delta of a `memory.grow` expression. """ function BinaryenMemoryGrowGetDelta(expr) ccall((:BinaryenMemoryGrowGetDelta, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryGrowSetDelta(expr, deltaExpr) Sets the delta of a `memory.grow` expression. """ function BinaryenMemoryGrowSetDelta(expr, deltaExpr) ccall((:BinaryenMemoryGrowSetDelta, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, deltaExpr) end """ BinaryenLoadIsAtomic(expr) Gets whether a `load` expression is atomic (is an `atomic.load`). """ function BinaryenLoadIsAtomic(expr) ccall((:BinaryenLoadIsAtomic, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenLoadSetAtomic(expr, isAtomic) Sets whether a `load` expression is atomic (is an `atomic.load`). """ function BinaryenLoadSetAtomic(expr, isAtomic) ccall((:BinaryenLoadSetAtomic, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, isAtomic) end """ BinaryenLoadIsSigned(expr) Gets whether a `load` expression operates on a signed value (`_s`). """ function BinaryenLoadIsSigned(expr) ccall((:BinaryenLoadIsSigned, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenLoadSetSigned(expr, isSigned) Sets whether a `load` expression operates on a signed value (`_s`). """ function BinaryenLoadSetSigned(expr, isSigned) ccall((:BinaryenLoadSetSigned, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, isSigned) end """ BinaryenLoadGetOffset(expr) Gets the constant offset of a `load` expression. """ function BinaryenLoadGetOffset(expr) ccall((:BinaryenLoadGetOffset, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenLoadSetOffset(expr, offset) Sets the constant offset of a `load` expression. """ function BinaryenLoadSetOffset(expr, offset) ccall((:BinaryenLoadSetOffset, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, offset) end """ BinaryenLoadGetBytes(expr) Gets the number of bytes loaded by a `load` expression. """ function BinaryenLoadGetBytes(expr) ccall((:BinaryenLoadGetBytes, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenLoadSetBytes(expr, bytes) Sets the number of bytes loaded by a `load` expression. """ function BinaryenLoadSetBytes(expr, bytes) ccall((:BinaryenLoadSetBytes, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, bytes) end """ BinaryenLoadGetAlign(expr) Gets the byte alignment of a `load` expression. """ function BinaryenLoadGetAlign(expr) ccall((:BinaryenLoadGetAlign, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenLoadSetAlign(expr, align) Sets the byte alignment of a `load` expression. """ function BinaryenLoadSetAlign(expr, align) ccall((:BinaryenLoadSetAlign, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, align) end """ BinaryenLoadGetPtr(expr) Gets the pointer expression of a `load` expression. """ function BinaryenLoadGetPtr(expr) ccall((:BinaryenLoadGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenLoadSetPtr(expr, ptrExpr) Sets the pointer expression of a `load` expression. """ function BinaryenLoadSetPtr(expr, ptrExpr) ccall((:BinaryenLoadSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenStoreIsAtomic(expr) Gets whether a `store` expression is atomic (is an `atomic.store`). """ function BinaryenStoreIsAtomic(expr) ccall((:BinaryenStoreIsAtomic, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenStoreSetAtomic(expr, isAtomic) Sets whether a `store` expression is atomic (is an `atomic.store`). """ function BinaryenStoreSetAtomic(expr, isAtomic) ccall((:BinaryenStoreSetAtomic, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, isAtomic) end """ BinaryenStoreGetBytes(expr) Gets the number of bytes stored by a `store` expression. """ function BinaryenStoreGetBytes(expr) ccall((:BinaryenStoreGetBytes, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenStoreSetBytes(expr, bytes) Sets the number of bytes stored by a `store` expression. """ function BinaryenStoreSetBytes(expr, bytes) ccall((:BinaryenStoreSetBytes, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, bytes) end """ BinaryenStoreGetOffset(expr) Gets the constant offset of a `store` expression. """ function BinaryenStoreGetOffset(expr) ccall((:BinaryenStoreGetOffset, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenStoreSetOffset(expr, offset) Sets the constant offset of a `store` expression. """ function BinaryenStoreSetOffset(expr, offset) ccall((:BinaryenStoreSetOffset, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, offset) end """ BinaryenStoreGetAlign(expr) Gets the byte alignment of a `store` expression. """ function BinaryenStoreGetAlign(expr) ccall((:BinaryenStoreGetAlign, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenStoreSetAlign(expr, align) Sets the byte alignment of a `store` expression. """ function BinaryenStoreSetAlign(expr, align) ccall((:BinaryenStoreSetAlign, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, align) end """ BinaryenStoreGetPtr(expr) Gets the pointer expression of a `store` expression. """ function BinaryenStoreGetPtr(expr) ccall((:BinaryenStoreGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenStoreSetPtr(expr, ptrExpr) Sets the pointer expression of a `store` expression. """ function BinaryenStoreSetPtr(expr, ptrExpr) ccall((:BinaryenStoreSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenStoreGetValue(expr) Gets the value expression of a `store` expression. """ function BinaryenStoreGetValue(expr) ccall((:BinaryenStoreGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenStoreSetValue(expr, valueExpr) Sets the value expression of a `store` expression. """ function BinaryenStoreSetValue(expr, valueExpr) ccall((:BinaryenStoreSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenStoreGetValueType(expr) Gets the value type of a `store` expression. """ function BinaryenStoreGetValueType(expr) ccall((:BinaryenStoreGetValueType, libbinaryen), BinaryenType, (BinaryenExpressionRef,), expr) end """ BinaryenStoreSetValueType(expr, valueType) Sets the value type of a `store` expression. """ function BinaryenStoreSetValueType(expr, valueType) ccall((:BinaryenStoreSetValueType, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenType), expr, valueType) end """ BinaryenConstGetValueI32(expr) Gets the 32-bit integer value of an `i32.const` expression. """ function BinaryenConstGetValueI32(expr) ccall((:BinaryenConstGetValueI32, libbinaryen), Int32, (BinaryenExpressionRef,), expr) end """ BinaryenConstSetValueI32(expr, value) Sets the 32-bit integer value of an `i32.const` expression. """ function BinaryenConstSetValueI32(expr, value) ccall((:BinaryenConstSetValueI32, libbinaryen), Cvoid, (BinaryenExpressionRef, Int32), expr, value) end """ BinaryenConstGetValueI64(expr) Gets the 64-bit integer value of an `i64.const` expression. """ function BinaryenConstGetValueI64(expr) ccall((:BinaryenConstGetValueI64, libbinaryen), Int64, (BinaryenExpressionRef,), expr) end """ BinaryenConstSetValueI64(expr, value) Sets the 64-bit integer value of an `i64.const` expression. """ function BinaryenConstSetValueI64(expr, value) ccall((:BinaryenConstSetValueI64, libbinaryen), Cvoid, (BinaryenExpressionRef, Int64), expr, value) end """ BinaryenConstGetValueI64Low(expr) Gets the low 32-bits of the 64-bit integer value of an `i64.const` expression. """ function BinaryenConstGetValueI64Low(expr) ccall((:BinaryenConstGetValueI64Low, libbinaryen), Int32, (BinaryenExpressionRef,), expr) end """ BinaryenConstSetValueI64Low(expr, valueLow) Sets the low 32-bits of the 64-bit integer value of an `i64.const` expression. """ function BinaryenConstSetValueI64Low(expr, valueLow) ccall((:BinaryenConstSetValueI64Low, libbinaryen), Cvoid, (BinaryenExpressionRef, Int32), expr, valueLow) end """ BinaryenConstGetValueI64High(expr) Gets the high 32-bits of the 64-bit integer value of an `i64.const` expression. """ function BinaryenConstGetValueI64High(expr) ccall((:BinaryenConstGetValueI64High, libbinaryen), Int32, (BinaryenExpressionRef,), expr) end """ BinaryenConstSetValueI64High(expr, valueHigh) Sets the high 32-bits of the 64-bit integer value of an `i64.const` expression. """ function BinaryenConstSetValueI64High(expr, valueHigh) ccall((:BinaryenConstSetValueI64High, libbinaryen), Cvoid, (BinaryenExpressionRef, Int32), expr, valueHigh) end """ BinaryenConstGetValueF32(expr) Gets the 32-bit float value of a `f32.const` expression. """ function BinaryenConstGetValueF32(expr) ccall((:BinaryenConstGetValueF32, libbinaryen), Cfloat, (BinaryenExpressionRef,), expr) end """ BinaryenConstSetValueF32(expr, value) Sets the 32-bit float value of a `f32.const` expression. """ function BinaryenConstSetValueF32(expr, value) ccall((:BinaryenConstSetValueF32, libbinaryen), Cvoid, (BinaryenExpressionRef, Cfloat), expr, value) end """ BinaryenConstGetValueF64(expr) Gets the 64-bit float (double) value of a `f64.const` expression. """ function BinaryenConstGetValueF64(expr) ccall((:BinaryenConstGetValueF64, libbinaryen), Cdouble, (BinaryenExpressionRef,), expr) end """ BinaryenConstSetValueF64(expr, value) Sets the 64-bit float (double) value of a `f64.const` expression. """ function BinaryenConstSetValueF64(expr, value) ccall((:BinaryenConstSetValueF64, libbinaryen), Cvoid, (BinaryenExpressionRef, Cdouble), expr, value) end """ BinaryenConstGetValueV128(expr, out) Reads the 128-bit vector value of a `v128.const` expression. """ function BinaryenConstGetValueV128(expr, out) ccall((:BinaryenConstGetValueV128, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{UInt8}), expr, out) end """ BinaryenConstSetValueV128(expr, value) Sets the 128-bit vector value of a `v128.const` expression. """ function BinaryenConstSetValueV128(expr, value) ccall((:BinaryenConstSetValueV128, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{UInt8}), expr, value) end """ BinaryenUnaryGetOp(expr) Gets the operation being performed by a unary expression. """ function BinaryenUnaryGetOp(expr) ccall((:BinaryenUnaryGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenUnarySetOp(expr, op) Sets the operation being performed by a unary expression. """ function BinaryenUnarySetOp(expr, op) ccall((:BinaryenUnarySetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenUnaryGetValue(expr) Gets the value expression of a unary expression. """ function BinaryenUnaryGetValue(expr) ccall((:BinaryenUnaryGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenUnarySetValue(expr, valueExpr) Sets the value expression of a unary expression. """ function BinaryenUnarySetValue(expr, valueExpr) ccall((:BinaryenUnarySetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenBinaryGetOp(expr) Gets the operation being performed by a binary expression. """ function BinaryenBinaryGetOp(expr) ccall((:BinaryenBinaryGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenBinarySetOp(expr, op) Sets the operation being performed by a binary expression. """ function BinaryenBinarySetOp(expr, op) ccall((:BinaryenBinarySetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenBinaryGetLeft(expr) Gets the left expression of a binary expression. """ function BinaryenBinaryGetLeft(expr) ccall((:BinaryenBinaryGetLeft, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenBinarySetLeft(expr, leftExpr) Sets the left expression of a binary expression. """ function BinaryenBinarySetLeft(expr, leftExpr) ccall((:BinaryenBinarySetLeft, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, leftExpr) end """ BinaryenBinaryGetRight(expr) Gets the right expression of a binary expression. """ function BinaryenBinaryGetRight(expr) ccall((:BinaryenBinaryGetRight, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenBinarySetRight(expr, rightExpr) Sets the right expression of a binary expression. """ function BinaryenBinarySetRight(expr, rightExpr) ccall((:BinaryenBinarySetRight, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, rightExpr) end """ BinaryenSelectGetIfTrue(expr) Gets the expression becoming selected by a `select` expression if the condition turns out true. """ function BinaryenSelectGetIfTrue(expr) ccall((:BinaryenSelectGetIfTrue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSelectSetIfTrue(expr, ifTrueExpr) Sets the expression becoming selected by a `select` expression if the condition turns out true. """ function BinaryenSelectSetIfTrue(expr, ifTrueExpr) ccall((:BinaryenSelectSetIfTrue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ifTrueExpr) end """ BinaryenSelectGetIfFalse(expr) Gets the expression becoming selected by a `select` expression if the condition turns out false. """ function BinaryenSelectGetIfFalse(expr) ccall((:BinaryenSelectGetIfFalse, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSelectSetIfFalse(expr, ifFalseExpr) Sets the expression becoming selected by a `select` expression if the condition turns out false. """ function BinaryenSelectSetIfFalse(expr, ifFalseExpr) ccall((:BinaryenSelectSetIfFalse, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ifFalseExpr) end """ BinaryenSelectGetCondition(expr) Gets the condition expression of a `select` expression. """ function BinaryenSelectGetCondition(expr) ccall((:BinaryenSelectGetCondition, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSelectSetCondition(expr, condExpr) Sets the condition expression of a `select` expression. """ function BinaryenSelectSetCondition(expr, condExpr) ccall((:BinaryenSelectSetCondition, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, condExpr) end """ BinaryenDropGetValue(expr) Gets the value expression being dropped by a `drop` expression. """ function BinaryenDropGetValue(expr) ccall((:BinaryenDropGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenDropSetValue(expr, valueExpr) Sets the value expression being dropped by a `drop` expression. """ function BinaryenDropSetValue(expr, valueExpr) ccall((:BinaryenDropSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenReturnGetValue(expr) Gets the value expression, if any, being returned by a `return` expression. """ function BinaryenReturnGetValue(expr) ccall((:BinaryenReturnGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenReturnSetValue(expr, valueExpr) Sets the value expression, if any, being returned by a `return` expression. """ function BinaryenReturnSetValue(expr, valueExpr) ccall((:BinaryenReturnSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenAtomicRMWGetOp(expr) Gets the operation being performed by an atomic read-modify-write expression. """ function BinaryenAtomicRMWGetOp(expr) ccall((:BinaryenAtomicRMWGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicRMWSetOp(expr, op) Sets the operation being performed by an atomic read-modify-write expression. """ function BinaryenAtomicRMWSetOp(expr, op) ccall((:BinaryenAtomicRMWSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenAtomicRMWGetBytes(expr) Gets the number of bytes affected by an atomic read-modify-write expression. """ function BinaryenAtomicRMWGetBytes(expr) ccall((:BinaryenAtomicRMWGetBytes, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicRMWSetBytes(expr, bytes) Sets the number of bytes affected by an atomic read-modify-write expression. """ function BinaryenAtomicRMWSetBytes(expr, bytes) ccall((:BinaryenAtomicRMWSetBytes, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, bytes) end """ BinaryenAtomicRMWGetOffset(expr) Gets the constant offset of an atomic read-modify-write expression. """ function BinaryenAtomicRMWGetOffset(expr) ccall((:BinaryenAtomicRMWGetOffset, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicRMWSetOffset(expr, offset) Sets the constant offset of an atomic read-modify-write expression. """ function BinaryenAtomicRMWSetOffset(expr, offset) ccall((:BinaryenAtomicRMWSetOffset, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, offset) end """ BinaryenAtomicRMWGetPtr(expr) Gets the pointer expression of an atomic read-modify-write expression. """ function BinaryenAtomicRMWGetPtr(expr) ccall((:BinaryenAtomicRMWGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicRMWSetPtr(expr, ptrExpr) Sets the pointer expression of an atomic read-modify-write expression. """ function BinaryenAtomicRMWSetPtr(expr, ptrExpr) ccall((:BinaryenAtomicRMWSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenAtomicRMWGetValue(expr) Gets the value expression of an atomic read-modify-write expression. """ function BinaryenAtomicRMWGetValue(expr) ccall((:BinaryenAtomicRMWGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicRMWSetValue(expr, valueExpr) Sets the value expression of an atomic read-modify-write expression. """ function BinaryenAtomicRMWSetValue(expr, valueExpr) ccall((:BinaryenAtomicRMWSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenAtomicCmpxchgGetBytes(expr) Gets the number of bytes affected by an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgGetBytes(expr) ccall((:BinaryenAtomicCmpxchgGetBytes, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicCmpxchgSetBytes(expr, bytes) Sets the number of bytes affected by an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgSetBytes(expr, bytes) ccall((:BinaryenAtomicCmpxchgSetBytes, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, bytes) end """ BinaryenAtomicCmpxchgGetOffset(expr) Gets the constant offset of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgGetOffset(expr) ccall((:BinaryenAtomicCmpxchgGetOffset, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicCmpxchgSetOffset(expr, offset) Sets the constant offset of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgSetOffset(expr, offset) ccall((:BinaryenAtomicCmpxchgSetOffset, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, offset) end """ BinaryenAtomicCmpxchgGetPtr(expr) Gets the pointer expression of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgGetPtr(expr) ccall((:BinaryenAtomicCmpxchgGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicCmpxchgSetPtr(expr, ptrExpr) Sets the pointer expression of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgSetPtr(expr, ptrExpr) ccall((:BinaryenAtomicCmpxchgSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenAtomicCmpxchgGetExpected(expr) Gets the expression representing the expected value of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgGetExpected(expr) ccall((:BinaryenAtomicCmpxchgGetExpected, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicCmpxchgSetExpected(expr, expectedExpr) Sets the expression representing the expected value of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgSetExpected(expr, expectedExpr) ccall((:BinaryenAtomicCmpxchgSetExpected, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, expectedExpr) end """ BinaryenAtomicCmpxchgGetReplacement(expr) Gets the replacement expression of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgGetReplacement(expr) ccall((:BinaryenAtomicCmpxchgGetReplacement, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicCmpxchgSetReplacement(expr, replacementExpr) Sets the replacement expression of an atomic compare and exchange expression. """ function BinaryenAtomicCmpxchgSetReplacement(expr, replacementExpr) ccall((:BinaryenAtomicCmpxchgSetReplacement, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, replacementExpr) end """ BinaryenAtomicWaitGetPtr(expr) Gets the pointer expression of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitGetPtr(expr) ccall((:BinaryenAtomicWaitGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicWaitSetPtr(expr, ptrExpr) Sets the pointer expression of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitSetPtr(expr, ptrExpr) ccall((:BinaryenAtomicWaitSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenAtomicWaitGetExpected(expr) Gets the expression representing the expected value of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitGetExpected(expr) ccall((:BinaryenAtomicWaitGetExpected, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicWaitSetExpected(expr, expectedExpr) Sets the expression representing the expected value of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitSetExpected(expr, expectedExpr) ccall((:BinaryenAtomicWaitSetExpected, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, expectedExpr) end """ BinaryenAtomicWaitGetTimeout(expr) Gets the timeout expression of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitGetTimeout(expr) ccall((:BinaryenAtomicWaitGetTimeout, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicWaitSetTimeout(expr, timeoutExpr) Sets the timeout expression of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitSetTimeout(expr, timeoutExpr) ccall((:BinaryenAtomicWaitSetTimeout, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, timeoutExpr) end """ BinaryenAtomicWaitGetExpectedType(expr) Gets the expected type of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitGetExpectedType(expr) ccall((:BinaryenAtomicWaitGetExpectedType, libbinaryen), BinaryenType, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicWaitSetExpectedType(expr, expectedType) Sets the expected type of an `memory.atomic.wait` expression. """ function BinaryenAtomicWaitSetExpectedType(expr, expectedType) ccall((:BinaryenAtomicWaitSetExpectedType, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenType), expr, expectedType) end """ BinaryenAtomicNotifyGetPtr(expr) Gets the pointer expression of an `memory.atomic.notify` expression. """ function BinaryenAtomicNotifyGetPtr(expr) ccall((:BinaryenAtomicNotifyGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicNotifySetPtr(expr, ptrExpr) Sets the pointer expression of an `memory.atomic.notify` expression. """ function BinaryenAtomicNotifySetPtr(expr, ptrExpr) ccall((:BinaryenAtomicNotifySetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenAtomicNotifyGetNotifyCount(expr) Gets the notify count expression of an `memory.atomic.notify` expression. """ function BinaryenAtomicNotifyGetNotifyCount(expr) ccall((:BinaryenAtomicNotifyGetNotifyCount, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicNotifySetNotifyCount(expr, notifyCountExpr) Sets the notify count expression of an `memory.atomic.notify` expression. """ function BinaryenAtomicNotifySetNotifyCount(expr, notifyCountExpr) ccall((:BinaryenAtomicNotifySetNotifyCount, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, notifyCountExpr) end """ BinaryenAtomicFenceGetOrder(expr) Gets the order of an `atomic.fence` expression. """ function BinaryenAtomicFenceGetOrder(expr) ccall((:BinaryenAtomicFenceGetOrder, libbinaryen), UInt8, (BinaryenExpressionRef,), expr) end """ BinaryenAtomicFenceSetOrder(expr, order) Sets the order of an `atomic.fence` expression. """ function BinaryenAtomicFenceSetOrder(expr, order) ccall((:BinaryenAtomicFenceSetOrder, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt8), expr, order) end """ BinaryenSIMDExtractGetOp(expr) Gets the operation being performed by a SIMD extract expression. """ function BinaryenSIMDExtractGetOp(expr) ccall((:BinaryenSIMDExtractGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDExtractSetOp(expr, op) Sets the operation being performed by a SIMD extract expression. """ function BinaryenSIMDExtractSetOp(expr, op) ccall((:BinaryenSIMDExtractSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenSIMDExtractGetVec(expr) Gets the vector expression a SIMD extract expression extracts from. """ function BinaryenSIMDExtractGetVec(expr) ccall((:BinaryenSIMDExtractGetVec, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDExtractSetVec(expr, vecExpr) Sets the vector expression a SIMD extract expression extracts from. """ function BinaryenSIMDExtractSetVec(expr, vecExpr) ccall((:BinaryenSIMDExtractSetVec, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, vecExpr) end """ BinaryenSIMDExtractGetIndex(expr) Gets the index of the extracted lane of a SIMD extract expression. """ function BinaryenSIMDExtractGetIndex(expr) ccall((:BinaryenSIMDExtractGetIndex, libbinaryen), UInt8, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDExtractSetIndex(expr, index) Sets the index of the extracted lane of a SIMD extract expression. """ function BinaryenSIMDExtractSetIndex(expr, index) ccall((:BinaryenSIMDExtractSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt8), expr, index) end """ BinaryenSIMDReplaceGetOp(expr) Gets the operation being performed by a SIMD replace expression. """ function BinaryenSIMDReplaceGetOp(expr) ccall((:BinaryenSIMDReplaceGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDReplaceSetOp(expr, op) Sets the operation being performed by a SIMD replace expression. """ function BinaryenSIMDReplaceSetOp(expr, op) ccall((:BinaryenSIMDReplaceSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenSIMDReplaceGetVec(expr) Gets the vector expression a SIMD replace expression replaces in. """ function BinaryenSIMDReplaceGetVec(expr) ccall((:BinaryenSIMDReplaceGetVec, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDReplaceSetVec(expr, vecExpr) Sets the vector expression a SIMD replace expression replaces in. """ function BinaryenSIMDReplaceSetVec(expr, vecExpr) ccall((:BinaryenSIMDReplaceSetVec, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, vecExpr) end """ BinaryenSIMDReplaceGetIndex(expr) Gets the index of the replaced lane of a SIMD replace expression. """ function BinaryenSIMDReplaceGetIndex(expr) ccall((:BinaryenSIMDReplaceGetIndex, libbinaryen), UInt8, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDReplaceSetIndex(expr, index) Sets the index of the replaced lane of a SIMD replace expression. """ function BinaryenSIMDReplaceSetIndex(expr, index) ccall((:BinaryenSIMDReplaceSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt8), expr, index) end """ BinaryenSIMDReplaceGetValue(expr) Gets the value expression a SIMD replace expression replaces with. """ function BinaryenSIMDReplaceGetValue(expr) ccall((:BinaryenSIMDReplaceGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDReplaceSetValue(expr, valueExpr) Sets the value expression a SIMD replace expression replaces with. """ function BinaryenSIMDReplaceSetValue(expr, valueExpr) ccall((:BinaryenSIMDReplaceSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenSIMDShuffleGetLeft(expr) Gets the left expression of a SIMD shuffle expression. """ function BinaryenSIMDShuffleGetLeft(expr) ccall((:BinaryenSIMDShuffleGetLeft, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDShuffleSetLeft(expr, leftExpr) Sets the left expression of a SIMD shuffle expression. """ function BinaryenSIMDShuffleSetLeft(expr, leftExpr) ccall((:BinaryenSIMDShuffleSetLeft, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, leftExpr) end """ BinaryenSIMDShuffleGetRight(expr) Gets the right expression of a SIMD shuffle expression. """ function BinaryenSIMDShuffleGetRight(expr) ccall((:BinaryenSIMDShuffleGetRight, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDShuffleSetRight(expr, rightExpr) Sets the right expression of a SIMD shuffle expression. """ function BinaryenSIMDShuffleSetRight(expr, rightExpr) ccall((:BinaryenSIMDShuffleSetRight, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, rightExpr) end """ BinaryenSIMDShuffleGetMask(expr, mask) Gets the 128-bit mask of a SIMD shuffle expression. """ function BinaryenSIMDShuffleGetMask(expr, mask) ccall((:BinaryenSIMDShuffleGetMask, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{UInt8}), expr, mask) end """ BinaryenSIMDShuffleSetMask(expr, mask) Sets the 128-bit mask of a SIMD shuffle expression. """ function BinaryenSIMDShuffleSetMask(expr, mask) ccall((:BinaryenSIMDShuffleSetMask, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{UInt8}), expr, mask) end """ BinaryenSIMDTernaryGetOp(expr) Gets the operation being performed by a SIMD ternary expression. """ function BinaryenSIMDTernaryGetOp(expr) ccall((:BinaryenSIMDTernaryGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDTernarySetOp(expr, op) Sets the operation being performed by a SIMD ternary expression. """ function BinaryenSIMDTernarySetOp(expr, op) ccall((:BinaryenSIMDTernarySetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenSIMDTernaryGetA(expr) Gets the first operand expression of a SIMD ternary expression. """ function BinaryenSIMDTernaryGetA(expr) ccall((:BinaryenSIMDTernaryGetA, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDTernarySetA(expr, aExpr) Sets the first operand expression of a SIMD ternary expression. """ function BinaryenSIMDTernarySetA(expr, aExpr) ccall((:BinaryenSIMDTernarySetA, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, aExpr) end """ BinaryenSIMDTernaryGetB(expr) Gets the second operand expression of a SIMD ternary expression. """ function BinaryenSIMDTernaryGetB(expr) ccall((:BinaryenSIMDTernaryGetB, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDTernarySetB(expr, bExpr) Sets the second operand expression of a SIMD ternary expression. """ function BinaryenSIMDTernarySetB(expr, bExpr) ccall((:BinaryenSIMDTernarySetB, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, bExpr) end """ BinaryenSIMDTernaryGetC(expr) Gets the third operand expression of a SIMD ternary expression. """ function BinaryenSIMDTernaryGetC(expr) ccall((:BinaryenSIMDTernaryGetC, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDTernarySetC(expr, cExpr) Sets the third operand expression of a SIMD ternary expression. """ function BinaryenSIMDTernarySetC(expr, cExpr) ccall((:BinaryenSIMDTernarySetC, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, cExpr) end """ BinaryenSIMDShiftGetOp(expr) Gets the operation being performed by a SIMD shift expression. """ function BinaryenSIMDShiftGetOp(expr) ccall((:BinaryenSIMDShiftGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDShiftSetOp(expr, op) Sets the operation being performed by a SIMD shift expression. """ function BinaryenSIMDShiftSetOp(expr, op) ccall((:BinaryenSIMDShiftSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenSIMDShiftGetVec(expr) Gets the expression being shifted by a SIMD shift expression. """ function BinaryenSIMDShiftGetVec(expr) ccall((:BinaryenSIMDShiftGetVec, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDShiftSetVec(expr, vecExpr) Sets the expression being shifted by a SIMD shift expression. """ function BinaryenSIMDShiftSetVec(expr, vecExpr) ccall((:BinaryenSIMDShiftSetVec, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, vecExpr) end """ BinaryenSIMDShiftGetShift(expr) Gets the expression representing the shift of a SIMD shift expression. """ function BinaryenSIMDShiftGetShift(expr) ccall((:BinaryenSIMDShiftGetShift, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDShiftSetShift(expr, shiftExpr) Sets the expression representing the shift of a SIMD shift expression. """ function BinaryenSIMDShiftSetShift(expr, shiftExpr) ccall((:BinaryenSIMDShiftSetShift, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, shiftExpr) end """ BinaryenSIMDLoadGetOp(expr) Gets the operation being performed by a SIMD load expression. """ function BinaryenSIMDLoadGetOp(expr) ccall((:BinaryenSIMDLoadGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadSetOp(expr, op) Sets the operation being performed by a SIMD load expression. """ function BinaryenSIMDLoadSetOp(expr, op) ccall((:BinaryenSIMDLoadSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenSIMDLoadGetOffset(expr) Gets the constant offset of a SIMD load expression. """ function BinaryenSIMDLoadGetOffset(expr) ccall((:BinaryenSIMDLoadGetOffset, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadSetOffset(expr, offset) Sets the constant offset of a SIMD load expression. """ function BinaryenSIMDLoadSetOffset(expr, offset) ccall((:BinaryenSIMDLoadSetOffset, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, offset) end """ BinaryenSIMDLoadGetAlign(expr) Gets the byte alignment of a SIMD load expression. """ function BinaryenSIMDLoadGetAlign(expr) ccall((:BinaryenSIMDLoadGetAlign, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadSetAlign(expr, align) Sets the byte alignment of a SIMD load expression. """ function BinaryenSIMDLoadSetAlign(expr, align) ccall((:BinaryenSIMDLoadSetAlign, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, align) end """ BinaryenSIMDLoadGetPtr(expr) Gets the pointer expression of a SIMD load expression. """ function BinaryenSIMDLoadGetPtr(expr) ccall((:BinaryenSIMDLoadGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadSetPtr(expr, ptrExpr) Sets the pointer expression of a SIMD load expression. """ function BinaryenSIMDLoadSetPtr(expr, ptrExpr) ccall((:BinaryenSIMDLoadSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenSIMDLoadStoreLaneGetOp(expr) Gets the operation being performed by a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneGetOp(expr) ccall((:BinaryenSIMDLoadStoreLaneGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadStoreLaneSetOp(expr, op) Sets the operation being performed by a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneSetOp(expr, op) ccall((:BinaryenSIMDLoadStoreLaneSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenSIMDLoadStoreLaneGetOffset(expr) Gets the constant offset of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneGetOffset(expr) ccall((:BinaryenSIMDLoadStoreLaneGetOffset, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadStoreLaneSetOffset(expr, offset) Sets the constant offset of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneSetOffset(expr, offset) ccall((:BinaryenSIMDLoadStoreLaneSetOffset, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, offset) end """ BinaryenSIMDLoadStoreLaneGetAlign(expr) Gets the byte alignment of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneGetAlign(expr) ccall((:BinaryenSIMDLoadStoreLaneGetAlign, libbinaryen), UInt32, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadStoreLaneSetAlign(expr, align) Sets the byte alignment of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneSetAlign(expr, align) ccall((:BinaryenSIMDLoadStoreLaneSetAlign, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt32), expr, align) end """ BinaryenSIMDLoadStoreLaneGetIndex(expr) Gets the lane index of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneGetIndex(expr) ccall((:BinaryenSIMDLoadStoreLaneGetIndex, libbinaryen), UInt8, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadStoreLaneSetIndex(expr, index) Sets the lane index of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneSetIndex(expr, index) ccall((:BinaryenSIMDLoadStoreLaneSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, UInt8), expr, index) end """ BinaryenSIMDLoadStoreLaneGetPtr(expr) Gets the pointer expression of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneGetPtr(expr) ccall((:BinaryenSIMDLoadStoreLaneGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadStoreLaneSetPtr(expr, ptrExpr) Sets the pointer expression of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneSetPtr(expr, ptrExpr) ccall((:BinaryenSIMDLoadStoreLaneSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end """ BinaryenSIMDLoadStoreLaneGetVec(expr) Gets the vector expression of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneGetVec(expr) ccall((:BinaryenSIMDLoadStoreLaneGetVec, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenSIMDLoadStoreLaneSetVec(expr, vecExpr) Sets the vector expression of a SIMD load/store lane expression. """ function BinaryenSIMDLoadStoreLaneSetVec(expr, vecExpr) ccall((:BinaryenSIMDLoadStoreLaneSetVec, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, vecExpr) end """ BinaryenSIMDLoadStoreLaneIsStore(expr) Gets whether a SIMD load/store lane expression performs a store. Otherwise it performs a load. """ function BinaryenSIMDLoadStoreLaneIsStore(expr) ccall((:BinaryenSIMDLoadStoreLaneIsStore, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryInitGetSegment(expr) Gets the index of the segment being initialized by a `memory.init` expression. """ function BinaryenMemoryInitGetSegment(expr) ccall((:BinaryenMemoryInitGetSegment, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryInitSetSegment(expr, segment) Sets the index of the segment being initialized by a `memory.init` expression. """ function BinaryenMemoryInitSetSegment(expr, segment) ccall((:BinaryenMemoryInitSetSegment, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, segment) end """ BinaryenMemoryInitGetDest(expr) Gets the destination expression of a `memory.init` expression. """ function BinaryenMemoryInitGetDest(expr) ccall((:BinaryenMemoryInitGetDest, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryInitSetDest(expr, destExpr) Sets the destination expression of a `memory.init` expression. """ function BinaryenMemoryInitSetDest(expr, destExpr) ccall((:BinaryenMemoryInitSetDest, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, destExpr) end """ BinaryenMemoryInitGetOffset(expr) Gets the offset expression of a `memory.init` expression. """ function BinaryenMemoryInitGetOffset(expr) ccall((:BinaryenMemoryInitGetOffset, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryInitSetOffset(expr, offsetExpr) Sets the offset expression of a `memory.init` expression. """ function BinaryenMemoryInitSetOffset(expr, offsetExpr) ccall((:BinaryenMemoryInitSetOffset, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, offsetExpr) end """ BinaryenMemoryInitGetSize(expr) Gets the size expression of a `memory.init` expression. """ function BinaryenMemoryInitGetSize(expr) ccall((:BinaryenMemoryInitGetSize, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryInitSetSize(expr, sizeExpr) Sets the size expression of a `memory.init` expression. """ function BinaryenMemoryInitSetSize(expr, sizeExpr) ccall((:BinaryenMemoryInitSetSize, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, sizeExpr) end """ BinaryenDataDropGetSegment(expr) Gets the index of the segment being dropped by a `data.drop` expression. """ function BinaryenDataDropGetSegment(expr) ccall((:BinaryenDataDropGetSegment, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenDataDropSetSegment(expr, segment) Sets the index of the segment being dropped by a `data.drop` expression. """ function BinaryenDataDropSetSegment(expr, segment) ccall((:BinaryenDataDropSetSegment, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, segment) end """ BinaryenMemoryCopyGetDest(expr) Gets the destination expression of a `memory.copy` expression. """ function BinaryenMemoryCopyGetDest(expr) ccall((:BinaryenMemoryCopyGetDest, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryCopySetDest(expr, destExpr) Sets the destination expression of a `memory.copy` expression. """ function BinaryenMemoryCopySetDest(expr, destExpr) ccall((:BinaryenMemoryCopySetDest, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, destExpr) end """ BinaryenMemoryCopyGetSource(expr) Gets the source expression of a `memory.copy` expression. """ function BinaryenMemoryCopyGetSource(expr) ccall((:BinaryenMemoryCopyGetSource, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryCopySetSource(expr, sourceExpr) Sets the source expression of a `memory.copy` expression. """ function BinaryenMemoryCopySetSource(expr, sourceExpr) ccall((:BinaryenMemoryCopySetSource, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, sourceExpr) end """ BinaryenMemoryCopyGetSize(expr) Gets the size expression (number of bytes copied) of a `memory.copy` expression. """ function BinaryenMemoryCopyGetSize(expr) ccall((:BinaryenMemoryCopyGetSize, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryCopySetSize(expr, sizeExpr) Sets the size expression (number of bytes copied) of a `memory.copy` expression. """ function BinaryenMemoryCopySetSize(expr, sizeExpr) ccall((:BinaryenMemoryCopySetSize, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, sizeExpr) end """ BinaryenMemoryFillGetDest(expr) Gets the destination expression of a `memory.fill` expression. """ function BinaryenMemoryFillGetDest(expr) ccall((:BinaryenMemoryFillGetDest, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryFillSetDest(expr, destExpr) Sets the destination expression of a `memory.fill` expression. """ function BinaryenMemoryFillSetDest(expr, destExpr) ccall((:BinaryenMemoryFillSetDest, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, destExpr) end """ BinaryenMemoryFillGetValue(expr) Gets the value expression of a `memory.fill` expression. """ function BinaryenMemoryFillGetValue(expr) ccall((:BinaryenMemoryFillGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryFillSetValue(expr, valueExpr) Sets the value expression of a `memory.fill` expression. """ function BinaryenMemoryFillSetValue(expr, valueExpr) ccall((:BinaryenMemoryFillSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenMemoryFillGetSize(expr) Gets the size expression (number of bytes filled) of a `memory.fill` expression. """ function BinaryenMemoryFillGetSize(expr) ccall((:BinaryenMemoryFillGetSize, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenMemoryFillSetSize(expr, sizeExpr) Sets the size expression (number of bytes filled) of a `memory.fill` expression. """ function BinaryenMemoryFillSetSize(expr, sizeExpr) ccall((:BinaryenMemoryFillSetSize, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, sizeExpr) end """ BinaryenRefIsNullGetValue(expr) RefIsNull """ function BinaryenRefIsNullGetValue(expr) ccall((:BinaryenRefIsNullGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenRefIsNullSetValue(expr, valueExpr) Sets the value expression tested by a `ref.is_null` expression. """ function BinaryenRefIsNullSetValue(expr, valueExpr) ccall((:BinaryenRefIsNullSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenRefAsGetOp(expr) Gets the operation performed by a `ref.as_*` expression. """ function BinaryenRefAsGetOp(expr) ccall((:BinaryenRefAsGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end """ BinaryenRefAsSetOp(expr, op) Sets the operation performed by a `ref.as_*` expression. """ function BinaryenRefAsSetOp(expr, op) ccall((:BinaryenRefAsSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end """ BinaryenRefAsGetValue(expr) Gets the value expression tested by a `ref.as_*` expression. """ function BinaryenRefAsGetValue(expr) ccall((:BinaryenRefAsGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenRefAsSetValue(expr, valueExpr) Sets the value expression tested by a `ref.as_*` expression. """ function BinaryenRefAsSetValue(expr, valueExpr) ccall((:BinaryenRefAsSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenRefFuncGetFunc(expr) Gets the name of the function being wrapped by a `ref.func` expression. """ function BinaryenRefFuncGetFunc(expr) ccall((:BinaryenRefFuncGetFunc, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenRefFuncSetFunc(expr, funcName) Sets the name of the function being wrapped by a `ref.func` expression. """ function BinaryenRefFuncSetFunc(expr, funcName) ccall((:BinaryenRefFuncSetFunc, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, funcName) end """ BinaryenRefEqGetLeft(expr) Gets the left expression of a `ref.eq` expression. """ function BinaryenRefEqGetLeft(expr) ccall((:BinaryenRefEqGetLeft, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenRefEqSetLeft(expr, left) Sets the left expression of a `ref.eq` expression. """ function BinaryenRefEqSetLeft(expr, left) ccall((:BinaryenRefEqSetLeft, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, left) end """ BinaryenRefEqGetRight(expr) Gets the right expression of a `ref.eq` expression. """ function BinaryenRefEqGetRight(expr) ccall((:BinaryenRefEqGetRight, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenRefEqSetRight(expr, right) Sets the right expression of a `ref.eq` expression. """ function BinaryenRefEqSetRight(expr, right) ccall((:BinaryenRefEqSetRight, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, right) end """ BinaryenTryGetName(expr) Gets the name (label) of a `try` expression. """ function BinaryenTryGetName(expr) ccall((:BinaryenTryGetName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenTrySetName(expr, name) Sets the name (label) of a `try` expression. """ function BinaryenTrySetName(expr, name) ccall((:BinaryenTrySetName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, name) end """ BinaryenTryGetBody(expr) Gets the body expression of a `try` expression. """ function BinaryenTryGetBody(expr) ccall((:BinaryenTryGetBody, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenTrySetBody(expr, bodyExpr) Sets the body expression of a `try` expression. """ function BinaryenTrySetBody(expr, bodyExpr) ccall((:BinaryenTrySetBody, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, bodyExpr) end """ BinaryenTryGetNumCatchTags(expr) Gets the number of catch blocks (= the number of catch tags) of a `try` expression. """ function BinaryenTryGetNumCatchTags(expr) ccall((:BinaryenTryGetNumCatchTags, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenTryGetNumCatchBodies(expr) Gets the number of catch/catch_all blocks of a `try` expression. """ function BinaryenTryGetNumCatchBodies(expr) ccall((:BinaryenTryGetNumCatchBodies, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenTryGetCatchTagAt(expr, index) Gets the catch tag at the specified index of a `try` expression. """ function BinaryenTryGetCatchTagAt(expr, index) ccall((:BinaryenTryGetCatchTagAt, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenTrySetCatchTagAt(expr, index, catchTag) Sets the catch tag at the specified index of a `try` expression. """ function BinaryenTrySetCatchTagAt(expr, index, catchTag) ccall((:BinaryenTrySetCatchTagAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, Ptr{Cchar}), expr, index, catchTag) end """ BinaryenTryAppendCatchTag(expr, catchTag) Appends a catch tag to a `try` expression, returning its insertion index. """ function BinaryenTryAppendCatchTag(expr, catchTag) ccall((:BinaryenTryAppendCatchTag, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, Ptr{Cchar}), expr, catchTag) end """ BinaryenTryInsertCatchTagAt(expr, index, catchTag) Inserts a catch tag at the specified index of a `try` expression, moving existing catch tags including the one previously at that index one index up. """ function BinaryenTryInsertCatchTagAt(expr, index, catchTag) ccall((:BinaryenTryInsertCatchTagAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, Ptr{Cchar}), expr, index, catchTag) end """ BinaryenTryRemoveCatchTagAt(expr, index) Removes the catch tag at the specified index of a `try` expression, moving all subsequent catch tags one index down. Returns the tag. """ function BinaryenTryRemoveCatchTagAt(expr, index) ccall((:BinaryenTryRemoveCatchTagAt, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenTryGetCatchBodyAt(expr, index) Gets the catch body expression at the specified index of a `try` expression. """ function BinaryenTryGetCatchBodyAt(expr, index) ccall((:BinaryenTryGetCatchBodyAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenTrySetCatchBodyAt(expr, index, catchExpr) Sets the catch body expression at the specified index of a `try` expression. """ function BinaryenTrySetCatchBodyAt(expr, index, catchExpr) ccall((:BinaryenTrySetCatchBodyAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, catchExpr) end """ BinaryenTryAppendCatchBody(expr, catchExpr) Appends a catch expression to a `try` expression, returning its insertion index. """ function BinaryenTryAppendCatchBody(expr, catchExpr) ccall((:BinaryenTryAppendCatchBody, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, catchExpr) end """ BinaryenTryInsertCatchBodyAt(expr, index, catchExpr) Inserts a catch expression at the specified index of a `try` expression, moving existing catch bodies including the one previously at that index one index up. """ function BinaryenTryInsertCatchBodyAt(expr, index, catchExpr) ccall((:BinaryenTryInsertCatchBodyAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, catchExpr) end """ BinaryenTryRemoveCatchBodyAt(expr, index) Removes the catch expression at the specified index of a `try` expression, moving all subsequent catch bodies one index down. Returns the catch expression. """ function BinaryenTryRemoveCatchBodyAt(expr, index) ccall((:BinaryenTryRemoveCatchBodyAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenTryHasCatchAll(expr) Gets whether a `try` expression has a catch_all clause. """ function BinaryenTryHasCatchAll(expr) ccall((:BinaryenTryHasCatchAll, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenTryGetDelegateTarget(expr) Gets the target label of a `delegate`. """ function BinaryenTryGetDelegateTarget(expr) ccall((:BinaryenTryGetDelegateTarget, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenTrySetDelegateTarget(expr, delegateTarget) Sets the target label of a `delegate`. """ function BinaryenTrySetDelegateTarget(expr, delegateTarget) ccall((:BinaryenTrySetDelegateTarget, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, delegateTarget) end """ BinaryenTryIsDelegate(expr) Gets whether a `try` expression is a try-delegate. """ function BinaryenTryIsDelegate(expr) ccall((:BinaryenTryIsDelegate, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenThrowGetTag(expr) Gets the name of the tag being thrown by a `throw` expression. """ function BinaryenThrowGetTag(expr) ccall((:BinaryenThrowGetTag, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenThrowSetTag(expr, tagName) Sets the name of the tag being thrown by a `throw` expression. """ function BinaryenThrowSetTag(expr, tagName) ccall((:BinaryenThrowSetTag, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, tagName) end """ BinaryenThrowGetNumOperands(expr) Gets the number of operands of a `throw` expression. """ function BinaryenThrowGetNumOperands(expr) ccall((:BinaryenThrowGetNumOperands, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenThrowGetOperandAt(expr, index) Gets the operand at the specified index of a `throw` expression. """ function BinaryenThrowGetOperandAt(expr, index) ccall((:BinaryenThrowGetOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenThrowSetOperandAt(expr, index, operandExpr) Sets the operand at the specified index of a `throw` expression. """ function BinaryenThrowSetOperandAt(expr, index, operandExpr) ccall((:BinaryenThrowSetOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenThrowAppendOperand(expr, operandExpr) Appends an operand expression to a `throw` expression, returning its insertion index. """ function BinaryenThrowAppendOperand(expr, operandExpr) ccall((:BinaryenThrowAppendOperand, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, operandExpr) end """ BinaryenThrowInsertOperandAt(expr, index, operandExpr) Inserts an operand expression at the specified index of a `throw` expression, moving existing operands including the one previously at that index one index up. """ function BinaryenThrowInsertOperandAt(expr, index, operandExpr) ccall((:BinaryenThrowInsertOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenThrowRemoveOperandAt(expr, index) Removes the operand expression at the specified index of a `throw` expression, moving all subsequent operands one index down. Returns the operand expression. """ function BinaryenThrowRemoveOperandAt(expr, index) ccall((:BinaryenThrowRemoveOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenRethrowGetTarget(expr) Gets the target catch's corresponding try label of a `rethrow` expression. """ function BinaryenRethrowGetTarget(expr) ccall((:BinaryenRethrowGetTarget, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end """ BinaryenRethrowSetTarget(expr, target) Sets the target catch's corresponding try label of a `rethrow` expression. """ function BinaryenRethrowSetTarget(expr, target) ccall((:BinaryenRethrowSetTarget, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, target) end """ BinaryenTupleMakeGetNumOperands(expr) Gets the number of operands of a `tuple.make` expression. """ function BinaryenTupleMakeGetNumOperands(expr) ccall((:BinaryenTupleMakeGetNumOperands, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenTupleMakeGetOperandAt(expr, index) Gets the operand at the specified index of a `tuple.make` expression. """ function BinaryenTupleMakeGetOperandAt(expr, index) ccall((:BinaryenTupleMakeGetOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenTupleMakeSetOperandAt(expr, index, operandExpr) Sets the operand at the specified index of a `tuple.make` expression. """ function BinaryenTupleMakeSetOperandAt(expr, index, operandExpr) ccall((:BinaryenTupleMakeSetOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenTupleMakeAppendOperand(expr, operandExpr) Appends an operand expression to a `tuple.make` expression, returning its insertion index. """ function BinaryenTupleMakeAppendOperand(expr, operandExpr) ccall((:BinaryenTupleMakeAppendOperand, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, operandExpr) end """ BinaryenTupleMakeInsertOperandAt(expr, index, operandExpr) Inserts an operand expression at the specified index of a `tuple.make` expression, moving existing operands including the one previously at that index one index up. """ function BinaryenTupleMakeInsertOperandAt(expr, index, operandExpr) ccall((:BinaryenTupleMakeInsertOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end """ BinaryenTupleMakeRemoveOperandAt(expr, index) Removes the operand expression at the specified index of a `tuple.make` expression, moving all subsequent operands one index down. Returns the operand expression. """ function BinaryenTupleMakeRemoveOperandAt(expr, index) ccall((:BinaryenTupleMakeRemoveOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenTupleExtractGetTuple(expr) Gets the tuple extracted from of a `tuple.extract` expression. """ function BinaryenTupleExtractGetTuple(expr) ccall((:BinaryenTupleExtractGetTuple, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenTupleExtractSetTuple(expr, tupleExpr) Sets the tuple extracted from of a `tuple.extract` expression. """ function BinaryenTupleExtractSetTuple(expr, tupleExpr) ccall((:BinaryenTupleExtractSetTuple, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, tupleExpr) end """ BinaryenTupleExtractGetIndex(expr) Gets the index extracted at of a `tuple.extract` expression. """ function BinaryenTupleExtractGetIndex(expr) ccall((:BinaryenTupleExtractGetIndex, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end """ BinaryenTupleExtractSetIndex(expr, index) Sets the index extracted at of a `tuple.extract` expression. """ function BinaryenTupleExtractSetIndex(expr, index) ccall((:BinaryenTupleExtractSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenI31NewGetValue(expr) Gets the value expression of an `i31.new` expression. """ function BinaryenI31NewGetValue(expr) ccall((:BinaryenI31NewGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenI31NewSetValue(expr, valueExpr) Sets the value expression of an `i31.new` expression. """ function BinaryenI31NewSetValue(expr, valueExpr) ccall((:BinaryenI31NewSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenI31GetGetI31(expr) Gets the i31 expression of an `i31.get` expression. """ function BinaryenI31GetGetI31(expr) ccall((:BinaryenI31GetGetI31, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end """ BinaryenI31GetSetI31(expr, i31Expr) Sets the i31 expression of an `i31.get` expression. """ function BinaryenI31GetSetI31(expr, i31Expr) ccall((:BinaryenI31GetSetI31, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, i31Expr) end """ BinaryenI31GetIsSigned(expr) Gets whether an `i31.get` expression returns a signed value (`_s`). """ function BinaryenI31GetIsSigned(expr) ccall((:BinaryenI31GetIsSigned, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenI31GetSetSigned(expr, signed_) Sets whether an `i31.get` expression returns a signed value (`_s`). """ function BinaryenI31GetSetSigned(expr, signed_) ccall((:BinaryenI31GetSetSigned, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, signed_) end """ BinaryenCallRefGetNumOperands(expr) CallRef """ function BinaryenCallRefGetNumOperands(expr) ccall((:BinaryenCallRefGetNumOperands, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end function BinaryenCallRefGetOperandAt(expr, index) ccall((:BinaryenCallRefGetOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end function BinaryenCallRefSetOperandAt(expr, index, operandExpr) ccall((:BinaryenCallRefSetOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end function BinaryenCallRefAppendOperand(expr, operandExpr) ccall((:BinaryenCallRefAppendOperand, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, operandExpr) end function BinaryenCallRefInsertOperandAt(expr, index, operandExpr) ccall((:BinaryenCallRefInsertOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end function BinaryenCallRefRemoveOperandAt(expr, index) ccall((:BinaryenCallRefRemoveOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end function BinaryenCallRefGetTarget(expr) ccall((:BinaryenCallRefGetTarget, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenCallRefSetTarget(expr, targetExpr) ccall((:BinaryenCallRefSetTarget, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, targetExpr) end function BinaryenCallRefIsReturn(expr) ccall((:BinaryenCallRefIsReturn, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end function BinaryenCallRefSetReturn(expr, isReturn) ccall((:BinaryenCallRefSetReturn, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, isReturn) end """ BinaryenRefTestGetRef(expr) RefTest """ function BinaryenRefTestGetRef(expr) ccall((:BinaryenRefTestGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenRefTestSetRef(expr, refExpr) ccall((:BinaryenRefTestSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenRefTestGetCastType(expr) ccall((:BinaryenRefTestGetCastType, libbinaryen), BinaryenType, (BinaryenExpressionRef,), expr) end function BinaryenRefTestSetCastType(expr, intendedType) ccall((:BinaryenRefTestSetCastType, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenType), expr, intendedType) end """ BinaryenRefCastGetRef(expr) RefCast """ function BinaryenRefCastGetRef(expr) ccall((:BinaryenRefCastGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenRefCastSetRef(expr, refExpr) ccall((:BinaryenRefCastSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end """ BinaryenBrOnGetOp(expr) BrOn """ function BinaryenBrOnGetOp(expr) ccall((:BinaryenBrOnGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenBrOnSetOp(expr, op) ccall((:BinaryenBrOnSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenBrOnGetName(expr) ccall((:BinaryenBrOnGetName, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end function BinaryenBrOnSetName(expr, nameStr) ccall((:BinaryenBrOnSetName, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, nameStr) end function BinaryenBrOnGetRef(expr) ccall((:BinaryenBrOnGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenBrOnSetRef(expr, refExpr) ccall((:BinaryenBrOnSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenBrOnGetCastType(expr) ccall((:BinaryenBrOnGetCastType, libbinaryen), BinaryenType, (BinaryenExpressionRef,), expr) end function BinaryenBrOnSetCastType(expr, castType) ccall((:BinaryenBrOnSetCastType, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenType), expr, castType) end """ BinaryenStructNewGetNumOperands(expr) StructNew """ function BinaryenStructNewGetNumOperands(expr) ccall((:BinaryenStructNewGetNumOperands, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end function BinaryenStructNewGetOperandAt(expr, index) ccall((:BinaryenStructNewGetOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end function BinaryenStructNewSetOperandAt(expr, index, operandExpr) ccall((:BinaryenStructNewSetOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end function BinaryenStructNewAppendOperand(expr, operandExpr) ccall((:BinaryenStructNewAppendOperand, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, operandExpr) end function BinaryenStructNewInsertOperandAt(expr, index, operandExpr) ccall((:BinaryenStructNewInsertOperandAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, operandExpr) end function BinaryenStructNewRemoveOperandAt(expr, index) ccall((:BinaryenStructNewRemoveOperandAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenStructGetGetIndex(expr) StructGet """ function BinaryenStructGetGetIndex(expr) ccall((:BinaryenStructGetGetIndex, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end function BinaryenStructGetSetIndex(expr, index) ccall((:BinaryenStructGetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex), expr, index) end function BinaryenStructGetGetRef(expr) ccall((:BinaryenStructGetGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStructGetSetRef(expr, refExpr) ccall((:BinaryenStructGetSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStructGetIsSigned(expr) ccall((:BinaryenStructGetIsSigned, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end function BinaryenStructGetSetSigned(expr, signed_) ccall((:BinaryenStructGetSetSigned, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, signed_) end """ BinaryenStructSetGetIndex(expr) StructSet """ function BinaryenStructSetGetIndex(expr) ccall((:BinaryenStructSetGetIndex, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end function BinaryenStructSetSetIndex(expr, index) ccall((:BinaryenStructSetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex), expr, index) end function BinaryenStructSetGetRef(expr) ccall((:BinaryenStructSetGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStructSetSetRef(expr, refExpr) ccall((:BinaryenStructSetSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStructSetGetValue(expr) ccall((:BinaryenStructSetGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStructSetSetValue(expr, valueExpr) ccall((:BinaryenStructSetSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenArrayNewGetInit(expr) ArrayNew """ function BinaryenArrayNewGetInit(expr) ccall((:BinaryenArrayNewGetInit, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayNewSetInit(expr, initExpr) ccall((:BinaryenArrayNewSetInit, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, initExpr) end function BinaryenArrayNewGetSize(expr) ccall((:BinaryenArrayNewGetSize, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayNewSetSize(expr, sizeExpr) ccall((:BinaryenArrayNewSetSize, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, sizeExpr) end """ BinaryenArrayNewFixedGetNumValues(expr) ArrayNewFixed """ function BinaryenArrayNewFixedGetNumValues(expr) ccall((:BinaryenArrayNewFixedGetNumValues, libbinaryen), BinaryenIndex, (BinaryenExpressionRef,), expr) end function BinaryenArrayNewFixedGetValueAt(expr, index) ccall((:BinaryenArrayNewFixedGetValueAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end function BinaryenArrayNewFixedSetValueAt(expr, index, valueExpr) ccall((:BinaryenArrayNewFixedSetValueAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, valueExpr) end function BinaryenArrayNewFixedAppendValue(expr, valueExpr) ccall((:BinaryenArrayNewFixedAppendValue, libbinaryen), BinaryenIndex, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end function BinaryenArrayNewFixedInsertValueAt(expr, index, valueExpr) ccall((:BinaryenArrayNewFixedInsertValueAt, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenIndex, BinaryenExpressionRef), expr, index, valueExpr) end function BinaryenArrayNewFixedRemoveValueAt(expr, index) ccall((:BinaryenArrayNewFixedRemoveValueAt, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef, BinaryenIndex), expr, index) end """ BinaryenArrayGetGetRef(expr) ArrayGet """ function BinaryenArrayGetGetRef(expr) ccall((:BinaryenArrayGetGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayGetSetRef(expr, refExpr) ccall((:BinaryenArrayGetSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenArrayGetGetIndex(expr) ccall((:BinaryenArrayGetGetIndex, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayGetSetIndex(expr, indexExpr) ccall((:BinaryenArrayGetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, indexExpr) end function BinaryenArrayGetIsSigned(expr) ccall((:BinaryenArrayGetIsSigned, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end function BinaryenArrayGetSetSigned(expr, signed_) ccall((:BinaryenArrayGetSetSigned, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, signed_) end """ BinaryenArraySetGetRef(expr) ArraySet """ function BinaryenArraySetGetRef(expr) ccall((:BinaryenArraySetGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArraySetSetRef(expr, refExpr) ccall((:BinaryenArraySetSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenArraySetGetIndex(expr) ccall((:BinaryenArraySetGetIndex, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArraySetSetIndex(expr, indexExpr) ccall((:BinaryenArraySetSetIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, indexExpr) end function BinaryenArraySetGetValue(expr) ccall((:BinaryenArraySetGetValue, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArraySetSetValue(expr, valueExpr) ccall((:BinaryenArraySetSetValue, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, valueExpr) end """ BinaryenArrayLenGetRef(expr) ArrayLen """ function BinaryenArrayLenGetRef(expr) ccall((:BinaryenArrayLenGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayLenSetRef(expr, refExpr) ccall((:BinaryenArrayLenSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end """ BinaryenArrayCopyGetDestRef(expr) ArrayCopy """ function BinaryenArrayCopyGetDestRef(expr) ccall((:BinaryenArrayCopyGetDestRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayCopySetDestRef(expr, destRefExpr) ccall((:BinaryenArrayCopySetDestRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, destRefExpr) end function BinaryenArrayCopyGetDestIndex(expr) ccall((:BinaryenArrayCopyGetDestIndex, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayCopySetDestIndex(expr, destIndexExpr) ccall((:BinaryenArrayCopySetDestIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, destIndexExpr) end function BinaryenArrayCopyGetSrcRef(expr) ccall((:BinaryenArrayCopyGetSrcRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayCopySetSrcRef(expr, srcRefExpr) ccall((:BinaryenArrayCopySetSrcRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, srcRefExpr) end function BinaryenArrayCopyGetSrcIndex(expr) ccall((:BinaryenArrayCopyGetSrcIndex, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayCopySetSrcIndex(expr, srcIndexExpr) ccall((:BinaryenArrayCopySetSrcIndex, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, srcIndexExpr) end function BinaryenArrayCopyGetLength(expr) ccall((:BinaryenArrayCopyGetLength, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenArrayCopySetLength(expr, lengthExpr) ccall((:BinaryenArrayCopySetLength, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, lengthExpr) end """ BinaryenStringNewGetOp(expr) StringNew """ function BinaryenStringNewGetOp(expr) ccall((:BinaryenStringNewGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenStringNewSetOp(expr, op) ccall((:BinaryenStringNewSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenStringNewGetPtr(expr) ccall((:BinaryenStringNewGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringNewSetPtr(expr, ptrExpr) ccall((:BinaryenStringNewSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end function BinaryenStringNewGetLength(expr) ccall((:BinaryenStringNewGetLength, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringNewSetLength(expr, lengthExpr) ccall((:BinaryenStringNewSetLength, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, lengthExpr) end function BinaryenStringNewGetStart(expr) ccall((:BinaryenStringNewGetStart, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringNewSetStart(expr, startExpr) ccall((:BinaryenStringNewSetStart, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, startExpr) end function BinaryenStringNewGetEnd(expr) ccall((:BinaryenStringNewGetEnd, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringNewSetEnd(expr, endExpr) ccall((:BinaryenStringNewSetEnd, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, endExpr) end function BinaryenStringNewSetTry(expr, try_) ccall((:BinaryenStringNewSetTry, libbinaryen), Cvoid, (BinaryenExpressionRef, Bool), expr, try_) end function BinaryenStringNewIsTry(expr) ccall((:BinaryenStringNewIsTry, libbinaryen), Bool, (BinaryenExpressionRef,), expr) end """ BinaryenStringConstGetString(expr) StringConst """ function BinaryenStringConstGetString(expr) ccall((:BinaryenStringConstGetString, libbinaryen), Ptr{Cchar}, (BinaryenExpressionRef,), expr) end function BinaryenStringConstSetString(expr, stringStr) ccall((:BinaryenStringConstSetString, libbinaryen), Cvoid, (BinaryenExpressionRef, Ptr{Cchar}), expr, stringStr) end """ BinaryenStringMeasureGetOp(expr) StringMeasure """ function BinaryenStringMeasureGetOp(expr) ccall((:BinaryenStringMeasureGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenStringMeasureSetOp(expr, op) ccall((:BinaryenStringMeasureSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenStringMeasureGetRef(expr) ccall((:BinaryenStringMeasureGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringMeasureSetRef(expr, refExpr) ccall((:BinaryenStringMeasureSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end """ BinaryenStringEncodeGetOp(expr) StringEncode """ function BinaryenStringEncodeGetOp(expr) ccall((:BinaryenStringEncodeGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenStringEncodeSetOp(expr, op) ccall((:BinaryenStringEncodeSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenStringEncodeGetRef(expr) ccall((:BinaryenStringEncodeGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringEncodeSetRef(expr, refExpr) ccall((:BinaryenStringEncodeSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStringEncodeGetPtr(expr) ccall((:BinaryenStringEncodeGetPtr, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringEncodeSetPtr(expr, ptrExpr) ccall((:BinaryenStringEncodeSetPtr, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, ptrExpr) end function BinaryenStringEncodeGetStart(expr) ccall((:BinaryenStringEncodeGetStart, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringEncodeSetStart(expr, startExpr) ccall((:BinaryenStringEncodeSetStart, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, startExpr) end """ BinaryenStringConcatGetLeft(expr) StringConcat """ function BinaryenStringConcatGetLeft(expr) ccall((:BinaryenStringConcatGetLeft, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringConcatSetLeft(expr, leftExpr) ccall((:BinaryenStringConcatSetLeft, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, leftExpr) end function BinaryenStringConcatGetRight(expr) ccall((:BinaryenStringConcatGetRight, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringConcatSetRight(expr, rightExpr) ccall((:BinaryenStringConcatSetRight, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, rightExpr) end """ BinaryenStringEqGetOp(expr) StringEq """ function BinaryenStringEqGetOp(expr) ccall((:BinaryenStringEqGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenStringEqSetOp(expr, op) ccall((:BinaryenStringEqSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenStringEqGetLeft(expr) ccall((:BinaryenStringEqGetLeft, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringEqSetLeft(expr, leftExpr) ccall((:BinaryenStringEqSetLeft, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, leftExpr) end function BinaryenStringEqGetRight(expr) ccall((:BinaryenStringEqGetRight, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringEqSetRight(expr, rightExpr) ccall((:BinaryenStringEqSetRight, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, rightExpr) end """ BinaryenStringAsGetOp(expr) StringAs """ function BinaryenStringAsGetOp(expr) ccall((:BinaryenStringAsGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenStringAsSetOp(expr, op) ccall((:BinaryenStringAsSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenStringAsGetRef(expr) ccall((:BinaryenStringAsGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringAsSetRef(expr, refExpr) ccall((:BinaryenStringAsSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end """ BinaryenStringWTF8AdvanceGetRef(expr) StringWTF8Advance """ function BinaryenStringWTF8AdvanceGetRef(expr) ccall((:BinaryenStringWTF8AdvanceGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringWTF8AdvanceSetRef(expr, refExpr) ccall((:BinaryenStringWTF8AdvanceSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStringWTF8AdvanceGetPos(expr) ccall((:BinaryenStringWTF8AdvanceGetPos, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringWTF8AdvanceSetPos(expr, posExpr) ccall((:BinaryenStringWTF8AdvanceSetPos, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, posExpr) end function BinaryenStringWTF8AdvanceGetBytes(expr) ccall((:BinaryenStringWTF8AdvanceGetBytes, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringWTF8AdvanceSetBytes(expr, bytesExpr) ccall((:BinaryenStringWTF8AdvanceSetBytes, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, bytesExpr) end """ BinaryenStringWTF16GetGetRef(expr) StringWTF16Get """ function BinaryenStringWTF16GetGetRef(expr) ccall((:BinaryenStringWTF16GetGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringWTF16GetSetRef(expr, refExpr) ccall((:BinaryenStringWTF16GetSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStringWTF16GetGetPos(expr) ccall((:BinaryenStringWTF16GetGetPos, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringWTF16GetSetPos(expr, posExpr) ccall((:BinaryenStringWTF16GetSetPos, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, posExpr) end """ BinaryenStringIterNextGetRef(expr) StringIterNext """ function BinaryenStringIterNextGetRef(expr) ccall((:BinaryenStringIterNextGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringIterNextSetRef(expr, refExpr) ccall((:BinaryenStringIterNextSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end """ BinaryenStringIterMoveGetOp(expr) StringIterMove """ function BinaryenStringIterMoveGetOp(expr) ccall((:BinaryenStringIterMoveGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenStringIterMoveSetOp(expr, op) ccall((:BinaryenStringIterMoveSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenStringIterMoveGetRef(expr) ccall((:BinaryenStringIterMoveGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringIterMoveSetRef(expr, refExpr) ccall((:BinaryenStringIterMoveSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStringIterMoveGetNum(expr) ccall((:BinaryenStringIterMoveGetNum, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringIterMoveSetNum(expr, numExpr) ccall((:BinaryenStringIterMoveSetNum, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, numExpr) end """ BinaryenStringSliceWTFGetOp(expr) StringSliceWTF """ function BinaryenStringSliceWTFGetOp(expr) ccall((:BinaryenStringSliceWTFGetOp, libbinaryen), BinaryenOp, (BinaryenExpressionRef,), expr) end function BinaryenStringSliceWTFSetOp(expr, op) ccall((:BinaryenStringSliceWTFSetOp, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenOp), expr, op) end function BinaryenStringSliceWTFGetRef(expr) ccall((:BinaryenStringSliceWTFGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringSliceWTFSetRef(expr, refExpr) ccall((:BinaryenStringSliceWTFSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStringSliceWTFGetStart(expr) ccall((:BinaryenStringSliceWTFGetStart, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringSliceWTFSetStart(expr, startExpr) ccall((:BinaryenStringSliceWTFSetStart, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, startExpr) end function BinaryenStringSliceWTFGetEnd(expr) ccall((:BinaryenStringSliceWTFGetEnd, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringSliceWTFSetEnd(expr, endExpr) ccall((:BinaryenStringSliceWTFSetEnd, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, endExpr) end """ BinaryenStringSliceIterGetRef(expr) StringSliceIter """ function BinaryenStringSliceIterGetRef(expr) ccall((:BinaryenStringSliceIterGetRef, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringSliceIterSetRef(expr, refExpr) ccall((:BinaryenStringSliceIterSetRef, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, refExpr) end function BinaryenStringSliceIterGetNum(expr) ccall((:BinaryenStringSliceIterGetNum, libbinaryen), BinaryenExpressionRef, (BinaryenExpressionRef,), expr) end function BinaryenStringSliceIterSetNum(expr, numExpr) ccall((:BinaryenStringSliceIterSetNum, libbinaryen), Cvoid, (BinaryenExpressionRef, BinaryenExpressionRef), expr, numExpr) end mutable struct BinaryenFunction end const BinaryenFunctionRef = Ptr{BinaryenFunction} """ BinaryenAddFunction(_module, name, params, results, varTypes, numVarTypes, body) Adds a function to the module. This is thread-safe. @varTypes: the types of variables. In WebAssembly, vars share an index space with params. In other words, params come from the function type, and vars are provided in this call, and together they are all the locals. The order is first params and then vars, so if you have one param it will be at index 0 (and written \$0), and if you also have 2 vars they will be at indexes 1 and 2, etc., that is, they share an index space. """ function BinaryenAddFunction(_module, name, params, results, varTypes, numVarTypes, body) ccall((:BinaryenAddFunction, libbinaryen), BinaryenFunctionRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenType, BinaryenType, Ptr{BinaryenType}, BinaryenIndex, BinaryenExpressionRef), _module, name, params, results, varTypes, numVarTypes, body) end """ BinaryenGetFunction(_module, name) Gets a function reference by name. Returns NULL if the function does not exist. """ function BinaryenGetFunction(_module, name) ccall((:BinaryenGetFunction, libbinaryen), BinaryenFunctionRef, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end """ BinaryenRemoveFunction(_module, name) Removes a function by name. """ function BinaryenRemoveFunction(_module, name) ccall((:BinaryenRemoveFunction, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end """ BinaryenGetNumFunctions(_module) Gets the number of functions in the module. """ function BinaryenGetNumFunctions(_module) ccall((:BinaryenGetNumFunctions, libbinaryen), BinaryenIndex, (BinaryenModuleRef,), _module) end """ BinaryenGetFunctionByIndex(_module, index) Gets the function at the specified index. """ function BinaryenGetFunctionByIndex(_module, index) ccall((:BinaryenGetFunctionByIndex, libbinaryen), BinaryenFunctionRef, (BinaryenModuleRef, BinaryenIndex), _module, index) end """ BinaryenAddFunctionImport(_module, internalName, externalModuleName, externalBaseName, params, results) These either create a new entity (function/table/memory/etc.) and mark it as an import, or, if an entity already exists with internalName then the existing entity is turned into an import. """ function BinaryenAddFunctionImport(_module, internalName, externalModuleName, externalBaseName, params, results) ccall((:BinaryenAddFunctionImport, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, BinaryenType, BinaryenType), _module, internalName, externalModuleName, externalBaseName, params, results) end function BinaryenAddTableImport(_module, internalName, externalModuleName, externalBaseName) ccall((:BinaryenAddTableImport, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}), _module, internalName, externalModuleName, externalBaseName) end function BinaryenAddMemoryImport(_module, internalName, externalModuleName, externalBaseName, shared) ccall((:BinaryenAddMemoryImport, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, UInt8), _module, internalName, externalModuleName, externalBaseName, shared) end function BinaryenAddGlobalImport(_module, internalName, externalModuleName, externalBaseName, globalType, mutable_) ccall((:BinaryenAddGlobalImport, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, BinaryenType, Bool), _module, internalName, externalModuleName, externalBaseName, globalType, mutable_) end function BinaryenAddTagImport(_module, internalName, externalModuleName, externalBaseName, params, results) ccall((:BinaryenAddTagImport, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, Ptr{Cchar}, BinaryenType, BinaryenType), _module, internalName, externalModuleName, externalBaseName, params, results) end mutable struct BinaryenMemory end const BinaryenMemoryRef = Ptr{BinaryenMemory} mutable struct BinaryenExport end const BinaryenExportRef = Ptr{BinaryenExport} function BinaryenAddExport(_module, internalName, externalName) ccall((:BinaryenAddExport, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}), _module, internalName, externalName) end """ BinaryenAddFunctionExport(_module, internalName, externalName) Adds a function export to the module. """ function BinaryenAddFunctionExport(_module, internalName, externalName) ccall((:BinaryenAddFunctionExport, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}), _module, internalName, externalName) end """ BinaryenAddTableExport(_module, internalName, externalName) Adds a table export to the module. """ function BinaryenAddTableExport(_module, internalName, externalName) ccall((:BinaryenAddTableExport, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}), _module, internalName, externalName) end """ BinaryenAddMemoryExport(_module, internalName, externalName) Adds a memory export to the module. """ function BinaryenAddMemoryExport(_module, internalName, externalName) ccall((:BinaryenAddMemoryExport, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}), _module, internalName, externalName) end """ BinaryenAddGlobalExport(_module, internalName, externalName) Adds a global export to the module. """ function BinaryenAddGlobalExport(_module, internalName, externalName) ccall((:BinaryenAddGlobalExport, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}), _module, internalName, externalName) end """ BinaryenAddTagExport(_module, internalName, externalName) Adds a tag export to the module. """ function BinaryenAddTagExport(_module, internalName, externalName) ccall((:BinaryenAddTagExport, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}), _module, internalName, externalName) end """ BinaryenGetExport(_module, externalName) Gets an export reference by external name. Returns NULL if the export does not exist. """ function BinaryenGetExport(_module, externalName) ccall((:BinaryenGetExport, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, Ptr{Cchar}), _module, externalName) end """ BinaryenRemoveExport(_module, externalName) Removes an export by external name. """ function BinaryenRemoveExport(_module, externalName) ccall((:BinaryenRemoveExport, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}), _module, externalName) end """ BinaryenGetNumExports(_module) Gets the number of exports in the module. """ function BinaryenGetNumExports(_module) ccall((:BinaryenGetNumExports, libbinaryen), BinaryenIndex, (BinaryenModuleRef,), _module) end """ BinaryenGetExportByIndex(_module, index) Gets the export at the specified index. """ function BinaryenGetExportByIndex(_module, index) ccall((:BinaryenGetExportByIndex, libbinaryen), BinaryenExportRef, (BinaryenModuleRef, BinaryenIndex), _module, index) end mutable struct BinaryenGlobal end const BinaryenGlobalRef = Ptr{BinaryenGlobal} """ BinaryenAddGlobal(_module, name, type, mutable_, init) Adds a global to the module. """ function BinaryenAddGlobal(_module, name, type, mutable_, init) ccall((:BinaryenAddGlobal, libbinaryen), BinaryenGlobalRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenType, Bool, BinaryenExpressionRef), _module, name, type, mutable_, init) end """ BinaryenGetGlobal(_module, name) Gets a global reference by name. Returns NULL if the global does not exist. """ function BinaryenGetGlobal(_module, name) ccall((:BinaryenGetGlobal, libbinaryen), BinaryenGlobalRef, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end """ BinaryenRemoveGlobal(_module, name) Removes a global by name. """ function BinaryenRemoveGlobal(_module, name) ccall((:BinaryenRemoveGlobal, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end """ BinaryenGetNumGlobals(_module) Gets the number of globals in the module. """ function BinaryenGetNumGlobals(_module) ccall((:BinaryenGetNumGlobals, libbinaryen), BinaryenIndex, (BinaryenModuleRef,), _module) end """ BinaryenGetGlobalByIndex(_module, index) Gets the global at the specified index. """ function BinaryenGetGlobalByIndex(_module, index) ccall((:BinaryenGetGlobalByIndex, libbinaryen), BinaryenGlobalRef, (BinaryenModuleRef, BinaryenIndex), _module, index) end mutable struct BinaryenTag end const BinaryenTagRef = Ptr{BinaryenTag} """ BinaryenAddTag(_module, name, params, results) Adds a tag to the module. """ function BinaryenAddTag(_module, name, params, results) ccall((:BinaryenAddTag, libbinaryen), BinaryenTagRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenType, BinaryenType), _module, name, params, results) end """ BinaryenGetTag(_module, name) Gets a tag reference by name. Returns NULL if the tag does not exist. """ function BinaryenGetTag(_module, name) ccall((:BinaryenGetTag, libbinaryen), BinaryenTagRef, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end """ BinaryenRemoveTag(_module, name) Removes a tag by name. """ function BinaryenRemoveTag(_module, name) ccall((:BinaryenRemoveTag, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end mutable struct BinaryenTable end const BinaryenTableRef = Ptr{BinaryenTable} function BinaryenAddTable(_module, table, initial, maximum, tableType) ccall((:BinaryenAddTable, libbinaryen), BinaryenTableRef, (BinaryenModuleRef, Ptr{Cchar}, BinaryenIndex, BinaryenIndex, BinaryenType), _module, table, initial, maximum, tableType) end function BinaryenRemoveTable(_module, table) ccall((:BinaryenRemoveTable, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}), _module, table) end function BinaryenGetNumTables(_module) ccall((:BinaryenGetNumTables, libbinaryen), BinaryenIndex, (BinaryenModuleRef,), _module) end function BinaryenGetTable(_module, name) ccall((:BinaryenGetTable, libbinaryen), BinaryenTableRef, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenGetTableByIndex(_module, index) ccall((:BinaryenGetTableByIndex, libbinaryen), BinaryenTableRef, (BinaryenModuleRef, BinaryenIndex), _module, index) end mutable struct BinaryenElementSegment end const BinaryenElementSegmentRef = Ptr{BinaryenElementSegment} function BinaryenAddActiveElementSegment(_module, table, name, funcNames, numFuncNames, offset) ccall((:BinaryenAddActiveElementSegment, libbinaryen), BinaryenElementSegmentRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, Ptr{Ptr{Cchar}}, BinaryenIndex, BinaryenExpressionRef), _module, table, name, funcNames, numFuncNames, offset) end function BinaryenAddPassiveElementSegment(_module, name, funcNames, numFuncNames) ccall((:BinaryenAddPassiveElementSegment, libbinaryen), BinaryenElementSegmentRef, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Ptr{Cchar}}, BinaryenIndex), _module, name, funcNames, numFuncNames) end function BinaryenRemoveElementSegment(_module, name) ccall((:BinaryenRemoveElementSegment, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenGetNumElementSegments(_module) ccall((:BinaryenGetNumElementSegments, libbinaryen), BinaryenIndex, (BinaryenModuleRef,), _module) end function BinaryenGetElementSegment(_module, name) ccall((:BinaryenGetElementSegment, libbinaryen), BinaryenElementSegmentRef, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenGetElementSegmentByIndex(_module, index) ccall((:BinaryenGetElementSegmentByIndex, libbinaryen), BinaryenElementSegmentRef, (BinaryenModuleRef, BinaryenIndex), _module, index) end """ BinaryenSetMemory(_module, initial, maximum, exportName, segments, segmentPassive, segmentOffsets, segmentSizes, numSegments, shared, memory64, name) This will create a memory, overwriting any existing memory Each memory has data in segments, a start offset in segmentOffsets, and a size in segmentSizes. exportName can be NULL """ function BinaryenSetMemory(_module, initial, maximum, exportName, segments, segmentPassive, segmentOffsets, segmentSizes, numSegments, shared, memory64, name) ccall((:BinaryenSetMemory, libbinaryen), Cvoid, (BinaryenModuleRef, BinaryenIndex, BinaryenIndex, Ptr{Cchar}, Ptr{Ptr{Cchar}}, Ptr{Bool}, Ptr{BinaryenExpressionRef}, Ptr{BinaryenIndex}, BinaryenIndex, Bool, Bool, Ptr{Cchar}), _module, initial, maximum, exportName, segments, segmentPassive, segmentOffsets, segmentSizes, numSegments, shared, memory64, name) end function BinaryenHasMemory(_module) ccall((:BinaryenHasMemory, libbinaryen), Bool, (BinaryenModuleRef,), _module) end function BinaryenMemoryGetInitial(_module, name) ccall((:BinaryenMemoryGetInitial, libbinaryen), BinaryenIndex, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenMemoryHasMax(_module, name) ccall((:BinaryenMemoryHasMax, libbinaryen), Bool, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenMemoryGetMax(_module, name) ccall((:BinaryenMemoryGetMax, libbinaryen), BinaryenIndex, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenMemoryImportGetModule(_module, name) ccall((:BinaryenMemoryImportGetModule, libbinaryen), Ptr{Cchar}, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenMemoryImportGetBase(_module, name) ccall((:BinaryenMemoryImportGetBase, libbinaryen), Ptr{Cchar}, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenMemoryIsShared(_module, name) ccall((:BinaryenMemoryIsShared, libbinaryen), Bool, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end function BinaryenMemoryIs64(_module, name) ccall((:BinaryenMemoryIs64, libbinaryen), Bool, (BinaryenModuleRef, Ptr{Cchar}), _module, name) end """ BinaryenGetNumMemorySegments(_module) Memory segments. Query utilities. """ function BinaryenGetNumMemorySegments(_module) ccall((:BinaryenGetNumMemorySegments, libbinaryen), UInt32, (BinaryenModuleRef,), _module) end function BinaryenGetMemorySegmentByteOffset(_module, id) ccall((:BinaryenGetMemorySegmentByteOffset, libbinaryen), UInt32, (BinaryenModuleRef, BinaryenIndex), _module, id) end function BinaryenGetMemorySegmentByteLength(_module, id) ccall((:BinaryenGetMemorySegmentByteLength, libbinaryen), Csize_t, (BinaryenModuleRef, BinaryenIndex), _module, id) end function BinaryenGetMemorySegmentPassive(_module, id) ccall((:BinaryenGetMemorySegmentPassive, libbinaryen), Bool, (BinaryenModuleRef, BinaryenIndex), _module, id) end function BinaryenCopyMemorySegmentData(_module, id, buffer) ccall((:BinaryenCopyMemorySegmentData, libbinaryen), Cvoid, (BinaryenModuleRef, BinaryenIndex, Ptr{Cchar}), _module, id, buffer) end """ BinaryenSetStart(_module, start) Start function. One per module """ function BinaryenSetStart(_module, start) ccall((:BinaryenSetStart, libbinaryen), Cvoid, (BinaryenModuleRef, BinaryenFunctionRef), _module, start) end """ BinaryenModuleGetFeatures(_module) These control what features are allowed when validation and in passes. """ function BinaryenModuleGetFeatures(_module) ccall((:BinaryenModuleGetFeatures, libbinaryen), BinaryenFeatures, (BinaryenModuleRef,), _module) end function BinaryenModuleSetFeatures(_module, features) ccall((:BinaryenModuleSetFeatures, libbinaryen), Cvoid, (BinaryenModuleRef, BinaryenFeatures), _module, features) end """ BinaryenModuleParse(text) Parse a module in s-expression text format """ function BinaryenModuleParse(text) ccall((:BinaryenModuleParse, libbinaryen), BinaryenModuleRef, (Ptr{Cchar},), text) end """ BinaryenModulePrint(_module) Print a module to stdout in s-expression text format. Useful for debugging. """ function BinaryenModulePrint(_module) ccall((:BinaryenModulePrint, libbinaryen), Cvoid, (BinaryenModuleRef,), _module) end """ BinaryenModulePrintStackIR(_module, optimize) Print a module to stdout in stack IR text format. Useful for debugging. """ function BinaryenModulePrintStackIR(_module, optimize) ccall((:BinaryenModulePrintStackIR, libbinaryen), Cvoid, (BinaryenModuleRef, Bool), _module, optimize) end """ BinaryenModulePrintAsmjs(_module) Print a module to stdout in asm.js syntax. """ function BinaryenModulePrintAsmjs(_module) ccall((:BinaryenModulePrintAsmjs, libbinaryen), Cvoid, (BinaryenModuleRef,), _module) end """ BinaryenModuleValidate(_module) Validate a module, showing errors on problems. @return 0 if an error occurred, 1 if validated succesfully """ function BinaryenModuleValidate(_module) ccall((:BinaryenModuleValidate, libbinaryen), Bool, (BinaryenModuleRef,), _module) end """ BinaryenModuleOptimize(_module) Runs the standard optimization passes on the module. Uses the currently set global optimize and shrink level. """ function BinaryenModuleOptimize(_module) ccall((:BinaryenModuleOptimize, libbinaryen), Cvoid, (BinaryenModuleRef,), _module) end """ BinaryenModuleUpdateMaps(_module) Updates the internal name mapping logic in a module. This must be called after renaming module elements. """ function BinaryenModuleUpdateMaps(_module) ccall((:BinaryenModuleUpdateMaps, libbinaryen), Cvoid, (BinaryenModuleRef,), _module) end """ BinaryenGetOptimizeLevel() Gets the currently set optimize level. Applies to all modules, globally. 0, 1, 2 correspond to -O0, -O1, -O2 (default), etc. """ function BinaryenGetOptimizeLevel() ccall((:BinaryenGetOptimizeLevel, libbinaryen), Cint, ()) end """ BinaryenSetOptimizeLevel(level) Sets the optimization level to use. Applies to all modules, globally. 0, 1, 2 correspond to -O0, -O1, -O2 (default), etc. """ function BinaryenSetOptimizeLevel(level) ccall((:BinaryenSetOptimizeLevel, libbinaryen), Cvoid, (Cint,), level) end """ BinaryenGetShrinkLevel() Gets the currently set shrink level. Applies to all modules, globally. 0, 1, 2 correspond to -O0, -Os (default), -Oz. """ function BinaryenGetShrinkLevel() ccall((:BinaryenGetShrinkLevel, libbinaryen), Cint, ()) end """ BinaryenSetShrinkLevel(level) Sets the shrink level to use. Applies to all modules, globally. 0, 1, 2 correspond to -O0, -Os (default), -Oz. """ function BinaryenSetShrinkLevel(level) ccall((:BinaryenSetShrinkLevel, libbinaryen), Cvoid, (Cint,), level) end """ BinaryenGetDebugInfo() Gets whether generating debug information is currently enabled or not. Applies to all modules, globally. """ function BinaryenGetDebugInfo() ccall((:BinaryenGetDebugInfo, libbinaryen), Bool, ()) end """ BinaryenSetDebugInfo(on) Enables or disables debug information in emitted binaries. Applies to all modules, globally. """ function BinaryenSetDebugInfo(on) ccall((:BinaryenSetDebugInfo, libbinaryen), Cvoid, (Bool,), on) end """ BinaryenGetLowMemoryUnused() Gets whether the low 1K of memory can be considered unused when optimizing. Applies to all modules, globally. """ function BinaryenGetLowMemoryUnused() ccall((:BinaryenGetLowMemoryUnused, libbinaryen), Bool, ()) end """ BinaryenSetLowMemoryUnused(on) Enables or disables whether the low 1K of memory can be considered unused when optimizing. Applies to all modules, globally. """ function BinaryenSetLowMemoryUnused(on) ccall((:BinaryenSetLowMemoryUnused, libbinaryen), Cvoid, (Bool,), on) end """ BinaryenGetZeroFilledMemory() Gets whether to assume that an imported memory is zero-initialized. """ function BinaryenGetZeroFilledMemory() ccall((:BinaryenGetZeroFilledMemory, libbinaryen), Bool, ()) end """ BinaryenSetZeroFilledMemory(on) Enables or disables whether to assume that an imported memory is zero-initialized. """ function BinaryenSetZeroFilledMemory(on) ccall((:BinaryenSetZeroFilledMemory, libbinaryen), Cvoid, (Bool,), on) end """ BinaryenGetFastMath() Gets whether fast math optimizations are enabled, ignoring for example corner cases of floating-point math like NaN changes. Applies to all modules, globally. """ function BinaryenGetFastMath() ccall((:BinaryenGetFastMath, libbinaryen), Bool, ()) end """ BinaryenSetFastMath(value) Enables or disables fast math optimizations, ignoring for example corner cases of floating-point math like NaN changes. Applies to all modules, globally. """ function BinaryenSetFastMath(value) ccall((:BinaryenSetFastMath, libbinaryen), Cvoid, (Bool,), value) end """ BinaryenGetPassArgument(name) Gets the value of the specified arbitrary pass argument. Applies to all modules, globally. """ function BinaryenGetPassArgument(name) ccall((:BinaryenGetPassArgument, libbinaryen), Ptr{Cchar}, (Ptr{Cchar},), name) end """ BinaryenSetPassArgument(name, value) Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is NULL. Applies to all modules, globally. """ function BinaryenSetPassArgument(name, value) ccall((:BinaryenSetPassArgument, libbinaryen), Cvoid, (Ptr{Cchar}, Ptr{Cchar}), name, value) end # no prototype is found for this function at binaryen-c.h:3039:19, please use with caution """ BinaryenClearPassArguments() Clears all arbitrary pass arguments. Applies to all modules, globally. """ function BinaryenClearPassArguments() ccall((:BinaryenClearPassArguments, libbinaryen), Cvoid, ()) end """ BinaryenGetAlwaysInlineMaxSize() Gets the function size at which we always inline. Applies to all modules, globally. """ function BinaryenGetAlwaysInlineMaxSize() ccall((:BinaryenGetAlwaysInlineMaxSize, libbinaryen), BinaryenIndex, ()) end """ BinaryenSetAlwaysInlineMaxSize(size) Sets the function size at which we always inline. Applies to all modules, globally. """ function BinaryenSetAlwaysInlineMaxSize(size) ccall((:BinaryenSetAlwaysInlineMaxSize, libbinaryen), Cvoid, (BinaryenIndex,), size) end """ BinaryenGetFlexibleInlineMaxSize() Gets the function size which we inline when functions are lightweight. Applies to all modules, globally. """ function BinaryenGetFlexibleInlineMaxSize() ccall((:BinaryenGetFlexibleInlineMaxSize, libbinaryen), BinaryenIndex, ()) end """ BinaryenSetFlexibleInlineMaxSize(size) Sets the function size which we inline when functions are lightweight. Applies to all modules, globally. """ function BinaryenSetFlexibleInlineMaxSize(size) ccall((:BinaryenSetFlexibleInlineMaxSize, libbinaryen), Cvoid, (BinaryenIndex,), size) end """ BinaryenGetOneCallerInlineMaxSize() Gets the function size which we inline when there is only one caller. Applies to all modules, globally. """ function BinaryenGetOneCallerInlineMaxSize() ccall((:BinaryenGetOneCallerInlineMaxSize, libbinaryen), BinaryenIndex, ()) end """ BinaryenSetOneCallerInlineMaxSize(size) Sets the function size which we inline when there is only one caller. Applies to all modules, globally. """ function BinaryenSetOneCallerInlineMaxSize(size) ccall((:BinaryenSetOneCallerInlineMaxSize, libbinaryen), Cvoid, (BinaryenIndex,), size) end """ BinaryenGetAllowInliningFunctionsWithLoops() Gets whether functions with loops are allowed to be inlined. Applies to all modules, globally. """ function BinaryenGetAllowInliningFunctionsWithLoops() ccall((:BinaryenGetAllowInliningFunctionsWithLoops, libbinaryen), Bool, ()) end """ BinaryenSetAllowInliningFunctionsWithLoops(enabled) Sets whether functions with loops are allowed to be inlined. Applies to all modules, globally. """ function BinaryenSetAllowInliningFunctionsWithLoops(enabled) ccall((:BinaryenSetAllowInliningFunctionsWithLoops, libbinaryen), Cvoid, (Bool,), enabled) end """ BinaryenModuleRunPasses(_module, passes, numPasses) Runs the specified passes on the module. Uses the currently set global optimize and shrink level. """ function BinaryenModuleRunPasses(_module, passes, numPasses) ccall((:BinaryenModuleRunPasses, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Ptr{Cchar}}, BinaryenIndex), _module, passes, numPasses) end """ BinaryenModuleAutoDrop(_module) Auto-generate drop() operations where needed. This lets you generate code without worrying about where they are needed. (It is more efficient to do it yourself, but simpler to use autodrop). """ function BinaryenModuleAutoDrop(_module) ccall((:BinaryenModuleAutoDrop, libbinaryen), Cvoid, (BinaryenModuleRef,), _module) end """ BinaryenModuleWrite(_module, output, outputSize) Serialize a module into binary form. Uses the currently set global debugInfo option. @return how many bytes were written. This will be less than or equal to outputSize """ function BinaryenModuleWrite(_module, output, outputSize) ccall((:BinaryenModuleWrite, libbinaryen), Csize_t, (BinaryenModuleRef, Ptr{Cchar}, Csize_t), _module, output, outputSize) end """ BinaryenModuleWriteText(_module, output, outputSize) Serialize a module in s-expression text format. @return how many bytes were written. This will be less than or equal to outputSize """ function BinaryenModuleWriteText(_module, output, outputSize) ccall((:BinaryenModuleWriteText, libbinaryen), Csize_t, (BinaryenModuleRef, Ptr{Cchar}, Csize_t), _module, output, outputSize) end """ BinaryenModuleWriteStackIR(_module, output, outputSize, optimize) Serialize a module in stack IR text format. @return how many bytes were written. This will be less than or equal to outputSize """ function BinaryenModuleWriteStackIR(_module, output, outputSize, optimize) ccall((:BinaryenModuleWriteStackIR, libbinaryen), Csize_t, (BinaryenModuleRef, Ptr{Cchar}, Csize_t, Bool), _module, output, outputSize, optimize) end struct BinaryenBufferSizes outputBytes::Csize_t sourceMapBytes::Csize_t end """ BinaryenModuleWriteWithSourceMap(_module, url, output, outputSize, sourceMap, sourceMapSize) Serialize a module into binary form including its source map. Uses the currently set global debugInfo option. @returns how many bytes were written. This will be less than or equal to outputSize """ function BinaryenModuleWriteWithSourceMap(_module, url, output, outputSize, sourceMap, sourceMapSize) ccall((:BinaryenModuleWriteWithSourceMap, libbinaryen), BinaryenBufferSizes, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, Csize_t, Ptr{Cchar}, Csize_t), _module, url, output, outputSize, sourceMap, sourceMapSize) end """ BinaryenModuleAllocateAndWriteResult Result structure of BinaryenModuleAllocateAndWrite. Contained buffers have been allocated using malloc() and the user is expected to free() them manually once not needed anymore. """ struct BinaryenModuleAllocateAndWriteResult binary::Ptr{Cvoid} binaryBytes::Csize_t sourceMap::Ptr{Cchar} end """ BinaryenModuleAllocateAndWrite(_module, sourceMapUrl) Serializes a module into binary form, optionally including its source map if sourceMapUrl has been specified. Uses the currently set global debugInfo option. Differs from BinaryenModuleWrite in that it implicitly allocates appropriate buffers using malloc(), and expects the user to free() them manually once not needed anymore. """ function BinaryenModuleAllocateAndWrite(_module, sourceMapUrl) ccall((:BinaryenModuleAllocateAndWrite, libbinaryen), BinaryenModuleAllocateAndWriteResult, (BinaryenModuleRef, Ptr{Cchar}), _module, sourceMapUrl) end """ BinaryenModuleAllocateAndWriteText(_module) Serialize a module in s-expression form. Implicity allocates the returned char* with malloc(), and expects the user to free() them manually once not needed anymore. """ function BinaryenModuleAllocateAndWriteText(_module) ccall((:BinaryenModuleAllocateAndWriteText, libbinaryen), Ptr{Cchar}, (BinaryenModuleRef,), _module) end """ BinaryenModuleAllocateAndWriteStackIR(_module, optimize) Serialize a module in stack IR form. Implicitly allocates the returned char* with malloc(), and expects the user to free() them manually once not needed anymore. """ function BinaryenModuleAllocateAndWriteStackIR(_module, optimize) ccall((:BinaryenModuleAllocateAndWriteStackIR, libbinaryen), Ptr{Cchar}, (BinaryenModuleRef, Bool), _module, optimize) end """ BinaryenModuleRead(input, inputSize) Deserialize a module from binary form. """ function BinaryenModuleRead(input, inputSize) ccall((:BinaryenModuleRead, libbinaryen), BinaryenModuleRef, (Ptr{Cchar}, Csize_t), input, inputSize) end """ BinaryenModuleInterpret(_module) Execute a module in the Binaryen interpreter. This will create an instance of the module, run it in the interpreter - which means running the start method - and then destroying the instance. """ function BinaryenModuleInterpret(_module) ccall((:BinaryenModuleInterpret, libbinaryen), Cvoid, (BinaryenModuleRef,), _module) end """ BinaryenModuleAddDebugInfoFileName(_module, filename) Adds a debug info file name to the module and returns its index. """ function BinaryenModuleAddDebugInfoFileName(_module, filename) ccall((:BinaryenModuleAddDebugInfoFileName, libbinaryen), BinaryenIndex, (BinaryenModuleRef, Ptr{Cchar}), _module, filename) end """ BinaryenModuleGetDebugInfoFileName(_module, index) Gets the name of the debug info file at the specified index. Returns `NULL` if it does not exist. """ function BinaryenModuleGetDebugInfoFileName(_module, index) ccall((:BinaryenModuleGetDebugInfoFileName, libbinaryen), Ptr{Cchar}, (BinaryenModuleRef, BinaryenIndex), _module, index) end """ BinaryenFunctionGetName(func) Gets the name of the specified `Function`. """ function BinaryenFunctionGetName(func) ccall((:BinaryenFunctionGetName, libbinaryen), Ptr{Cchar}, (BinaryenFunctionRef,), func) end """ BinaryenFunctionGetParams(func) Gets the type of the parameter at the specified index of the specified `Function`. """ function BinaryenFunctionGetParams(func) ccall((:BinaryenFunctionGetParams, libbinaryen), BinaryenType, (BinaryenFunctionRef,), func) end """ BinaryenFunctionGetResults(func) Gets the result type of the specified `Function`. """ function BinaryenFunctionGetResults(func) ccall((:BinaryenFunctionGetResults, libbinaryen), BinaryenType, (BinaryenFunctionRef,), func) end """ BinaryenFunctionGetNumVars(func) Gets the number of additional locals within the specified `Function`. """ function BinaryenFunctionGetNumVars(func) ccall((:BinaryenFunctionGetNumVars, libbinaryen), BinaryenIndex, (BinaryenFunctionRef,), func) end """ BinaryenFunctionGetVar(func, index) Gets the type of the additional local at the specified index within the specified `Function`. """ function BinaryenFunctionGetVar(func, index) ccall((:BinaryenFunctionGetVar, libbinaryen), BinaryenType, (BinaryenFunctionRef, BinaryenIndex), func, index) end """ BinaryenFunctionGetNumLocals(func) Gets the number of locals within the specified function. Includes parameters. """ function BinaryenFunctionGetNumLocals(func) ccall((:BinaryenFunctionGetNumLocals, libbinaryen), BinaryenIndex, (BinaryenFunctionRef,), func) end """ BinaryenFunctionHasLocalName(func, index) Tests if the local at the specified index has a name. """ function BinaryenFunctionHasLocalName(func, index) ccall((:BinaryenFunctionHasLocalName, libbinaryen), Bool, (BinaryenFunctionRef, BinaryenIndex), func, index) end """ BinaryenFunctionGetLocalName(func, index) Gets the name of the local at the specified index. """ function BinaryenFunctionGetLocalName(func, index) ccall((:BinaryenFunctionGetLocalName, libbinaryen), Ptr{Cchar}, (BinaryenFunctionRef, BinaryenIndex), func, index) end """ BinaryenFunctionSetLocalName(func, index, name) Sets the name of the local at the specified index. """ function BinaryenFunctionSetLocalName(func, index, name) ccall((:BinaryenFunctionSetLocalName, libbinaryen), Cvoid, (BinaryenFunctionRef, BinaryenIndex, Ptr{Cchar}), func, index, name) end """ BinaryenFunctionGetBody(func) Gets the body of the specified `Function`. """ function BinaryenFunctionGetBody(func) ccall((:BinaryenFunctionGetBody, libbinaryen), BinaryenExpressionRef, (BinaryenFunctionRef,), func) end """ BinaryenFunctionSetBody(func, body) Sets the body of the specified `Function`. """ function BinaryenFunctionSetBody(func, body) ccall((:BinaryenFunctionSetBody, libbinaryen), Cvoid, (BinaryenFunctionRef, BinaryenExpressionRef), func, body) end """ BinaryenFunctionOptimize(func, _module) Runs the standard optimization passes on the function. Uses the currently set global optimize and shrink level. """ function BinaryenFunctionOptimize(func, _module) ccall((:BinaryenFunctionOptimize, libbinaryen), Cvoid, (BinaryenFunctionRef, BinaryenModuleRef), func, _module) end """ BinaryenFunctionRunPasses(func, _module, passes, numPasses) Runs the specified passes on the function. Uses the currently set global optimize and shrink level. """ function BinaryenFunctionRunPasses(func, _module, passes, numPasses) ccall((:BinaryenFunctionRunPasses, libbinaryen), Cvoid, (BinaryenFunctionRef, BinaryenModuleRef, Ptr{Ptr{Cchar}}, BinaryenIndex), func, _module, passes, numPasses) end """ BinaryenFunctionSetDebugLocation(func, expr, fileIndex, lineNumber, columnNumber) Sets the debug location of the specified `Expression` within the specified `Function`. """ function BinaryenFunctionSetDebugLocation(func, expr, fileIndex, lineNumber, columnNumber) ccall((:BinaryenFunctionSetDebugLocation, libbinaryen), Cvoid, (BinaryenFunctionRef, BinaryenExpressionRef, BinaryenIndex, BinaryenIndex, BinaryenIndex), func, expr, fileIndex, lineNumber, columnNumber) end """ BinaryenTableGetName(table) Gets the name of the specified `Table`. """ function BinaryenTableGetName(table) ccall((:BinaryenTableGetName, libbinaryen), Ptr{Cchar}, (BinaryenTableRef,), table) end """ BinaryenTableSetName(table, name) Sets the name of the specified `Table`. """ function BinaryenTableSetName(table, name) ccall((:BinaryenTableSetName, libbinaryen), Cvoid, (BinaryenTableRef, Ptr{Cchar}), table, name) end """ BinaryenTableGetInitial(table) Gets the initial number of pages of the specified `Table`. """ function BinaryenTableGetInitial(table) ccall((:BinaryenTableGetInitial, libbinaryen), BinaryenIndex, (BinaryenTableRef,), table) end """ BinaryenTableSetInitial(table, initial) Sets the initial number of pages of the specified `Table`. """ function BinaryenTableSetInitial(table, initial) ccall((:BinaryenTableSetInitial, libbinaryen), Cvoid, (BinaryenTableRef, BinaryenIndex), table, initial) end """ BinaryenTableHasMax(table) Tests whether the specified `Table` has a maximum number of pages. """ function BinaryenTableHasMax(table) ccall((:BinaryenTableHasMax, libbinaryen), Bool, (BinaryenTableRef,), table) end """ BinaryenTableGetMax(table) Gets the maximum number of pages of the specified `Table`. """ function BinaryenTableGetMax(table) ccall((:BinaryenTableGetMax, libbinaryen), BinaryenIndex, (BinaryenTableRef,), table) end """ BinaryenTableSetMax(table, max) Sets the maximum number of pages of the specified `Table`. """ function BinaryenTableSetMax(table, max) ccall((:BinaryenTableSetMax, libbinaryen), Cvoid, (BinaryenTableRef, BinaryenIndex), table, max) end """ BinaryenElementSegmentGetName(elem) Gets the name of the specified `ElementSegment`. """ function BinaryenElementSegmentGetName(elem) ccall((:BinaryenElementSegmentGetName, libbinaryen), Ptr{Cchar}, (BinaryenElementSegmentRef,), elem) end """ BinaryenElementSegmentSetName(elem, name) Sets the name of the specified `ElementSegment`. """ function BinaryenElementSegmentSetName(elem, name) ccall((:BinaryenElementSegmentSetName, libbinaryen), Cvoid, (BinaryenElementSegmentRef, Ptr{Cchar}), elem, name) end """ BinaryenElementSegmentGetTable(elem) Gets the table name of the specified `ElementSegment`. """ function BinaryenElementSegmentGetTable(elem) ccall((:BinaryenElementSegmentGetTable, libbinaryen), Ptr{Cchar}, (BinaryenElementSegmentRef,), elem) end """ BinaryenElementSegmentSetTable(elem, table) Sets the table name of the specified `ElementSegment`. """ function BinaryenElementSegmentSetTable(elem, table) ccall((:BinaryenElementSegmentSetTable, libbinaryen), Cvoid, (BinaryenElementSegmentRef, Ptr{Cchar}), elem, table) end """ BinaryenElementSegmentGetOffset(elem) Gets the segment offset in case of active segments """ function BinaryenElementSegmentGetOffset(elem) ccall((:BinaryenElementSegmentGetOffset, libbinaryen), BinaryenExpressionRef, (BinaryenElementSegmentRef,), elem) end """ BinaryenElementSegmentGetLength(elem) Gets the length of items in the segment """ function BinaryenElementSegmentGetLength(elem) ccall((:BinaryenElementSegmentGetLength, libbinaryen), BinaryenIndex, (BinaryenElementSegmentRef,), elem) end """ BinaryenElementSegmentGetData(elem, dataId) Gets the item at the specified index """ function BinaryenElementSegmentGetData(elem, dataId) ccall((:BinaryenElementSegmentGetData, libbinaryen), Ptr{Cchar}, (BinaryenElementSegmentRef, BinaryenIndex), elem, dataId) end """ BinaryenElementSegmentIsPassive(elem) Returns true if the specified elem segment is passive """ function BinaryenElementSegmentIsPassive(elem) ccall((:BinaryenElementSegmentIsPassive, libbinaryen), Bool, (BinaryenElementSegmentRef,), elem) end """ BinaryenGlobalGetName(_global) Gets the name of the specified `Global`. """ function BinaryenGlobalGetName(_global) ccall((:BinaryenGlobalGetName, libbinaryen), Ptr{Cchar}, (BinaryenGlobalRef,), _global) end """ BinaryenGlobalGetType(_global) Gets the name of the `GlobalType` associated with the specified `Global`. May be `NULL` if the signature is implicit. """ function BinaryenGlobalGetType(_global) ccall((:BinaryenGlobalGetType, libbinaryen), BinaryenType, (BinaryenGlobalRef,), _global) end """ BinaryenGlobalIsMutable(_global) Returns true if the specified `Global` is mutable. """ function BinaryenGlobalIsMutable(_global) ccall((:BinaryenGlobalIsMutable, libbinaryen), Bool, (BinaryenGlobalRef,), _global) end """ BinaryenGlobalGetInitExpr(_global) Gets the initialization expression of the specified `Global`. """ function BinaryenGlobalGetInitExpr(_global) ccall((:BinaryenGlobalGetInitExpr, libbinaryen), BinaryenExpressionRef, (BinaryenGlobalRef,), _global) end """ BinaryenTagGetName(tag) Gets the name of the specified `Tag`. """ function BinaryenTagGetName(tag) ccall((:BinaryenTagGetName, libbinaryen), Ptr{Cchar}, (BinaryenTagRef,), tag) end """ BinaryenTagGetParams(tag) Gets the parameters type of the specified `Tag`. """ function BinaryenTagGetParams(tag) ccall((:BinaryenTagGetParams, libbinaryen), BinaryenType, (BinaryenTagRef,), tag) end """ BinaryenTagGetResults(tag) Gets the results type of the specified `Tag`. """ function BinaryenTagGetResults(tag) ccall((:BinaryenTagGetResults, libbinaryen), BinaryenType, (BinaryenTagRef,), tag) end """ BinaryenFunctionImportGetModule(_import) Gets the external module name of the specified import. """ function BinaryenFunctionImportGetModule(_import) ccall((:BinaryenFunctionImportGetModule, libbinaryen), Ptr{Cchar}, (BinaryenFunctionRef,), _import) end function BinaryenTableImportGetModule(_import) ccall((:BinaryenTableImportGetModule, libbinaryen), Ptr{Cchar}, (BinaryenTableRef,), _import) end function BinaryenGlobalImportGetModule(_import) ccall((:BinaryenGlobalImportGetModule, libbinaryen), Ptr{Cchar}, (BinaryenGlobalRef,), _import) end function BinaryenTagImportGetModule(_import) ccall((:BinaryenTagImportGetModule, libbinaryen), Ptr{Cchar}, (BinaryenTagRef,), _import) end """ BinaryenFunctionImportGetBase(_import) Gets the external base name of the specified import. """ function BinaryenFunctionImportGetBase(_import) ccall((:BinaryenFunctionImportGetBase, libbinaryen), Ptr{Cchar}, (BinaryenFunctionRef,), _import) end function BinaryenTableImportGetBase(_import) ccall((:BinaryenTableImportGetBase, libbinaryen), Ptr{Cchar}, (BinaryenTableRef,), _import) end function BinaryenGlobalImportGetBase(_import) ccall((:BinaryenGlobalImportGetBase, libbinaryen), Ptr{Cchar}, (BinaryenGlobalRef,), _import) end function BinaryenTagImportGetBase(_import) ccall((:BinaryenTagImportGetBase, libbinaryen), Ptr{Cchar}, (BinaryenTagRef,), _import) end """ BinaryenExportGetKind(export_) Gets the external kind of the specified export. """ function BinaryenExportGetKind(export_) ccall((:BinaryenExportGetKind, libbinaryen), BinaryenExternalKind, (BinaryenExportRef,), export_) end """ BinaryenExportGetName(export_) Gets the external name of the specified export. """ function BinaryenExportGetName(export_) ccall((:BinaryenExportGetName, libbinaryen), Ptr{Cchar}, (BinaryenExportRef,), export_) end """ BinaryenExportGetValue(export_) Gets the internal name of the specified export. """ function BinaryenExportGetValue(export_) ccall((:BinaryenExportGetValue, libbinaryen), Ptr{Cchar}, (BinaryenExportRef,), export_) end """ BinaryenAddCustomSection(_module, name, contents, contentsSize) ========= Custom sections ========= """ function BinaryenAddCustomSection(_module, name, contents, contentsSize) ccall((:BinaryenAddCustomSection, libbinaryen), Cvoid, (BinaryenModuleRef, Ptr{Cchar}, Ptr{Cchar}, BinaryenIndex), _module, name, contents, contentsSize) end """ ========= Effect analyzer ========= """ const BinaryenSideEffects = UInt32 function BinaryenSideEffectNone() ccall((:BinaryenSideEffectNone, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectBranches() ccall((:BinaryenSideEffectBranches, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectCalls() ccall((:BinaryenSideEffectCalls, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectReadsLocal() ccall((:BinaryenSideEffectReadsLocal, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectWritesLocal() ccall((:BinaryenSideEffectWritesLocal, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectReadsGlobal() ccall((:BinaryenSideEffectReadsGlobal, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectWritesGlobal() ccall((:BinaryenSideEffectWritesGlobal, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectReadsMemory() ccall((:BinaryenSideEffectReadsMemory, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectWritesMemory() ccall((:BinaryenSideEffectWritesMemory, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectReadsTable() ccall((:BinaryenSideEffectReadsTable, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectWritesTable() ccall((:BinaryenSideEffectWritesTable, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectImplicitTrap() ccall((:BinaryenSideEffectImplicitTrap, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectTrapsNeverHappen() ccall((:BinaryenSideEffectTrapsNeverHappen, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectIsAtomic() ccall((:BinaryenSideEffectIsAtomic, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectThrows() ccall((:BinaryenSideEffectThrows, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectDanglingPop() ccall((:BinaryenSideEffectDanglingPop, libbinaryen), BinaryenSideEffects, ()) end function BinaryenSideEffectAny() ccall((:BinaryenSideEffectAny, libbinaryen), BinaryenSideEffects, ()) end function BinaryenExpressionGetSideEffects(expr, _module) ccall((:BinaryenExpressionGetSideEffects, libbinaryen), BinaryenSideEffects, (BinaryenExpressionRef, BinaryenModuleRef), expr, _module) end mutable struct Relooper end const RelooperRef = Ptr{Relooper} mutable struct RelooperBlock end const RelooperBlockRef = Ptr{RelooperBlock} """ RelooperCreate(_module) Create a relooper instance """ function RelooperCreate(_module) ccall((:RelooperCreate, libbinaryen), RelooperRef, (BinaryenModuleRef,), _module) end """ RelooperAddBlock(relooper, code) Create a basic block that ends with nothing, or with some simple branching """ function RelooperAddBlock(relooper, code) ccall((:RelooperAddBlock, libbinaryen), RelooperBlockRef, (RelooperRef, BinaryenExpressionRef), relooper, code) end """ RelooperAddBranch(from, to, condition, code) Create a branch to another basic block The branch can have code on it, that is executed as the branch happens. this is useful for phis. otherwise, code can be NULL """ function RelooperAddBranch(from, to, condition, code) ccall((:RelooperAddBranch, libbinaryen), Cvoid, (RelooperBlockRef, RelooperBlockRef, BinaryenExpressionRef, BinaryenExpressionRef), from, to, condition, code) end """ RelooperAddBlockWithSwitch(relooper, code, condition) Create a basic block that ends a switch on a condition """ function RelooperAddBlockWithSwitch(relooper, code, condition) ccall((:RelooperAddBlockWithSwitch, libbinaryen), RelooperBlockRef, (RelooperRef, BinaryenExpressionRef, BinaryenExpressionRef), relooper, code, condition) end """ RelooperAddBranchForSwitch(from, to, indexes, numIndexes, code) Create a switch-style branch to another basic block. The block's switch table will have these indexes going to that target """ function RelooperAddBranchForSwitch(from, to, indexes, numIndexes, code) ccall((:RelooperAddBranchForSwitch, libbinaryen), Cvoid, (RelooperBlockRef, RelooperBlockRef, Ptr{BinaryenIndex}, BinaryenIndex, BinaryenExpressionRef), from, to, indexes, numIndexes, code) end """ RelooperRenderAndDispose(relooper, entry, labelHelper) Generate structed wasm control flow from the CFG of blocks and branches that were created on this relooper instance. This returns the rendered output, and also disposes of the relooper and its blocks and branches, as they are no longer needed. @param labelHelper To render irreducible control flow, we may need a helper variable to guide us to the right target label. This value should be an index of an i32 local variable that is free for us to use. """ function RelooperRenderAndDispose(relooper, entry, labelHelper) ccall((:RelooperRenderAndDispose, libbinaryen), BinaryenExpressionRef, (RelooperRef, RelooperBlockRef, BinaryenIndex), relooper, entry, labelHelper) end mutable struct CExpressionRunner end const ExpressionRunnerRef = Ptr{CExpressionRunner} const ExpressionRunnerFlags = UInt32 # no prototype is found for this function at binaryen-c.h:3451:36, please use with caution """ ExpressionRunnerFlagsDefault() By default, just evaluate the expression, i.e. all we want to know is whether it computes down to a concrete value, where it is not necessary to preserve side effects like those of a `local.tee`. """ function ExpressionRunnerFlagsDefault() ccall((:ExpressionRunnerFlagsDefault, libbinaryen), ExpressionRunnerFlags, ()) end # no prototype is found for this function at binaryen-c.h:3458:36, please use with caution """ ExpressionRunnerFlagsPreserveSideeffects() Be very careful to preserve any side effects. For example, if we are intending to replace the expression with a constant afterwards, even if we can technically evaluate down to a constant, we still cannot replace the expression if it also sets a local, which must be preserved in this scenario so subsequent code keeps functioning. """ function ExpressionRunnerFlagsPreserveSideeffects() ccall((:ExpressionRunnerFlagsPreserveSideeffects, libbinaryen), ExpressionRunnerFlags, ()) end # no prototype is found for this function at binaryen-c.h:3464:36, please use with caution """ ExpressionRunnerFlagsTraverseCalls() Traverse through function calls, attempting to compute their concrete value. Must not be used in function-parallel scenarios, where the called function might be concurrently modified, leading to undefined behavior. Traversing another function reuses all of this runner's flags. """ function ExpressionRunnerFlagsTraverseCalls() ccall((:ExpressionRunnerFlagsTraverseCalls, libbinaryen), ExpressionRunnerFlags, ()) end """ ExpressionRunnerCreate(_module, flags, maxDepth, maxLoopIterations) Creates an ExpressionRunner instance """ function ExpressionRunnerCreate(_module, flags, maxDepth, maxLoopIterations) ccall((:ExpressionRunnerCreate, libbinaryen), ExpressionRunnerRef, (BinaryenModuleRef, ExpressionRunnerFlags, BinaryenIndex, BinaryenIndex), _module, flags, maxDepth, maxLoopIterations) end """ ExpressionRunnerSetLocalValue(runner, index, value) Sets a known local value to use. Order matters if expressions have side effects. For example, if the expression also sets a local, this side effect will also happen (not affected by any flags). Returns `true` if the expression actually evaluates to a constant. """ function ExpressionRunnerSetLocalValue(runner, index, value) ccall((:ExpressionRunnerSetLocalValue, libbinaryen), Bool, (ExpressionRunnerRef, BinaryenIndex, BinaryenExpressionRef), runner, index, value) end """ ExpressionRunnerSetGlobalValue(runner, name, value) Sets a known global value to use. Order matters if expressions have side effects. For example, if the expression also sets a local, this side effect will also happen (not affected by any flags). Returns `true` if the expression actually evaluates to a constant. """ function ExpressionRunnerSetGlobalValue(runner, name, value) ccall((:ExpressionRunnerSetGlobalValue, libbinaryen), Bool, (ExpressionRunnerRef, Ptr{Cchar}, BinaryenExpressionRef), runner, name, value) end """ ExpressionRunnerRunAndDispose(runner, expr) Runs the expression and returns the constant value expression it evaluates to, if any. Otherwise returns `NULL`. Also disposes the runner. """ function ExpressionRunnerRunAndDispose(runner, expr) ccall((:ExpressionRunnerRunAndDispose, libbinaryen), BinaryenExpressionRef, (ExpressionRunnerRef, BinaryenExpressionRef), runner, expr) end mutable struct TypeBuilder end const TypeBuilderRef = Ptr{TypeBuilder} const TypeBuilderErrorReason = UInt32 """ TypeBuilderErrorReasonSelfSupertype() Indicates a cycle in the supertype relation. """ function TypeBuilderErrorReasonSelfSupertype() ccall((:TypeBuilderErrorReasonSelfSupertype, libbinaryen), TypeBuilderErrorReason, ()) end """ TypeBuilderErrorReasonInvalidSupertype() Indicates that the declared supertype of a type is invalid. """ function TypeBuilderErrorReasonInvalidSupertype() ccall((:TypeBuilderErrorReasonInvalidSupertype, libbinaryen), TypeBuilderErrorReason, ()) end """ TypeBuilderErrorReasonForwardSupertypeReference() Indicates that the declared supertype is an invalid forward reference. """ function TypeBuilderErrorReasonForwardSupertypeReference() ccall((:TypeBuilderErrorReasonForwardSupertypeReference, libbinaryen), TypeBuilderErrorReason, ()) end """ TypeBuilderErrorReasonForwardChildReference() Indicates that a child of a type is an invalid forward reference. """ function TypeBuilderErrorReasonForwardChildReference() ccall((:TypeBuilderErrorReasonForwardChildReference, libbinaryen), TypeBuilderErrorReason, ()) end const BinaryenBasicHeapType = UInt32 """ TypeBuilderCreate(size) Constructs a new type builder that allows for the construction of recursive types. Contains a table of `size` mutable heap types. """ function TypeBuilderCreate(size) ccall((:TypeBuilderCreate, libbinaryen), TypeBuilderRef, (BinaryenIndex,), size) end """ TypeBuilderGrow(builder, count) Grows the backing table of the type builder by `count` slots. """ function TypeBuilderGrow(builder, count) ccall((:TypeBuilderGrow, libbinaryen), Cvoid, (TypeBuilderRef, BinaryenIndex), builder, count) end """ TypeBuilderGetSize(builder) Gets the size of the backing table of the type builder. """ function TypeBuilderGetSize(builder) ccall((:TypeBuilderGetSize, libbinaryen), BinaryenIndex, (TypeBuilderRef,), builder) end """ TypeBuilderSetSignatureType(builder, index, paramTypes, resultTypes) Sets the heap type at index `index` to a concrete signature type. Expects temporary tuple types if multiple parameter and/or result types include temporary types. """ function TypeBuilderSetSignatureType(builder, index, paramTypes, resultTypes) ccall((:TypeBuilderSetSignatureType, libbinaryen), Cvoid, (TypeBuilderRef, BinaryenIndex, BinaryenType, BinaryenType), builder, index, paramTypes, resultTypes) end """ TypeBuilderSetStructType(builder, index, fieldTypes, fieldPackedTypes, fieldMutables, numFields) Sets the heap type at index `index` to a concrete struct type. """ function TypeBuilderSetStructType(builder, index, fieldTypes, fieldPackedTypes, fieldMutables, numFields) ccall((:TypeBuilderSetStructType, libbinaryen), Cvoid, (TypeBuilderRef, BinaryenIndex, Ptr{BinaryenType}, Ptr{BinaryenPackedType}, Ptr{Bool}, Cint), builder, index, fieldTypes, fieldPackedTypes, fieldMutables, numFields) end """ TypeBuilderSetArrayType(builder, index, elementType, elementPackedType, elementMutable) Sets the heap type at index `index` to a concrete array type. """ function TypeBuilderSetArrayType(builder, index, elementType, elementPackedType, elementMutable) ccall((:TypeBuilderSetArrayType, libbinaryen), Cvoid, (TypeBuilderRef, BinaryenIndex, BinaryenType, BinaryenPackedType, Cint), builder, index, elementType, elementPackedType, elementMutable) end """ TypeBuilderGetTempHeapType(builder, index) Gets the temporary heap type to use at index `index`. Temporary heap types may only be used to construct temporary types using the type builder. """ function TypeBuilderGetTempHeapType(builder, index) ccall((:TypeBuilderGetTempHeapType, libbinaryen), BinaryenHeapType, (TypeBuilderRef, BinaryenIndex), builder, index) end """ TypeBuilderGetTempTupleType(builder, types, numTypes) Gets a temporary tuple type for use with and owned by the type builder. """ function TypeBuilderGetTempTupleType(builder, types, numTypes) ccall((:TypeBuilderGetTempTupleType, libbinaryen), BinaryenType, (TypeBuilderRef, Ptr{BinaryenType}, BinaryenIndex), builder, types, numTypes) end """ TypeBuilderGetTempRefType(builder, heapType, nullable) Gets a temporary reference type for use with and owned by the type builder. """ function TypeBuilderGetTempRefType(builder, heapType, nullable) ccall((:TypeBuilderGetTempRefType, libbinaryen), BinaryenType, (TypeBuilderRef, BinaryenHeapType, Cint), builder, heapType, nullable) end """ TypeBuilderSetSubType(builder, index, superType) Sets the type at `index` to be a subtype of the given super type. """ function TypeBuilderSetSubType(builder, index, superType) ccall((:TypeBuilderSetSubType, libbinaryen), Cvoid, (TypeBuilderRef, BinaryenIndex, BinaryenHeapType), builder, index, superType) end """ TypeBuilderCreateRecGroup(builder, index, length) Creates a new recursion group in the range `index` inclusive to `index + length` exclusive. Recursion groups must not overlap. """ function TypeBuilderCreateRecGroup(builder, index, length) ccall((:TypeBuilderCreateRecGroup, libbinaryen), Cvoid, (TypeBuilderRef, BinaryenIndex, BinaryenIndex), builder, index, length) end """ TypeBuilderBuildAndDispose(builder, heapTypes, errorIndex, errorReason) Builds the heap type hierarchy and disposes the builder. Returns `false` and populates `errorIndex` and `errorReason` on failure. """ function TypeBuilderBuildAndDispose(builder, heapTypes, errorIndex, errorReason) ccall((:TypeBuilderBuildAndDispose, libbinaryen), Bool, (TypeBuilderRef, Ptr{BinaryenHeapType}, Ptr{BinaryenIndex}, Ptr{TypeBuilderErrorReason}), builder, heapTypes, errorIndex, errorReason) end """ BinaryenModuleSetTypeName(_module, heapType, name) Sets the textual name of a compound `heapType`. Has no effect if the type already has a canonical name. """ function BinaryenModuleSetTypeName(_module, heapType, name) ccall((:BinaryenModuleSetTypeName, libbinaryen), Cvoid, (BinaryenModuleRef, BinaryenHeapType, Ptr{Cchar}), _module, heapType, name) end """ BinaryenModuleSetFieldName(_module, heapType, index, name) Sets the field name of a struct `heapType` at index `index`. """ function BinaryenModuleSetFieldName(_module, heapType, index, name) ccall((:BinaryenModuleSetFieldName, libbinaryen), Cvoid, (BinaryenModuleRef, BinaryenHeapType, BinaryenIndex, Ptr{Cchar}), _module, heapType, index, name) end """ BinaryenSetColorsEnabled(enabled) Enable or disable coloring for the Wasm printer """ function BinaryenSetColorsEnabled(enabled) ccall((:BinaryenSetColorsEnabled, libbinaryen), Cvoid, (Bool,), enabled) end # no prototype is found for this function at binaryen-c.h:3598:19, please use with caution """ BinaryenAreColorsEnabled() Query whether color is enable for the Wasm printer """ function BinaryenAreColorsEnabled() ccall((:BinaryenAreColorsEnabled, libbinaryen), Bool, ()) end # Skipping MacroDefinition: WASM_DEPRECATED __attribute__ ( ( deprecated ) ) # Skipping MacroDefinition: DELEGATE ( CLASS_TO_VISIT ) BINARYEN_API BinaryenExpressionId Binaryen ## CLASS_TO_VISIT ## Id ( void ) ; # exports const PREFIXES = ["Binaryen", "Relooper", "ExpressionRunner", "TypeBuilder"] for name in names(@__MODULE__; all=true), prefix in PREFIXES if startswith(string(name), prefix) @eval export $name end end end # module
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
432
module WebAssemblyCompiler using Binaryen_jll include("../lib/LibBinaryen.jl") using .LibBinaryen module Bin using Reexport @reexport using Binaryen_jll end include("debug.jl") include("types.jl") include("mixtape.jl") include("interpreter.jl") include("array.jl") include("compile_block.jl") include("_compile.jl") include("utils.jl") include("javascript-interop.jl") include("quirks.jl") include("compiler.jl") end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
7778
function _compile(ctx::CompilerContext, x::Core.Argument; kw...) if callablestruct(ctx) && x.n == 1 && ctx.toplevel return ctx.gfun end if ctx.ci.slottypes[x.n] isa Core.Const type = typeof(ctx.ci.slottypes[x.n].val) else type = ctx.ci.slottypes[x.n] end # If at the top level or if it's not a callable struct, # we don't include the fun as the first argument. BinaryenLocalGet(ctx.mod, argmap(ctx, x.n) - 1, gettype(ctx, type)) end function _compile(ctx::CompilerContext, x::Core.SSAValue; kw...) # These come after the function arguments. bt = basetype(ctx, x) if Base.issingletontype(bt) getglobal(ctx, _compile(ctx, nothing)) else BinaryenLocalGet(ctx.mod, ctx.varmap[x.id], gettype(ctx, ssatype(ctx, x.id))) end # localid = ctx.varmap[x.id] # BinaryenLocalGet(ctx.mod, localid, ctx.locals[localid]) end _compile(ctx::CompilerContext, x::Float64; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralFloat64(x)) _compile(ctx::CompilerContext, x::Float32; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralFloat32(x)) _compile(ctx::CompilerContext, x::Int64; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralInt64(x)) _compile(ctx::CompilerContext, x::Int32; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralInt32(x)) _compile(ctx::CompilerContext, x::UInt8; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralInt32(x)) _compile(ctx::CompilerContext, x::Int8; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralInt32(x)) _compile(ctx::CompilerContext, x::UInt64; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralInt64(reinterpret(Int64, x))) _compile(ctx::CompilerContext, x::UInt32; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralInt32(reinterpret(Int32, x))) _compile(ctx::CompilerContext, x::Bool; kw...) = BinaryenConst(ctx.mod, BinaryenLiteralInt32(x)) _compile(ctx::CompilerContext, x::Ptr{BinaryenExpression}; kw...) = x _compile(ctx::CompilerContext, x::GlobalRef; kw...) = getglobal(ctx, x.mod, x.name) _compile(ctx::CompilerContext, x::QuoteNode; kw...) = _compile(ctx, x.value) # _compile(ctx::CompilerContext, x::String; globals = false, kw...) = globals ? # BinaryenStringConst(ctx.mod, x) : # getglobal(ctx, x, compiledval = BinaryenStringConst(ctx.mod, x)) # _compile(ctx::CompilerContext, x::Symbol; globals = false, kw...) = globals ? # BinaryenStringConst(ctx.mod, x) : # getglobal(ctx, x, compiledval = BinaryenStringConst(ctx.mod, x)) _compile(ctx::CompilerContext, x::String; globals = false, kw...) = _compile(ctx, unsafe_wrap(Vector{UInt8}, x)) _compile(ctx::CompilerContext, x::Symbol; globals = false, kw...) = _compile(ctx, unsafe_wrap(Vector{UInt8}, string(x))) function _compile(ctx::CompilerContext, x::Tuple{}; kw...) arraytype = BinaryenTypeGetHeapType(gettype(ctx, Tuple{})) values = [] return BinaryenArrayNewFixed(ctx.mod, arraytype, values, 0) end function _compile(ctx::CompilerContext, x::NTuple{N,T}; globals = false, kw...) where {N,T} arraytype = BinaryenTypeGetHeapType(gettype(ctx, NTuple{N, roottype(ctx, x[1])})) if globals values = [T in basictypes ? _compile(ctx, v) : getglobal(ctx, v) for v in x] else values = [_compile(ctx, v) for v in x] end return BinaryenArrayNewFixed(ctx.mod, arraytype, values, N) end function _compile(ctx::CompilerContext, x::Val; kw...) return _compile(ctx, hash(x)) # TODO: what am I doing here? type = BinaryenTypeGetHeapType(gettype(ctx, roottype(ctx, x))) nargs = nfields(x) args = [_compile(ctx, getfield(x, i)) for i in 1:nargs] return BinaryenStructNew(ctx.mod, args, nargs, type) end function _compile(ctx::CompilerContext, x::Type) _compile(ctx, Int32(-99)) # _compile(ctx, nothing) end struct Pass{T} val::T end _compile(ctx::CompilerContext, x::Pass) = x.val struct I32{T} val::T end function _compile(ctx::CompilerContext, x::I32; kw...) res = _compile(ctx, x.val) if sizeof(Int) == 8 # wrap in an res = BinaryenUnary(ctx.mod, BinaryenWrapInt64(), res) end return res end function _compile(ctx::CompilerContext, x::T; globals = false, kw...) where T <: Array if haskey(ctx.globals, x) return ctx.globals[x] end if haskey(ctx.objects, x) ox = ctx.objects[x] if ox == Nothing # indicates a circular reference return default(x) end return ox end ctx.objects[x] = nothing elT = eltype(roottype(ctx, T)) buffertype = BinaryenTypeGetHeapType(gettype(ctx, Buffer{elT})) _f(i) = isassigned(x, i) ? x[i] : default(elT) if globals values = [elT in basictypes ? _compile(ctx, _f(i)) : getglobal(ctx, _f(i)) for i in eachindex(x)] else values = [_compile(ctx, _f(i)) for i in eachindex(x)] end buffer = BinaryenArrayNewFixed(ctx.mod, buffertype, values, length(x)) wrappertype = BinaryenTypeGetHeapType(gettype(ctx, FakeArrayWrapper{elT})) result = BinaryenStructNew(ctx.mod, [buffer, _compile(ctx, Int32(length(x)))], 2, wrappertype) ctx.objects[x] = result return result end # general tuples function _compile(ctx::CompilerContext, x::T; globals = false, kw...) where T <: Tuple TT = Tuple{(roottype(ctx, v) for v in x)...} type = BinaryenTypeGetHeapType(gettype(ctx, TT)) if globals args = [roottype(ctx, x[i]) in basictypes ? _compile(ctx, x[i]) : getglobal(ctx, x[i]) for i in 1:length(x)] else args = [_compile(ctx, x[i]) for i in 1:length(x)] end return BinaryenStructNew(ctx.mod, args, length(args), type) end # general version for structs function _compile(ctx::CompilerContext, x::T; globals = false, kw...) where T if haskey(ctx.globals, x) return ctx.globals[x] end if ismutabletype(T) && haskey(ctx.objects, x) # if haskey(ctx.objects, x) ox = ctx.objects[x] if ox === nothing # indicates a circular reference # show(stdout, MIME"text/plain"(), ctx.objects) return _compile(ctx, default(x)) end return ox end ctx.objects[x] = nothing type = BinaryenTypeGetHeapType(gettype(ctx, T)) if globals args = [fieldtype(T, field) in basictypes ? _compile(ctx, getfield(x, field)) : # maybeboxfield(x, field) : getglobal(ctx, getfield(x, field)) for field in fieldskept(T)] else args = [_compile(ctx, getfield(x, field)) for field in fieldskept(T)] end result = BinaryenStructNew(ctx.mod, args, length(args), type) if ismutabletype(T) ctx.objects[x] = result end return result end function maybeboxfield(x, field) val = getfield(x, field) ftype = fieldtype(typeof(x), field) if typeof(val) == ftype return _compile(ctx, val) else return BinaryenRefCast(ctx.mod, _compile(ctx, Box{ftype}(val))) end end function _compile(ctx::CompilerContext, x::Expr; kw...) if x.head == :boundscheck return _compile(ctx, false) else return _compile(ctx, false) # not sure what to put here... end end # function _compileglobal(ctx::CompilerContext, x::T; kw...) where T <: Array # _compile(ctx, x) # end # function _compileglobal(ctx::CompilerContext, x::T; kw...) where T # type = BinaryenTypeGetHeapType(gettype(ctx, T)) # args = [fieldtype(T, field) in basictypes ? # _compile(ctx, getfield(x, field)) : # _compileglobal(ctx, getfield(x, field)) for field in fieldnames(T)] # return BinaryenStructNew(ctx.mod, args, length(args), type) # end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
2789
# Adapted from https://github.com/tpapp/PushVectors.jl # Copyright (c) 2018: Tamas K. Papp. # MIT license. # https://github.com/tpapp/PushVectors.jl/blob/master/LICENSE.md struct Buffer{T} <: AbstractVector{T} end mutable struct FakeArrayWrapper{T} <: AbstractVector{T} "Vector used for storage." parent::Buffer{T} "Number of elements held by `parent`." len::Int32 end Base.eltype(::FakeArrayWrapper{T}) where T = T mutable struct ArrayWrapper{T} <: AbstractVector{T} "Vector used for storage." parent::Vector{T} "Number of elements held by `parent`." len::Int32 end Base.eltype(::ArrayWrapper{T}) where T = T """ ArrayWrapper{T}(sizehint = 4) Create a `ArrayWrapper` for elements typed `T`, with no initial elements. `sizehint` determines the initial allocated size. """ function ArrayWrapper{T}(sizehint::Integer = 4) where {T} sizehint ≥ 0 || throw(DomainError(sizehint, "Invalid initial size.")) ArrayWrapper{T}(Vector{T}(undef, sizehint), 0) end @inline Base.length(v::ArrayWrapper) = v.len @inline Base.size(v::ArrayWrapper) = (v.len, ) function Base.sizehint!(v::ArrayWrapper, n) if length(v.parent) < n || n ≥ v.len resize!(v.parent, n) end nothing end @inline function Base.getindex(v::ArrayWrapper, i) @boundscheck checkbounds(v, i) @inbounds v.parent[i] end @inline function Base.setindex!(v::ArrayWrapper, x, i) @boundscheck checkbounds(v, i) @inbounds v.parent[i] = x end function Base.push!(v::ArrayWrapper, x) v.len += 1 if v.len > length(v.parent) newbuffer = similar(v.parent, min(v.len * Int32(2), j)) copyto!(newbuffer, 1:length(v), v, 1:length(v)) v.parent = newbuffer end v.parent[v.len] = x v end function Base._growend!(v::ArrayWrapper, amount) v.len += amount if v.len > length(v.parent) # newbuffer = similar(v.parent, nextpow(Int32(2), nextpow(Int32(2), v.len))) newbuffer = similar(v.parent, Int32(2) * v.len) copyto!(newbuffer, 1:length(v), v, 1:length(v)) v.parent = newbuffer end end Base.empty!(v::ArrayWrapper) = (v.len = 0; v) function Base.append!(v::ArrayWrapper, xs) ι_xs = eachindex(xs) # allow generalized indexing l = length(ι_xs) if l ≤ 4 for x in xs push!(v, x) end else L = l + v.len if length(v.parent) < L resize!(v.parent, nextpow(2, nextpow(2, L))) end @inbounds copyto!(v.parent, v.len + 1, xs, first(ι_xs), l) v.len += l end v end """ finish!(v) Shrink the buffer `v` to its current content and return that vector. !!! NOTE Consequences are undefined if you modify `v` after this. """ finish!(v::ArrayWrapper) = resize!(v.parent, v.len)
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
40053
@static if VERSION ≥ v"1.9-" const CCCallInfo = Core.Compiler.CallInfo else const CCCallInfo = Any end function update!(ctx::CompilerContext, x, localtype = nothing) # TODO: check the type of x, compare that with the wasm type of localtype, and if they differ, # convert one to the other. Hopefully, this is mainly Int32 -> Int64. push!(ctx.body, x) if localtype !== nothing push!(ctx.locals, gettype(ctx, localtype)) ctx.localidx += 1 end # BinaryenExpressionPrint(x) s = _debug_binaryen_get(ctx, x) debug(:offline) && _debug_binaryen(ctx, x) return nothing end function setlocal!(ctx, idx, x; set = true, drop = false) T = ssatype(ctx, idx) if T != Union{} && set # && T != Nothing && set # && T != Any ctx.varmap[idx] = ctx.localidx x = BinaryenLocalSet(ctx.mod, ctx.localidx, x) update!(ctx, x, T) else if drop x = BinaryenDrop(ctx.mod, x) end debug(:offline) && _debug_binaryen(ctx, x) push!(ctx.body, x) end end function binaryfun(ctx, idx, bfuns, a, b; adjustsizes = true) ctx.varmap[idx] = ctx.localidx Ta = roottype(ctx, a) Tb = roottype(ctx, b) _a = _compile(ctx, a) _b = _compile(ctx, b) if adjustsizes && sizeof(Ta) !== sizeof(Tb) # try to make the sizes the same, at least for Integers if sizeof(Ta) == 4 _b = BinaryenUnary(ctx.mod, BinaryenWrapInt64(), _b) elseif sizeof(Ta) == 8 _b = BinaryenUnary(ctx.mod, Tb <: Signed ? BinaryenExtendSInt32() : BinaryenExtendUInt32(), _b) end end x = BinaryenBinary(ctx.mod, sizeof(Ta) < 8 && length(bfuns) > 1 ? bfuns[2]() : bfuns[1](), _a, _b) setlocal!(ctx, idx, x) end function unaryfun(ctx, idx, bfuns, a) x = BinaryenUnary(ctx.mod, sizeof(roottype(ctx, a)) < 8 && length(bfuns) > 1 ? bfuns[2]() : bfuns[1](), _compile(ctx, a)) setlocal!(ctx, idx, x) end function binaryenfun(ctx, idx, bfun, args...; passall = false) x = bfun(ctx.mod, (passall ? a : _compile(ctx, a) for a in args)...) setlocal!(ctx, idx, x) end # Compile one block of code function compile_block(ctx::CompilerContext, cfg::Core.Compiler.CFG, phis, idx) idxs = cfg.blocks[idx].stmts ci = ctx.ci ctx.body = BinaryenExpressionRef[] for idx in idxs node = ci.code[idx] debug(:inline) && @show idx node ssatype(ctx, idx) debug(:offline) && _debug_line(ctx, idx, node) if node isa Union{Core.GotoNode, Core.GotoIfNot, Core.PhiNode, Nothing} # do nothing elseif node == Core.ReturnNode() update!(ctx, BinaryenUnreachable(ctx.mod)) elseif node isa Core.ReturnNode val = node.val isa GlobalRef ? Core.eval(node.val.mod, node.val.name) : node.val isa Core.Const ? node.val.val : node.val update!(ctx, BinaryenReturn(ctx.mod, roottype(ctx, val) == Nothing ? C_NULL : _compile(ctx, val))) elseif node isa Core.PiNode fromT = roottype(ctx, node.val) toT = ssatype(ctx, idx) x = _compile(ctx, node.val) if fromT == Any # Need to cast to the right value x = BinaryenRefCast(ctx.mod, x, gettype(ctx, toT)) end setlocal!(ctx, idx, x) ## Intrinsics ## elseif matchgr(node, :neg_int) do a T = roottype(ctx, a) binaryfun(ctx, idx, (BinaryenSubInt64, BinaryenSubInt32), T(0), a) end elseif matchgr(node, :neg_float) do a unaryfun(ctx, idx, (BinaryenNegFloat64, BinaryenNegFloat32), a) end elseif matchgr(node, :add_int) do a, b binaryfun(ctx, idx, (BinaryenAddInt64, BinaryenAddInt32), a, b) end elseif matchgr(node, :sub_int) do a, b binaryfun(ctx, idx, (BinaryenSubInt64, BinaryenSubInt32), a, b) end elseif matchgr(node, :mul_int) do a, b binaryfun(ctx, idx, (BinaryenMulInt64, BinaryenMulInt32), a, b) end elseif matchgr(node, :sdiv_int) do a, b binaryfun(ctx, idx, (BinaryenDivSInt64, BinaryenDivSInt32), a, b) end elseif matchgr(node, :checked_sdiv_int) do a, b binaryfun(ctx, idx, (BinaryenDivSInt64, BinaryenDivSInt32), a, b) end elseif matchgr(node, :udiv_int) do a, b binaryfun(ctx, idx, (BinaryenDivUInt64, BinaryenDivUInt32), a, b) end elseif matchgr(node, :checked_udiv_int) do a, b binaryfun(ctx, idx, (BinaryenDivUInt64, BinaryenDivUInt32), a, b) end elseif matchgr(node, :srem_int) do a, b binaryfun(ctx, idx, (BinaryenRemSInt64, BinaryenRemSInt32), a, b) end elseif matchgr(node, :checked_srem_int) do a, b # LIES - it isn't checked binaryfun(ctx, idx, (BinaryenRemSInt64, BinaryenRemSInt32), a, b) end elseif matchgr(node, :urem_int) do a, b binaryfun(ctx, idx, (BinaryenRemUInt64, BinaryenRemUInt32), a, b) end elseif matchgr(node, :checked_urem_int) do a, b binaryfun(ctx, idx, (BinaryenRemUInt64, BinaryenRemUInt32), a, b) end elseif matchgr(node, :add_float) do a, b binaryfun(ctx, idx, (BinaryenAddFloat64, BinaryenAddFloat32), a, b) end elseif matchgr(node, :add_float_fast) do a, b binaryfun(ctx, idx, (BinaryenAddFloat64, BinaryenAddFloat32), a, b) end elseif matchgr(node, :sub_float) do a, b binaryfun(ctx, idx, (BinaryenSubFloat64, BinaryenSubFloat32), a, b) end elseif matchgr(node, :mul_float) do a, b binaryfun(ctx, idx, (BinaryenMulFloat64, BinaryenMulFloat32), a, b) end elseif matchgr(node, :mul_float_fast) do a, b binaryfun(ctx, idx, (BinaryenMulFloat64, BinaryenMulFloat32), a, b) end elseif matchgr(node, :muladd_float) do a, b, c ab = BinaryenBinary(ctx.mod, sizeof(roottype(ctx, a)) < 8 ? BinaryenMulFloat32() : BinaryenMulFloat64(), _compile(ctx, a), _compile(ctx, b)) binaryfun(ctx, idx, (BinaryenAddFloat64, BinaryenAddFloat32), c, Pass(ab), adjustsizes = false) end elseif matchgr(node, :fma_float) do a, b, c ab = BinaryenBinary(ctx.mod, sizeof(roottype(ctx, a)) < 8 ? BinaryenMulFloat32() : BinaryenMulFloat64(), _compile(ctx, a), _compile(ctx, b)) binaryfun(ctx, idx, (BinaryenAddFloat64, BinaryenAddFloat32), Pass(ab), c) end elseif matchgr(node, :div_float) do a, b binaryfun(ctx, idx, (BinaryenDivFloat64, BinaryenDivFloat32), a, b) end elseif matchgr(node, :div_float_fast) do a, b binaryfun(ctx, idx, (BinaryenDivFloat64, BinaryenDivFloat32), a, b) end elseif matchgr(node, :eq_int) do a, b binaryfun(ctx, idx, (BinaryenEqInt64, BinaryenEqInt32), a, b) end elseif matchgr(node, :(===)) do a, b if roottype(ctx, a) <: Integer binaryfun(ctx, idx, (BinaryenEqInt64, BinaryenEqInt32), a, b) elseif roottype(ctx, a) <: AbstractFloat binaryfun(ctx, idx, (BinaryenEqFloat64, BinaryenEqFloat32), a, b) # elseif roottype(ctx, a) <: Union{String, Symbol} # x = BinaryenStringEq(ctx.mod, BinaryenStringEqEqual(), _compile(ctx, a), _compile(ctx, b)) # setlocal!(ctx, idx, x) else x = BinaryenRefEq(ctx.mod, _compile(ctx, a), _compile(ctx, b)) setlocal!(ctx, idx, x) end end elseif matchgr(node, :ne_int) do a, b binaryfun(ctx, idx, (BinaryenNeInt64, BinaryenNeInt32), a, b) end elseif matchgr(node, :slt_int) do a, b binaryfun(ctx, idx, (BinaryenLtSInt64, BinaryenLtSInt32), a, b) end elseif matchgr(node, :ult_int) do a, b binaryfun(ctx, idx, (BinaryenLtUInt64, BinaryenLtUInt32), a, b) end elseif matchgr(node, :sle_int) do a, b binaryfun(ctx, idx, (BinaryenLeSInt64, BinaryenLeSInt32), a, b) end elseif matchgr(node, :ule_int) do a, b binaryfun(ctx, idx, (BinaryenLeUInt64, BinaryenLeUInt32), a, b) end elseif matchgr(node, :eq_float) do a, b binaryfun(ctx, idx, (BinaryenEqFloat64, BinaryenEqFloat32), a, b) end elseif matchgr(node, :fpiseq) do a, b binaryfun(ctx, idx, (BinaryenEqFloat64, BinaryenEqFloat32), a, b) end elseif matchgr(node, :ne_float) do a, b binaryfun(ctx, idx, (BinaryenNeFloat64, BinaryenNeFloat32), a, b) end elseif matchgr(node, :lt_float) do a, b binaryfun(ctx, idx, (BinaryenLtFloat64, BinaryenLtFloat32), a, b) end elseif matchgr(node, :le_float) do a, b binaryfun(ctx, idx, (BinaryenLeFloat64, BinaryenLeFloat32), a, b) end elseif matchgr(node, :and_int) do a, b binaryfun(ctx, idx, (BinaryenAndInt64, BinaryenAndInt32), a, b) end elseif matchgr(node, :or_int) do a, b binaryfun(ctx, idx, (BinaryenOrInt64, BinaryenOrInt32), a, b) end elseif matchgr(node, :xor_int) do a, b binaryfun(ctx, idx, (BinaryenXorInt64, BinaryenXorInt32), a, b) end elseif matchgr(node, :shl_int) do a, b binaryfun(ctx, idx, (BinaryenShlInt64, BinaryenShlInt32), a, b) end elseif matchgr(node, :lshr_int) do a, b binaryfun(ctx, idx, (BinaryenShrUInt64, BinaryenShrUInt32), a, b) end elseif matchgr(node, :ashr_int) do a, b binaryfun(ctx, idx, (BinaryenShrSInt64, BinaryenShrSInt32), a, b) end elseif matchgr(node, :ctpop_int) do a, b binaryfun(ctx, idx, (BinaryenPopcntInt64, BinaryenPopcntInt32), a, b) end elseif matchgr(node, :ctpop_int) do a, b binaryfun(ctx, idx, (BinaryenPopcntInt64, BinaryenPopcntInt32), a, b) end elseif matchgr(node, :copysign_float) do a, b binaryfun(ctx, idx, (BinaryenCopySignInt64, BinaryenCopySignInt32), a, b) end elseif matchgr(node, :not_int) do a Ta = roottype(ctx, a) if sizeof(Ta) == 8 x = BinaryenBinary(ctx.mod, BinaryenXorInt64(), _compile(ctx, a), _compile(ctx, Int64(-1))) if ssatype(ctx, idx) <: Bool x = BinaryenBinary(ctx.mod, BinaryenAndInt64(), x, _compile(ctx, UInt64(1))) end else x = BinaryenBinary(ctx.mod, BinaryenXorInt32(), _compile(ctx, a), _compile(ctx, Int32(-1))) if ssatype(ctx, idx) <: Bool x = BinaryenBinary(ctx.mod, BinaryenAndInt32(), x, _compile(ctx, UInt32(1))) end end setlocal!(ctx, idx, x) end elseif matchgr(node, :ctlz_int) do a unaryfun(ctx, idx, (BinaryenClzInt64, BinaryenClzInt32), a) end elseif matchgr(node, :cttz_int) do a unaryfun(ctx, idx, (BinaryenCtzInt64, BinaryenCtzInt32), a) end ## I'm not sure these are right elseif matchgr(node, :sext_int) do a, b t = (roottype(ctx, a), roottype(ctx, b)) sizeof(t[1]) == 8 && sizeof(t[2]) == 1 ? unaryfun(ctx, idx, (BinaryenExtendS8Int64,), b) : sizeof(t[1]) == 8 && sizeof(t[2]) == 2 ? unaryfun(ctx, idx, (BinaryenExtendS16Int64,), b) : sizeof(t[1]) == 8 && sizeof(t[2]) == 4 ? unaryfun(ctx, idx, (BinaryenExtendSInt32,), b) : sizeof(t[1]) == 4 && sizeof(t[2]) == 1 ? unaryfun(ctx, idx, (BinaryenExtendS8Int32,), b) : sizeof(t[1]) == 4 && sizeof(t[2]) == 2 ? unaryfun(ctx, idx, (BinaryenExtendS16Int32,), b) : error("Unsupported `sext_int` types $t") end elseif matchgr(node, :zext_int) do a, b t = (roottype(ctx, a), roottype(ctx, b)) sizeof(t[1]) == 4 && sizeof(t[2]) <= 4 ? b : sizeof(t[1]) == 8 && sizeof(t[2]) <= 4 ? unaryfun(ctx, idx, (BinaryenExtendUInt32,), b) : error("Unsupported `zext_int` types $t") end elseif matchgr(node, :trunc_int) do a, b t = (roottype(ctx, a), roottype(ctx, b)) t == (Int32, Int64) ? unaryfun(ctx, idx, (BinaryenWrapInt64,), b) : t == (Int32, UInt64) ? unaryfun(ctx, idx, (BinaryenWrapInt64,), b) : t == (UInt32, UInt64) ? unaryfun(ctx, idx, (BinaryenWrapInt64,), b) : t == (UInt32, Int64) ? unaryfun(ctx, idx, (BinaryenWrapInt64,), b) : t == (UInt8, UInt64) ? unaryfun(ctx, idx, (BinaryenWrapInt64,), b) : t == (UInt8, Int64) ? unaryfun(ctx, idx, (BinaryenWrapInt64,), b) : error("Unsupported `trunc_int` types $t") end elseif matchgr(node, :flipsign_int) do a, b Ta = eltype(roottype(ctx, a)) Tb = eltype(roottype(ctx, b)) # check the sign of b if sizeof(Ta) == 8 isnegative = BinaryenUnary(ctx.mod, BinaryenWrapInt64(), BinaryenBinary(ctx.mod, BinaryenShrUInt64(), _compile(ctx, b), _compile(ctx, UInt64(63)))) x = BinaryenIf(ctx.mod, isnegative, BinaryenBinary(ctx.mod, BinaryenMulInt64(), _compile(ctx, a), _compile(ctx, Int64(-1))), _compile(ctx, a)) else isnegative = BinaryenBinary(ctx.mod, BinaryenShrUInt32(), _compile(ctx, b), _compile(ctx, UInt32(31))) x = BinaryenIf(ctx.mod, isnegative, BinaryenBinary(ctx.mod, BinaryenMulInt32(), _compile(ctx, a), _compile(ctx, Int32(-1))), _compile(ctx, a)) end setlocal!(ctx, idx, x) end elseif matchgr(node, :fptoui) do a, b t = (roottype(ctx, a), roottype(ctx, b)) t == (UInt64, Float32) ? unaryfun(ctx, idx, (BinaryenTruncSatUFloat32ToInt64,), b) : t == (UInt64, Float64) ? unaryfun(ctx, idx, (BinaryenTruncSatUFloat64ToInt64,), b) : t == (UInt32, Float32) ? unaryfun(ctx, idx, (BinaryenTruncSatUFloat32ToInt32,), b) : t == (UInt32, Float64) ? unaryfun(ctx, idx, (BinaryenTruncSatUFloat64ToInt32,), b) : error("Unsupported `fptoui` types") end elseif matchgr(node, :fptosi) do a, b t = (roottype(ctx, a), roottype(ctx, b)) t == (Int64, Float32) ? unaryfun(ctx, idx, (BinaryenTruncSatSFloat32ToInt64,), b) : t == (Int64, Float64) ? unaryfun(ctx, idx, (BinaryenTruncSatSFloat64ToInt64,), b) : t == (Int32, Float32) ? unaryfun(ctx, idx, (BinaryenTruncSatSFloat32ToInt32,), b) : t == (Int32, Float64) ? unaryfun(ctx, idx, (BinaryenTruncSatSFloat64ToInt32,), b) : error("Unsupported `fptosi` types") end elseif matchgr(node, :uitofp) do a, b t = (roottype(ctx, a), roottype(ctx, b)) t == (Float64, UInt32) ? unaryfun(ctx, idx, (BinaryenConvertUInt32ToFloat64,), b) : t == (Float64, UInt64) ? unaryfun(ctx, idx, (BinaryenConvertUInt64ToFloat64,), b) : t == (Float32, UInt32) ? unaryfun(ctx, idx, (BinaryenConvertUInt32ToFloat32,), b) : t == (Float32, UInt64) ? unaryfun(ctx, idx, (BinaryenConvertUInt64ToFloat32,), b) : error("Unsupported `uitofp` types") end elseif matchgr(node, :sitofp) do a, b t = (roottype(ctx, a), roottype(ctx, b)) t == (Float64, Int32) ? unaryfun(ctx, idx, (BinaryenConvertSInt32ToFloat64,), b) : t == (Float64, Int64) ? unaryfun(ctx, idx, (BinaryenConvertSInt64ToFloat64,), b) : t == (Float32, Int32) ? unaryfun(ctx, idx, (BinaryenConvertSInt32ToFloat32,), b) : t == (Float32, Int64) ? unaryfun(ctx, idx, (BinaryenConvertSInt64ToFloat32,), b) : error("Unsupported `sitofp` types") end elseif matchgr(node, :fptrunc) do a, b t = (roottype(ctx, a), roottype(ctx, b)) t == (Float32, Float64) ? unaryfun(ctx, idx, (BinaryenDemoteFloat64,), b) : error("Unsupported `fptrunc` types") end elseif matchgr(node, :fpext) do a, b t = (roottype(ctx, a), roottype(ctx, b)) t == (Float64, Float32) ? unaryfun(ctx, idx, (BinaryenPromoteFloat32,), b) : error("Unsupported `fpext` types") end elseif matchgr(node, :ifelse) do cond, a, b binaryenfun(ctx, idx, BinaryenIf, cond, a, b) end elseif matchgr(node, :abs_float) do a unaryfun(ctx, idx, (BinaryenAbsFloat64, BinaryenAbsFloat32), a) end elseif matchgr(node, :ceil_llvm) do a unaryfun(ctx, idx, (BinaryenCeilFloat64, BinaryenCeilFloat32), a) end elseif matchgr(node, :floor_llvm) do a unaryfun(ctx, idx, (BinaryenFloorFloat64, BinaryenFloorFloat32), a) end elseif matchgr(node, :trunc_llvm) do a unaryfun(ctx, idx, (BinaryenTruncFloat64, BinaryenTruncFloat32), a) end elseif matchgr(node, :rint_llvm) do a unaryfun(ctx, idx, (BinaryenNearestFloat64, BinaryenNearestFloat32), a) end elseif matchgr(node, :sqrt_llvm) do a unaryfun(ctx, idx, (BinaryenSqrtFloat64, BinaryenSqrtFloat32), a) end elseif matchgr(node, :sqrt_llvm_fast) do a unaryfun(ctx, idx, (BinaryenSqrtFloat64, BinaryenSqrtFloat32), a) end elseif matchgr(node, :have_fma) do a setlocal!(ctx, idx, _compile(ctx, Int32(0))) end elseif matchgr(node, :bitcast) do t, val T = roottype(ctx, t) Tval = roottype(ctx, val) T == Float64 && Tval <: Integer ? unaryfun(ctx, idx, (BinaryenReinterpretInt64,), val) : T == Float32 && Tval <: Integer ? unaryfun(ctx, idx, (BinaryenReinterpretInt32,), val) : T <: Integer && sizeof(T) == 8 && Tval <: AbstractFloat ? unaryfun(ctx, idx, (BinaryenReinterpretFloat64,), val) : T <: Integer && sizeof(T) == 4 && Tval <: AbstractFloat ? unaryfun(ctx, idx, (BinaryenReinterpretFloat32,), val) : T <: Integer && Tval <: Integer ? setlocal!(ctx, idx, _compile(ctx, val)) : # T <: Integer && Tval :: Char ? unaryfun(ctx, idx, (BinaryenReinterpretInt32,), val) : error("Unsupported `bitcast` types, ($T, $Tval)") end ## TODO # ADD_I(cglobal, 2) \ ## Builtins / key functions ## elseif matchforeigncall(node, :jl_string_to_array) do args # This is just a pass-through because strings are already Vector{UInt8} setlocal!(ctx, idx, _compile(ctx, args[5])) end elseif matchforeigncall(node, :jl_array_to_string) do args # This is just a pass-through because strings are already Vector{UInt8} setlocal!(ctx, idx, _compile(ctx, args[5])) end elseif matchforeigncall(node, :_jl_symbol_to_array) do args # This is just a pass-through because Symbols are already Vector{UInt8} setlocal!(ctx, idx, _compile(ctx, args[5])) end elseif matchgr(node, :arrayref) do bool, arraywrapper, i buffer = getbuffer(ctx, arraywrapper) # signed = eT <: Signed && sizeof(eT) < 4 signed = false ## subtract one from i for zero-based indexing in WASM i = BinaryenBinary(ctx.mod, BinaryenAddInt32(), _compile(ctx, I32(i)), _compile(ctx, Int32(-1))) binaryenfun(ctx, idx, BinaryenArrayGet, buffer, i, gettype(ctx, roottype(ctx, arraywrapper)), Pass(signed)) end elseif matchgr(node, :arrayset) do bool, arraywrapper, val, i buffer = getbuffer(ctx, arraywrapper) i = BinaryenBinary(ctx.mod, BinaryenAddInt32(), _compile(ctx, I32(i)), _compile(ctx, Int32(-1))) x = _compile(ctx, val) aT = eltype(roottype(ctx, arraywrapper)) if aT == Any # Box if needed x = box(ctx, x, roottype(ctx, val)) end x = BinaryenArraySet(ctx.mod, buffer, i, x) update!(ctx, x) end elseif matchgr(node, :arraylen) do arraywrapper x = BinaryenStructGet(ctx.mod, 1, _compile(ctx, arraywrapper), C_NULL, false) if sizeof(Int) == 8 # extend to Int64 unaryfun(ctx, idx, (BinaryenExtendUInt32,), x) else setlocal!(ctx, idx, x) end end elseif matchgr(node, :arraysize) do arraywrapper, n x = BinaryenStructGet(ctx.mod, 1, _compile(ctx, arraywrapper), C_NULL, false) if sizeof(Int) == 8 # extend to Int64 unaryfun(ctx, idx, (BinaryenExtendUInt32,), x) else setlocal!(ctx, idx, x) end end elseif matchforeigncall(node, :jl_alloc_array_1d) do args elT = eltype(args[1]) size = _compile(ctx, I32(args[6])) arraytype = BinaryenTypeGetHeapType(gettype(ctx, Buffer{elT})) buffer = BinaryenArrayNew(ctx.mod, arraytype, size, _compile(ctx, default(elT))) wrappertype = BinaryenTypeGetHeapType(gettype(ctx, FakeArrayWrapper{elT})) binaryenfun(ctx, idx, BinaryenStructNew, [buffer, size], UInt32(2), wrappertype; passall = true) end elseif matchforeigncall(node, :jl_array_grow_end) do args arraywrapper = args[5] elT = eltype(roottype(ctx, args[5])) arraytype = gettype(ctx, Buffer{elT}) arrayheaptype = BinaryenTypeGetHeapType(arraytype) arraywrappertype = gettype(ctx, Vector{elT}) _arraywrapper = _compile(ctx, arraywrapper) buffer = getbuffer(ctx, args[5]) bufferlen = BinaryenArrayLen(ctx.mod, buffer) extralen = _compile(ctx, I32(args[6])) arraylen = BinaryenStructGet(ctx.mod, 1, _arraywrapper, C_NULL, false) newlen = BinaryenBinary(ctx.mod, BinaryenAddInt32(), arraylen, extralen) newbufferlen = BinaryenBinary(ctx.mod, BinaryenMulInt32(), newlen, _compile(ctx, I32(2))) neednewbuffer = BinaryenBinary(ctx.mod, BinaryenLeUInt32(), arraylen, newlen) newbufferget = BinaryenLocalGet(ctx.mod, ctx.localidx, arraytype) newbufferblock = [ BinaryenLocalSet(ctx.mod, ctx.localidx, BinaryenArrayNew(ctx.mod, arrayheaptype, newbufferlen, _compile(ctx, default(elT)))), BinaryenArrayCopy(ctx.mod, newbufferget, _compile(ctx, I32(0)), buffer, _compile(ctx, I32(0)), _compile(ctx, arraylen)), BinaryenStructSet(ctx.mod, 0, _arraywrapper, newbufferget), ] push!(ctx.locals, arraytype) ctx.localidx += 1 x = BinaryenIf(ctx.mod, neednewbuffer, BinaryenBlock(ctx.mod, "newbuff", newbufferblock, length(newbufferblock), BinaryenTypeAuto()), C_NULL) update!(ctx, x) x = BinaryenStructSet(ctx.mod, 1, _arraywrapper, newlen) update!(ctx, x) end elseif matchforeigncall(node, :jl_array_del_end) do args arraywrapper = _compile(ctx, args[5]) i = _compile(ctx, I32(args[6])) arraylen = BinaryenStructGet(ctx.mod, 1, arraywrapper, C_NULL, false) newlen = BinaryenBinary(ctx.mod, BinaryenSubInt32(), arraylen, i) x = BinaryenStructSet(ctx.mod, 1, arraywrapper, newlen) update!(ctx, x) end elseif matchforeigncall(node, :_jl_array_copy) do args srcbuffer = getbuffer(ctx, args[5]) destbuffer = getbuffer(ctx, args[6]) n = args[7] x = BinaryenArrayCopy(ctx.mod, destbuffer, _compile(ctx, I32(0)), srcbuffer, _compile(ctx, I32(0)), _compile(ctx, n)) update!(ctx, x) end elseif matchforeigncall(node, :_jl_array_copyto) do args destbuffer = getbuffer(ctx, args[5]) doffs = _compile(ctx, args[6]) srcbuffer = getbuffer(ctx, args[7]) soffs = _compile(ctx, args[8]) n = _compile(ctx, args[9]) x = BinaryenArrayCopy(ctx.mod, destbuffer, doffs, srcbuffer, soffs, n) update!(ctx, x) setlocal!(ctx, idx, _compile(ctx, args[5])) end elseif matchforeigncall(node, :jl_object_id) do args setlocal!(ctx, idx, _compile(ctx, objectid(_compile(ctx, args[5])))) end elseif matchgr(node, :getfield) || matchcall(node, getfield) x = node.args[2] index = node.args[3] T = basetype(ctx, x) if T <: NTuple # unsigned = eltype(T) <: Unsigned unsigned = true ## subtract one from i for zero-based indexing in WASM i = BinaryenBinary(ctx.mod, BinaryenAddInt32(), _compile(ctx, I32(index)), _compile(ctx, Int32(-1))) binaryenfun(ctx, idx, BinaryenArrayGet, _compile(ctx, x), Pass(i), gettype(ctx, eltype(T)), Pass(!unsigned)) elseif roottype(ctx, index) <: Integer # if length(node.args) == 3 # 2-arg version eT = fieldtypeskept(T)[index] # unsigned = eT <: Unsigned unsigned = true binaryenfun(ctx, idx, BinaryenStructGet, UInt32(index - 1), _compile(ctx, x), gettype(ctx, eT), !unsigned, passall = true) # else # 3-arg version # end else field = index nT = T <: Type ? DataType : T # handle Types index = UInt32(findfirst(x -> x == field.value, fieldskept(nT)) - 1) eT = Base.datatype_fieldtypes(nT)[index + 1] # unsigned = eT <: Unsigned unsigned = true binaryenfun(ctx, idx, BinaryenStructGet, index, _compile(ctx, x), gettype(ctx, eT), !unsigned, passall = true) end ## 3-arg version of getfield for integer field access elseif matchgr(node, :getfield) do x, index, bool T = roottype(ctx, x) if T <: NTuple # unsigned = eltype(T) <: Unsigned unsigned = true ## subtract one from i for zero-based indexing in WASM i = BinaryenBinary(ctx.mod, BinaryenAddInt32(), _compile(ctx, I32(index)), _compile(ctx, Int32(-1))) binaryenfun(ctx, idx, BinaryenArrayGet, _compile(ctx, x), Pass(i), gettype(ctx, eltype(T)), Pass(!unsigned)) else eT = Base.datatype_fieldtypes(T)[_compile(ctx, index)] # unsigned = eT <: Unsigned unsigned = true binaryenfun(ctx, idx, BinaryenStructGet, UInt32(index - 1), _compile(ctx, x), gettype(ctx, eT), !unsigned, passall = true) end end elseif matchgr(node, :setfield!) do x, field, value if field isa QuoteNode && field.value isa Symbol T = roottype(ctx, x) index = UInt32(findfirst(x -> x == field.value, fieldskept(T)) - 1) elseif field isa Integer index = UInt32(field) else error("setfield! indexing with $field is not supported in $node.") end x = BinaryenStructSet(ctx.mod, index, _compile(ctx, x), _compile(ctx, value)) update!(ctx, x) end elseif node isa Expr && (node.head == :new || (node.head == :call && node.args[1] isa GlobalRef && node.args[1].name == :tuple)) nargs = UInt32(length(node.args) - 1) args = [_compile(ctx, x) for x in node.args[2:end]] jtype = ssatype(ctx, idx) if jtype isa GlobalRef jtype = jtype.mod.eval(jtype.name) end type = BinaryenTypeGetHeapType(gettype(ctx, jtype)) # BinaryenModuleSetTypeName(ctx.mod, type, string(jtype)) if jtype <: NTuple values = [_compile(ctx, v) for v in node.args[2:end]] N = Int32(length(node.args) - 1) binaryenfun(ctx, idx, BinaryenArrayNewFixed, type, values, N; passall = true) else x = BinaryenStructNew(ctx.mod, args, nargs, type) binaryenfun(ctx, idx, BinaryenStructNew, args, nargs, type; passall = true) # for (i,name) in enumerate(fieldnames(jtype)) # BinaryenModuleSetFieldName(ctx.mod, type, i - 1, string(name)) # end end elseif node isa Expr && node.head == :call && node.args[1] isa GlobalRef && node.args[1].name == :tuple ## need to cover NTuple case -> fixed array T = ssatype(ctx, idx) if T <: NTuple arraytype = BinaryenTypeGetHeapType(gettype(ctx, typeof(x))) values = [_compile(ctx, v) for v in node.args[2:end]] N = _compile(ctx, Int32(length(node.args) - 1)) binaryenfun(ctx, idx, BinaryenArrayNewFixed, arraytype, values, N; passall = true) else nargs = UInt32(length(node.args) - 1) args = [_compile(ctx, x) for x in node.args[2:end]] jtype = node.args[1] type = BinaryenTypeGetHeapType(gettype(ctx, jtype)) x = BinaryenStructNew(ctx.mod, args, nargs, type) binaryenfun(ctx, idx, BinaryenStructNew, args, nargs, type; passall = true) end elseif node isa Expr && node.head == :call && ((node.args[1] isa GlobalRef && node.args[1].name == :llvmcall) || node.args[1] == Core.Intrinsics.llvmcall) jscode = node.args[2] internalfun = jscode[1] == '$' jlrettype = eval(node.args[3]) rettype = gettype(ctx, jlrettype) if jlrettype == Nothing rettype = gettype(ctx, Union{}) end typeparameters = node.args[4].parameters name = internalfun ? jscode[2:end] : validname(string(jscode, jlrettype, typeparameters...)) sig = node.args[5:end] jparams = [gettype(ctx, T) for T in typeparameters] bparams = BinaryenTypeCreate(jparams, length(jparams)) args = [_compile(ctx, x) for x in sig] if !internalfun if !haskey(ctx.imports, name) BinaryenAddFunctionImport(ctx.mod, name, "js", jscode, bparams, rettype) ctx.imports[name] = jscode elseif ctx.imports[name] != name # error("Mismatch in llvmcall import for $name: $sig vs. $(ctx.imports[name]).") end end x = BinaryenCall(ctx.mod, name, args, length(args), rettype) if jlrettype == Nothing push!(ctx.body, x) else setlocal!(ctx, idx, x) end #= `invoke` is one of the toughest parts of compilation. Cases that must be handled include: * Variable arguments: We pass these as the last argument as a tuple. * Callable struct / closure: We pass these as the first argument if it's not a toplevel function. If it's top level, then the struct is stored as a global variable. * Keyword arguments: These come in as the first argument after the function/callable struct argument. Notes: * The first argument is the function itself. Use that for callable structs. We remove it if it's not callable. * If an argument isn't used (including types or other non-data arguments), it is not included in the argument list. This might be weird for top-level definitions, so it's not done there (but might cause issues). =# elseif node isa Expr && node.head == :invoke T = node.args[1].specTypes.parameters[1] if isa(DomainError, T) || isa(DimensionMismatch, T) || isa(InexactError, T) || isa(ArgumentError, T) || isa(OverflowError, T) || isa(AssertionError, T) || isa(Base.throw_domerr_powbysq, T) || isa(Core.throw_inexacterror, T) || isa(Base.Math.throw_complex_domainerror, T) # skip errors continue end argtypes = [basetype(ctx, x) for x in node.args[2:end]] # Get the specialized method for this invocation TT = Tuple{argtypes...} match = Base._which(TT) # mi = Core.Compiler.specialize_method(match; preexisting=true) mi = Core.Compiler.specialize_method(match) sig = mi.specTypes newci = Base.code_typed_by_type(mi.specTypes, interp = StaticInterpreter())[1][1] n2 = node.args[2] newfun = n2 isa QuoteNode ? n2.value : n2 isa GlobalRef ? Core.eval(n2.mod, n2.name) : n2 newctx = CompilerContext(ctx, newci) callable = callablestruct(newctx) argstart = callable ? 2 : 3 newsig = newci.parent.specTypes n = length(node.args) if newci.parent.def.isva # varargs na = length(newci.slottypes) - (callable ? 1 : 2) jargs = [node.args[i] for i in argstart:argstart+na-1 if argused(newctx, i-1)] # up to the last arg which is a vararg args = [_compile(ctx, x) for x in jargs] nva = length(newci.slottypes[end].parameters) push!(args, _compile(ctx, tuple((node.args[i] for i in n-nva+1:n)...))) np = newsig.parameters newsig = Tuple{np[1:end-nva]..., Tuple{np[end-nva+1:end]...}} else jargs = [node.args[i] for i in argstart:n if argused(newctx, i-1)] args = [_compile(ctx, x) for x in jargs] end if haskey(ctx.names, newsig) name = ctx.names[newsig] else name = validname(string("julia_", node.args[1].def.name, newsig.parameters[2:end]...))[1:min(end,255)] ctx.sigs[name] = newsig ctx.names[newsig] = name newci.parent.specTypes = newsig debug(:offline) && _debug_ci(newctx, ctx) compile_method(newctx, name) end # `set` controls whether a local variable is set to the return value. # ssarettype == Any normally means that the return type isn't used. # It can sometimes be Any if the method really does return Any, # so compare against the real return type. wrettype = gettype(ctx, newci.rettype == Nothing ? Union{} : newci.rettype) ssarettype = ssatype(ctx, idx) drop = ssarettype == Any && newci.rettype != Nothing set = ssarettype != Nothing && (ssarettype != Any || ssarettype == newci.rettype) setlocal!(ctx, idx, BinaryenCall(ctx.mod, name, args, length(args), wrettype); set, drop) elseif node isa Expr && node.head == :call && node.args[1] isa GlobalRef && node.args[1].name == :isa # val isa T T = node.args[3] wT = gettype(ctx, T) # do I need heap type here? val = _compile(ctx, node.args[2]) x = BinaryenRefTest(ctx.mod, val, wT) setlocal!(ctx, idx, x) # DECLARE_BUILTIN(applicable); # DECLARE_BUILTIN(_apply_iterate); # DECLARE_BUILTIN(_apply_pure); # DECLARE_BUILTIN(apply_type); # DECLARE_BUILTIN(_call_in_world); # DECLARE_BUILTIN(_call_in_world_total); # DECLARE_BUILTIN(_call_latest); # DECLARE_BUILTIN(replacefield); # DECLARE_BUILTIN(const_arrayref); # DECLARE_BUILTIN(_expr); # DECLARE_BUILTIN(fieldtype); # DECLARE_BUILTIN(is); # DECLARE_BUILTIN(isa); # DECLARE_BUILTIN(isdefined); # DECLARE_BUILTIN(issubtype); # DECLARE_BUILTIN(modifyfield); # DECLARE_BUILTIN(nfields); # DECLARE_BUILTIN(sizeof); # DECLARE_BUILTIN(svec); # DECLARE_BUILTIN(swapfield); # DECLARE_BUILTIN(throw); # DECLARE_BUILTIN(typeassert); # DECLARE_BUILTIN(_typebody); # DECLARE_BUILTIN(typeof); # DECLARE_BUILTIN(_typevar); # DECLARE_BUILTIN(donotdelete); # DECLARE_BUILTIN(compilerbarrier); # DECLARE_BUILTIN(getglobal); # DECLARE_BUILTIN(setglobal); # DECLARE_BUILTIN(finalizer); # DECLARE_BUILTIN(_compute_sparams); # DECLARE_BUILTIN(_svec_ref); ## Other ## elseif node isa GlobalRef setlocal!(ctx, idx, getglobal(ctx, node.mod, node.name)) elseif node isa Expr # ignore other expressions for now # println("----------------------------------------------------------------") # @show idx node # dump(node) # println("----------------------------------------------------------------") else error("Unsupported Julia construct $node") end end if haskey(phis, idx) for (i, var) in phis[idx] push!(ctx.body, BinaryenLocalSet(ctx.mod, ctx.varmap[i], _compile(ctx, var))) end end body = BinaryenBlock(ctx.mod, "body", ctx.body, length(ctx.body), BinaryenTypeAuto()) return body end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
7057
export compile """ compile(funs::Tuple...; filepath = "foo.wasm", jspath = filepath * ".js", names = nothing, validate = true, optimize = false, experimental = true) Compile the methods defined by `funs`. Each function definition to be compiled is a tuple with the first entry as the function followed by argument types. Keyword arguments include: * `filepath`--File path for the WebAssembly binary. The path will be created if it doesn't exist. * `jspath`--File path for the extra JavaScript file that defines `jsexports` which are the JS functions imported into WebAssembly (those normally defined by [`@jscall`](@ref)). * `names`--A vector or other indexable object with names of functions that are compiled. It's length must equal the length of `funs`. * `validate`--Apply Binaryen's validation tests. * `optimize`--Apply Binaryen's default optimization passes (still shaky). * `experimental`--Use experimental WebAssembly features. `compile` also writes a WebAssembly text tile to the same path as `filepath` with an added ".wat" extension. Examples: compile((exp, Float64), filepath = "exp.wasm", optimize = true) compile((acos, Float64), (asin, Float64), filepath = "trigs.wasm", optimize = true) """ function compile(funs::Tuple...; filepath = "foo.wasm", jspath = filepath * ".js", validate = true, optimize = false, experimental = false, names = nothing) mkpath(dirname(filepath)) cis = Core.CodeInfo[] dummyci = code_typed(() -> nothing, Tuple{})[1].first ctx = CompilerContext(dummyci; experimental) debug(:offline) && _debug_ci(ctx) # BinaryenModuleSetFeatures(ctx.mod, BinaryenFeatureReferenceTypes() | BinaryenFeatureGC() | (experimental ? BinaryenFeatureStrings() : 0)) BinaryenModuleSetFeatures(ctx.mod, BinaryenFeatureAll()) BinaryenModuleAutoDrop(ctx.mod) # Create CodeInfo's, and fill in names first for (i, funtpl) in enumerate(funs) tt = length(funtpl) > 1 ? Base.to_tuple_type(funtpl[2:end]) : Tuple{} # isconcretetype(tt) || error("input type signature $tt for $(funtpl[1]) is not concrete") ci = code_typed(funtpl[1], tt, interp = StaticInterpreter())[1].first push!(cis, ci) if names === nothing name = string(funtpl[1]) # [1:min(end,20)] else name = string(names[i]) end sig = ci.parent.specTypes ctx.sigs[name] = sig ctx.names[sig] = name # end # # Compile funs # for i in eachindex(cis) fun = funs[i][1] newctx = CompilerContext(ctx, cis[i], toplevel = true) if callablestruct(newctx) newctx.gfun = getglobal(newctx, fun) end debug(:offline) && _debug_ci(newctx, ctx) compile_method(newctx, name, exported = true) end BinaryenModuleAutoDrop(ctx.mod) debug(:offline) && _debug_module(ctx) debug(:inline) && BinaryenModulePrint(ctx.mod) validate && BinaryenModuleValidate(ctx.mod) # BinaryenSetShrinkLevel(0) # BinaryenSetOptimizeLevel(2) optimize && BinaryenModuleOptimize(ctx.mod) out = BinaryenModuleAllocateAndWrite(ctx.mod, C_NULL) write(filepath, unsafe_wrap(Vector{UInt8}, Ptr{UInt8}(out.binary), (out.binaryBytes,))) Libc.free(out.binary) out = BinaryenModuleAllocateAndWriteText(ctx.mod) write(filepath * ".wat", unsafe_string(out)) Libc.free(out) BinaryenModuleDispose(ctx.mod) jstext = "var jsexports = { js: {} };\n" imports = unique(values(ctx.imports)) jstext *= join(["jsexports['js']['$v'] = $v;" for v in imports], "\n") write(jspath, jstext) nothing end function sigargs(ctx, sig) sigparams = collect(sig.parameters) jparams = [gettype(ctx, sigparams[1]), (gettype(ctx, sigparams[i]) for i in 2:length(sigparams) if argused(ctx, i))...] if ctx.toplevel || !callablestruct(ctx) jparams = jparams[2:end] end return jparams end function compile_method(ctx::CompilerContext, funname; sig = ctx.ci.parent.specTypes, exported = false) # funname = ctx.names[sig] sigparams = collect(sig.parameters) jparams = [gettype(ctx, sigparams[1]), (gettype(ctx, sigparams[i]) for i in 2:length(sigparams) if argused(ctx, i))...] if ctx.toplevel || !callablestruct(ctx) jparams = jparams[2:end] end bparams = BinaryenTypeCreate(jparams, length(jparams)) rettype = gettype(ctx, ctx.ci.rettype == Nothing ? Union{} : ctx.ci.rettype) body = compile_method_body(ctx) debug(:inline) && println("---------------------------------------") debug(:inline) && @show ctx.ci.parent.def.name debug(:inline) && @show ctx.ci.parent.def debug(:inline) && @show ctx.ci debug(:inline) && @show ctx.ci.parent.def.name debug(:inline) && BinaryenExpressionPrint(body) if BinaryenGetFunction(ctx.mod, funname) == C_NULL BinaryenAddFunction(ctx.mod, funname, bparams, rettype, ctx.locals, length(ctx.locals), body) if exported BinaryenAddFunctionExport(ctx.mod, funname, funname) end end return nothing end import Core.Compiler: block_for_inst, compute_basic_blocks function compile_method_body(ctx::CompilerContext) ci = ctx.ci code = ci.code ctx.localidx += nargs(ctx) cfg = Core.Compiler.compute_basic_blocks(code) relooper = RelooperCreate(ctx.mod) # Find and collect phis phis = Dict{Int, Any}() for (idx, block) in enumerate(cfg.blocks) for stmt in block.stmts node = code[stmt] !isa(node, Core.PhiNode) && break for (i, edge) in enumerate(node.edges) blocknum = block_for_inst(cfg, Int(edge)) if !haskey(phis, blocknum) phis[blocknum] = Pair{Int64, Any}[] end push!(phis[blocknum], stmt => node.values[i]) end ctx.varmap[stmt] = ctx.localidx push!(ctx.locals, gettype(ctx, ctx.ci.ssavaluetypes[stmt])) ctx.localidx += 1 end end # Create blocks rblocks = [RelooperAddBlock(relooper, compile_block(ctx, cfg, phis, idx)) for idx in eachindex(cfg.blocks)] # Create branches for (idx, block) in enumerate(cfg.blocks) terminator = code[last(block.stmts)] if isa(terminator, Core.ReturnNode) # return never has any successors, so no branches needed elseif isa(terminator, Core.GotoNode) toblock = block_for_inst(cfg, terminator.label) RelooperAddBranch(rblocks[idx], rblocks[toblock], C_NULL, C_NULL) elseif isa(terminator, Core.GotoIfNot) toblock = block_for_inst(cfg, terminator.dest) RelooperAddBranch(rblocks[idx], rblocks[idx + 1], _compile(ctx, terminator.cond), C_NULL) RelooperAddBranch(rblocks[idx], rblocks[toblock], C_NULL, C_NULL) elseif idx < length(cfg.blocks) RelooperAddBranch(rblocks[idx], rblocks[idx + 1], C_NULL, C_NULL) end end RelooperRenderAndDispose(relooper, rblocks[1], 0) end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
1762
# This is a kludge. Logging.jl caused a crash. const _DEBUG_::Set{Symbol} = Set{Symbol}() # options are: # :inline - show stuff inline in the REPL # :offline - store stuff in WebAssemblyCompiler.DEBUG debug(x) = x in _DEBUG_ setdebug(x) = push!(_DEBUG_, x) unsetdebug(x) = delete!(_DEBUG_, x) const DEBUG = Ref{Any}() mutable struct DB def::Core.Method ci::Core.CodeInfo steps::Vector{Any} children::Vector{Any} end function _debug_ci(ctx, parent = nothing) db = DB(ctx.ci.parent.def, ctx.ci, Any[], Any[]) ctx.meta[:debug] = db if parent === nothing DEBUG[] = db else push!(parent.meta[:debug].children, db) end nothing end function _debug_module(ctx) original_stdout = stdout (rd, wr) = redirect_stdout() BinaryenModulePrint(ctx.mod) Libc.flush_cstdio() redirect_stdout(original_stdout) close(wr) s = read(rd, String) push!(ctx.meta[:debug].steps, :module => s) nothing end function _debug_binaryen(ctx, x) original_stdout = stdout (rd, wr) = redirect_stdout() BinaryenExpressionPrint(x) Libc.flush_cstdio() close(wr) redirect_stdout(original_stdout) s = read(rd, String) push!(ctx.meta[:debug].steps, :wasm => s) nothing end function _debug_line(ctx, idx, node) push!(ctx.meta[:debug].steps, :idx => idx) push!(ctx.meta[:debug].steps, :ssavalue => ssatype(ctx, idx)) push!(ctx.meta[:debug].steps, :node => node) nothing end function _debug_binaryen_get(ctx, x) original_stdout = stdout (rd, wr) = redirect_stdout() BinaryenExpressionPrint(x) Libc.flush_cstdio() close(wr) redirect_stdout(original_stdout) return read(rd, String) end macro record(e) push!(_Binaryen_, e) e end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
5362
## interpreter using Core.Compiler: AbstractInterpreter, InferenceResult, InferenceParams, InferenceState, MethodInstance, OptimizationParams, WorldView, get_world_counter using GPUCompiler: @safe_debug, AbstractCompilerParams, CodeCache, CompilerJob, methodinstance using CodeInfoTools using CodeInfoTools: resolve Base.Experimental.@MethodTable MT struct EmptyCompilerParams <: AbstractCompilerParams end struct StaticInterpreter{M} <: AbstractInterpreter global_cache::CodeCache method_table::Union{Nothing,Core.MethodTable} # Cache of inference results for this particular interpreter local_cache::Vector{InferenceResult} # The world age we're working inside of world::UInt # Parameters for inference and optimization inf_params::InferenceParams opt_params::OptimizationParams # Mixtape context mixtape::M function StaticInterpreter(; cache::CodeCache = CodeCache(), world::UInt = Base.get_world_counter(), ip::InferenceParams = Core.Compiler.InferenceParams(; unoptimize_throw_blocks=false), op::OptimizationParams = Core.Compiler.OptimizationParams(), mixtape::CompilationContext = NoContext() ) @assert world <= Base.get_world_counter() return new{typeof(mixtape)}( cache, MT, # Initially empty cache Vector{InferenceResult}(), # world age counter world, # parameters for inference and optimization ip, op, # Mixtape context mixtape ) end end Core.Compiler.InferenceParams(interp::StaticInterpreter) = interp.inf_params Core.Compiler.OptimizationParams(interp::StaticInterpreter) = interp.opt_params Core.Compiler.get_world_counter(interp::StaticInterpreter) = interp.world Core.Compiler.get_inference_cache(interp::StaticInterpreter) = interp.local_cache Core.Compiler.code_cache(interp::StaticInterpreter) = WorldView(interp.global_cache, interp.world) # No need to do any locking since we're not putting our results into the runtime cache Core.Compiler.lock_mi_inference(interp::StaticInterpreter, mi::MethodInstance) = nothing Core.Compiler.unlock_mi_inference(interp::StaticInterpreter, mi::MethodInstance) = nothing function Core.Compiler.add_remark!(interp::StaticInterpreter, sv::InferenceState, msg) # @safe_debug "Inference remark during static compilation of $(sv.linfo): $msg" end ##### ##### Pre-inference ##### function resolve_generic(a) if a isa Type && a <: Function && isdefined(a, :instance) return a.instance else return resolve(a) end end function custom_pass!(interp::StaticInterpreter, result::InferenceResult, mi::Core.MethodInstance, src) src === nothing && return src mi.specTypes isa UnionAll && return src sig = Tuple(mi.specTypes.parameters) as = map(resolve_generic, sig) if allow(interp.mixtape, mi.def.module, as...) src = transform(interp.mixtape, src, sig) end return src end function Core.Compiler.InferenceState(result::InferenceResult, cache::Symbol, interp::StaticInterpreter) world = get_world_counter(interp) src = @static if VERSION >= v"1.10.0-DEV.873" Core.Compiler.retrieve_code_info(result.linfo, world) else Core.Compiler.retrieve_code_info(result.linfo) end mi = result.linfo src = custom_pass!(interp, result, mi, src) src === nothing && return nothing Core.Compiler.validate_code_in_debug_mode(result.linfo, src, "lowered") return InferenceState(result, src, cache, interp) end Core.Compiler.may_optimize(interp::StaticInterpreter) = true Core.Compiler.may_compress(interp::StaticInterpreter) = true Core.Compiler.may_discard_trees(interp::StaticInterpreter) = true if VERSION >= v"1.7.0-DEV.577" Core.Compiler.verbose_stmt_info(interp::StaticInterpreter) = false end if isdefined(Base.Experimental, Symbol("@overlay")) using Core.Compiler: OverlayMethodTable if v"1.8-beta2" <= VERSION < v"1.9-" || VERSION >= v"1.9.0-DEV.120" Core.Compiler.method_table(interp::StaticInterpreter) = OverlayMethodTable(interp.world, interp.method_table) else Core.Compiler.method_table(interp::StaticInterpreter, sv::InferenceState) = OverlayMethodTable(interp.world, interp.method_table) end else Core.Compiler.method_table(interp::StaticInterpreter, sv::InferenceState) = WorldOverlayMethodTable(interp.world) end # semi-concrete interepretation is broken with overlays (JuliaLang/julia#47349) @static if VERSION >= v"1.9.0-DEV.1248" function Core.Compiler.concrete_eval_eligible(interp::StaticInterpreter, @nospecialize(f), result::Core.Compiler.MethodCallResult, arginfo::Core.Compiler.ArgInfo) ret = @invoke Core.Compiler.concrete_eval_eligible(interp::AbstractInterpreter, f::Any, result::Core.Compiler.MethodCallResult, arginfo::Core.Compiler.ArgInfo) ret === false && return nothing return ret end end struct StaticCompilerParams <: AbstractCompilerParams opt::Bool optlevel::Int mixtape::CompilationContext cache::CodeCache end function StaticCompilerParams(; opt = false, optlevel = Base.JLOptions().opt_level, mixtape = NoContext(), cache = CodeCache()) return StaticCompilerParams(opt, optlevel, mixtape, cache) end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
15372
export @jscall """ @jscall(fun, rettype, tt, args...) Call a JavaScript function `fun`. `fun` is a string and normally includes the JavaScript function definition. Under the hood, these use `Base.llvmcall`. All `@jscall` definitions are imported from JavaScript. `rettype`, `tt`, ang `args...` all follow the `Base.llvmcall` format. `tt` is a Tuple type (not a regular Tuple). Arguments are converted to the types specified in `tt`. The following types can be included: `String`, `Int64`, `Int32`, `UInt64`, `UInt32`, `Float64`, `Float32`, `Char`, `Bool`, `UInt8`, and `Int8`. For all other types, specify [`Externref`](@ref). [`Externref`](@ref) types are converted with [`JS.object`](@ref). Examples: @jscall("x => alert(x)", Nothing, Tuple{String}, x) d = @jscall("() => getElementById('someid')", Externref, Tuple{}) @jscall("d => d.innerHTML = 'hello world'", Nothing, Tuple{Externref}, d) `@jscall` is used extensively in [quirks.jl](https://github.com/tshort/WebAssemblyCompiler.jl/blob/main/src/javascript-interop.jl) and [javascript-interop.jl](https://github.com/tshort/WebAssemblyCompiler.jl/blob/main/src/javascript-interop.jl). """ macro jscall(fun, rettype, tt, args...) tp = tt.args[2:end] convertedargs = (:($_convert($(tp[i]), $a)) for (i,a) in enumerate(args)) esc(:(Base.llvmcall($fun, $rettype, $tt, $(convertedargs...)))) end _convert(::Type{T}, x) where T = Base.convert(T, x) _convert(::Type{Externref}, x) = JS.object(x) _convert(::Type{String}, x::Symbol) = x export JS module JS using ..WebAssemblyCompiler: Externref, Box, @jscall using CompTime struct JSString <: AbstractString x::Externref end JSString(s::String) = JSString(@jscall("(x) => (new TextDecoder()).decode(x)", Externref, Tuple{Externref}, object(unsafe_wrap(Vector{UInt8}, s)))) JSString(x) = JSString(@jscall("(x) => String(x)", Externref, Tuple{Externref}, object(x))) Base.String(s::JSString) = String(Vector{UInt8}(@jscall("(x) => (new TextEncoder()).encode(x)", Externref, Tuple{Externref}, s))) Base.string(s::JSString) = String(s) JSStrings = Union{String,JSString} struct JSSymbol x::Externref end JSSymbol(s::Symbol) = JSSymbol(@jscall("(x) => (new TextDecoder()).decode(x)", Externref, Tuple{Externref}, object(ccall(:_jl_symbol_to_array, Ref{Vector{UInt8}}, (Any,), s)))) arraynew(n) = @jscall("n => Array(n)", Externref, Tuple{Int32}, unsafe_trunc(Int32, n)) ## Use setindex! instead?? If so, need an ArrayRef type? _set(jsa::Externref, i::Integer, x::T) where T <: Union{Int64, Int32, UInt64, UInt32, Float64, Float32, Char, Bool, UInt8, Int8} = @jscall("(v, i, x) => v[i] = x", Nothing, Tuple{Externref, Int32, T}, jsa, Int32(i - Int32(1)), x) _set(jsa::Externref, i::Integer, x) = @jscall("(v, i, x) => v[i] = x", Nothing, Tuple{Externref, Int32, Externref}, jsa, Int32(i - Int32(1)), object(x)) _set(jsa::Externref, str::String, x::T) where T = @jscall("(v, i, x) => v[i] = x", Nothing, Tuple{Externref, Externref, T}, jsa, object(str), object(x)) _get(jsa::Externref, i::Integer, ::Type{T}) where T = @jscall("(v, i) => v[i]", T, Tuple{Externref, Int32}, jsa, Int32(i - Int32(1))) _get(jsa::Externref, str::String, ::Type{T}) where T = @jscall("(v, i) => v[i]", T, Tuple{Externref, String}, jsa, str) struct TypedArray{T} end TypedArray{Float64}(n) = @jscall("n => new Float64Array(n)", Externref, Tuple{Int32}, n) TypedArray{Float32}(n) = @jscall("n => new Float32Array(n)", Externref, Tuple{Int32}, n) TypedArray{UInt8}(n) = @jscall("n => new Uint8Array(n)", Externref, Tuple{Int32}, unsafe_trunc(Int32, n)) objectnew() = @jscall("() => ({})", Externref, Tuple{}) """ Applies JavaScript's `console.log` to show `x` in the browser log. Returns nothing. """ console_log(x::Externref) = @jscall("(x) => console.log(x)", Nothing, Tuple{Externref}, x) console_log(x::T) where {T <: Union{Int32, Float32, Float64}} = @jscall("x => console.log(x)", Nothing, Tuple{T}, x) console_log(x::Symbol) = @jscall("x => console.log(x)", Nothing, Tuple{String}, x) console_log(x) = console_log(object(x)) console_log(x::JSString) = console_log(x.x) """ Returns a DOM object based on `document.getElementById(x)`. """ getelementbyid(x) = @jscall("(x) => document.getElementById(x)", Externref, Tuple{Externref}, object(x)) """ Sets the innerHTML of the DOM object `ref` to `str`. """ sethtml(ref::Externref, str) = @jscall("(x, str) => x.innerHTML = str", Nothing, Tuple{Externref, Externref}, ref, object(str)) sethtml(id::JSStrings, str) = sethtml(getelementbyid(id), str) """ Evaluate the JavaScript string `x`. Returns an [`Externref`](@ref). """ eval(x) = @jscall("(x) => eval(x)", Externref, Tuple{Externref}, object(x)) join(x, sep = "") = JSString(@jscall("(x,sep) => x.join(sep)", Externref, Tuple{Externref, Externref}, object(x), object(sep))) function Base.Vector{T}(jsa::Externref) where T n = @jscall("x => x.length", Int32, Tuple{Externref}, jsa) v = Vector{T}(undef, n) for i in 1:n v[i] = _get(jsa, unsafe_trunc(Int32, i), T) end return v end function object(v::Vector{T}) where T <: Union{Float64, Float32, UInt8} jsa = TypedArray{T}(unsafe_trunc(Int32, length(v))) for (i, x) in enumerate(v) _set(jsa, unsafe_trunc(Int32, i), x) end return jsa end """ object(x) Return an [`Externref`](@ref) (JavaScript object) representing the Julia object `x`. This is useful for transfering arrays, named tuples, and other objects to JavaScript. The types `Int32`, `Float32`, `Float64`, `Bool`, and `Externref` are passed straight through. """ object(x::Union{Int32, Float32, Float64, Bool, Externref}) = x # object(x::Union{Int32, Float32, Float64, Bool, String, Symbol, Externref}) = x function object(v::Vector{Any}) jsa = arraynew(unsafe_trunc(Int32, length(v))) for (i, x) in enumerate(v) i = unsafe_trunc(Int32, i) if x isa Box{Float64} _set(jsa, i, x.x) elseif x isa Box{Float32} _set(jsa, i, x.x) elseif x isa Box{Int32} _set(jsa, i, x.x) elseif x isa Box{String} _set(jsa, i, object(x.x)) elseif x isa Box{JSString} _set(jsa, i, x.x.x) elseif x isa Box{Int64} _set(jsa, i, unsafe_trunc(Int32, x.x)) elseif x isa Box{Bool} _set(jsa, i, x.x) # elseif x isa Box{Symbol} # _set(jsa, i, x.x) # elseif x isa Box{Char} # _set(jsa, i, x.x) elseif x isa Vector{Any} _set(jsa, i, object(x)) end end return jsa end # function object(v::Vector{T}) where T <: Union{Int64, Int32, UInt64, UInt32, Float64, Float32, Char, Bool, UInt8, Int8} function object(v::Vector{T}) where T <: Union{Float64, Float32, UInt8} jsa = TypedArray{T}(unsafe_trunc(Int32, length(v))) for (i, x) in enumerate(v) _set(jsa, unsafe_trunc(Int32, i), x) end return jsa end object(s::String) = object(JSString(s)) object(s::JSString) = s.x object(s::Symbol) = object(JSSymbol(s)) object(s::JSSymbol) = s.x using Unrolled @inline @generated function object(nt::NamedTuple) ks = fieldnames(nt) res = Expr(:block) push!(res.args, :(jso = objectnew())) for k in ks sk = String(k) qk = QuoteNode(k) push!(res.args, :(_set(jso, $sk, object(getfield(nt, $qk))))) end push!(res.args, :(return jso)) return res end function object(tpl::Tuple) n = length(tpl) jsa = arraynew(Int32(n)) _setjsa(jsa, 1, tpl...) return jsa end @inline _setjsa(jsa, i) = nothing @inline _setjsa(jsa, i, x::T) where {T <: Union{Int64, Int32, UInt64, UInt32, Float64, Float32, Char, Bool, UInt8, Int8}} = _set(jsa, i, x) @inline _setjsa(jsa, i, x) = _set(jsa, i, object(x)) @inline function _setjsa(jsa, i, x, xs...) _setjsa(jsa, i, x) _setjsa(jsa, i + 1, xs...) end # Simple IO buffer for printing to strings struct IOBuff <: IO x::Vector{Any} end IOBuff() = IOBuff(Any[]) Base.isreadable(io::IOBuff) = false Base.iswritable(io::IOBuff) = true Base.take!(b::IOBuff) = JS.join(b.x) @inline Base.print(io::IOBuff, a::String) = push!(io.x, a) @inline Base.print(io::IOBuff, a) = push!(io.x, a) @inline Base.print(io::IOBuff, a, b) = (push!(io.x, a); push!(io.x, b)) @inline Base.print(io::IOBuff, a, b, c...) = (push!(io.x, a); push!(io.x, b); print(io, c...)) @inline _string(x...) = JS.join(object(Any[x...])) # @inline _string(x) = x @inline _string(x::Symbol) = string("", x) # cheating here, but how do we make this better? """ Node(tag::String, attrs::NamedTuple, children::Tuple) Should not often be used directly. See [`h`](@ref). """ struct Node{A <: NamedTuple} tag::String attrs::A children::Vector{String} end function Node(tag::AbstractString, attrs::A, children::AbstractVector) where A Node{A}(string(tag), attrs, _collect(children)) end tag(o::Node) = getfield(o, :tag) attrs(o::Node) = getfield(o, :attrs) children(o::Node) = getfield(o, :children) @ct_enable function _collect(t::T) where T x = Vector{String}(undef, length(T.parameters)) @ct_ctrl for i = 1:(length(T.parameters)) x[@ct i] = string(t[@ct i]) end return x end attrs(kw::AbstractDict) = NamedTuple(kw) # function (o::Node)(x...; kw...) # newchildren = copy(children(o)) # for v in x # push!(newchildren, v) # end # return Node(tag(o), (;attrs(o)..., attrs(kw)...), newchildren) # end @generated function (o::Node)(x...; kw...) res = Expr(:block) push!(res.args, :(newchildren = copy(children(o)))) for i in 1:length(x) push!(res.args, :(push!(newchildren, string(x[$i])))) end push!(res.args, :(return Node(tag(o), (;attrs(o)..., attrs(kw)...), newchildren))) return res end Base.:(==)(a::Node, b::Node) = all(f(a) == f(b) for f in (tag, attrs, children)) # methods that pass through to attrs(o) Base.propertynames(o::Node) = propertynames(attrs(o)) Base.get(o::Node, name, val) = length(attrs(o)) > 0 ? hasfield(typeof(attrs(o)), Symbol(name)) ? getindex(attrs(o), Symbol(name)) : val : "" Base.haskey(o::Node, name) = haskey(attrs(o), Symbol(name)) Base.keys(o::Node) = keys(attrs(o)) # append classes Base.getproperty(o::Node, class::String) = o(class = string(Base.get(o, :class, ""), " ", class)) Base.getproperty(o::Node, class::Symbol) = o(class = string(Base.get(o, :class, ""), " ", class)) # methods that pass through to children(o) Base.lastindex(o::Node) = lastindex(children(o)) Base.getindex(o::Node, i::Union{Integer, AbstractVector{<:Integer}, Colon}) = children(o)[i] Base.setindex!(o::Node, x, i::Union{Integer, AbstractVector{<:Integer}, Colon}) = setindex!(children(o), x, i) Base.length(o::Node) = length(children(o)) Base.iterate(o::Node) = iterate(children(o)) Base.iterate(o::Node, state) = iterate(children(o), state) Base.push!(o::Node, x) = push!(children(o), x) Base.append!(o::Node, x) = append!(children(o), x) #-----------------------------------------------------------------------------# h """ h(tag, children...; kw...) h.tag(children...; kw...) h.tag."classes"(children...; kw...) Create an html node with the given `tag`, `children`, and `kw` attributes. ### Examples h.div("child", class="myclass", id="myid") # <div class="myclass" id="myid">child</div> h.div."myclass"("content") # <div class="myclass">content</div> Adapted from [Cobweb](https://github.com/JuliaComputing/Cobweb.jl). `h` uses the same API as `Cobweb.h`, except for `getindex` with symbols. For `WebAssemblyCompiler.h`, the following are equivalent: h.div."myclass"("content") h.div.myclass("content") Note that strings are not encoded, so be sure not to include problematic HTML characters like `<`. Use [`escape`](@ref) or [`esc"..."`](@ref @esc_str) to fix strings with problematic characters. """ @inline h(tag, children...; attrs...) = Node(tag, NamedTuple(attrs), _collect(children)) @inline Base.getproperty(::typeof(h), tag::Symbol) = h(_string(tag)) @inline Base.getproperty(::typeof(h), tag::String) = h(tag) Base.propertynames(::typeof(h)) = HTML5_TAGS #-----------------------------------------------------------------------------# @h const HTML5_TAGS = [:a,:abbr,:address,:area,:article,:aside,:audio,:b,:base,:bdi,:bdo,:blockquote,:body,:br,:button,:canvas,:caption,:cite,:code,:col,:colgroup,:data,:datalist,:dd,:del,:details,:dfn,:dialog,:div,:dl,:dt,:em,:embed,:fieldset,:figcaption,:figure,:footer,:form,:h1,:h2,:h3,:h4,:h5,:h6,:head,:header,:hgroup,:hr,:html,:i,:iframe,:img,:input,:ins,:kbd,:label,:legend,:li,:link,:main,:map,:mark,:math,:menu,:menuitem,:meta,:meter,:nav,:noscript,:object,:ol,:optgroup,:option,:output,:p,:param,:picture,:pre,:progress,:q,:rb,:rp,:rt,:rtc,:ruby,:s,:samp,:script,:section,:select,:slot,:small,:source,:span,:strong,:style,:sub,:summary,:sup,:svg,:table,:tbody,:td,:template,:textarea,:tfoot,:th,:thead,:time,:title,:tr,:track,:u,:ul,:var,:video,:wbr] #-----------------------------------------------------------------------------# escape escape_chars = ['&' => "&amp;", '"' => "&quot;", ''' => "&#39;", '<' => "&lt;", '>' => "&gt;"] """ escape(x) Replaces HTML-specific characters in the string `x` with encoded versions. It converts '&', '"', ''', '<', and '>'. """ function escape(x; patterns = escape_chars) for pat in patterns x = replace(x, pat) end return x end unescape(x::AbstractString) = escape(x; patterns = reverse.(escape_chars)) """ esc"..." Uses [`escape`](@ref) to fix up an HTML string. Example esc"An HTML string with problematic characters, including ', >, and &" """ macro esc_str(str) escape(str) end #-----------------------------------------------------------------------------# show (html) @inline function print_opening_tag(io::IO, o::Node; self_close::Bool = false) print(io, "<", tag(o)) _printattrs(io, pairs(attrs(o))...) # for (k,v) in pairs(attrs(o)) # v == "true" ? print(io, " ", k) : v != "false" && print(io, " ", k, "=\"", v, "\"") # # print(io, " ", k, "=\"", v, "\"") # end # self_close && Symbol(tag(o)) ∉ VOID_ELEMENTS && length(children(o)) == 0 ? # print(io, " />") : print(io, ">") nothing end @inline _printattrs(io) = nothing @inline function _printattrs(io, x) # k = string(x[1]) k = x[1] v = x[2] # v == "true" ? print(io, " ", k) : v != "false" && print(io, " ", k, "=\"", v, "\"") print(io, " ", k, "=\"", v, "\"") end @inline function _printattrs(io, x, others...) _printattrs(io, x) _printattrs(io, others...) end @inline function Base.show(io::IO, o::Node) p(args...) = print(io, args...) print_opening_tag(io, o) for x in children(o) p(x) end p("</", tag(o), ">") nothing end Base.show(io::IO, ::MIME"text/html", node::Node) = show(io, node) Base.show(io::IO, ::MIME"text/xml", node::Node) = show(io, node) Base.show(io::IO, ::MIME"application/xml", node::Node) = show(io, node) function sethtml(id, n::Node) io = IOBuff() print(io, n) str = take!(io) sethtml(id, str) nothing end function _string(n::Node) # Base.string won't work because we override it io = IOBuff() print(io, n) String(take!(io)) end @inline Base.print(io::JS.IOBuff, a::Node) = show(io, a) end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
2233
##### ##### Exports ##### # export CompilationContext, # NoContext, # allow, # transform ##### ##### Compilation context ##### # User-extended context allows parametrization of the pipeline through # our subtype of AbstractInterpreter abstract type CompilationContext end struct NoContext <: CompilationContext end @doc( """ abstract type CompilationContext end Parametrize the Mixtape pipeline by inheriting from `CompilationContext`. Similar to the context objects in [Cassette.jl](https://julia.mit.edu/Cassette.jl/stable/contextualdispatch.html). By using the interface methods [`transform`](@ref) -- the user can control different parts of the compilation pipeline. """, CompilationContext) transform(ctx::CompilationContext, b) = b transform(ctx::CompilationContext, b, sig) = transform(ctx, b) @doc( """ transform(ctx::CompilationContext, b::Core.CodeInfo)::Core.CodeInfo transform(ctx::CompilationContext, b::Core.CodeInfo, sig::Tuple)::Core.CodeInfo User-defined transform which operates on lowered `Core.CodeInfo`. There's two versions: (1) ignores the signature of the current method body under consideration and (2) provides the signature as `sig`. Transforms might typically follow a simple "swap" format using `CodeInfoTools.Builder`: ```julia function transform(::MyCtx, src) b = CodeInfoTools.Builder(b) for (k, st) in b b[k] = swap(st)) end return CodeInfoTools.finish(b) end ``` but more advanced formats are possible. For further utilities, please see [CodeInfoTools.jl](https://github.com/JuliaCompilerPlugins/CodeInfoTools.jl). """, transform) allow(f::C, args...) where {C <: CompilationContext} = false function allow(ctx::CompilationContext, mod::Module, fn, args...) return allow(ctx, mod) || allow(ctx, fn, args...) end @doc( """ allow(f::CompilationContext, args...)::Bool Determines whether the user-defined [`transform`](@ref) is allowed to look at a lowered `Core.CodeInfo` or `Core.Compiler.IRCode` instance. The user is allowed to greenlight modules: ```julia allow(::MyCtx, m::Module) == m == SomeModule ``` or even specific signatures ```julia allow(::MyCtx, fn::typeof(rand), args...) = true ``` """, allow)
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
7832
using Base.Experimental: @overlay macro print_and_throw(err) quote JS.console_log($err) end end # @overlay MT Base.sqrt(x::Float64) = @ccall BinaryenUnary.BinaryenSqrtFloat32(x::Float64)::Float64 @overlay MT Base.sin(x::Float64) = @jscall("(x) => Math.sin(x)", Float64, Tuple{Float64}, x) @overlay MT Base.cos(x::Float64) = @jscall("(x) => Math.cos(x)", Float64, Tuple{Float64}, x) @overlay MT Base.tan(x::Float64) = @jscall("(x) => Math.tan(x)", Float64, Tuple{Float64}, x) @overlay MT Base.asin(x::Float64) = @jscall("(x) => Math.asin(x)", Float64, Tuple{Float64}, x) @overlay MT Base.acos(x::Float64) = @jscall("(x) => Math.acos(x)", Float64, Tuple{Float64}, x) @overlay MT Base.atan(x::Float64) = @jscall("(x) => Math.atan(x)", Float64, Tuple{Float64}, x) @overlay MT Base.sinh(x::Float64) = @jscall("(x) => Math.sinh(x)", Float64, Tuple{Float64}, x) @overlay MT Base.cosh(x::Float64) = @jscall("(x) => Math.cosh(x)", Float64, Tuple{Float64}, x) @overlay MT Base.tanh(x::Float64) = @jscall("(x) => Math.tanh(x)", Float64, Tuple{Float64}, x) @overlay MT Base.asinh(x::Float64) = @jscall("(x) => Math.asinh(x)", Float64, Tuple{Float64}, x) @overlay MT Base.acosh(x::Float64) = @jscall("(x) => Math.acosh(x)", Float64, Tuple{Float64}, x) @overlay MT Base.atanh(x::Float64) = @jscall("(x) => Math.atanh(x)", Float64, Tuple{Float64}, x) @overlay MT Base.log(x::Float64) = @jscall("(x) => Math.log(x)", Float64, Tuple{Float64}, x) @overlay MT Base.log2(x::Float64) = @jscall("(x) => Math.log2(x)", Float64, Tuple{Float64}, x) @overlay MT Base.log10(x::Float64) = @jscall("(x) => Math.log10(x)", Float64, Tuple{Float64}, x) @overlay MT Base.log1p(x::Float64) = @jscall("(x) => Math.log1p(x)", Float64, Tuple{Float64}, x) @overlay MT Base.exp(x::Float64) = @jscall("(x) => Math.exp(x)", Float64, Tuple{Float64}, x) @overlay MT Base.expm1(x::Float64) = @jscall("(x) => Math.expm1(x)", Float64, Tuple{Float64}, x) @overlay MT Base.cbrt(x::Float64) = @jscall("(x) => Math.cbrt(x)", Float64, Tuple{Float64}, x) @overlay MT Base.sign(x::Float64) = @jscall("(x) => Math.sign(x)", Float64, Tuple{Float64}, x) @overlay MT Base.rand() = @jscall("() => Math.random()", Float64, Tuple{}) @overlay MT Base.:^(x::Float64, y::Float64) = @jscall("(x, y) => Math.pow(x)", Float64, Tuple{Float64, Float64}, x, y) @overlay MT Base.atan(x::Float64, y::Float64) = @jscall("(x, y) => Math.atan2(x, y)", Float64, Tuple{Float64, Float64}, x, y) @overlay MT Base.cconvert(::Type{String}, x::String) = x @overlay MT Base.unsafe_convert(::Type{String}, x::String) = x @overlay MT function Base.copy(src::Array{T, N}) where {T, N} dest = similar(src) @ccall _jl_array_copy(src::Array{T,N}, dest::Array{T,N}, length(src)::Int32)::Cvoid return dest end # @overlay MT Base._unsafe_copyto!(dest::Array{U, 1}, doffs::Integer, src::Array{T, 1}, soffs::Integer, n::Integer) where {T,U} = # @ccall _jl_array_copyto(dest::Array{U,1}, (doffs-1)::Int32, src::Array{T,1}, (soffs-1)::Int32, n::Int32)::Array{T,1} @overlay MT function Base._unsafe_copyto!(dest::Array, doffs::Integer, src::Array, soffs::Integer, n::Integer) @inbounds for i in 1:n dest[i+doffs-1] = src[i+soffs-1] end return dest end @overlay MT Base._copyto_impl!(dest::Array{T, 1}, doffs::Integer, src::Array{T, 1}, soffs::Integer, n::Integer) where {T} = @ccall _jl_array_copyto(dest::Array{T,1}, (doffs-1)::Int32, src::Array{T,1}, (soffs-1)::Int32, n::Int32)::Array{T,1} # @overlay MT Base.size(x::Vector) = length(x) # @overlay MT @inline Base.string(x...) = JS._string(x...) @overlay MT @inline Base.string(x...) = JS.join(JS.object(Any[x...])) @overlay MT Base.getindex(::Type{Any}, @nospecialize vals...) = unrolledgetindex(vals) using Unrolled @unroll function unrolledgetindex(vals) a = Vector{Any}(undef, length(vals)) @unroll for i = 1:length(vals) a[i] = vals[i] end return a end # @overlay MT Base.hash(x::String) = @jscall("\$hash-string", UInt64, Tuple{String}, x) @overlay MT Base.CoreLogging.current_logger_for_env(x...) = nothing @overlay MT Base.display(x) = JS.console_log(x) # Avoid some memcpy's or memcmp's @overlay MT function fill!(a::Union{Array{UInt8}, Array{Int8}}, x::Integer) val = x isa eltype(a) ? x : convert(eltype(a), x) for i in eachindex(a) a[i] = val end return nothing end @overlay MT function Base.:(==)(a::Arr, b::Arr) where {Arr <: Base.BitIntegerArray} length(a) !== length(b) && return false for i in eachindex(a) if a[i] != b[i] return false end end return true end # @overlay MT Base.:(==)(s1::String, s2::String) = Bool(@jscall("\$string-eq", Int32, Tuple{String, String}, s1, s2)) # @overlay MT Base.:(==)(s1::String, s2::String) = unsafe_wrap(Vector{UInt8}, s1) == unsafe_wrap(Vector{UInt8}, s2) @overlay MT function Base.:(==)(a::String, b::String) wa = unsafe_wrap(Vector{UInt8}, a) wb = unsafe_wrap(Vector{UInt8}, b) length(wa) !== length(wb) && return false for i in eachindex(wa) if wa[i] != wb[i] return false end end return true end # Make this match the version for AbstractArrays (removes a pointer access) @overlay MT @inline Base.dataids(A::Array) = (UInt(objectid(A)),) # I'm not sure this works: @overlay MT @inline Base.FastMath.mul_float_fast(a, b) = a * b @overlay MT @inline Base.FastMath.div_float_fast(a, b) = a / b @overlay MT @inline Base.FastMath.add_float_fast(a, b) = a + b #### Error handling struct DummyException <: Exception end @overlay MT @inline Base.error(err) = throw(DummyException()) # @overlay MT @inline Base.error(err) = JS.console_log(err) # @overlay MT @inline Base.throw(err) = JS.console_log(err) @overlay MT @inline Base.DomainError(str) = str @overlay MT @inline Base.InexactError(str...) = str @overlay MT @inline Base.ArgumentError(str) = str @overlay MT @inline Base.OverflowError(str) = str @overlay MT @inline Base.AssertionError(str) = str @overlay MT @inline Base.DimensionMismatch(str) = str # math.jl @overlay MT @inline Base.Math.throw_complex_domainerror(f::Symbol, x) = @print_and_throw "This operation requires a complex input to return a complex result" @overlay MT @inline Base.Math.throw_exp_domainerror(f::Symbol, x) = @print_and_throw "Exponentiation yielding a complex result requires a complex argument" # intfuncs.jl @overlay MT @inline Base.throw_domerr_powbysq(::Any, p) = @print_and_throw "Cannot raise an integer to a negative power" @overlay MT @inline Base.throw_domerr_powbysq(::Integer, p) = @print_and_throw "Cannot raise an integer to a negative power" @overlay MT @inline Base.throw_domerr_powbysq(::AbstractMatrix, p) = @print_and_throw "Cannot raise an integer to a negative power" @overlay MT @inline Base.__throw_gcd_overflow(a, b) = @print_and_throw "gcd overflow" # checked.jl @overlay MT @inline Base.Checked.throw_overflowerr_binaryop(op, x, y) = @print_and_throw "Binary operation overflowed" @overlay MT @inline Base.Checked.throw_overflowerr_negation(op, x, y) = @print_and_throw "Negation overflowed" @overlay MT function Base.Checked.checked_abs(x::Base.Checked.SignedInt) r = ifelse(x < 0, -x, x) r < 0 && @print_and_throw("checked arithmetic: cannot compute |x|") r end # boot.jl @overlay MT @inline Core.throw_inexacterror(f::Symbol, ::Type{T}, val) where {T} = @print_and_throw "Inexact conversion" # abstractarray.jl @overlay MT @inline Base.throw_boundserror(A, I) = @print_and_throw "Out-of-bounds array access" # trig.jl @overlay MT @inline Base.Math.sincos_domain_error(x) = @print_and_throw "sincos(x) is only defined for finite x." @overlay MT @inline Base.throw_eachindex_mismatch_indices(x...) = @print_and_throw "all inputs to eachindex must have the same indices."
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
2879
export Externref """ Externref() A type representing an external object in the host system (JavaScript). This object can be passed around, but no direct operations are supported. The object can be passed back to JavaScript methods. To convert a Julia object to an `Externref`, use [`JS.object`](@ref). """ struct Externref dummy::Int32 end Externref() = Int32(-1) struct Box{T} x::T end wtypes() = Dict{Any, BinaryenType}( Int64 => BinaryenTypeInt64(), Int32 => BinaryenTypeInt32(), UInt64 => BinaryenTypeInt64(), UInt32 => BinaryenTypeInt32(), UInt8 => BinaryenTypeInt32(), Bool => BinaryenTypeInt32(), Float64 => BinaryenTypeFloat64(), Float32 => BinaryenTypeFloat32(), # Symbol => BinaryenTypeStringref(), # String => BinaryenTypeStringref(), Externref => BinaryenTypeExternref(), Any => BinaryenTypeEqref(), Union{} => BinaryenTypeNone(), Core.TypeofBottom => BinaryenTypeNone(), ) const basictypes = [Int64, Int32, UInt64, UInt32, UInt8, Bool, Float64, Float32] mutable struct CompilerContext ## module-level context mod::BinaryenModuleRef names::Dict{DataType, String} # function signature to name sigs::Dict{String, DataType} # name to function signature imports::Dict{String, Any} wtypes::Dict{Any, BinaryenType} globals::IdDict{Any, Any} objects::IdDict{Any, Any} ## function-level context ci::Core.CodeInfo body::Vector{BinaryenExpressionRef} locals::Vector{BinaryenType} localidx::Int varmap::Dict{Int, Int} toplevel::Bool gfun::Any ## special context meta::Dict{Symbol, Any} end const experimentalwat = raw""" (module (func $hash-string (param $s stringref) (result i64) (return (i64.extend_i32_s (string.hash (local.get $s))))) (func $string-eq (param $s1 stringref) (param $s2 stringref) (result i32) (return (string.eq (local.get $s1) (local.get $s2)))) ) """ # The approach above is nice, because WAT is easier to write than Binaryen code. # But, the one above errors in NodeCall with the older version of V8. const wat = raw""" (module ) """ CompilerContext(ci::Core.CodeInfo; experimental = false) = CompilerContext(BinaryenModuleParse(experimental ? experimentalwat : wat), Dict{DataType, String}(), Dict{String, DataType}(), Dict{String, Any}(), wtypes(), IdDict{Any, Any}(), IdDict{Any, Any}(), ci, BinaryenExpressionRef[], BinaryenType[], 0, Dict{Int, Int}(), true, nothing, Dict{Symbol, Any}()) CompilerContext(ctx::CompilerContext, ci::Core.CodeInfo; toplevel = false) = CompilerContext(ctx.mod, ctx.names, ctx.sigs, ctx.imports, ctx.wtypes, ctx.globals, ctx.objects, ci, BinaryenExpressionRef[], BinaryenType[], 0, Dict{Int, Int}(), toplevel, nothing, Dict{Symbol, Any}())
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
11649
# Return the argument that function matches with the n'th slottype. # Unused arguments are skipped. # If the 1st and 4th arguments are unused, argmap(3) == 2 and argmap(6) == 4. function argmap(ctx, n) used = argsused(ctx) result = sum(used[1:n]) return result end # Number of arguments, accounting for skipped args. nargs(ctx::CompilerContext) = sum(argsused(ctx)) # A Vector{Bool} showing whether arguments are used. function argused(ctx, i) if ctx.toplevel return true end sT = ctx.ci.slottypes[i] if sT isa Core.Const sT = sT.val end notused = ctx.ci.slotflags[i] == 0x00 || sT == () || (Base.issingletontype(sT) && sT != Tuple{}) || (sT isa Type && sT <: Type) return !notused end argsused(ctx::CompilerContext) = [callablestruct(ctx) && !ctx.toplevel, (argused(ctx, i) for i in 2:length(ctx.ci.slotflags))...] function ssatype(ctx::CompilerContext, idx) ctx.ci.ssavaluetypes[idx] end # Find the type of `x`, specifically if it's a global or argument basetype(ctx::CompilerContext, x) = typeof(x) basetype(ctx::CompilerContext, x::Type{T}) where T = Type{T} basetype(ctx::CompilerContext, x::GlobalRef) = basetype(ctx, eval(x)) basetype(ctx::CompilerContext, x::Core.Argument) = ctx.ci.parent.specTypes.parameters[x.n] basetype(ctx::CompilerContext, x::Core.SSAValue) = ctx.ci.ssavaluetypes[x.id] basetype(ctx::CompilerContext, x::QuoteNode) = basetype(ctx, x.value) # same as basetype, but for types, it returns the type roottype(ctx::CompilerContext, x) = typeof(x) roottype(ctx::CompilerContext, x::Type{T}) where T = T roottype(ctx::CompilerContext, x::GlobalRef) = roottype(ctx, eval(x)) roottype(ctx::CompilerContext, x::Core.Argument) = ctx.ci.parent.specTypes.parameters[x.n] roottype(ctx::CompilerContext, x::Core.SSAValue) = ctx.ci.ssavaluetypes[x.id] roottype(ctx::CompilerContext, x::QuoteNode) = roottype(ctx, x.value) ## Matching helpers ## Matches an expression starting with a GlobalRef given by `sym`. ## This is common for intrinsics. function matchgr(fun, node, sym; combinedargs = false) match = matchgr(node, sym) if match && fun !== Nothing if !combinedargs && length(methods(fun)[1].sig.parameters) != length(node.args) return false end fargs = length(node.args) > 1 ? node.args[2:end] : [] if combinedargs fun(fargs) else fun(fargs...) end end return match end matchgr(node, sym) = node isa Expr && length(node.args) > 0 && ((node.args[1] isa GlobalRef && node.args[1].name == sym) || (node.args[1] isa Core.IntrinsicFunction && nameof(node.args[1]) == sym)) matchcall(node, sym::Symbol) = node isa Expr && node.head == :call && node.args[1] isa GlobalRef && node.args[1].name == sym matchcall(node, fun) = node isa Expr && node.head == :call && node.args[1] == fun ## Matches an expression starting with a foreigncall given by `sym`. ## This is common for intrinsics. function matchforeigncall(fun, node, sym) match = node isa Expr && node.head == :foreigncall && node.args[1] isa QuoteNode && node.args[1].value == sym if match fargs = length(node.args) > 1 ? node.args[2:end] : [] fun(fargs) end return match end function matchllvmcall(fun, node, sym) match = node isa Expr && node.head == :call && ((node.args[1] isa GlobalRef && node.args[1].name == :llvmcall) || node.args[1] == Core.Intrinsics.llvmcall) && node.args[2] == sym if match fargs = length(node.args) > 1 ? node.args[2:end] : [] fun(fargs) end return match end # Other utilities getfun(x::Core.MethodInstance) = getfun(x.def) getfun(x::Method) = getfield(x.module, basename(x)) basename(f::Function) = Base.function_name(f) basename(f::Core.IntrinsicFunction) = Symbol(unsafe_string(ccall(:jl_intrinsic_name, Cstring, (Core.IntrinsicFunction,), f))) basename(x::GlobalRef) = x.name basename(m::Core.MethodInstance) = basename(m.def) basename(m::Method) = m.name == :Type ? m.sig.parameters[1].parameters[1].name.name : m.name function gettype(ctx, type) if type <: Array && haskey(ctx.meta, :arraypass) return gettype(ctx, Buffer{eltype(type)}) end if haskey(ctx.wtypes, type) return ctx.wtypes[type] end if type isa Union || isabstracttype(type) return gettype(ctx, Any) end if type <: String return gettype(ctx, Vector{UInt8}) end if type <: Symbol return gettype(ctx, Vector{UInt8}) end if type <: Array && !haskey(ctx.meta, :arraypass) wrappertype = gettype(ctx, FakeArrayWrapper{eltype(type)}) ctx.wtypes[type] = wrappertype return wrappertype end # exit() if type <: Type return BinaryenTypeInt32() end tb = TypeBuilderCreate(1) builtheaptypes = Array{BinaryenHeapType}(undef, 1) if type <: Buffer || type <: Array || type <: NTuple elt = eltype(type) if elt == Union{} elt = Int32 end TypeBuilderSetArrayType(tb, 0, gettype(ctx, elt), isbitstype(elt) && sizeof(elt) == 1 ? BinaryenPackedTypeInt8() : BinaryenPackedTypeNotPacked(), type <: Buffer) else # Structs fieldtypes = [gettype(ctx, T) for T in fieldtypeskept(type)] n = length(fieldtypes) fieldpackedtypes = fill(BinaryenPackedTypeNotPacked(), n) fieldmutables = fill(ismutabletype(type), n) TypeBuilderSetStructType(tb, 0, fieldtypes, fieldpackedtypes, fieldmutables, n) end TypeBuilderBuildAndDispose(tb, builtheaptypes, C_NULL, C_NULL) newtype = BinaryenTypeFromHeapType(builtheaptypes[1], true) # if isconcretetype(type) && sizeof(type) > 0 # BinaryenModuleSetTypeName(ctx.mod, builtheaptypes[1], string(type)) # end # BinaryenExpressionPrint( BinaryenLocalSet(ctx.mod, 100, BinaryenLocalGet(ctx.mod, 99, newtype))) ctx.wtypes[type] = newtype return newtype end # could override this to ignore some types fieldskept(::Type{T}) where T = fieldnames(T) fieldtypeskept(::Type{T}) where T = tuple(collect(Base.datatype_fieldtypes(T))[indexin([fieldskept(T)...], [fieldnames(T)...])]...) function getglobal(ctx, gval; compiledval = nothing) id = objectid(gval) if haskey(ctx.globals, gval) return ctx.globals[gval] end T = typeof(gval) wtype = gettype(ctx, T) name = string("g", id) if BinaryenGetGlobal(ctx.mod, name) == BinaryenGlobalRef(0) cx = _compile(ctx, gval; globals = true) if cx isa Nothing cx = _compile(ctx, default(gval)) name = string("g", hash(cx)) end if BinaryenGetGlobal(ctx.mod, name) == BinaryenGlobalRef(0) BinaryenAddGlobal(ctx.mod, name, wtype, # ismutable(gval), false, isnothing(compiledval) ? cx : compiledval) # isnothing(compiledval) ? _compileglobal(ctx, gval) : compiledval) # BinaryenExpressionPrint(isnothing(compiledval) ? cx : compiledval) end end gv = BinaryenGlobalGet(ctx.mod, name, wtype) ctx.globals[gval] = gv return gv end getglobal(ctx, mod, name; compiledval = nothing) = getglobal(ctx, Core.eval(mod, name); compiledval) hasglobal(ctx, gval) = haskey(ctx.globals, gval) hasglobal(ctx, mod, name) = hasglobal(ctx, mod.eval(name)) # BROKEN function compile_inline(ctx::CompilerContext, idx, fun, tt, args, meta = nothing) tt = Base.to_tuple_type(tt) ci = code_typed(fun, tt, interp = StaticInterpreter())[1].first meta = meta !== Nothing ? Dict{Symbol, Any}(meta => 1) : Dict{Symbol, Any}() meta[:inlining] = ctx.localidx # this is the local variable used in place of the return ctx.localidx += 1 newctx = CompilerContext(ctx.mod, ctx.names, ctx.sigs, ctx.imports, ctx.wtypes, ctx.globals, ci, ctx.body, ctx.locals, ctx.localidx, ctx.varmap, meta) # TODO: how to wire in input args? for (i, a) in enumerate(args) setlocal!(newctx, idx + i - 1, _compile(newctx, a)) end return compile_method_body(newctx) end # Not used function jlinvoke(ctx::CompilerContext, idx, fun, argtypes, args...; meta = nothing) nargs = length(args) sig = Tuple{typeof(fun), argtypes...} args = [_compile(ctx, x) for x in args] if haskey(ctx.names, sig) name = ctx.names[sig] else meta = meta !== Nothing ? Dict{Symbol, Any}(meta => 1) : Dict{Symbol, Any}() newci = code_typed(fun, Base.to_tuple_type(argtypes), interp = StaticInterpreter())[1].first name = string("julia_", fun) ctx.sigs[name] = sig ctx.names[sig] = name newctx = CompilerContext(ctx.mod, ctx.names, ctx.sigs, ctx.imports, ctx.wtypes, ctx.globals, newci, BinaryenExpressionRef[], BinaryenType[], 0, Dict{Int, Int}(), meta) compile_method(newctx) end jlrettype = ssatype(ctx, idx) rettype = gettype(ctx, jlrettype) x = BinaryenCall(ctx.mod, name, args, nargs, rettype) if jlrettype !== Nothing setlocal!(ctx, idx, x) else update!(ctx, x) end end function getbuffer(ctx::CompilerContext, arraywrapper) T = roottype(ctx, arraywrapper) eT = eltype(T) return BinaryenStructGet(ctx.mod, UInt32(0), _compile(ctx, arraywrapper), gettype(ctx, Buffer{eT}), false) end function box(ctx::CompilerContext, val, valT) if valT <: Union{Int64, Int32, UInt64, UInt32, Float64, Float32, Bool, UInt8, Int8, String, Symbol} boxtype = BinaryenTypeGetHeapType(gettype(ctx, Box{valT})) return BinaryenStructNew(ctx.mod, [val], UInt32(1), boxtype) end return val end default(x::Union{Int64, Int32, UInt64, UInt32, Float64, Float32, Bool, UInt8, Int8}) = zero(x) # default(::Any) = Ref(0) default(::String) = "" default(::Symbol) = :_ default(x::Core.SimpleVector) = x default(::Vector{T}) where T = T[] default(x::Type{T}) where T <: Union{Int64, Int32, UInt64, UInt32, Float64, Float32, Bool, UInt8, Int8} = zero(x) default(x::Tuple) = x default(::Tuple{}) = () default(::Type{Any}) = Ref(0) default(::Type{String}) = "" default(::Type{Symbol}) = :_ default(::Type{Vector{T}}) where T = T[] # default(::Type{Tuple{T}}) where T = tuple((default(t) for t in T)...) default(::Type{Tuple{}}) = () function default(::Type{T}) where T fieldtypes = Base.datatype_fieldtypes(T) args = [default(ft) for ft in fieldtypes] res = T(args...) return res end function default(::Type{T}) where T <: Tuple fieldtypes = Base.datatype_fieldtypes(T) args = [default(ft) for ft in fieldtypes] res = tuple(args...) return res end # Note that this will mess up for nonstandard type constructors function default(x::T) where T args = [default(getfield(x, i)) for i in 1:fieldcount(T)] res = T(args...) return res end # from Cthulhu if isdefined(Core, :kwcall) is_kw_dispatch(meth::Method) = meth.name == :kwcall || Base.unwrap_unionall(meth.sig).parameters[1] === typeof(Core.kwcall) || !isempty(Base.kwarg_decl(meth)) else is_kw_dispatch(meth::Method) = endswith(string(meth.name), "##kw") || !isempty(Base.kwarg_decl(meth)) end validname(s::String) = replace(s, r"\W" => "_") function callablestruct(ctx::CompilerContext) sT = ctx.ci.slottypes[1] callable = !(sT isa Core.Const) && isstructtype(sT) && fieldcount(sT) > 0 return callable end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
22208
@testitem "Function arguments" begin include("setup.jl") # singleton arg @noinline fargs1a(a, b) = 2a function fargs1(x) y = fargs1a(x, sin) return x * y end compile((fargs1, Float64,); filepath = "tmp/fargs1.wasm", validate = true) # closures and callable structs struct X a::Float64 end @noinline (x::X)(w) = w * x.a function fargs2(x) y = X(2.0)(x) return x * y end compile((fargs2, Float64,); filepath = "tmp/fargs2.wasm", validate = true) # keyword args @noinline fargs3a(a; b = 2, c = 5) = a + b function fargs3(x) y = fargs3a(x, b = 1) return x * y end compile((fargs3, Float64,); filepath = "tmp/fargs3.wasm", validate = true) # keyword varargs @noinline fargs4a(a; b = 2, kw...) = a + b + kw[1] function fargs4(x) y = fargs4a(x, b = 1, c = 9) return x * y end compile((fargs4, Float64,); filepath = "tmp/fargs4.wasm", validate = true) # varargs @noinline fargs5a(a, args...) = args function fargs5(x) tup = fargs5a(x, 1, 1.1) return x * tup[2] end compile((fargs5, Float64,); filepath = "tmp/fargs5.wasm", validate = true) # varargs - 1 arg @noinline fargs6a(a, args...) = args function fargs6(x) tup = fargs6a(x, 1.0) return x * tup[1] end compile((fargs6, Float64,); filepath = "tmp/fargs6.wasm", validate = true) # varargs - 1 arg, splice @noinline fargs7a(a, args...) = (a, args...) function fargs7(x) tup = fargs7a(x, 1.0) return x * tup[1] end compile((fargs7, Float64,); filepath = "tmp/fargs7.wasm", validate = true) # varargs - 0 args @noinline fargs8a(a, args...) = (a, args...) function fargs8(x) tup = fargs8a(x) return x * tup[1] end compile((fargs8, Float64,); filepath = "tmp/fargs8.wasm", validate = true) # type error in Chrome compile((fargs8, Float64,); filepath = "tmp/fargs8.wasm", validate = true, optimize = true) end @testitem "Misc" begin include("setup.jl") function f13(x) y = Core.bitcast(UInt64, x) return Core.bitcast(Float64, y) end compile((f13, Float64); filepath = "tmp/f13.wasm", validate = true) x = 3.0 jsfun = jsfunctions((f13, Float64,)) @test f13(x) == jsfun.f13(x) end @testitem "Basics" begin include("setup.jl") function fb1(x,y) a = x + y a + 1 end # compile((fb1, Float64,Float64); filepath = "tmp/fb1.wasm") jsfun = jsfunctions((fb1, Float64,Float64)) @test fb1(3.0, 4.0) == jsfun.fb1(3.0, 4.0) jsfun = jsfunctions((fb1, Int32,Int32)) @test fb1(3, 4) == jsfun.fb1(3, 4) jsfun = jsfunctions((fb1, Float64,Int32)) @test fb1(3, 4) == jsfun.fb1(3, 4) function fb2(x,y) a = x + y a > 2 ? a + 1 : 2a end jsfun = jsfunctions((fb2, Float64,Float64)) @test fb2(3.0, 4.0) == jsfun.fb2(3.0, 4.0) @test fb2(-3.0, 4.0) == jsfun.fb2(-3.0, 4.0) jsfun = jsfunctions((fb2, Int32,Int32)) @test fb2(3, 4) == jsfun.fb2(3, 4) @test fb2(-3, 4) == jsfun.fb2(-3, 4) jsfun = jsfunctions((fb1, Float64, Float64), (fb2, Float64, Float64)) @test fb1(3.0, 4.0) == jsfun.fb1(3.0, 4.0) @test fb2(3.0, 4.0) == jsfun.fb2(3.0, 4.0) function fb3(x,y) if x > 1.0 a = x + y else a = x + y + 3 end a end jsfun = jsfunctions((fb3, Float64,Float64)) @test fb3(0.0, 4.0) == jsfun.fb3(0.0, 4.0) @test fb3(2.0, 4.0) == jsfun.fb3(2.0, 4.0) function fb4(x,y) if x > 1.0 a = x + 1.0 b = 3.0 else a = y + 2.0 b = 4.0 end a + b end jsfun = jsfunctions((fb4, Float64,Float64)) @test fb4(0.0, 4.0) == jsfun.fb4(0.0, 4.0) @test fb4(2.0, 4.0) == jsfun.fb4(2.0, 4.0) function fb5(x,y) a = 0.0 while a < 4.0 a = a + x end a + y end jsfun = jsfunctions((fb5, Float64,Float64)) @test fb5(1.0, 4.0) == jsfun.fb5(1.0, 4.0) @test fb5(5.0, 4.0) == jsfun.fb5(5.0, 4.0) @noinline twox(x) = 2x function fb7(x,y) x + twox(y) end compile((fb7, Float64,Float64); filepath = "tmp/fb7.wasm") jsfun = jsfunctions((fb7, Float64,Float64)) @test fb7(3.0, 4.0) == jsfun.fb7(3.0, 4.0) function fb8(x) 2x + twox(x) end jsfun = jsfunctions((fb7, Float64,Float64), (fb8, Float64)) @test fb7(3.0, 4.0) == jsfun.fb7(3.0, 4.0) @test fb8(3.0) == jsfun.fb8(3.0) @noinline fb9a(x, ::Type{I}) where {I} = I === Int ? 1.0 * x : 5.0 * x fb9(x) = fb9a(x, Float64) * x compile((fb9, Float64); filepath = "tmp/fb9.wasm") # jsfun = jsfunctions((fb9, Float64)) # @test fb9(3.0) == jsfun.fb9(3.0) function fb10(x) i32 = Int32(x) JS.console_log(i32) return x end compile((fb10, Int64,); filepath = "tmp/fb10.wasm") end @testitem "Arrays" begin include("setup.jl") function fa1(i) a = Array{Float64,1}(undef, Int32(3)) @inbounds a[i] = 3.0 @inbounds a[i] end compile((fa1, Int32,); filepath = "tmp/fa1.wasm") compile((fa1, Int32,); filepath = "tmp/fa1o.wasm", optimize = true) # jsfun = jsfunctions((fa1, Int32,)) # @test fa1(Int32(3)) == jsfun.fa1(Int32(3)) function fa2(i) a = Array{Float64,1}(undef, Int32(i)) unsafe_trunc(Int32, length(a)) end compile((fa2, Int32,); filepath = "tmp/fa2.wasm") # compile((fa2, Int32,); filepath = "tmp/fa2o.wasm", optimize = true) # crashes ## BROKEN # jsfun = jsfunctions((fa2, Int32,)) # @test fa2(Int32(3)) == jsfun.fa2(Int32(3)) @noinline function fa3a(x) @inbounds x[2] end function fa3(x) # a = [1.,2.,3.] a = Array{Float64, 1}(undef, 3) fa3a(a) + x end compile((fa3, Float64,); filepath = "tmp/fa3.wasm") # jsfun = jsfunctions((fa3, Float64,)) # x = 3.0 # @test fa3(x) == jsfun.fa3(x) function fa4(x) a = ones(5) b = copy(a) b[2] * x end compile((fa4, Float64,); filepath = "tmp/fa4.wasm", validate = true) # In NodeCall: Compiling function #0 failed: invalid array index. # Works in the browser. # jsfun = jsfunctions((f11, Float64,)) # x = 2.0 # @test jsfun.f11(x) == f11(x) function fa5(x) a = Array{Float64, 1}(undef, 0) push!(a, x) push!(a, x) push!(a, x) push!(a, x) push!(a, x) push!(a, 2x) return @inbounds x * a[6] end x = 2.0 compile((fa5, Float64,); filepath = "tmp/fa5.wasm", validate = true) # function fa6(x) # a = [1.,2.,3.] # a[2] + x # end # compile((fa6, Float64,); filepath = "tmp/fa6.wasm") const a = [1.,2.] @noinline function fa7!(x) a[1] = x return x end function fa7(x) fa7!(x) x end compile((fa7, Float64,); filepath = "fa7.wasm") # References to a common object function fcommon1(x) a = Float64[1.0] b = [a] c = [a] a[1] = 2.0 return x + b[1][1] + c[1][1] end compile((fcommon1, Float64,); filepath = "tmp/fcommon1.wasm", validate = true) function fa8(x) a1 = UInt8[0x01, 0x02] a2 = UInt8[0x01, 0x02] a3 = UInt8[0x01, 0x03] a1 == a2 && JS.console_log("a1 == a2") a1 == a3 && JS.console_log("a1 == a3") a1 != a3 && JS.console_log("a1 != a3") return x end compile((fa8, Float64,); filepath = "tmp/fa8.wasm", validate = true) end @testitem "Structs" begin include("setup.jl") mutable struct X{A,B,C} a::A b::B c::C end @noinline function fstructs1a(y) X(y, 2y, 3y) end function fstructs1(x) x = fstructs1a(x) x.c + 1 end # x = X(1., 2., 3.) compile((fstructs1, Float64,); filepath = "tmp/fstructs1.wasm") # jsfun = jsfunctions((fstructs1, Float64,)) # x = 3.0 # @test fstructs1(x) == jsfun.fstructs1(x) @noinline function fstructs2a(y) x = X(y, 2y, 3y) x.b = x.c x end function fstructs2(x) y = fstructs2a(x) y.c + 1 end compile((fstructs2, Float64); filepath = "tmp/fstructs2.wasm") # jsfun = jsfunctions((fstructs2, Float64,)) # x = 3.0 # @test fstructs2(x) == jsfun.fstructs2(x) function fstructs3(x) a = [1.,2.,x] a[2] + x end compile((fstructs3, Float64,); filepath = "tmp/fstructs3.wasm", validate = true) x = 3.0 # jsfun = jsfunctions((fstructs3, Float64,)) # @test fstructs3(x) == jsfun.fstructs3(x) mutable struct Y a::Float64 b end const y = Y(2.0, Any[]) push!(y.b, y) function fcircular1(x) return y.a + x end compile((fcircular1, Float64,); filepath = "tmp/fcircular1.wasm", validate = true) end @testitem "Strings" begin include("setup.jl") function fstrings1(x) a = "hello" @ccall console.log(a::String)::Cvoid return x end compile((fstrings1, Float64,); filepath = "tmp/fstrings1.wasm") ## NodeCall doesn't work because its version of Node doesn't support stringrefs. # jsfun = jsfunctions((f, Float64,)) # jsfun.f(1.0) function fstrings2(x) a = "hello" b = "world" JS.console_log(a) f() = @jscall("() => [\"a\", \"b\"]", Externref, Tuple{}) JS.console_log(JS.join(f())) y = Any[a,b] jy = JS.object(y) # JS._set(jy, Int32(1), 1.1) JS.console_log(jy) z = JS.join(jy, "-") JS.console_log(z) return x end compile((fstrings2, Float64,); filepath = "tmp/fstrings2.wasm") end @testitem "llvmcall" begin include("setup.jl") ftwox(x) = Base.llvmcall("(x) => 2*x", Float64, Tuple{Float64}, x) x = 0.5 # compile((ftwox, Float64,); filepath = "tmp/ftwox.wasm") jsfun = jsfunctions((ftwox, Float64,)) @test jsfun.ftwox(x) == 2x mysin(x) = Base.llvmcall("(x) => Math.sin(x)", Float64, Tuple{Float64}, x) # compile((mysin, Float64,); filepath = "tmp/mysin.wasm") jsfun = jsfunctions((mysin, Float64,)) x = 0.5 @test jsfun.mysin(x) == sin(x) end @testitem "Math" begin include("setup.jl") # This one calls the JavaScript version because `cos` is in a function. f(x) = cos(x) jsfun = jsfunctions((f, Float64,)) x = 0.5 @test f(x) == jsfun.f(x) # This one compiles the Julia version because `sqrt` is compiled directly. # jsfun = jsfunctions((sqrt, Float64,)) # for x in (0.5, 1.01, 3.0, 300.0) # @test sqrt(x) == jsfun.sqrt(x) # end ## These log functions used to test fine when a Symbol was represented by an Int32 value. ## Now, they fail because of the stringref used to represent Symbols. # jsfun = jsfunctions((log, Float64,)) # for x in (0.5, 1.01, 3.0, 300.0) # @test log(x) == jsfun.log(x) # end # jsfun = jsfunctions((log10, Float64,)) # for x in (0.5, 1.01, 3.0, 300.0) # @test log10(x) == jsfun.log10(x) # end jsfun = jsfunctions((muladd, Float64, Float64, Float64,)) x, y, z = 3.0, 2.0, 1.0 @test muladd(x, y, z) == jsfun.muladd(x, y, z) # jsfun = jsfunctions((exp, Float64,)) # x = 3.0 # @test exp(x) == jsfun.exp(x) # jsfun = jsfunctions((acos, Float64,)) # x = 0.3 # @test acos(x) == jsfun.acos(x) end @testitem "Tuples / globals" begin include("setup.jl") const tpl = (1.,2.,3.) function ftuples1(x) @inbounds tpl[x] end compile((ftuples1, Int32,); filepath = "tmp/ftuples1.wasm") # jsfun = jsfunctions((ftuples1, Int32,)) # x = Int32(1) # @test ftuples1(x) == jsfun.ftuples1(x) end @testitem "Globals" begin include("setup.jl") const a = [1.,2.,3.,4.] fglobals1(i) = @inbounds length(a) compile((fglobals1, Int32,); filepath = "tmp/fglobals1.wasm", validate = true) # works in browser! # jsfun = jsfunctions((fglobals1, Int32,)) # @test jsfun.fglobals1(1) == fglobals1(1) fglobals2(i) = @inbounds a[i] compile((fglobals2, Int32,); filepath = "tmp/fglobals2.wasm", validate = true, optimize = true) # jsfun = jsfunctions((fglobals2, Int32,)) # @test jsfun.fglobals2(1) == fglobals2(1) struct Y a::Float64 b::Float64 end mutable struct Z a::Y b::Float64 end const x = Z(Y(1.,2.), 3.) g1(i) = x.a.a compile((g1, Int32,); filepath = "tmp/globalcombo.wasm") # jsfun = jsfunctions((g1, Int32,)) # @test jsfun.g1(1) == g1(1) mutable struct X a::Array{Float64,1} b::Array{Float64,1} c::Float64 end const xx = X([1.,2.], [5., 6.], 3.) g1(i) = xx.b[i] compile((g1, Int32,); filepath = "tmp/globalcombo2.wasm") # jsfun = jsfunctions((g1, Int32,)) # @test jsfun.g1(1) == g1(1) # # @show jsfun.g1(2) g2(i) = xx.b[i] + length(xx.a) compile((g2, Int32,); filepath = "tmp/globalcombo3.wasm") # jsfun = jsfunctions((g2, Int32,)) # @test jsfun.g2(1) == g2(1) # @show jsfun.g2(2) function fglobals3(x) xx.b[2] = 4. xx.c = 5. return x + xx.c end compile((fglobals3, Float64,); filepath = "tmp/fglobals3.wasm") const d = Dict{Int32,Int32}(1 => 10, 2 => 20, 3 => 30, 4 => 40) f(i) = get(d, i, Int32(-1)) compile((f, Int32,); filepath = "tmp/dict.wasm") # works in browser! # jsfun = jsfunctions((f, Int32,)) # @show jsfun.f(1) function fdict1(x) d = Dict{Int, Float64}((1 => 10., 2 => 20., 3 => 30.)) get(d, 2, -1.0) + x end compile((fdict1, Float64,); filepath = "tmp/fdict1.wasm") # function fhash2(x) # z = Base.hashindex("jhkjh", 3) # z[1] + x # end # compile((fhash2, Float64,); filepath = "tmp/fhash2.wasm") # function fdict2(x) # d = Dict{String, String}(("1" => "10.", "2" => "20.", "3" => "30.")) # get(d, 2, -1.0) + x # end # compile((fdict2, Float64,); filepath = "tmp/fdict2.wasm") end @testitem "Aliasing" begin const a = Float64[1.,2.,3.] const tpl = (a, a) function falias(x) @inline tpl[1][1] = 10. y = tpl[2][1] display(y) return x end compile((falias, Float64,); filepath = "tmp/falias.wasm", validate = true) function falias2(x) # works a = Float64[1:1.:10;] tpl = (a = a, aa = a, b = 3) tpl.a[1] = 10. y = tpl.aa[1] JS.console_log(1.0) JS.console_log(string(y, " ")) JS.console_log(3.0) JS.console_log("hello") return x end compile((falias2, Float64,); filepath = "tmp/falias2.wasm", validate = true) end @testitem "Dictionaries" begin include("setup.jl") # using Dictionaries # function fdict2(x) # d = Dictionary{Int32, Float64}(Int32[Int32(1),Int32(2),Int32(3)], [10.,20.,30.]) # get(d, 2, -1.0) + x # end # compile((fdict2, Float64,); filepath = "tmp/fdict2.wasm", validate = true) end @testitem "JavaScript interop" begin include("setup.jl") function fjs10(x) a = Vector{Any}(undef, 3) a[1] = 1.5 a[2] = Int32(2) jsa = JS.object(a) JS.console_log(jsa) return x end compile((fjs10, Float64,); filepath = "tmp/fjs10.wasm", validate = true) function fjs11(x) a = Any[1.5, Int32(2), "hello"] jsa = JS.object(a) JS.console_log(jsa) return x end compile((fjs11, Float64,); filepath = "tmp/fjs11.wasm", validate = true) compile((fjs11, Float64,); filepath = "tmp/fjs11o.wasm", optimize = true) function fjs12(x) JS.console_log(string("hello", "world")) return x end compile((fjs12, Float64,); filepath = "tmp/fjs12.wasm", validate = true) function fjs13(x) JS.eval("console.log('hello world')") return x end compile((fjs13, Float64,); filepath = "tmp/fjs13.wasm", validate = true) # function fjs14(x) # y = hash("hello") # return Float64(y) + x # end # compile((fjs14, Float64,); filepath = "tmp/fjs14.wasm", validate = true) function fjs15(x) y = JS.getelementbyid("myid") JS.sethtml(y, "hello <strong>world</strong>") return x end compile((fjs15, Float64,); filepath = "tmp/fjs15.wasm", validate = true) function fjs16(x) JS.sethtml("myid", "hello <strong>world</strong>") return x end compile((fjs16, Float64,); filepath = "tmp/fjs16.wasm", validate = true) function fjs17(x) a = Any[1.5, Int32(2), "hello", Any[1.5, "world"]] jsa = JS.object(a) JS.console_log(jsa) return x end compile((fjs17, Float64,); filepath = "tmp/fjs17.wasm", validate = true) function fjs18(x) a = [1.5, 3.0] jsa = JS.object(a) JS.console_log(jsa) return x end compile((fjs18, Float64,); filepath = "tmp/fjs18.wasm", validate = true) function fjs19(x) a = :Hello jso = JS.object(a) JS.console_log(jso) return x end compile((fjs19, Float64,); filepath = "tmp/fjs19.wasm", validate = true) function fjs20(x) a = 1.3 jso = JS.object(a) JS.console_log(jso) return x end compile((fjs20, Float64,); filepath = "tmp/fjs20.wasm", validate = true) function fjs21(x) JS.console_log(:Cheers) return x end compile((fjs21, Float64,); filepath = "tmp/fjs21.wasm", validate = true) function fjs22(x) a = (a = 1.5, b = Int32(3), c = "hello", d = (x = x, y = 22.0)) jso = JS.object(a) JS.console_log(jso) return x end compile((fjs22, Float64,); filepath = "tmp/fjs22.wasm", validate = true) function fjs23(x) JS.console_log(Float64[1.1, 2.2]) return x end compile((fjs23, Float64,); filepath = "tmp/fjs23.wasm", validate = true) end @testitem "IO" begin include("setup.jl") function fio1(x) io = JS.IOBuff() print(io, x) print(io, " hello", " hello", " world") print(io, " hello", " hello", " world", "1", "2", "3", "4") print(io, "X") JS.console_log(take!(io)) return x end compile((fio1, Float64,); filepath = "tmp/fio1.wasm", validate = true) end @testitem "Cobweb / Hyperscript" begin include("setup.jl") const h = JS.h function fcw1(x) n = h("div", "jkl", h("strong", "!!!!!", "xxxx"), class = "myclass") n = h("div", "hi", "abc", x, n, class = "myclass2") JS.sethtml("myid", string(n)) return x end # ## This version crashes Julia: # function fcw1(_x) # n = h("div", "jkl", h("strong", "!!!!!", "xxxx"), class = "myclass") # n = h("div", "hi", "abc", _x, n, class = "myclass2") # JS.sethtml("myid", n) # return _x # end compile((fcw1, Float64,); filepath = "tmp/fcw1.wasm", validate = true) function fcw2(x) snip = h("div", h.h1("Hello there"), h.p("This is some ", h.strong("strong text")), h.p("more text", class = "myclass")) JS.sethtml("myid", string(snip)) return x end compile((fcw2, Float64,); filepath = "tmp/fcw2.wasm", validate = true) # const obj = JS.object # const Ext = WebAssemblyCompiler.Externref # @inline _mithril(n::JS.Node) = mithril(n) # @inline _mithril(x) = obj(x) # @inline _mithril(x, xs::Tuple...) = (x, _mithril(xs...)...) # @inline _mithril(x, y) = (x, y) # mithril(tag::String, attrs::Ext, content::Ext) = # Base.llvmcall("(tag, attrs, content) => m(tag, attrs, content)", # Ext, # Tuple{String, Ext, Ext}, # tag, attrs, content) # mithril(tag::String, attrs::Ext, content::String) = # Base.llvmcall("(tag, attrs, content) => m(tag, attrs, content)", # Ext, # Tuple{String, Ext, String}, # tag, attrs, content) # mithril(n::JS.Node) = # mithril(JS.tag(n), obj(JS.attrs(n)), obj(_mithril(JS.children(n)...))) # function fcw3(x) # snip = h("div", # h("p", h("strong", "strong text"), " text")) # JS.sethtml("myid", string(snip)) # # JS.console_log(mithril(snip)) # return x # end # compile((fcw3, Float64,); filepath = "tmp/fcw3.wasm", validate = true) # # Here's a more direct approach to convert to mithril objects as you go. # m(tag, attrs::Ext, content::Ext) = # Base.llvmcall("(tag, attrs, content) => m(tag, attrs, content)", # Ext, # Tuple{String, Ext, Ext}, # tag, attrs, content) # m(tag, attrs::Ext, content::String) = # Base.llvmcall("(tag, attrs, content) => m(tag, attrs, content)", # Ext, # Tuple{String, Ext, String}, # tag, attrs, content) # m(tag, attrs, content) = # m(tag, JS.object(attrs), content) # m(tag, attrs::Ext, content) = # m(tag, attrs, JS.object(content)) # m(tag, attrs::Ext, content...) = # m(tag, attrs, _m(content...)) # m(tag, content::String="") = m(tag, (;), content) # @inline _m() = () # @inline _m(x) = (x,) # @inline _m(x, xs::Tuple...) = (x, _m(xs...)...) # @inline _m(x, y) = (x, y) # function fcw4(x) # snip = m("div", # m("h1", (class = "myclass",), "Hello there"), # m("p", m("strong", "strong text"))) # JS.sethtml("myid", string(snip)) # # JS.console_log(snip) # return x # end # compile((fcw4, Float64,); filepath = "tmp/fcw4.wasm", validate = true) end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
4845
@testitem "LibBinaryen" begin using WebAssemblyCompiler.LibBinaryen using NodeCall NodeCall.initialize(node_args = ["--experimental-wasm-gc"]); # adapted from https://github.com/WebAssembly/binaryen/blob/main/test/example/c-api-hello-world.c # Apache License mod = BinaryenModuleCreate() # Create a function type for i32 (i32, i32) ii = [BinaryenTypeInt32(), BinaryenTypeInt32()] params = BinaryenTypeCreate(ii, 2) results = BinaryenTypeInt32() # Get the 0 and 1 arguments, and add them x = BinaryenLocalGet(mod, 0, BinaryenTypeInt32()) y = BinaryenLocalGet(mod, 1, BinaryenTypeInt32()) add = BinaryenBinary(mod, BinaryenAddInt32(), x, y) # Create the add function # Note: no additional local variables # Note: no basic blocks here, we are an AST. The function body is just an # expression node. adder = BinaryenAddFunction(mod, "adder", params, results, C_NULL, 0, add) BinaryenAddFunctionExport(mod, "adder", "adder") # Print it out # BinaryenModulePrint(mod) out = BinaryenModuleAllocateAndWrite(mod, C_NULL) write("tmp/t.wasm", unsafe_wrap(Vector{UInt8}, Ptr{UInt8}(out.binary), (out.binaryBytes,))) Libc.free(out.binary) # Clean up the mod, which owns all the objects we created above BinaryenModuleDispose(mod) js = """ var funs = {}; (async () => { const fs = require('fs'); const wasmBuffer = fs.readFileSync('tmp/t.wasm'); const {instance} = await WebAssembly.instantiate(wasmBuffer); funs.adder = instance.exports.adder; })(); """ p = node_eval(js) @await p @test node"funs.adder(5,6)" == 11 run(`$(WebAssemblyCompiler.Bin.wasmdis()) tmp/t.wasm -o tmp/t.wat`) wat = read("tmp/t.wat", String) @test contains(wat, raw"func $0 (param $0 i32) (param $1 i32) (result i32)") end @testitem "LibBinaryen 2" begin using WebAssemblyCompiler.LibBinaryen using NodeCall NodeCall.initialize(node_args = ["--experimental-wasm-gc"]); # adapted from https://github.com/WebAssembly/binaryen/blob/main/test/example/c-api-hello-world.c # Apache License mod = BinaryenModuleCreate() # Create a function type for i32 (i32, i32) ii = [BinaryenTypeInt32(), BinaryenTypeInt32()] params = BinaryenTypeCreate(ii, 2) results = BinaryenTypeInt32() BinaryenAddGlobal(mod, "string-global", BinaryenTypeStringref(), true, BinaryenStringConst(mod, "hi there")) x = BinaryenGlobalGet(mod, "string-global", BinaryenTypeStringref()) jparams = [BinaryenTypeStringref()] bparams = BinaryenTypeCreate(jparams, length(jparams)) BinaryenAddFunctionImport(mod, "imp", "console", "log", bparams, BinaryenTypeNone()) call = BinaryenCall(mod, "imp", [x], 1, BinaryenTypeNone()) # call = BinaryenLocalSet(mod, 2, call) # call = BinaryenLocalGet(mod, 2, BinaryenTypeNone()) # call = BinaryenLocalSet(mod, 0, BinaryenTypeInt32()) # Get the 0 and 1 arguments, and add them x = BinaryenLocalGet(mod, 0, BinaryenTypeInt32()) y = BinaryenLocalGet(mod, 1, BinaryenTypeInt32()) add = BinaryenBinary(mod, BinaryenAddInt32(), x, y) # body = BinaryenBlock(ctx.mod, "body", ctx.body, length(ctx.body), BinaryenTypeAuto()) # Create the add function # Note: no additional local variables # Note: no basic blocks here, we are an AST. The function body is just an # expression node. # adder = BinaryenAddFunction(mod, "adder", params, results, C_NULL, 0, add) adder = BinaryenAddFunction(mod, "adder", params, BinaryenTypeNone(), [BinaryenTypeNone()], 1, call) BinaryenAddFunctionExport(mod, "adder", "adder") features = BinaryenFeatureAll(); BinaryenModuleSetFeatures(mod, features); # Print it out # BinaryenModulePrint(mod) out = BinaryenModuleAllocateAndWrite(mod, C_NULL) write("tmp/t2.wasm", unsafe_wrap(Vector{UInt8}, Ptr{UInt8}(out.binary), (out.binaryBytes,))) Libc.free(out.binary) # Clean up the mod, which owns all the objects we created above BinaryenModuleDispose(mod) run(`$(WebAssemblyCompiler.Bin.wasmdis()) tmp/t2.wasm -o tmp/t2.wat`) # js = """ # var funs = {}; # (async () => { # const fs = require('fs'); # const wasmBuffer = fs.readFileSync('tmp/t.wasm'); # const {instance} = await WebAssembly.instantiate(wasmBuffer); # funs.adder = instance.exports.adder; # })(); # """ # p = node_eval(js) # @await p # @test node"funs.adder(5,6)" == 11 # run(`$(WebAssemblyCompiler.Bin.wasmdis()) tmp/t.wasm -o tmp/t.wat`) # wat = read("t.wat", String) # @test contains(wat, raw"func $0 (param $0 i32) (param $1 i32) (result i32)") end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
2329
using Revise using WebAssemblyCompiler const W = WebAssemblyCompiler W.setdebug(:offline) W.setdebug(:inline) struct X a::Float64 end @noinline (x::X)(w) = w * x.a function fargs2(x) y = X(2.0)(x) return x * y end compile((fargs2, Float64,); filepath = "tmp/fargs2.wasm", validate = true) # function fa2(i) # a = Array{Float64,1}(undef, Int32(i)) # unsafe_trunc(Int32, length(a)) # end # compile((fa2, Int32,); filepath = "tmp/fa2.wasm") # # compile((fa2, Int32,); filepath = "tmp/fa2o.wasm", optimize = true) # crashes # function falias2(x) # works # a = Float64[1:1.:10;] # tpl = (a = a, aa = a, b = 3) # tpl.a[1] = 10. # y = tpl.aa[1] # JS.console_log(1.0) # JS.console_log(string(y, " ")) # JS.console_log(3.0) # JS.console_log("hello") # return x # end # compile((falias2, Float64,); filepath = "tmp/falias2.wasm", validate = true) # function fdict1(x) # d = Dict{Int, Float64}((1 => 10., 2 => 20., 3 => 30.)) # get(d, 2, -1.0) + x # end # compile((fdict1, Float64,); filepath = "tmp/fdict1.wasm") # function fstringx(x) # s = "hello" # JS.console_log(s) # fs() = JS.JSString(@jscall("() => \"hello\"", Externref, Tuple{})) # js = fs() # JS.console_log(js) # v = Vector{UInt8}(@jscall("(x) => (new TextEncoder()).encode(x)", Externref, Tuple{Externref}, js)) # JS.console_log(v) # if String(js) == s # JS.console_log("Same") # end # return x # end # compile((fstringx, Float64,); filepath = "tmp/fstringx.wasm", validate = true) # function fdict2(x) # d = Dict{String, String}(("1" => "10.", "2" => "20.", "3" => "30.")) # get(d, 2, -1.0) + x # end # compile((fdict2, Float64,); filepath = "tmp/fdict2.wasm") # function fhash2(x) # z = Base.hashindex("jhkjh", 3) # z[1] + x # end # compile((fhash2, Float64,); filepath = "tmp/fhash2.wasm") # function fdict2(x) # d = Dict{String, String}(("1" => "10.", "2" => "20.", "3" => "30.")) # get(d, 2, -1.0) + x # end # compile((fdict2, Float64,); filepath = "tmp/fdict2.wasm")
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
1158
function f1(x) d = Dict{Int32, Float64}((1 => 10., 2 => 20., 3 => 30.)) get(d, 2, -1.0) + x end compile(f1, (Float64,); filepath = "dict.wasm") # jsfun = jsfunctions(f1, (Float64,)) # x = 1.0 # @test jsfun.f1(x) == f1(x) # @show jsfun.f1(x) # compile(nextpow, (Int32,Int32); filepath = "nextpow.wasm") # run(`$(WebAssemblyCompiler.Bin.wasmdis()) nextpow.wasm -o nextpow.wat`) # jsfun = jsfunctions(nextpow, (Int32,Int32)) # x = Int32(2) # y = Int32(7) # @test jsfun.nextpow(x,y) == nextpow(x,y) # @show jsfun.nextpow(x,y) # Circular references # Here, just the type is circular struct Y a::Float64 b::Vector{Y} end const y = Y(1.0, Vector{Y}[]) const z = Y(1.0, Vector{Y}[]) push!(y.b, z) function frecurs1(x) return x + y.b[1].a end compile((frecurs1, Float64,); filepath = "tmp/frecurs1.wasm", validate = true) # Here, the value is circular push!(y.b, y) function frecurs2(x) return x + y.b[1].a end # compile((frecurs2, Float64,); filepath = "tmp/frecurs2.wasm", validate = true)
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
185
using TestItemRunner using Test using WebAssemblyCompiler include("setup.jl") const W = WebAssemblyCompiler mkpath("tmp") ENV["wac_outpath"] = "./tmp" # exit() @run_package_tests
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
code
837
using Test using WebAssemblyCompiler mkpath("tmp") using NodeCall # NodeCall.initialize(node_args = ["--experimental-wasm-gc", "--experimental-wasm-stringref"]); NodeCall.initialize(node_args = ["--experimental-wasm-gc"]); # jsfunctions(fun, tt) = jsfunctions(((fun, tt...),)) function jsfunctions(funs...) wpath = tempname() * ".wasm" jspath = wpath * ".js" compile(funs..., filepath = wpath, experimental = false, optimize = false) jsexports = read(jspath, String) js = """ $jsexports var funs = {}; (async () => { const fs = require('fs'); const wasmBuffer = fs.readFileSync('$wpath'); const { instance } = await WebAssembly.instantiate(wasmBuffer, jsexports); funs = instance.exports; })(); """ p = node_eval(js) @await p return node"funs" end
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
docs
367
# WebAssemblyCompiler [![Build Status](https://github.com/tshort/WebAssemblyCompiler.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/tshort/WebAssemblyCompiler.jl/actions/workflows/CI.yml?query=branch%3Amain) ## Compile Julia to WebAssembly > [!NOTE] > See the [examples and documentation](http://tshort.github.io/WebAssemblyCompiler.jl).
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
docs
3064
# API ## Main API `compile` is the main method exported by WebAssemblyCompiler. ```@docs compile ``` Debugging is often needed when trying to fix code to make it compile. You can enable debugging output using: WebAssemblyCompiler.debug(x) where `x` is `:inline` to display debugging information at the REPL or `:offline` do store information in `WebAssemblyCompiler.DEBUG`. Outputs from that are stored in `WebAssemblyCompiler.DEBUG`, include: * Julia IR for each method compiled * WebAssembly code generated for each statement ## JavaScript interoperability WebAssemblyCompiler provides several utilities to ease interoperability with the browser. The main way to call JavaScript methods is with `@jscall` (exported): ```@docs @jscall ``` Objects on the JavaScript side are accessed using the `Externref` type (exported): ```@docs Externref ``` The module `JS` provides several utility functions to help with browser interoperability. The `JS` module is exported, but its methods are not. ```@autodocs Modules = [WebAssemblyCompiler.JS] Order = [:function, :macro, :type] ``` ## Overlays It is common to need to swap out problematic parts of code when compiling to WebAssembly. The compilation pipeline uses `Base.Experimental.@overlay` to methods to be redefined. Here is an example of redefining `Base.log10`: ``` using Base.Experimental: @overlay @overlay WebAssemblyCompiler.MT Base.log10(x::Float64) = @jscall("(x) => Math.log10(x)", Float64, Tuple{Float64}, x) ``` `WebAssemblyCompiler.MT` is the MethodTable that is used during compilation. Redefinitions built into WebAssemblyCompiler are defined in [quirks.jl](https://github.com/tshort/WebAssemblyCompiler.jl/blob/main/src/quirks.jl). Many math functions are replaced by JavaScript versions. Many error functions are also replaced. ## Mixtape support Overlays are the most common way to manipulate code for compilation. More advanced manipulation is possible with [Mixtape](https://github.com/JuliaCompilerPlugins/Mixtape.jl) support built in. Mixtape support is considered experimental and not part of the official API. This support has not been tested extensively. Mixtape is enabled using the following methods and types (none are exported): ```@docs WebAssemblyCompiler.CompilationContext WebAssemblyCompiler.allow WebAssemblyCompiler.transform ``` ## Binaryen utilities Binaryen binary utilities from [Binaryen_jll](https://github.com/JuliaBinaryWrappers/Binaryen_jll.jl) such as `wasm-dis` are available in `WebAssemblyCompiler.Bin`. This is not official API in terms of semver. Each release of WebAssemblyCompiler targets a specific version of Binaryen. There are no compatibility guarantees between versions of Binaryen. These are unlikely to change though. ## LibBinaryen The C interface to Binaryen is provided through `WebAssemblyCompiler.LibBinaryen`. This is not official API in terms of semver. Each release of WebAssemblyCompiler targets a specific version of Binaryen. There are no compatibility guarantees between versions of Binaryen.
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
docs
2309
### Compile Julia code to WebAssembly This package uses [Binaryen](https://github.com/WebAssembly/binaryen/) to compile Julia's IR to WebAssembly. !!! warning "Experimental and in progress" This code is experimental. Expect to find errors or failures when compiling Julia code. This uses very recent features of WebAssembly. A bleeding-edge browser is needed. At least version 119 of Chrome or version 120 of Firefox is needed. WebAssemblyCompiler supports many Julia constructs, including: * Vector{T} where T is a bitstype and Vector{Any} * Strings * Symbols * Dicts (not including strings) * Mutable and immutable structs * Tuples and NamedTuples * Global variables * Varargs and keyword arguments Heap allocation is handled by WebAssembly's garbage collector (see [wasm-GC](https://github.com/WebAssembly/gc)). Interoperability with JavaScript is quite good. Julia code can run JavaScript functions and exchange objects. This functionality allows Julia to interact with the browsers DOM. Code must be type stable (no dynamic dispatches). In addition, several Julia constructs are not supported, including: * Multi-dimensional arrays (waiting on the [Memory type PR](https://github.com/JuliaLang/julia/pull/51319)) * Pointers * Union types * Exception handling * Errors * Some integer types (Int16, Int128, ...) * BLAS and all other C dependencies WebAssemblyCompiler supports [overlays](@ref Overlays) and other ways to fix up code when compiling. Once compiled to WebAssembly, you can integrate that into web apps in many ways. The examples in these docs are made with: * [Literate.jl](https://fredrikekre.github.io/Literate.jl/v2/)--The Julia files in [/examples](https://github.com/tshort/WebAssemblyCompiler.jl/tree/main/examples/) can run standalone, or they can be used with [Franklin](https://franklinjl.org/) or [Documenter](https://documenter.juliadocs.org/stable/) (as done here). * [mdpad](https://mdpad.netlify.app/)--This small JavaScript package provides features for single-page web apps, including auto-updates of inputs and address-bar handling. * [Bulma](https://bulma.io/)--Any CSS framework should work. Because Documenter uses a theme based on Bulma, that is used for styling web apps. The web apps are very Julia focused. Not much JavaScript is needed.
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
docs
7079
# Notes * WebAssembly's Tuples and Structs cannot be indexed dynamically. Only fixed integer indexing works. So, Tuples are mapped as follows: - NTuple -> WebAssembly's Fixed Array - Tuple -> WebAssembly's Tuple or Struct. The Struct will GC. WebAssembly's Tuple is more for handling multiple return values. The only option for dynamic indexing is some sort of table lookup. * There is no equivalent of stack-allocated Tuples for StaticArrays. There are Fixed Arrays that are heap allocated. Maybe the browser can convert some of those to stack values. [Bumper](https://github.com/MasonProtter/Bumper.jl) could substitute for stack allocation. * You can't get a pointer from GC heap-allocated arrays. You can't reinterpret or use pointer operations. You can have a buffer and pull in individual values and reinterpret those. That's slow, though. * Exception handling doesn't work. The compiler doesn't currently handle PhiC nodes or Upsilon nodes in the SSA IR. Binaryen and WebAssembly support try, catch, and throw, so there's no technical reason this can't be supported. * Similarly error handling isn't attempted. Overlays are used to bypass error code to make things compile. * The compiler includes some known bandaids and rough spots. * In `compile_block`, the handling of `QuoteNode`s and `Core.Const` wrappers is uneven. Handling is included in a spotty fashion, but a more consistent approach would be better. * On the WebAssembly side, on-the-fly type detection doesn't work. Heap objects are not stored with type information. It would be possible to add type info to all types. [Guile Hoot](https://gitlab.com/spritely/guile-hoot) does this by adding a type hash to every struct. * Union's are not supported, and the path to supporting them is unclear. WebAssembly's type system doesn't have anything like that, and it also doesn't allow re-interpeting content easily. * Several intrinsics are not supported. Some are challenging. `do_apply` / `_apply_iterate` look tough. * Several of the existing intrinsics only support basic types (Int32, Int64, etc.). Better handling of these would be nice. * String support is very limited. JavaScript is used to concatenate using `string(...)`. JavaScript uses UTF16 for strings, and Julia's String uses UTF8. WebAssembly supports different string encodings and conversions. Right now, Strings are stored as GC'd UTF8 vectors. These are converted to JavaScript strings on the JavaScript side. No character-level operations are supported. In the future, the [stringref proposal](https://github.com/WebAssembly/stringref) will improve string interop. String hashing isn't supported, and that's needed for Dicts with Strings. * Symbols are currently converted straight to strings. That allows basic operations to work, including comparisons. This simple approach may cause issues for some code. * Binaryen doesn't do any auto-vectorization. WebAssembly has basic SIMD types, but none are supported by WebAssemblyCompiler. * LoopVectorization doesn't work. It's LLVM specific. * Using overlays with `@jscall` of normal Julia code will block constant propagation by the Julia compiler because the Julia compiler can't know what's happening and can't run it in the existing process. * WebAssembly doesn't support circular references, but Julia does. What we do is assign a default value for the circular reference and hope it doesn't cause problems. This works for the Observables support because the circular references aren't used after the set of Observables is statically compiled. * The support of aliased objects may still be patchy. Some were fixed up recently, but I worry that some still lurk (meaning you might get a copy when you want two references to point to the same object). ## Comparing Approaches to Generating WebAssembly [StaticCompiler](https://github.com/tshort/StaticCompiler.jl) can also generate WebAssembly from Julia code. Some of the advantages of that approach include: * LLVM generates fast code. * The package is simple ([GPUCompiler](https://github.com/JuliaGPU/GPUCompiler.jl) and Julia's compiler does all the work). The main disadvantages of StaticCompiler are: * No GC built in. * No clear path to include libjulia capability, so no GC, and everything must be manually allocated ([StaticTools](https://github.com/brenhinkeller/StaticTools.jl)). * No global variables. * The Julia compiler doesn't make a good cross compiler. For example, indexes into structs sometimes use the host index and sometimes the target index ([discussions](https://github.com/JuliaGPU/GPUCompiler.jl/issues/486#)). The compiler in this project is better in some ways, including: * Support for WebAssembly GC (structs, strings, arrays, ...). * Good interop with JavaScript. * Can tailor compilation to WebAssembly better. * Hacking the compiler is easier. The downsides of this approach are: * Code isn't as good as LLVM's. The biggest issue may be no autovectorization. * WebAssembly's type system is limited. This should improve in the future. * No nested structs or arrays of structs; nesting boxes everything; use [StructArrays](https://github.com/JuliaArrays/StructArrays.jl), [ComponentArrays](https://github.com/jonniedie/ComponentArrays.jl), [ValueShapes](https://github.com/oschulz/ValueShapes.jl), or other Julia packages to organize nested data using flat arrays. * All structs are boxed. * Browser support for WASM-GC is just beginning. * More bugs. # Project ideas ## BLAS Implement replacements for key BLAS functionality. This could be tackled by compiling an existing library to WebAssembly (like [BLIS](https://github.com/flame/blis)) or by implementing functionality in Julia. ## Makie Makie in the browser would be so useful. Plot directly via WebGL or WebGPU. ## Robust Array support Once the [Memory type PR](https://github.com/JuliaLang/julia/pull/51319) is merged, update the Array support in WebAssemblyCompiler. Support grow and multidimensional arrays. ## Vectorization / SIMD WebAssembly supports basic SIMD types. There are several ways that could be incorporated: * Write a Binaryen pass to do auto-vectorization (C++). * For loops with `@simd`, vectorize those with Julia. This would be at the typed IR level. * Add support for WebAssembly's basic SIMD types. ## Implement Int128 Use of Int128's is common in Julia code, but it's not a native WebAssembly type. Add a package to mimic Int128's which can be incorporated using overlays. ## Exception handling Handle PhiC and Upsilon nodes in the SSA IR. WebAssembly has `throw` and other exception-handling features. This might need the equivalent of relooping but for exceptions. ## Union types WebAssembly doesn't have this capability, so some mechanism would be needed to mimic these. ## CI / testing Update [NodeCall](https://github.com/sunoru/NodeCall.jl) to support the latest WebAssembly features, and update tests ([issue](https://github.com/sunoru/NodeCall.jl/issues/14)). ## Convert / test your favorite package Compiling code using key packages would help improve the code.
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
docs
5333
```@meta EditURL = "makie.jl" ``` # Sum of Sines Demo using Makie Plot with Makie in the browser with interactivity. Adapted from [this demo](https://github.com/garrekstemo/InteractivePlotExamples.jl/blob/main/examples/sum_of_sines.jl). ````@example makie using WebAssemblyCompiler # prep some input #hideall #hide using WebAssemblyCompiler.JS: h #hide const W = WebAssemblyCompiler #hide #hide const names = [] #hide #hide function numform(description; jl = description, value = 1, args...) #hide push!(names, jl) #hide # push!(os, Observable(value)) #hide h.div."field"( #hide h.label."label"( #hide description #hide ), #hide h.div."control"( #hide h.input(;type = "range", value, step = "any", oninput = "document.wasm.$jl(this.value)", args...) #hide ), #hide ) #hide end #hide #hide html = h.div( #hide h.div."columns is-vcentered"( #hide h.div."column is-3"( #hide h.form( #hide numform("a₁", jl = "k1", value = 1.0, min = 0.0, max = 2.5), #hide numform("ω₁", jl = "k2", value = 1.0, min = 1.0, max = 6.0), #hide numform("δ₁", jl = "k3", value = 0.0, min = 0.0, max = 7.0), #hide numform("a₂", jl = "k4", value = 1.0, min = 0.0, max = 2.5), #hide numform("ω₂", jl = "k5", value = 3.0, min = 1.0, max = 6.0), #hide numform("δ₂", jl = "k6", value = 0.5, min = 0.0, max = 7.0), #hide ) #hide ), #hide h.div."column"( #hide h.div(id = "plot") #hide ) #hide ), #hide ) #hide ```` !!! warning "Technology demonstration" This uses results compiled using [`examples/makie/makie.jl`](https://github.com/tshort/WebAssemblyCompiler.jl/blob/main/examples/makie/makie.jl). That code does not compile out of the box. It uses dev'd versions of Observables and Makie. These contain hacks to make them more amenable to static compilation. The Makie backend uses SVG and is rather simplistic. The purpose of this demo is to show that this is feasible. ```@raw html <script src="makie.wasm.js"></script> <script> // Weird hack to load noUISlider: https://stackoverflow.com/a/3363588 // https://github.com/JuliaDocs/Documenter.jl/issues/12471 window.__define = window.define; window.__require = window.require; window.define = undefined; window.require = undefined; </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.7.1/nouislider.min.js" integrity="sha512-UOJe4paV6hYWBnS0c9GnIRH8PLm2nFK22uhfAvsTIqd3uwnWsVri1OPn5fJYdLtGY3wB11LGHJ4yPU1WFJeBYQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script> window.define = window.__define; window.require = window.__require; window.__define = undefined; window.__require = undefined; </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/15.7.1/nouislider.css" integrity="sha512-MKxcSu/LDtbIYHBNAWUQwfB3iVoG9xeMCm32QV5hZ/9lFaQZJVaXfz9aFa0IZExWzCpm7OWvp9zq9gVip/nLMg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script type="module"> setTimeout(function() { var x = document.getElementById("plot") if (x.innerHTML === "") { x.innerHTML = "<strong>Unsupported browser.</strong> Chrome v119 or Firefox v120 or better should work." } }, 1000) export async function load_wasm() { const response = await fetch('makie.wasm'); const bytes = await response.arrayBuffer(); const { instance } = await WebAssembly.instantiate(bytes, jsexports); const { basics } = instance.exports; return instance.exports; } document.wasm = await load_wasm(); document.wasm.k4(1.5); </script> <style> /********** Range Input Styles **********/ /*Range Reset*/ input[type="range"] { -webkit-appearance: none; appearance: none; background: transparent; cursor: pointer; width: 15rem; } /* Removes default focus */ input[type="range"]:focus { outline: none; } /***** Chrome, Safari, Opera and Edge Chromium styles *****/ /* slider track */ input[type="range"]::-webkit-slider-runnable-track { background-color: #053a5f; border-radius: 0.5rem; height: 0.5rem; } /* slider thumb */ input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; /* Override default look */ appearance: none; margin-top: -12px; /* Centers thumb on the track */ /*custom styles*/ background-color: #5cd5eb; height: 2rem; width: 1rem; } input[type="range"]:focus::-webkit-slider-thumb { border: 1px solid #053a5f; outline: 3px solid #053a5f; outline-offset: 0.125rem; } /******** Firefox styles ********/ /* slider track */ input[type="range"]::-moz-range-track { background-color: #053a5f; border-radius: 0.5rem; height: 0.5rem; } /* slider thumb */ input[type="range"]::-moz-range-thumb { border: none; /*Removes extra border that FF applies*/ border-radius: 0; /*Removes default border-radius that FF applies*/ /*custom styles*/ background-color: #5cd5eb; height: 2rem; width: 1rem; } input[type="range"]:focus::-moz-range-thumb { border: 1px solid #053a5f; outline: 3px solid #053a5f; outline-offset: 0.125rem; } </style> ```
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
docs
42
Work in progress... It's broken currently.
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.1.15
b9166ab12916a96d60bb65e4827edcee240c9844
docs
2218
WebAssembly compiler processed Julia IR code to generate WebAssembly. Every `invoke` function call is compiled. Binaryen is used to compile code. Binaryen's "relooper" is used to convert Julia's IR in SSA form to WebAssembly code. Each "block" is compiled separately. Here are the key contents for the source. * `compiler.jl`--The main file that defines `compile` (exported) which calls `compile_method` which calls `compile_method_body`. * `compile_block.jl`--`compile_block` is the key function that compiles Julia IR. It's one giant if-elseif function that evaluates each line of IR code. * `_compile.jl`--`_compile` compiles specific objects to WebAssembly. * `utilities.jl`--Defines several helpers, including: - `matchcall`, `matchgr`, `matchforeigncall`: match IR for use by `compile_block` - `roottype`, `basetype`: type lookups to account for SSA stuff - `getglobal`: get and/or create a global variable - `gettype`: get and/or create the WebAssembly type based on the Julia type * `types.jl`--Defines the main context variable to hold state (`CompilerContext`). Defines `Externref` for interoperation with the browser (exported). These files define the AbstractInterpreter used as part of compilation. This comes from StaticCompiler. * `interpreter.jl`--The AbstractInterpreter. * `mixtape.jl`--Mixtape functionality for manipulating Julia IR. These files define extensions that help when compiling common code. * `javascript-interop.jl`--Defines module `JS` for interoperation with the browser. Key methods include: - `@jscall`--call JavaScript (exported) - `JS.object`--convert a Julia object to JavaScript - `JS.console_log`--log results to the browser console - `JS.sethtml`--set HTML at the given id - `JS.getelementbyid`--get the Externref that's the DOM element at the given id - `JS.h`--hyperscript-style generation of HTML nodes * `quirks.jl`--Uses overlays to redefine several key functions. Key parts redefined include: - Error functions - Basic math functions to use JavaScript versions (reduces WebAssembly size, and not all Julia functions can currently be compiled) - Basic string functions Other: * `array.jl`--Includes a wrapper to implement arrays.
WebAssemblyCompiler
https://github.com/tshort/WebAssemblyCompiler.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
2013
module Vcov using Combinatorics: combinations using GroupedArrays: GroupedArray using LinearAlgebra: cholesky!, Symmetric, Hermitian, svd, rmul!, eigen, Diagonal using StatsAPI: StatsAPI, RegressionModel, modelmatrix, crossmodelmatrix, residuals, dof_residual using StatsBase: CovarianceEstimator using Tables: Tables using Base: @propagate_inbounds ############################################################################## ## ## Mimimum RegressionModel used in Vcov ## ############################################################################## struct VcovData{T, Tu, N} <: RegressionModel modelmatrix::Matrix{Float64} # X crossmodelmatrix::T # X'X invcrossmodelmatrix::Tu # inv(X'X) residuals::Array{Float64, N} # vector or matrix of residuals (matrix in the case of IV, residuals of Xendo on (Z, Xexo)) dof_residual::Int end StatsAPI.modelmatrix(x::VcovData) = x.modelmatrix StatsAPI.crossmodelmatrix(x::VcovData) = x.crossmodelmatrix invcrossmodelmatrix(x::VcovData) = x.invcrossmodelmatrix StatsAPI.residuals(x::VcovData) = x.residuals StatsAPI.dof_residual(x::VcovData) = x.dof_residual ############################################################################## ## ## Any type used for standard errors must define the following methods: ## ############################################################################## function completecases(table, ::CovarianceEstimator) Tables.istable(table) || throw(ArgumentError("completecases requires a table input")) return trues(length(Tables.rows(table))) end materialize(table, v::CovarianceEstimator) = v S_hat(x::RegressionModel, ::CovarianceEstimator) = error("S_hat not defined for this type") StatsAPI.dof_residual(x::RegressionModel, ::CovarianceEstimator) = dof_residual(x) include("utils.jl") include("covarianceestimators/vcovsimple.jl") include("covarianceestimators/vcovrobust.jl") include("covarianceestimators/vcovcluster.jl") include("ranktest.jl") include("precompile.jl") _precompile_() end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
437
function _precompile_() Base.precompile(Tuple{typeof(Vcov.ranktest!),Array{Float64,2},Array{Float64,2},Array{Float64,2},Vcov.SimpleCovariance,Int64,Int64}) Base.precompile(Tuple{typeof(Vcov.ranktest!),Array{Float64,2},Array{Float64,2},Array{Float64,2},Vcov.RobustCovariance,Int64,Int64}) Base.precompile(Tuple{typeof(Vcov.ranktest!),Array{Float64,2},Array{Float64,2},Array{Float64,2},Vcov.ClusterCovariance,Int64,Int64}) end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
2370
############################################################################## ## ## Generalized reduced rank tests using the singularvalue decomposition ## ## See also the Stata command ranktest ## RANKTEST: Stata module to test the rank of a matrix using the Kleibergen-Paap rk statistic ## Authors: Frank Kleibergen, Mark E Schaffer ## More precisely, it corresponds to the Stata command: ranktest (X) (Z), wald full ## For Kleibergen-Paap first-stage F-statistics ## See "Generalized reduced rank tests using the singular value decomposition" ## Journal of Econometrics, 2006, 133:1 ## Frank Kleibergen and Richard Paap ## doi:10.1016/j.jeconom.2005.02.011 ############################################################################## function ranktest!(X::Matrix{Float64}, Z::Matrix{Float64}, Pi::Matrix{Float64}, vcov_method::CovarianceEstimator, dof_small::Int, dof_fes::Int) if (size(X, 2) == 0) | (size(Z, 2) == 0) return NaN end # Compute theta Fmatrix = cholesky!(Symmetric(Z' * Z), check = false).U Gmatrix = cholesky!(Symmetric(X' * X), check = false).U theta = Fmatrix * (Gmatrix' \ Pi')' # compute lambda svddecomposition = svd(theta, full = true) u = svddecomposition.U vt = svddecomposition.Vt k = size(X, 2) l = size(Z, 2) u_sub = u[k:l, k:l] vt_sub = vt[k,k] # see p.102 of KP # the operation u_sup \ sqrt(u_sup * u_sub') may fail. For now, we handle the case k = l but not the more general one a_qq = iszero(u_sub) ? u[1:l, k:l] : u[1:l, k:l] * (u_sub \ sqrt(u_sub * u_sub')) b_qq = iszero(vt_sub) ? vt[1:k, k]' : sqrt(vt_sub * vt_sub') * (vt_sub' \ vt[1:k, k]') kronv = kron(b_qq, a_qq') lambda = kronv * vec(theta) # compute vhat if vcov_method isa Vcov.SimpleCovariance vlab = cholesky!(Hermitian((kronv * kronv') ./ size(X, 1)), check = false) else K = kron(Gmatrix, Fmatrix)' vcovmodel = Vcov.VcovData(Z, K, nothing, X, size(Z, 1) - dof_small - dof_fes) matrix_vcov2 = Vcov.S_hat(vcovmodel, vcov_method) vhat = K \ (K \ matrix_vcov2)' vlab = cholesky!(Hermitian(kronv * vhat * kronv'), check = false) end r_kp = lambda' * (vlab \ lambda) return r_kp[1] end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
516
function pinvertible(A::Symmetric, tol = eps(real(float(one(eltype(A)))))) eigval, eigvect = eigen(A) small = eigval .<= tol if any(small) @warn "estimated covariance matrix of moment conditions not positive-semidefinite. adjustment from Cameron, Gelbach & Miller (2011, JBES) applied. model tests should be interpreted with caution." eigval[small] .= 0 return Symmetric(eigvect * Diagonal(eigval) * eigvect') else return A end end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
3895
############################################################################## ## ## Cluster Covariance ## ############################################################################## struct ClusterCovariance <: CovarianceEstimator clusternames::Tuple{Symbol, Vararg{Symbol}} # names are not allowed to be empty clusters::Union{Tuple{Vararg{GroupedArray}}, Nothing} end """ cluster(names::Symbol...) Estimate variance-covariance matrix with a cluster-robust estimator. # Arguments - `names::Symbol...`: column names of variables that represent the clusters. """ cluster(ns::Symbol...) = ClusterCovariance((ns...,), nothing) cluster(ns::NTuple{N, Symbol}, gs::NTuple{N, GroupedArray}) where N = ClusterCovariance(ns, gs) """ names(vce::ClusterCovariance) Return column names of variables used to form clusters for `vce`. """ names(v::ClusterCovariance) = v.clusternames Base.length(v::ClusterCovariance) = length(names(v)) Base.show(io::IO, ::ClusterCovariance) = print(io, "Cluster-robust covariance estimator") function Base.show(io::IO, ::MIME"text/plain", v::ClusterCovariance) print(io, length(v), "-way cluster-robust covariance estimator:") for n in names(v) print(io, "\n ", n) end end function Vcov.completecases(table, v::ClusterCovariance) Tables.istable(table) || throw(ArgumentError("completecases requires a table input")) N = length(Tables.rows(table)) out = trues(N) # See https://github.com/JuliaData/DataFrames.jl/pull/2726 aux = BitVector(undef, N) columns = Tables.columns(table) for name in names(v) col = Tables.getcolumn(columns, name) if Missing <: eltype(col) aux .= .!ismissing.(col) out .&= aux end end return out end function materialize(table, v::ClusterCovariance) Tables.istable(table) || throw(ArgumentError("materialize requires a table input")) ns = names(v) return cluster(ns, map(n -> GroupedArray(Tables.getcolumn(table, n), sort = nothing), ns)) end """ nclusters(vce::ClusterCovariance) Return the number of clusters for each dimension/way of clustering. """ function nclusters(v::ClusterCovariance) NamedTuple{names(v)}(map(x -> x.ngroups, v.clusters)) end function StatsAPI.dof_residual(x::RegressionModel, v::ClusterCovariance) minimum(nclusters(v)) - 1 end function S_hat(x::RegressionModel, v::ClusterCovariance) # Cameron, Gelbach, & Miller (2011): section 2.3 dim = size(modelmatrix(x), 2) * size(residuals(x), 2) S = zeros(dim, dim) for c in combinations(1:length(v)) if length(c) == 1 g = v.clusters[c[1]] else g = GroupedArray((v.clusters[i] for i in c)..., sort = nothing) end S += (-1)^(length(c) - 1) * helper_cluster(modelmatrix(x), residuals(x), g) end # scale total vcov estimate by ((N-1)/(N-K)) * (G/(G-1)) # another option would be to adjust each matrix given by helper_cluster by number of its categories # both methods are presented in Cameron, Gelbach and Miller (2011), section 2.3 # I choose the first option following reghdfe G = minimum(nclusters(v)) rmul!(S, (size(modelmatrix(x), 1) - 1) / dof_residual(x) * G / (G - 1)) return Symmetric(S) end # res is a Vector in OLS, Matrix in IV function helper_cluster(X::Matrix, res::Union{Vector, Matrix}, g::GroupedArray) X2 = zeros(eltype(X), g.ngroups, size(X, 2) * size(res, 2)) idx = 0 for k in 1:size(res, 2) for j in 1:size(X, 2) idx += 1 @inbounds @simd for i in 1:size(X, 1) X2[g.groups[i], idx] += X[i, j] * res[i, k] end end end return Symmetric(X2' * X2) end function StatsAPI.vcov(x::RegressionModel, v::ClusterCovariance) xtx = invcrossmodelmatrix(x) pinvertible(Symmetric(xtx * S_hat(x, v) * xtx)) end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
885
struct RobustCovariance <: CovarianceEstimator end """ robust() Estimate variance-covariance matrix with a heteroskedasticity-robust estimator. """ robust() = RobustCovariance() Base.show(io::IO, ::RobustCovariance) = print(io, "Heteroskedasticity-robust covariance estimator") function S_hat(x::RegressionModel, ::RobustCovariance) m = modelmatrix(x) r = residuals(x) X2 = zeros(size(m, 1), size(m, 2) * size(r, 2)) index = 0 for k in 1:size(r, 2) for j in 1:size(m, 2) index += 1 for i in 1:size(m, 1) X2[i, index] = m[i, j] * r[i, k] end end end S2 = X2' * X2 Symmetric(rmul!(S2, size(m, 1) / dof_residual(x))) end function StatsAPI.vcov(x::RegressionModel, v::RobustCovariance) xtx = invcrossmodelmatrix(x) pinvertible(Symmetric(xtx * S_hat(x, v) * xtx)) end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
539
struct SimpleCovariance <: CovarianceEstimator end """ simple() Estimate variance-covariance matrix with a simple estimator. """ simple() = SimpleCovariance() Base.show(io::IO, ::SimpleCovariance) = print(io, "Simple covariance estimator") function S_hat(x::RegressionModel, ::SimpleCovariance) Symmetric(crossmodelmatrix(x) .* sum(abs2, residuals(x))) end function StatsAPI.vcov(x::RegressionModel, ::SimpleCovariance) xtx = invcrossmodelmatrix(x) Symmetric(xtx .* (sum(abs2, residuals(x)) / dof_residual(x))) end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
1376
@testset "SimpleCovariance" begin v = simple() @test sprint(show, v) == "Simple covariance estimator" end @testset "RobustCovariance" begin v = robust() @test sprint(show, v) == "Heteroskedasticity-robust covariance estimator" end @testset "ClusterCovariance" begin @test_throws MethodError cluster() c1 = cluster(:a) @test names(c1) == (:a,) @test length(c1) == 1 c2 = cluster(:a, :b) @test names(c2) == (:a, :b) @test length(c2) == 2 @test sprint(show, c1) == "Cluster-robust covariance estimator" @test sprint(show, MIME("text/plain"), c1) == """ 1-way cluster-robust covariance estimator: a""" @test sprint(show, MIME("text/plain"), c2) == """ 2-way cluster-robust covariance estimator: a b""" N = 10 a1 = collect(1:N) a2 = convert(Vector{Union{Float64, Missing}}, a1) a2[1] = missing cols = (a=a1, b=a2) g1 = GroupedArray(a1) c1 = cluster((:a,), (g1,)) @test nclusters(c1) == (a=N,) c1m = materialize(cols, cluster(:a)) @test c1m.clusternames == c1.clusternames @test c1m.clusters[1] == g1 @test completecases(cols, c1) == trues(N) c2 = materialize(cols, cluster(:b)) @test completecases(cols, c2) == (1:N.!=1) c3 = materialize(cols, cluster(:a, :b)) @test completecases(cols, c3) == (1:N.!=1) end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
code
305
using Test using Vcov: completecases, materialize, simple, robust, cluster, names, nclusters using GroupedArrays const tests = [ "estimators" ] printstyled("Running tests:\n", color=:blue, bold=true) for test in tests include("$test.jl") println("\033[1m\033[32mPASSED\033[0m: $(test)") end
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.8.1
22491492d601448b0fef54afe8a5bdfd67282965
docs
1442
[![Build status](https://github.com/FixedEffects/Vcov.jl/workflows/CI/badge.svg)](https://github.com/FixedEffects/Vcov.jl/actions) This package should be used as a backend by package developers. It allows developers to add a `::CovarianceEstimator` argument in the `fit` method defined by their package. See `FixedEffectModels` for an example. Each type defined in this package defines the following methods: ```julia # return a vector indicating non-missing observations for standard errors completecases(table, ::CovarianceEstimator) = trues(size(df, 1)) # materialize a CovarianceEstimator by using the data needed to compute the standard errors materialize(table, v::CovarianceEstimator) = v # return variance-covariance matrix vcov(x::RegressionModel, ::CovarianceEstimator) = error("vcov not defined for this type") # returns the degree of freedom for the t-statistics and F-statistic dof_tstat(x::RegressionModel, ::CovarianceEstimator, hasintercept::Bool) = dof_residual(x) - hasintercept ``` For now, it includes `Vcov.simple()`, `Vcov.robust()`, and `Vcov.cluster(...)`. ## References Kleibergen, F, and Paap, R. (2006) *Generalized reduced rank tests using the singular value decomposition.* Journal of econometrics Kleibergen, F. and Schaffer, M. (2007) *RANKTEST: Stata module to test the rank of a matrix using the Kleibergen-Paap rk statistic*. Statistical Software Components, Boston College Department of Economics.
Vcov
https://github.com/FixedEffects/Vcov.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
1214
using Libdl if haskey(ENV, "JULIA_SYSTEM_UCX") @info "using system UCX" paths = String[] if haskey(ENV, "JULIA_UCX_LIBPATH") push!(paths,) libucp = ENV["JULIA_UCP_LIB"] else libucp = Libdl.find_library(["libucp"], []) libucs = Libdl.find_library(["libucs"], []) @debug "UCX paths" libucp libucs if isempty(libucs) || isempty(libucp) error("Did not find UCX libraries, please set the JULIA_UCX_LIBPATH environment variable.") end end deps = quote const libucp = $libucp const libucs = $libucs end else deps = quote import UCX_jll: libucp, libucs end end remove_line_numbers(x) = x function remove_line_numbers(ex::Expr) if ex.head == :macrocall ex.args[2] = nothing else ex.args = [remove_line_numbers(arg) for arg in ex.args if !(arg isa LineNumberNode)] end return ex end # only update deps.jl if it has changed. # allows users to call Pkg.build("FluxRM") without triggering another round of precompilation deps_str = string(remove_line_numbers(deps)) if !isfile("deps.jl") || deps_str != read("deps.jl", String) write("deps.jl", deps_str) end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
1532
using Clang using UCX_jll UCS = joinpath(UCX_jll.artifact_dir, "include", "ucs") |> normpath UCS_INCLUDES = [joinpath(UCS, dir) for dir in readdir(UCS)] UCS_HEADERS = String[] for dir in UCS_INCLUDES headers = [joinpath(dir, header) for header in readdir(dir) if endswith(header, ".h")] append!(UCS_HEADERS, headers) end wc = init(; headers = UCS_HEADERS, output_file = joinpath(@__DIR__, "libucs_api.jl"), common_file = joinpath(@__DIR__, "libucs_common.jl"), clang_includes = vcat(UCS_INCLUDES, CLANG_INCLUDE), clang_args = ["-I", joinpath(UCS, "..")], header_wrapped = (root, current)->root == current, header_library = x->"libucs", clang_diagnostics = true, ) run(wc) function wrap_ucx_component(name) INCLUDE = joinpath(UCX_jll.artifact_dir, "include", name, "api") |> normpath HEADERS = [joinpath(INCLUDE, header) for header in readdir(INCLUDE) if endswith(header, ".h")] wc = init(; headers = HEADERS, output_file = joinpath(@__DIR__, "lib$(name)_api.jl"), common_file = joinpath(@__DIR__, "lib$(name)_common.jl"), clang_includes = vcat(INCLUDE, CLANG_INCLUDE), clang_args = ["-I", joinpath(INCLUDE, "..", "..")], header_wrapped = (root, current)->root == current, header_library = x->"lib$name", clang_diagnostics = true, ) run(wc) end wrap_ucx_component("ucp")
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
2258
using UCX using Sockets using UCX: recv, send using Base.Threads const default_port = 8890 const expected_clients = Atomic{Int}(0) function echo_server(ep::UCX.Endpoint) size = Int[0] wait(recv(ep, size, sizeof(Int))) data = Array{UInt8}(undef, size[1]) wait(recv(ep, data, sizeof(data))) wait(send(ep, data, sizeof(data))) end function start_server(ch_port = Channel{Int}(1), port = default_port) ctx = UCX.UCXContext() worker = UCX.Worker(ctx) function listener_callback(::UCX.UCXListener, conn_request::UCX.UCXConnectionRequest) UCX.@spawn_showerr begin try echo_server(UCX.Endpoint($worker, $conn_request)) atomic_sub!(expected_clients, 1) if expected_clients[] <= 0 close($worker) end finally close($worker) end end nothing end listener = UCX.UCXListener(worker.worker, listener_callback, port) push!(ch_port, listener.port) GC.@preserve listener begin while isopen(worker) wait(worker) end close(worker) end end function start_client(port=default_port) ctx = UCX.UCXContext() worker = UCX.Worker(ctx) ep = UCX.Endpoint(worker, IPv4("127.0.0.1"), port) data = "Hello world" req1 = send(ep, Int[sizeof(data)], sizeof(Int)) # XXX: Order gurantuees? req2 = send(ep, data, sizeof(data)) wait(req1); wait(req2) buffer = Array{UInt8}(undef, sizeof(data)) wait(recv(ep, buffer, sizeof(buffer))) @assert String(buffer) == data close(worker) end if !isinteractive() @assert length(ARGS) >= 1 "Expected command line argument role: 'client', 'server', 'test'" kind = ARGS[1] expected_clients[] = length(ARGS) == 2 ? parse(Int, ARGS[2]) : 1 if kind == "server" start_server() elseif kind == "client" start_client() elseif kind =="test" ch_port = Channel{Int}(1) @sync begin UCX.@spawn_showerr start_server(ch_port, nothing) port = take!(ch_port) for i in 1:expected_clients[] UCX.@spawn_showerr start_client(port) end end end end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
2331
using UCX using Sockets using UCX: UCXEndpoint using UCX: recv, send, stream_recv, stream_send using Base.Threads const default_port = 8890 const expected_clients = Atomic{Int}(0) function echo_server(ep::UCX.Endpoint) size = Int[0] wait(recv(ep, size, sizeof(Int))) data = Array{UInt8}(undef, size[1]) wait(stream_recv(ep, data, sizeof(data))) wait(stream_send(ep, data, sizeof(data))) end function start_server(ch_port = Channel{Int}(1), port = default_port) ctx = UCX.UCXContext() worker = UCX.Worker(ctx) function listener_callback(::UCX.UCXListener, conn_request::UCX.UCXConnectionRequest) UCX.@spawn_showerr begin try echo_server(UCX.Endpoint($worker, $conn_request)) atomic_sub!(expected_clients, 1) if expected_clients[] <= 0 close($worker) end finally close($worker) end end nothing end listener = UCX.UCXListener(worker.worker, listener_callback, port) push!(ch_port, listener.port) GC.@preserve listener begin while isopen(worker) wait(worker) end close(worker) end end function start_client(port = default_port) ctx = UCX.UCXContext() worker = UCX.Worker(ctx) ep = UCX.Endpoint(worker, IPv4("127.0.0.1"), port) data = "Hello world" req1 = send(ep, Int[sizeof(data)], sizeof(Int)) req2 = stream_send(ep, data, sizeof(data)) buffer = Array{UInt8}(undef, sizeof(data)) req3 = stream_recv(ep, buffer, sizeof(buffer)) wait(req1) wait(req2) wait(req3) @assert String(buffer) == data close(worker) end if !isinteractive() @assert length(ARGS) >= 1 "Expected command line argument role: 'client', 'server', 'test'" kind = ARGS[1] expected_clients[] = length(ARGS) == 2 ? parse(Int, ARGS[2]) : 1 if kind == "server" start_server() elseif kind == "client" start_client() elseif kind =="test" ch_port = Channel{Int}(1) @sync begin UCX.@spawn_showerr start_server(ch_port, nothing) port = take!(ch_port) for i in 1:expected_clients[] UCX.@spawn_showerr start_client(port) end end end end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
509
using Printf using TypedTables using CSV const MAX_MESSAGE_SIZE = 1<<22 const LARGE_MESSAGE_SIZE = 8192 const LAT_LOOP_SMALL = 10000 const LAT_SKIP_SMALL = 100 const LAT_LOOP_LARGE = 1000 const LAT_SKIP_LARGE = 10 function prettytime(t) if t < 1e3 value, units = t, "ns" elseif t < 1e6 value, units = t / 1e3, "μs" elseif t < 1e9 value, units = t / 1e6, "ms" else value, units = t / 1e9, "s" end return string(@sprintf("%.3f", value), " ", units) end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
668
using CairoMakie using TypedTables using CSV # Latency dist_latency = Table(CSV.File("distributed/latency.csv")) ucx_latency = Table(CSV.File("ucx/latency.csv")) mpi_latency = Table(CSV.File("mpi/latency.csv")) let f = Figure() fig = f[1, 1] = Axis(f, palette = (color = [:black],)) fig.xlabel = "Message size (bytes)" fig.ylabel = "Latency (ns)" lines!(dist_latency.msg_size, dist_latency.latency, label = "Distributed", linewidth = 2) lines!(ucx_latency.msg_size, ucx_latency.latency, label = "UCX", linewidth = 2) lines!(mpi_latency.msg_size, mpi_latency.latency, label = "MPI", linewidth = 2) f[1, 2] = Legend(f, fig) f end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
1304
using Distributed include(joinpath(@__DIR__, "..", "config.jl")) addprocs(1) @everywhere function target(A) nothing end const MAX_MESSAGE_SIZE = 1<<22 const LARGE_MESSAGE_SIZE = 8192 const LAT_LOOP_SMALL = 10000 const LAT_SKIP_SMALL = 100 const LAT_LOOP_LARGE = 1000 const LAT_SKIP_LARGE = 10 function touch_data(send_buf, size) send_buf[1:size] .= 'A' % UInt8 end function benchmark() send_buf = Vector{UInt8}(undef, MAX_MESSAGE_SIZE) t = Table(msg_size = Int[], latency = Float64[], kind=Symbol[]) size = 1 while size <= MAX_MESSAGE_SIZE touch_data(send_buf, size) if size > LARGE_MESSAGE_SIZE loop = LAT_LOOP_LARGE skip = LAT_SKIP_LARGE else loop = LAT_LOOP_SMALL skip = LAT_SKIP_SMALL end t_start = 0 for i in -skip:loop if i == 1 t_start = Base.time_ns() end remotecall_wait(target, 2, view(send_buf, 1:size)) end t_end = Base.time_ns() t_delta = t_end-t_start t_op = t_delta / loop push!(t, (msg_size = size, latency = t_op, kind = :distributed)) size *= 2 end CSV.write(joinpath(@__DIR__, "latency.csv"), t) end if !isinteractive() benchmark() end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
1896
using MPI using Sockets include(joinpath(@__DIR__, "..", "config.jl")) # mpiexec() do cmd # run(`$cmd -n 2 $(Base.julia_cmd()) --project=examples/benchmarks examples/benchmarks/mpi/latency.jl`) # end # Inspired by OSU Microbenchmark latency test function touch_data(send_buf, recv_buf, size) send_buf[1:size] .= 'A' % UInt8 recv_buf[1:size] .= 'B' % UInt8 end function benchmark() MPI.Init() myid = MPI.Comm_rank(MPI.COMM_WORLD) recv_buf = Vector{UInt8}(undef, MAX_MESSAGE_SIZE) send_buf = Vector{UInt8}(undef, MAX_MESSAGE_SIZE) t = Table(msg_size = Int[], latency = Float64[], kind=Symbol[]) size = 1 while size <= MAX_MESSAGE_SIZE touch_data(send_buf, recv_buf, size) if size > LARGE_MESSAGE_SIZE loop = LAT_LOOP_LARGE skip = LAT_SKIP_LARGE else loop = LAT_LOOP_SMALL skip = LAT_SKIP_SMALL end MPI.Barrier(MPI.COMM_WORLD) t_start = 0 t_end = 0 if myid == 0 for i in -skip:loop if i == 1 t_start = Base.time_ns() end MPI.Send(view(send_buf, 1:size), 1, 1, MPI.COMM_WORLD) MPI.Recv!(view(recv_buf, 1:size), 1, 1, MPI.COMM_WORLD) end t_end = Base.time_ns() else for i in -skip:loop MPI.Recv!(view(recv_buf, 1:size), 0, 1, MPI.COMM_WORLD) MPI.Send(view(send_buf, 1:size), 0, 1, MPI.COMM_WORLD) end end if myid == 0 t_delta = t_end-t_start t_op = t_delta / (2*loop) push!(t, (msg_size = size, latency = t_op, kind=:mpi)) end size *= 2 end if myid == 0 CSV.write(joinpath(@__DIR__, "latency.csv"), t) end exit() end if !isinteractive() benchmark() end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
2730
using UCX using Sockets const port = 8890 include(joinpath(@__DIR__, "..", "config.jl")) # Inspired by OSU Microbenchmark latency test function touch_data(send_buf, recv_buf, size) send_buf[1:size] .= 'A' % UInt8 recv_buf[1:size] .= 'B' % UInt8 end function benchmark(ep, myid) recv_buf = Vector{UInt8}(undef, MAX_MESSAGE_SIZE) send_buf = Vector{UInt8}(undef, MAX_MESSAGE_SIZE) t = Table(msg_size = Int[], latency = Float64[], kind=Symbol[]) size = 1 while size <= MAX_MESSAGE_SIZE touch_data(send_buf, recv_buf, size) if size > LARGE_MESSAGE_SIZE loop = LAT_LOOP_LARGE skip = LAT_SKIP_LARGE else loop = LAT_LOOP_SMALL skip = LAT_SKIP_SMALL end # TODO Barrier t_start = 0 t_end = 0 if myid == 0 for i in -skip:loop if i == 1 t_start = Base.time_ns() end UCX.stream_send(ep, send_buf, size) UCX.stream_recv(ep, recv_buf, size) end t_end = Base.time_ns() else for i in -skip:loop UCX.stream_recv(ep, recv_buf, size) UCX.stream_send(ep, send_buf, size) end end if myid == 0 t_delta = t_end-t_start t_op = t_delta / (2*loop) push!(t, (msg_size = size, latency = t_op, kind=:ucx)) end size *= 2 end if myid == 0 CSV.write(joinpath(@__DIR__, "latency.csv"), t) end exit() end function start_server() ctx = UCX.UCXContext() worker = UCX.UCXWorker(ctx) function listener_callback(conn_request_h::UCX.API.ucp_conn_request_h, args::Ptr{Cvoid}) conn_request = UCX.UCXConnectionRequest(conn_request_h) Threads.@spawn begin try benchmark(UCX.UCXEndpoint($worker, $conn_request), 0) catch err showerror(stderr, err, catch_backtrace()) exit(-1) end end nothing end cb = @cfunction($listener_callback, Cvoid, (UCX.API.ucp_conn_request_h, Ptr{Cvoid})) listener = UCX.UCXListener(worker, port, cb) while true UCX.progress(worker) yield() end end function start_client() ctx = UCX.UCXContext() worker = UCX.UCXWorker(ctx) ep = UCX.UCXEndpoint(worker, IPv4("127.0.0.1"), port) benchmark(ep, 1) end if !isinteractive() @assert length(ARGS) == 1 "Expected command line argument role: 'client', 'server" kind = ARGS[1] if kind == "server" start_server() elseif kind == "client" start_client() end end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
366
include(joinpath(@__DIR__, "..", "deps", "deps.jl")) const FILE = Base.Libc.FILE const __socklen_t = Cuint const socklen_t = __socklen_t const sa_family_t = Cushort # FIXME: Clang.jl should have defined this UCS_BIT(i) = (UInt(1) << (convert(UInt, i))) UCP_VERSION(_major, _minor) = (((_major) << UCP_VERSION_MAJOR_SHIFT) | ((_minor) << UCP_VERSION_MINOR_SHIFT))
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
447
using Clang.Generators using UCX_jll include_dir = joinpath(UCX_jll.artifact_dir ,"include") options = load_options(joinpath(@__DIR__, "wrap.toml")) args = get_default_args() push!(args, "-I$include_dir") headers = [joinpath(include_dir, "ucp", "api", header) for header in ["ucp.h"]] @add_def socklen_t @add_def sa_family_t # @add_def sockaddr @add_def sockaddr_storage @add_def FILE ctx = create_context(headers, args, options) build!(ctx)
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
30990
module UCX using Sockets: InetAddr, IPv4, listenany using Random import FunctionWrappers: FunctionWrapper const PROGRESS_MODE = Ref(:idling) include("api.jl") include("ip.jl") function __init__() # Julia multithreading uses SIGSEGV to sync thread # https://docs.julialang.org/en/v1/devdocs/debuggingtips/#Dealing-with-signals-1 # By default, UCX will error if this occurs (see https://github.com/JuliaParallel/MPI.jl/issues/337) # This is a global flag and can't be set per context, since Julia generally # handles signals I don't see any additional value in having UCX mess with # signal handlers. Setting the environment here does not work, since it is # global, not context specific, and is being parsed on library load. # reinstall signal handlers ccall((:ucs_debug_disable_signals, API.libucs), Cvoid, ()) @assert version() >= VersionNumber(API.UCP_API_MAJOR, API.UCP_API_MINOR) mode = get(ENV, "JLUCX_PROGRESS_MODE", "idling") if mode == "busy" PROGRESS_MODE[] = :busy elseif mode == "idling" PROGRESS_MODE[] = :idling elseif mode == "polling" PROGRESS_MODE[] = :polling else error("JLUCX_PROGRESS_MODE set to unkown progress mode: $mode") end @debug "UCX progress mode" mode end function memzero!(ref::Ref) ccall(:memset, Ptr{Cvoid}, (Ptr{Cvoid}, Cint, Csize_t), ref, 0, sizeof(ref)) end Base.@pure function find_field(::Type{T}, fieldname) where T findfirst(f->f === fieldname, fieldnames(T)) end @inline function unsafe_fieldptr(ref::Ref{T}, fieldname) where T field = find_field(T, fieldname) @assert field !== nothing offset = fieldoffset(T, field) base_ptr = Base.unsafe_convert(Ptr{T}, ref) ptr = reinterpret(UInt, base_ptr) + offset return reinterpret(Ptr{fieldtype(T, field)}, ptr) end @inline function set!(ref::Ref{T}, fieldname, val) where T GC.@preserve ref begin Base.unsafe_store!(unsafe_fieldptr(ref, fieldname), val) end val end # Exceptions/Status uintptr_t(ptr::Ptr) = reinterpret(UInt, ptr) uintptr_t(status::API.ucs_status_t) = reinterpret(UInt, convert(Int, status)) UCS_PTR_STATUS(ptr::Ptr{Cvoid}) = API.ucs_status_t(reinterpret(UInt, ptr)) UCS_PTR_IS_ERR(ptr::Ptr{Cvoid}) = uintptr_t(ptr) >= uintptr_t(API.UCS_ERR_LAST) UCS_PTR_IS_PTR(ptr::Ptr{Cvoid}) = (uintptr_t(ptr) - 1) < (uintptr_t(API.UCS_ERR_LAST) - 1) struct UCXException <: Exception status::API.ucs_status_t end macro check(ex) quote status = $(esc(ex)) if status != API.UCS_OK throw(UCXException(status)) end end end # Utils macro async_showerr(ex) esc(quote @async try $ex catch err bt = catch_backtrace() showerror(stderr, err, bt) rethrow() end end) end macro spawn_showerr(ex) esc(quote Base.Threads.@spawn try $ex catch err bt = catch_backtrace() showerror(stderr, err, bt) rethrow() end end) end # Config function version() major = Ref{Cuint}() minor = Ref{Cuint}() patch = Ref{Cuint}() API.ucp_get_version(major, minor, patch) VersionNumber(major[], minor[], patch[]) end mutable struct UCXConfig handle::Ptr{API.ucp_config_t} function UCXConfig(; kwargs...) r_handle = Ref{Ptr{API.ucp_config_t}}() @check API.ucp_config_read(C_NULL, C_NULL, r_handle) # XXX: Prefix is broken config = new(r_handle[]) finalizer(config) do config API.ucp_config_release(config) end for (key, value) in kwargs config[key] = string(value) end config end end Base.unsafe_convert(::Type{Ptr{API.ucp_config_t}}, config::UCXConfig) = config.handle function Base.setindex!(config::UCXConfig, value::String, key::Union{String, Symbol}) @check API.ucp_config_modify(config, key, value) return value end function Base.parse(::Type{Dict}, config::UCXConfig) ptr = Ref{Ptr{Cchar}}() size = Ref{Csize_t}() fd = ccall(:open_memstream, Ptr{API.FILE}, (Ptr{Ptr{Cchar}}, Ptr{Csize_t}), ptr, size) # Flush the just created fd to have `ptr` be valid systemerror("fflush", ccall(:fflush, Cint, (Ptr{API.FILE},), fd) != 0) try API.ucp_config_print(config, fd, C_NULL, API.UCS_CONFIG_PRINT_CONFIG) systemerror("fclose", ccall(:fclose, Cint, (Ptr{API.FILE},), fd) != 0) catch Base.Libc.free(ptr[]) rethrow() end io = IOBuffer(unsafe_wrap(Array, Base.unsafe_convert(Ptr{UInt8}, ptr[]), (size[],), own=true)) dict = Dict{Symbol, String}() for line in readlines(io) key, value = split(line, '=') key = key[5:end] # Remove `UCX_` dict[Symbol(key)] = value end return dict end mutable struct UCXContext handle::API.ucp_context_h config::Dict{Symbol, String} function UCXContext(wakeup = PROGRESS_MODE[] == :polling; kwargs...) field_mask = API.UCP_PARAM_FIELD_FEATURES # Note: ucx-py always request UCP_FEATURE_WAKEUP even when in blocking mode # See <https://github.com/rapidsai/ucx-py/pull/377> # But FEATURE_WAKEUP disables shared memory, see https://github.com/openucx/ucx/issues/5322 # and https://github.com/JuliaParallel/UCX.jl/issues/36 # There is also AMO32 & AMO64 (atomic), RMA, features = API.UCP_FEATURE_TAG | API.UCP_FEATURE_STREAM | API.UCP_FEATURE_AM if wakeup features |= API.UCP_FEATURE_WAKEUP end params = Ref{API.ucp_params}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :features, features) config = UCXConfig(; kwargs...) r_handle = Ref{API.ucp_context_h}() # UCP.ucp_init is a header function so we call, UCP.ucp_init_version @check API.ucp_init_version(API.UCP_API_MAJOR, API.UCP_API_MINOR, params, config, r_handle) context = new(r_handle[], parse(Dict, config)) finalizer(context) do context API.ucp_cleanup(context) end end end Base.unsafe_convert(::Type{API.ucp_context_h}, ctx::UCXContext) = ctx.handle function info(ucx::UCXContext) ptr = Ref{Ptr{Cchar}}() size = Ref{Csize_t}() fd = ccall(:open_memstream, Ptr{API.FILE}, (Ptr{Ptr{Cchar}}, Ptr{Csize_t}), ptr, size) # Flush the just created fd to have `ptr` be valid systemerror("fflush", ccall(:fflush, Cint, (Ptr{API.FILE},), fd) != 0) try API.ucp_context_print_info(ucx, fd) systemerror("fclose", ccall(:fclose, Cint, (Ptr{API.FILE},), fd) != 0) catch Base.Libc.free(ptr[]) rethrow() end str = unsafe_string(ptr[], size[]) Base.Libc.free(ptr[]) str end function query(ctx::UCXContext) r_attr = Ref{API.ucp_context_attr_t}() API.ucp_context_query(ctx, r_attr) r_attr[] end mutable struct UCXWorker handle::API.ucp_worker_h fd::RawFD context::UCXContext inflight::IdDict{Any, Nothing} # IdSet -- Can't use UCXRequest since that is defined after am_handlers::Dict{UInt16, Any} in_amhandler::Vector{Bool} open::Bool mode::Symbol function UCXWorker(context::UCXContext; progress_mode=PROGRESS_MODE[]) field_mask = API.UCP_WORKER_PARAM_FIELD_THREAD_MODE thread_mode = API.UCS_THREAD_MODE_MULTI params = Ref{API.ucp_worker_params}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :thread_mode, thread_mode) @debug "Creating UCXWorker" thread_mode progress_mode r_handle = Ref{API.ucp_worker_h}() @check API.ucp_worker_create(context, params, r_handle) handle = r_handle[] # TODO: Verify that UCXContext has been created with WAKEUP if progress_mode === :polling r_fd = Ref{API.Cint}() @check API.ucp_worker_get_efd(handle, r_fd) fd = Libc.RawFD(r_fd[]) else fd = RawFD(-1) end worker = new(handle, fd, context, IdDict{Any,Nothing}(), Dict{UInt16, Any}(), fill(false, Base.Threads.nthreads()), true, progress_mode) finalizer(worker) do worker worker.open = false @assert isempty(worker.inflight) API.ucp_worker_destroy(worker) end return worker end end Base.unsafe_convert(::Type{API.ucp_worker_h}, worker::UCXWorker) = worker.handle ispolling(worker::UCXWorker) = worker.fd != RawFD(-1) progress_mode(worker::UCXWorker) = worker.mode """ progress(worker::UCXWorker) Allows `worker` to make progress, this includes finalizing requests and call callbacks. Returns `true` if progress was made, `false` if no work was waiting. """ function progress(worker::UCXWorker, allow_yield=true) tid = Base.Threads.threadid() if worker.in_amhandler[tid] @debug """ UCXWorker is processing a Active Message on this thread Calling `progress` is not permitted and leads to recursion. """ tid exception=(UCXException(API.UCS_ERR_NO_PROGRESS), catch_backtrace()) if allow_yield yield() end return false else return API.ucp_worker_progress(worker) != 0 end end function fence(worker::UCXWorker) @check API.ucp_worker_fence(worker) end function lock_am(worker::UCXWorker) tid = Base.Threads.threadid() if worker.in_amhandler[tid] error("UCXWorker already in AMHandler on this thread! Concurrency violation.") end worker.in_amhandler[tid] = true end function unlock_am(worker::UCXWorker) tid = Base.Threads.threadid() if !worker.in_amhandler[tid] error("UCXWorker is not in AMHandler on this thread! Concurrency violation.") end worker.in_amhandler[tid] = false end include("idle.jl") import FileWatching: poll_fd function Base.wait(worker::UCXWorker) if ispolling(worker) @assert progress_mode(worker) === :polling # Use fd_poll to suspend worker when no progress is being made while isopen(worker) if progress(worker) # progress was made yield() continue end # Wait for poll status = API.ucp_worker_arm(worker) if status == API.UCS_OK if !isopen(worker) error("UCXWorker already closed") end # wait for events poll_fd(worker.fd; writable=true, readable=true) progress(worker) break elseif status == API.UCS_ERR_BUSY # could not arm, need to progress more continue else @check status end end elseif progress_mode(worker) === :idling idler = UvWorkerIdle(worker) wait(idler) close(idler) elseif progress_mode(worker) === :busy progress(worker) while isopen(worker) # Temporary solution before we have gc transition support in codegen. # XXX: `yield()` is supposed to be a safepoint, but without this we easily # deadlock in a multithreaded test. ccall(:jl_gc_safepoint, Cvoid, ()) yield() progress(worker) end else throw(UCXException(API.UCS_ERR_UNREACHABLE)) end end function Base.notify(worker::UCXWorker) # If we don't use polling, we can't signal the worker if ispolling(worker) @check API.ucp_worker_signal(worker) end end function Base.isopen(worker::UCXWorker) worker.open end function Base.close(worker::UCXWorker) @debug "Close worker" worker.open = false notify(worker) end """ AMHandler(func) ## Arguments to callback - `worker::UCXWorker` - `data::Ptr{Cvoid}` - `length::Csize_t` - `reply_ep::API.ucp_ep_h` - `flags::Cuint` ## Return values The callback `func` needs to return either `UCX.API.UCS_OK` or `UCX.API.UCS_INPROGRESS`. If it returns `UCX.API.UCS_INPROGRESS` it **must** call `am_data_release(worker, data)`, or call `am_recv`. """ mutable struct AMHandler func::FunctionWrapper{API.ucs_status_t, Tuple{UCXWorker, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Ptr{API.ucp_am_recv_param_t}}} worker::UCXWorker end function am_recv_callback(arg::Ptr{Cvoid}, header::Ptr{Cvoid}, header_length::Csize_t, data::Ptr{Cvoid}, length::Csize_t, param::Ptr{API.ucp_am_recv_param_t})::API.ucs_status_t handler = Base.unsafe_pointer_to_objref(arg)::AMHandler try lock_am(handler.worker) return handler.func(handler.worker, header, header_length, data, length, param)::API.ucs_status_t catch err showerror(stderr, err, catch_backtrace()) return API.UCS_OK finally unlock_am(handler.worker) end end AMHandler(f, w::UCXWorker, id) = AMHandler(w, f, id) function AMHandler(worker::UCXWorker, func, id) @debug "Installing AMHandler on worker" func id handler = AMHandler(func, worker) worker.am_handlers[id] = handler # root handler in worker arg = Base.pointer_from_objref(handler) cb = @cfunction(am_recv_callback, API.ucs_status_t, (Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Ptr{API.ucp_am_recv_param_t})) field_mask = API.UCP_AM_HANDLER_PARAM_FIELD_ID | API.UCP_AM_HANDLER_PARAM_FIELD_CB | API.UCP_AM_HANDLER_PARAM_FIELD_ARG params = Ref{API.ucp_am_handler_param_t}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :id, id) set!(params, :cb, cb) set!(params, :arg, arg) @check API.ucp_worker_set_am_recv_handler(worker, params) end function delete_am!(worker::UCXWorker, id) delete!(worker.am_handlers, id) field_mask = API.UCP_AM_HANDLER_PARAM_FIELD_ID | API.UCP_AM_HANDLER_PARAM_FIELD_CB | API.UCP_AM_HANDLER_PARAM_FIELD_ARG params = Ref{API.ucp_am_handler_param_t}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :id, id) set!(params, :cb, C_NULL) set!(params, :arg, C_NULL) @check API.ucp_worker_set_am_recv_handler(worker, params) end function am_data_release(worker::UCXWorker, data) API.ucp_am_data_release(worker, data) end mutable struct UCXAddress worker::UCXWorker handle::Ptr{API.ucp_address_t} len::Csize_t function UCXAddress(worker::UCXWorker) addr = Ref{Ptr{API.ucp_address_t}}() len = Ref{Csize_t}() @check API.ucp_worker_get_address(worker, addr, len) this = new(worker, addr[], len[]) finalizer(this) do addr API.ucp_worker_release_address(addr.worker, addr.handle) end return this end end struct UCXConnectionRequest handle::API.ucp_conn_request_h end mutable struct UCXEndpoint handle::API.ucp_ep_h worker::UCXWorker function UCXEndpoint(worker::UCXWorker, handle::API.ucp_ep_h) @assert handle != C_NULL endpoint = new(handle, worker) finalizer(endpoint) do endpoint # NOTE: Generally not safe to spin in finalizer # - ucp_ep_destroy # - ucp_ep_close_nb (Gracefully shutdown) # - UCP_EP_CLOSE_MODE_FORCE # - UCP_EP_CLOSE_MODE_FLUSH let handle = endpoint.handle # Valid since we are aleady finalizing endpoint @async_showerr begin status = API.ucp_ep_close_nb(handle, API.UCP_EP_CLOSE_MODE_FLUSH) if UCS_PTR_IS_PTR(status) while API.ucp_request_check_status(status) == API.UCS_INPROGRESS progress(worker) yield() end API.ucp_request_free(status) else @check UCS_PTR_STATUS(status) end end end end endpoint end end Base.unsafe_convert(::Type{API.ucp_ep_h}, ep::UCXEndpoint) = ep.handle function UCXEndpoint(worker::UCXWorker, ip::IPv4, port) field_mask = API.UCP_EP_PARAM_FIELD_FLAGS | API.UCP_EP_PARAM_FIELD_SOCK_ADDR flags = API.UCP_EP_PARAMS_FLAGS_CLIENT_SERVER sockaddr = Ref(IP.sockaddr_in(InetAddr(ip, port))) r_handle = Ref{API.ucp_ep_h}() GC.@preserve sockaddr begin ptr = Base.unsafe_convert(Ptr{IP.sockaddr_in}, sockaddr) addrlen = sizeof(IP.sockaddr_in) ucs_sockaddr = API.ucs_sock_addr(reinterpret(Ptr{API.sockaddr}, ptr), addrlen) params = Ref{API.ucp_ep_params}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :sockaddr, ucs_sockaddr) set!(params, :flags, flags) # TODO: Error callback @check API.ucp_ep_create(worker, params, r_handle) end UCXEndpoint(worker, r_handle[]) end function UCXEndpoint(worker::UCXWorker, conn_request::UCXConnectionRequest) field_mask = API.UCP_EP_PARAM_FIELD_FLAGS | API.UCP_EP_PARAM_FIELD_CONN_REQUEST flags = API.UCP_EP_PARAMS_FLAGS_NO_LOOPBACK params = Ref{API.ucp_ep_params}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :conn_request, conn_request.handle) set!(params, :flags, flags) # TODO: Error callback r_handle = Ref{API.ucp_ep_h}() @check API.ucp_ep_create(worker, params, r_handle) UCXEndpoint(worker, r_handle[]) end function UCXEndpoint(worker::UCXWorker, addr::UCXAddress) GC.@preserve addr begin _UCXEndpoint(worker, addr.handle) end end function UCXEndpoint(worker::UCXWorker, addr_buf::Vector{UInt8}) GC.@preserve addr_buf begin addr = Base.unsafe_convert(Ptr{API.ucp_address_t}, pointer(addr_buf)) _UCXEndpoint(worker, addr) end end function _UCXEndpoint(worker::UCXWorker, addr::Ptr{API.ucp_address_t}) field_mask = API.UCP_EP_PARAM_FIELD_REMOTE_ADDRESS r_handle = Ref{API.ucp_ep_h}() params = Ref{API.ucp_ep_params}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :address, addr) # TODO: Error callback @check API.ucp_ep_create(worker, params, r_handle) UCXEndpoint(worker, r_handle[]) end function listener_callback(conn_request_h::API.ucp_conn_request_h, args::Ptr{Cvoid}) conn_request = UCX.UCXConnectionRequest(conn_request_h) listener = Base.unsafe_pointer_to_objref(args)::UCXListener Base.invokelatest(listener.callback, listener, conn_request) nothing end mutable struct UCXListener handle::API.ucp_listener_h worker::UCXWorker port::Cint callback::Any function UCXListener(worker::UCXWorker, callback, port=nothing) # Choose free port if port === nothing || port == 0 port_hint = 9000 + (getpid() % 1000) port, sock = listenany(UInt16(port_hint)) close(sock) # FIXME: https://github.com/rapidsai/ucx-py/blob/72552d1dd1d193d1c8ce749171cdd34d64523d53/ucp/core.py#L288-L304 end field_mask = API.UCP_LISTENER_PARAM_FIELD_SOCK_ADDR | API.UCP_LISTENER_PARAM_FIELD_CONN_HANDLER sockaddr = Ref(IP.sockaddr_in(InetAddr(IPv4(IP.INADDR_ANY), port))) this = new(C_NULL, worker, port, callback) r_handle = Ref{API.ucp_listener_h}() GC.@preserve sockaddr this begin args = Base.pointer_from_objref(this) conn_handler = API.ucp_listener_conn_handler(@cfunction(listener_callback, Cvoid, (API.ucp_conn_request_h, Ptr{Cvoid})), args) ptr = Base.unsafe_convert(Ptr{IP.sockaddr_in}, sockaddr) addrlen = sizeof(IP.sockaddr_in) ucs_sockaddr = API.ucs_sock_addr(reinterpret(Ptr{API.sockaddr}, ptr), addrlen) params = Ref{API.ucp_listener_params}() memzero!(params) set!(params, :field_mask, field_mask) set!(params, :sockaddr, ucs_sockaddr) set!(params, :conn_handler, conn_handler) @check API.ucp_listener_create(worker, params, r_handle) end this.handle = r_handle[] finalizer(this) do listener API.ucp_listener_destroy(listener) end this end end Base.unsafe_convert(::Type{API.ucp_listener_h}, listener::UCXListener) = listener.handle function reject(listener::UCXListener, conn_request::UCXConnectionRequest) @check API.ucp_listener_reject(listener, conn_request.handle) end function ucp_dt_make_contig(elem_size) ((elem_size%API.ucp_datatype_t) << convert(API.ucp_datatype_t, API.UCP_DATATYPE_SHIFT)) | API.UCP_DATATYPE_CONTIG end ## # Request handling ## # User representation of a request # don't create these manually mutable struct UCXRequest worker::UCXWorker event::Base.Event status::API.ucs_status_t data::Any function UCXRequest(worker::UCXWorker, data) req = new(worker, Base.Event(), API.UCS_OK, data) worker.inflight[req] = nothing return req end end UCXRequest(ep::UCXEndpoint, data) = UCXRequest(ep.worker, data) function unroot(request::UCXRequest) inflight = request.worker.inflight delete!(inflight, request) end function UCXRequest(_request::Ptr{Cvoid}) request = Base.unsafe_pointer_to_objref(_request) # rooted through inflight unroot(request) # caller is now responsible return request end @inline function handle_request(request::UCXRequest, ptr) if !UCS_PTR_IS_PTR(ptr) # Request is already done unroot(request) status = UCS_PTR_STATUS(ptr) request.status = status notify(request) end return request end Base.notify(req::UCXRequest) = notify(req.event) function Base.wait(req::UCXRequest) if progress_mode(req.worker) === :busy # The worker will make independent progress # and if we don't suspend here we will get a livelock. wait(req.event) @check req.status else # Request busy loop # It can be that only due to us calling progress we will trigger # the Event, and the Worker will suspend due to the use of polling. progress(req.worker) ev = req.event while true lock(ev.notify) if ev.set break end unlock(ev.notify) yield() progress(req.worker) end unlock(ev.notify) @check req.status end end ## # UCX tagged send and receive ## function send_callback(req::Ptr{Cvoid}, status::API.ucs_status_t, user_data::Ptr{Cvoid}) @assert user_data !== C_NULL request = UCXRequest(user_data) request.status = status notify(request) API.ucp_request_free(req) nothing end function recv_callback(req::Ptr{Cvoid}, status::API.ucs_status_t, info::Ptr{API.ucp_tag_recv_info_t}, user_data::Ptr{Cvoid}) @assert user_data !== C_NULL request = UCXRequest(user_data) request.status = status notify(request) API.ucp_request_free(req) nothing end @inline function request_param(dt, request, (cb, name), flags=nothing) attr_mask = API.UCP_OP_ATTR_FIELD_CALLBACK | API.UCP_OP_ATTR_FIELD_USER_DATA | API.UCP_OP_ATTR_FIELD_DATATYPE if flags !== nothing attr_mask |= API.UCP_OP_ATTR_FIELD_FLAGS end param = Ref{API.ucp_request_param_t}() memzero!(param) set!(param, :op_attr_mask, attr_mask) GC.@preserve param begin ptr = unsafe_fieldptr(param, :cb) Base.setproperty!(ptr, name, cb) end set!(param, :datatype, dt) set!(param, :user_data, Base.pointer_from_objref(request)) if flags !== nothing set!(param, :flags, flags) end param end function send(ep::UCXEndpoint, buffer, nbytes, tag) dt = ucp_dt_make_contig(1) # since we are sending nbytes request = UCXRequest(ep, buffer) # rooted through worker cb = @cfunction(send_callback, Cvoid, (Ptr{Cvoid}, API.ucs_status_t, Ptr{Cvoid})) param = request_param(dt, request, (cb, :send)) GC.@preserve buffer begin data = pointer(buffer) ptr = API.ucp_tag_send_nbx(ep, data, nbytes, tag, param) return handle_request(request, ptr) end end function recv(worker::UCXWorker, buffer, nbytes, tag, tag_mask=~zero(UCX.API.ucp_tag_t)) dt = ucp_dt_make_contig(1) # since we are receiving nbytes request = UCXRequest(worker, buffer) # rooted through worker cb = @cfunction(recv_callback, Cvoid, (Ptr{Cvoid}, API.ucs_status_t, Ptr{API.ucp_tag_recv_info_t}, Ptr{Cvoid})) param = request_param(dt, request, (cb, :recv)) GC.@preserve buffer begin data = pointer(buffer) ptr = API.ucp_tag_recv_nbx(worker, data, nbytes, tag, tag_mask, param) return handle_request(request, ptr) end end # UCX probe & probe msg receive ## # UCX stream interface ## function stream_recv_callback(req::Ptr{Cvoid}, status::API.ucs_status_t, length::Csize_t, user_data::Ptr{Cvoid}) @assert user_data !== C_NULL request = UCXRequest(user_data) request.status = status notify(request) API.ucp_request_free(req) nothing end function stream_send(ep::UCXEndpoint, buffer, nbytes) request = UCXRequest(ep, buffer) # rooted through ep.worker GC.@preserve buffer begin data = pointer(buffer) stream_send(ep, request, data, nbytes) end end function stream_send(ep::UCXEndpoint, ref::Ref{T}) where T request = UCXRequest(ep, ref) # rooted through ep.worker GC.@preserve ref begin data = Base.unsafe_convert(Ptr{Cvoid}, ref) stream_send(ep, request, data, sizeof(T)) end end function stream_send(ep::UCXEndpoint, request::UCXRequest, data::Ptr, nbytes) dt = ucp_dt_make_contig(1) # since we are sending nbytes cb = @cfunction(send_callback, Cvoid, (Ptr{Cvoid}, API.ucs_status_t, Ptr{Cvoid})) param = request_param(dt, request, (cb, :send)) ptr = API.ucp_stream_send_nbx(ep, data, nbytes, param) return handle_request(request, ptr) end function stream_recv(ep::UCXEndpoint, buffer, nbytes) request = UCXRequest(ep, buffer) # rooted through ep.worker GC.@preserve buffer begin data = pointer(buffer) stream_recv(ep, request, data, nbytes) end end function stream_recv(ep::UCXEndpoint, ref::Ref{T}) where T request = UCXRequest(ep, ref) # rooted through ep.worker GC.@preserve ref begin data = Base.unsafe_convert(Ptr{Cvoid}, ref) stream_recv(ep, request, data, sizeof(T)) end end function stream_recv(ep::UCXEndpoint, request::UCXRequest, data::Ptr, nbytes) dt = ucp_dt_make_contig(1) # since we are sending nbytes cb = @cfunction(stream_recv_callback, Cvoid, (Ptr{Cvoid}, API.ucs_status_t, Csize_t, Ptr{Cvoid})) flags = API.UCP_STREAM_RECV_FLAG_WAITALL length = Ref{Csize_t}(0) param = request_param(dt, request, (cb, :recv_stream), flags) ptr = API.ucp_stream_recv_nbx(ep, data, nbytes, length, param) return handle_request(request, ptr) end ### TODO: stream_recv_data_nbx ## RMA ## Atomics ## AM function am_send(ep::UCXEndpoint, id, header, buffer=nothing, flags=nothing) dt = ucp_dt_make_contig(1) # since we are sending nbytes cb = @cfunction(send_callback, Cvoid, (Ptr{Cvoid}, API.ucs_status_t, Ptr{Cvoid})) request = UCXRequest(ep, (header, buffer)) # rooted through ep.worker param = request_param(dt, request, (cb, :send), flags) GC.@preserve buffer header begin if buffer === nothing data = C_NULL nbytes = 0 else data = Base.unsafe_convert(Ptr{Cvoid}, Base.cconvert(Ptr{Cvoid}, buffer)) nbytes = sizeof(buffer) end header_ptr = Base.unsafe_convert(Ptr{Cvoid}, Base.cconvert(Ptr{Cvoid}, header)) ptr = API.ucp_am_send_nbx(ep, id, header_ptr, sizeof(header), data, nbytes, param) end return handle_request(request, ptr) end function am_data_recv_callback(req::Ptr{Cvoid}, status::API.ucs_status_t, length::Csize_t, user_data::Ptr{Cvoid}) @assert user_data !== C_NULL request = UCXRequest(user_data) request.status = status notify(request) API.ucp_request_free(req) return nothing end function am_recv(worker::UCXWorker, data_desc, buffer, nbytes) dt = ucp_dt_make_contig(1) # since we are sending nbytes cb = @cfunction(am_data_recv_callback, Cvoid, (Ptr{Cvoid}, API.ucs_status_t, Csize_t, Ptr{Cvoid})) request = UCXRequest(worker, buffer) # rooted through ep.worker param = request_param(dt, request, (cb, :recv_am)) GC.@preserve buffer begin data = pointer(buffer) ptr = API.ucp_am_recv_data_nbx(worker, data_desc, data, nbytes, param) end return handle_request(request, ptr) end ## Collectives # Higher-Level API mutable struct Worker worker::UCXWorker function Worker(ctx::UCXContext) new(UCXWorker(ctx)) end end Base.isopen(worker::Worker) = isopen(worker.worker) Base.notify(worker::Worker) = notify(worker.worker) Base.wait(worker::Worker) = wait(worker.worker) Base.close(worker::Worker) = close(worker.worker) mutable struct Endpoint worker::Worker ep::UCXEndpoint msg_tag_send::API.ucp_tag_t msg_tag_recv::API.ucp_tag_t end # TODO: Tag structure # OMPI uses msg_tag (24) | source_rank (20) | context_id (20) tag(kind, seed, port) = hash(kind, hash(seed, hash(port))) function Endpoint(worker::Worker, addr, port) ep = UCX.UCXEndpoint(worker.worker, addr, port) Endpoint(worker, ep, false) end function Endpoint(worker::Worker, connection::UCXConnectionRequest) ep = UCX.UCXEndpoint(worker.worker, connection) Endpoint(worker, ep, true) end function Endpoint(worker::Worker, ep::UCXEndpoint, listener) seed = rand(UInt128) pid = getpid() msg_tag = tag(:ctrl, seed, pid) send_tag = Ref(msg_tag) recv_tag = Ref(msg_tag) if listener req1 = stream_send(ep, send_tag) req2 = stream_recv(ep, recv_tag) else req1 = stream_recv(ep, recv_tag) req2 = stream_send(ep, send_tag) end wait(req1) wait(req2) @assert msg_tag !== recv_tag[] Endpoint(worker, ep, msg_tag, recv_tag[]) end function send(ep::Endpoint, buffer, nbytes) send(ep.ep, buffer, nbytes, ep.msg_tag_send) end function recv(ep::Endpoint, buffer, nbytes) recv(ep.ep.worker, buffer, nbytes, ep.msg_tag_recv) end function stream_send(ep::Endpoint, args...) stream_send(ep.ep, args...) end function stream_recv(ep::Endpoint, args...) stream_recv(ep.ep, args...) end end #module
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
41334
module API using CEnum include(joinpath(@__DIR__, "..", "deps", "deps.jl")) const FILE = Base.Libc.FILE const __socklen_t = Cuint const socklen_t = __socklen_t const sa_family_t = Cushort # FIXME: Clang.jl should have defined this UCS_BIT(i) = (UInt(1) << (convert(UInt, i))) UCP_VERSION(_major, _minor) = (((_major) << UCP_VERSION_MAJOR_SHIFT) | ((_minor) << UCP_VERSION_MINOR_SHIFT)) struct sockaddr sa_family::sa_family_t sa_data::NTuple{14, Cchar} end @cenum ucs_status_t::Int8 begin UCS_OK = 0 UCS_INPROGRESS = 1 UCS_ERR_NO_MESSAGE = -1 UCS_ERR_NO_RESOURCE = -2 UCS_ERR_IO_ERROR = -3 UCS_ERR_NO_MEMORY = -4 UCS_ERR_INVALID_PARAM = -5 UCS_ERR_UNREACHABLE = -6 UCS_ERR_INVALID_ADDR = -7 UCS_ERR_NOT_IMPLEMENTED = -8 UCS_ERR_MESSAGE_TRUNCATED = -9 UCS_ERR_NO_PROGRESS = -10 UCS_ERR_BUFFER_TOO_SMALL = -11 UCS_ERR_NO_ELEM = -12 UCS_ERR_SOME_CONNECTS_FAILED = -13 UCS_ERR_NO_DEVICE = -14 UCS_ERR_BUSY = -15 UCS_ERR_CANCELED = -16 UCS_ERR_SHMEM_SEGMENT = -17 UCS_ERR_ALREADY_EXISTS = -18 UCS_ERR_OUT_OF_RANGE = -19 UCS_ERR_TIMED_OUT = -20 UCS_ERR_EXCEEDS_LIMIT = -21 UCS_ERR_UNSUPPORTED = -22 UCS_ERR_REJECTED = -23 UCS_ERR_NOT_CONNECTED = -24 UCS_ERR_CONNECTION_RESET = -25 UCS_ERR_FIRST_LINK_FAILURE = -40 UCS_ERR_LAST_LINK_FAILURE = -59 UCS_ERR_FIRST_ENDPOINT_FAILURE = -60 UCS_ERR_ENDPOINT_TIMEOUT = -80 UCS_ERR_LAST_ENDPOINT_FAILURE = -89 UCS_ERR_LAST = -100 end const ucs_cpu_mask_t = Culong struct ucs_cpu_set_t ucs_bits::NTuple{16, ucs_cpu_mask_t} end const ucp_datatype_t = UInt64 @cenum ucs_memory_type::UInt32 begin UCS_MEMORY_TYPE_HOST = 0 UCS_MEMORY_TYPE_CUDA = 1 UCS_MEMORY_TYPE_CUDA_MANAGED = 2 UCS_MEMORY_TYPE_ROCM = 3 UCS_MEMORY_TYPE_ROCM_MANAGED = 4 UCS_MEMORY_TYPE_LAST = 5 UCS_MEMORY_TYPE_UNKNOWN = 5 end const ucs_memory_type_t = ucs_memory_type const ucs_status_ptr_t = Ptr{Cvoid} function ucs_status_string(status) ccall((:ucs_status_string, libucp), Ptr{Cchar}, (ucs_status_t,), status) end @cenum ucs_log_level_t::UInt32 begin UCS_LOG_LEVEL_FATAL = 0 UCS_LOG_LEVEL_ERROR = 1 UCS_LOG_LEVEL_WARN = 2 UCS_LOG_LEVEL_DIAG = 3 UCS_LOG_LEVEL_INFO = 4 UCS_LOG_LEVEL_DEBUG = 5 UCS_LOG_LEVEL_TRACE = 6 UCS_LOG_LEVEL_TRACE_REQ = 7 UCS_LOG_LEVEL_TRACE_DATA = 8 UCS_LOG_LEVEL_TRACE_ASYNC = 9 UCS_LOG_LEVEL_TRACE_FUNC = 10 UCS_LOG_LEVEL_TRACE_POLL = 11 UCS_LOG_LEVEL_LAST = 12 UCS_LOG_LEVEL_PRINT = 13 end @cenum ucs_async_mode_t::UInt32 begin UCS_ASYNC_MODE_SIGNAL = 0 UCS_ASYNC_MODE_THREAD = 1 UCS_ASYNC_MODE_THREAD_SPINLOCK = 1 UCS_ASYNC_MODE_THREAD_MUTEX = 2 UCS_ASYNC_MODE_POLL = 3 UCS_ASYNC_MODE_LAST = 4 end @cenum ucs_ternary_auto_value::UInt32 begin UCS_NO = 0 UCS_YES = 1 UCS_TRY = 2 UCS_AUTO = 3 UCS_TERNARY_LAST = 4 end const ucs_ternary_auto_value_t = ucs_ternary_auto_value @cenum ucs_on_off_auto_value::UInt32 begin UCS_CONFIG_OFF = 0 UCS_CONFIG_ON = 1 UCS_CONFIG_AUTO = 2 UCS_CONFIG_ON_OFF_LAST = 3 end const ucs_on_off_auto_value_t = ucs_on_off_auto_value @cenum ucs_handle_error_t::UInt32 begin UCS_HANDLE_ERROR_BACKTRACE = 0 UCS_HANDLE_ERROR_FREEZE = 1 UCS_HANDLE_ERROR_DEBUG = 2 UCS_HANDLE_ERROR_NONE = 3 UCS_HANDLE_ERROR_LAST = 4 end @cenum ucs_config_print_flags_t::UInt32 begin UCS_CONFIG_PRINT_CONFIG = 1 UCS_CONFIG_PRINT_HEADER = 2 UCS_CONFIG_PRINT_DOC = 4 UCS_CONFIG_PRINT_HIDDEN = 8 UCS_CONFIG_PRINT_COMMENT_DEFAULT = 16 end struct ucs_config_names_array_t names::Ptr{Ptr{Cchar}} count::Cuint pad::Cuint end @cenum ucs_config_allow_list_mode_t::UInt32 begin UCS_CONFIG_ALLOW_LIST_ALLOW_ALL = 0 UCS_CONFIG_ALLOW_LIST_ALLOW = 1 UCS_CONFIG_ALLOW_LIST_NEGATE = 2 end struct ucs_config_allow_list_t array::ucs_config_names_array_t mode::ucs_config_allow_list_mode_t end struct ucs_sock_addr addr::Ptr{sockaddr} addrlen::socklen_t end const ucs_sock_addr_t = ucs_sock_addr struct ucs_log_component_config log_level::ucs_log_level_t name::NTuple{16, Cchar} file_filter::Ptr{Cchar} end const ucs_log_component_config_t = ucs_log_component_config const ucp_tag_t = UInt64 struct ucp_tag_recv_info sender_tag::ucp_tag_t length::Csize_t end const ucp_tag_recv_info_t = ucp_tag_recv_info mutable struct ucp_ep end const ucp_ep_h = Ptr{ucp_ep} struct ucp_am_recv_param recv_attr::UInt64 reply_ep::ucp_ep_h end const ucp_am_recv_param_t = ucp_am_recv_param mutable struct ucp_context end const ucp_context_h = Ptr{ucp_context} mutable struct ucp_config end const ucp_config_t = ucp_config mutable struct ucp_conn_request end const ucp_conn_request_h = Ptr{ucp_conn_request} mutable struct ucp_address end const ucp_address_t = ucp_address @cenum ucp_err_handling_mode_t::UInt32 begin UCP_ERR_HANDLING_MODE_NONE = 0 UCP_ERR_HANDLING_MODE_PEER = 1 end mutable struct ucp_rkey end const ucp_rkey_h = Ptr{ucp_rkey} mutable struct ucp_mem end const ucp_mem_h = Ptr{ucp_mem} mutable struct ucp_listener end const ucp_listener_h = Ptr{ucp_listener} struct ucp_mem_attr field_mask::UInt64 address::Ptr{Cvoid} length::Csize_t mem_type::ucs_memory_type_t end const ucp_mem_attr_t = ucp_mem_attr @cenum ucp_mem_attr_field::UInt32 begin UCP_MEM_ATTR_FIELD_ADDRESS = 1 UCP_MEM_ATTR_FIELD_LENGTH = 2 UCP_MEM_ATTR_FIELD_MEM_TYPE = 4 end mutable struct ucp_worker end const ucp_worker_h = Ptr{ucp_worker} mutable struct ucp_recv_desc end const ucp_tag_message_h = Ptr{ucp_recv_desc} # typedef void ( * ucp_request_init_callback_t ) ( void * request ) const ucp_request_init_callback_t = Ptr{Cvoid} # typedef void ( * ucp_request_cleanup_callback_t ) ( void * request ) const ucp_request_cleanup_callback_t = Ptr{Cvoid} # typedef void ( * ucp_send_callback_t ) ( void * request , ucs_status_t status ) const ucp_send_callback_t = Ptr{Cvoid} # typedef void ( * ucp_send_nbx_callback_t ) ( void * request , ucs_status_t status , void * user_data ) const ucp_send_nbx_callback_t = Ptr{Cvoid} # typedef void ( * ucp_err_handler_cb_t ) ( void * arg , ucp_ep_h ep , ucs_status_t status ) const ucp_err_handler_cb_t = Ptr{Cvoid} struct ucp_err_handler cb::ucp_err_handler_cb_t arg::Ptr{Cvoid} end const ucp_err_handler_t = ucp_err_handler # typedef void ( * ucp_listener_accept_callback_t ) ( ucp_ep_h ep , void * arg ) const ucp_listener_accept_callback_t = Ptr{Cvoid} # typedef void ( * ucp_listener_conn_callback_t ) ( ucp_conn_request_h conn_request , void * arg ) const ucp_listener_conn_callback_t = Ptr{Cvoid} struct ucp_listener_conn_handler cb::ucp_listener_conn_callback_t arg::Ptr{Cvoid} end const ucp_listener_conn_handler_t = ucp_listener_conn_handler # typedef void ( * ucp_stream_recv_callback_t ) ( void * request , ucs_status_t status , size_t length ) const ucp_stream_recv_callback_t = Ptr{Cvoid} # typedef void ( * ucp_stream_recv_nbx_callback_t ) ( void * request , ucs_status_t status , size_t length , void * user_data ) const ucp_stream_recv_nbx_callback_t = Ptr{Cvoid} # typedef void ( * ucp_tag_recv_callback_t ) ( void * request , ucs_status_t status , ucp_tag_recv_info_t * info ) const ucp_tag_recv_callback_t = Ptr{Cvoid} # typedef void ( * ucp_tag_recv_nbx_callback_t ) ( void * request , ucs_status_t status , const ucp_tag_recv_info_t * tag_info , void * user_data ) const ucp_tag_recv_nbx_callback_t = Ptr{Cvoid} # typedef void ( * ucp_am_recv_data_nbx_callback_t ) ( void * request , ucs_status_t status , size_t length , void * user_data ) const ucp_am_recv_data_nbx_callback_t = Ptr{Cvoid} @cenum ucp_wakeup_event_types::UInt32 begin UCP_WAKEUP_RMA = 1 UCP_WAKEUP_AMO = 2 UCP_WAKEUP_TAG_SEND = 4 UCP_WAKEUP_TAG_RECV = 8 UCP_WAKEUP_TX = 1024 UCP_WAKEUP_RX = 2048 UCP_WAKEUP_EDGE = 65536 end const ucp_wakeup_event_t = ucp_wakeup_event_types # typedef ucs_status_t ( * ucp_am_callback_t ) ( void * arg , void * data , size_t length , ucp_ep_h reply_ep , unsigned flags ) const ucp_am_callback_t = Ptr{Cvoid} # typedef ucs_status_t ( * ucp_am_recv_callback_t ) ( void * arg , const void * header , size_t header_length , void * data , size_t length , const ucp_am_recv_param_t * param ) const ucp_am_recv_callback_t = Ptr{Cvoid} struct ucp_ep_params field_mask::UInt64 address::Ptr{ucp_address_t} err_mode::ucp_err_handling_mode_t err_handler::ucp_err_handler_t user_data::Ptr{Cvoid} flags::Cuint sockaddr::ucs_sock_addr_t conn_request::ucp_conn_request_h name::Ptr{Cchar} end const ucp_ep_params_t = ucp_ep_params struct ucp_listener_accept_handler cb::ucp_listener_accept_callback_t arg::Ptr{Cvoid} end const ucp_listener_accept_handler_t = ucp_listener_accept_handler function ucp_request_is_completed(request) ccall((:ucp_request_is_completed, libucp), Cint, (Ptr{Cvoid},), request) end function ucp_request_release(request) ccall((:ucp_request_release, libucp), Cvoid, (Ptr{Cvoid},), request) end function ucp_ep_destroy(ep) ccall((:ucp_ep_destroy, libucp), Cvoid, (ucp_ep_h,), ep) end function ucp_disconnect_nb(ep) ccall((:ucp_disconnect_nb, libucp), ucs_status_ptr_t, (ucp_ep_h,), ep) end function ucp_request_test(request, info) ccall((:ucp_request_test, libucp), ucs_status_t, (Ptr{Cvoid}, Ptr{ucp_tag_recv_info_t}), request, info) end function ucp_ep_flush(ep) ccall((:ucp_ep_flush, libucp), ucs_status_t, (ucp_ep_h,), ep) end function ucp_worker_flush(worker) ccall((:ucp_worker_flush, libucp), ucs_status_t, (ucp_worker_h,), worker) end function ucp_put(ep, buffer, length, remote_addr, rkey) ccall((:ucp_put, libucp), ucs_status_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h), ep, buffer, length, remote_addr, rkey) end function ucp_get(ep, buffer, length, remote_addr, rkey) ccall((:ucp_get, libucp), ucs_status_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h), ep, buffer, length, remote_addr, rkey) end function ucp_atomic_add32(ep, add, remote_addr, rkey) ccall((:ucp_atomic_add32, libucp), ucs_status_t, (ucp_ep_h, UInt32, UInt64, ucp_rkey_h), ep, add, remote_addr, rkey) end function ucp_atomic_add64(ep, add, remote_addr, rkey) ccall((:ucp_atomic_add64, libucp), ucs_status_t, (ucp_ep_h, UInt64, UInt64, ucp_rkey_h), ep, add, remote_addr, rkey) end function ucp_atomic_fadd32(ep, add, remote_addr, rkey, result) ccall((:ucp_atomic_fadd32, libucp), ucs_status_t, (ucp_ep_h, UInt32, UInt64, ucp_rkey_h, Ptr{UInt32}), ep, add, remote_addr, rkey, result) end function ucp_atomic_fadd64(ep, add, remote_addr, rkey, result) ccall((:ucp_atomic_fadd64, libucp), ucs_status_t, (ucp_ep_h, UInt64, UInt64, ucp_rkey_h, Ptr{UInt64}), ep, add, remote_addr, rkey, result) end function ucp_atomic_swap32(ep, swap, remote_addr, rkey, result) ccall((:ucp_atomic_swap32, libucp), ucs_status_t, (ucp_ep_h, UInt32, UInt64, ucp_rkey_h, Ptr{UInt32}), ep, swap, remote_addr, rkey, result) end function ucp_atomic_swap64(ep, swap, remote_addr, rkey, result) ccall((:ucp_atomic_swap64, libucp), ucs_status_t, (ucp_ep_h, UInt64, UInt64, ucp_rkey_h, Ptr{UInt64}), ep, swap, remote_addr, rkey, result) end function ucp_atomic_cswap32(ep, compare, swap, remote_addr, rkey, result) ccall((:ucp_atomic_cswap32, libucp), ucs_status_t, (ucp_ep_h, UInt32, UInt32, UInt64, ucp_rkey_h, Ptr{UInt32}), ep, compare, swap, remote_addr, rkey, result) end function ucp_atomic_cswap64(ep, compare, swap, remote_addr, rkey, result) ccall((:ucp_atomic_cswap64, libucp), ucs_status_t, (ucp_ep_h, UInt64, UInt64, UInt64, ucp_rkey_h, Ptr{UInt64}), ep, compare, swap, remote_addr, rkey, result) end function ucp_ep_modify_nb(ep, params) ccall((:ucp_ep_modify_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{ucp_ep_params_t}), ep, params) end @cenum ucs_thread_mode_t::UInt32 begin UCS_THREAD_MODE_SINGLE = 0 UCS_THREAD_MODE_SERIALIZED = 1 UCS_THREAD_MODE_MULTI = 2 UCS_THREAD_MODE_LAST = 3 end function ucs_cpu_is_set(cpu, cpusetp) ccall((:ucs_cpu_is_set, libucp), Cint, (Cint, Ptr{ucs_cpu_set_t}), cpu, cpusetp) end function ucs_cpu_set_find_lcs(cpu_mask) ccall((:ucs_cpu_set_find_lcs, libucp), Cint, (Ptr{ucs_cpu_set_t},), cpu_mask) end @cenum ucp_params_field::UInt32 begin UCP_PARAM_FIELD_FEATURES = 1 UCP_PARAM_FIELD_REQUEST_SIZE = 2 UCP_PARAM_FIELD_REQUEST_INIT = 4 UCP_PARAM_FIELD_REQUEST_CLEANUP = 8 UCP_PARAM_FIELD_TAG_SENDER_MASK = 16 UCP_PARAM_FIELD_MT_WORKERS_SHARED = 32 UCP_PARAM_FIELD_ESTIMATED_NUM_EPS = 64 UCP_PARAM_FIELD_ESTIMATED_NUM_PPN = 128 UCP_PARAM_FIELD_NAME = 256 end @cenum ucp_feature::UInt32 begin UCP_FEATURE_TAG = 1 UCP_FEATURE_RMA = 2 UCP_FEATURE_AMO32 = 4 UCP_FEATURE_AMO64 = 8 UCP_FEATURE_WAKEUP = 16 UCP_FEATURE_STREAM = 32 UCP_FEATURE_AM = 64 end @cenum ucp_worker_params_field::UInt32 begin UCP_WORKER_PARAM_FIELD_THREAD_MODE = 1 UCP_WORKER_PARAM_FIELD_CPU_MASK = 2 UCP_WORKER_PARAM_FIELD_EVENTS = 4 UCP_WORKER_PARAM_FIELD_USER_DATA = 8 UCP_WORKER_PARAM_FIELD_EVENT_FD = 16 UCP_WORKER_PARAM_FIELD_FLAGS = 32 UCP_WORKER_PARAM_FIELD_NAME = 64 end @cenum ucp_worker_flags_t::UInt32 begin UCP_WORKER_FLAG_IGNORE_REQUEST_LEAK = 1 end @cenum ucp_listener_params_field::UInt32 begin UCP_LISTENER_PARAM_FIELD_SOCK_ADDR = 1 UCP_LISTENER_PARAM_FIELD_ACCEPT_HANDLER = 2 UCP_LISTENER_PARAM_FIELD_CONN_HANDLER = 4 end @cenum ucp_worker_address_flags_t::UInt32 begin UCP_WORKER_ADDRESS_FLAG_NET_ONLY = 1 end @cenum ucp_ep_params_field::UInt32 begin UCP_EP_PARAM_FIELD_REMOTE_ADDRESS = 1 UCP_EP_PARAM_FIELD_ERR_HANDLING_MODE = 2 UCP_EP_PARAM_FIELD_ERR_HANDLER = 4 UCP_EP_PARAM_FIELD_USER_DATA = 8 UCP_EP_PARAM_FIELD_SOCK_ADDR = 16 UCP_EP_PARAM_FIELD_FLAGS = 32 UCP_EP_PARAM_FIELD_CONN_REQUEST = 64 UCP_EP_PARAM_FIELD_NAME = 128 end @cenum ucp_ep_params_flags_field::UInt32 begin UCP_EP_PARAMS_FLAGS_CLIENT_SERVER = 1 UCP_EP_PARAMS_FLAGS_NO_LOOPBACK = 2 end @cenum ucp_ep_close_flags_t::UInt32 begin UCP_EP_CLOSE_FLAG_FORCE = 1 end @cenum ucp_ep_close_mode::UInt32 begin UCP_EP_CLOSE_MODE_FORCE = 0 UCP_EP_CLOSE_MODE_FLUSH = 1 end @cenum ucp_ep_perf_param_field::UInt32 begin UCP_EP_PERF_PARAM_FIELD_MESSAGE_SIZE = 1 end const ucp_ep_perf_param_field_t = ucp_ep_perf_param_field @cenum ucp_ep_perf_attr_field::UInt32 begin UCP_EP_PERF_ATTR_FIELD_ESTIMATED_TIME = 1 end const ucp_ep_perf_attr_field_t = ucp_ep_perf_attr_field @cenum ucp_mem_map_params_field::UInt32 begin UCP_MEM_MAP_PARAM_FIELD_ADDRESS = 1 UCP_MEM_MAP_PARAM_FIELD_LENGTH = 2 UCP_MEM_MAP_PARAM_FIELD_FLAGS = 4 UCP_MEM_MAP_PARAM_FIELD_PROT = 8 UCP_MEM_MAP_PARAM_FIELD_MEMORY_TYPE = 16 end @cenum ucp_mem_advise_params_field::UInt32 begin UCP_MEM_ADVISE_PARAM_FIELD_ADDRESS = 1 UCP_MEM_ADVISE_PARAM_FIELD_LENGTH = 2 UCP_MEM_ADVISE_PARAM_FIELD_ADVICE = 4 end @cenum ucp_lib_attr_field::UInt32 begin UCP_LIB_ATTR_FIELD_MAX_THREAD_LEVEL = 1 end @cenum ucp_context_attr_field::UInt32 begin UCP_ATTR_FIELD_REQUEST_SIZE = 1 UCP_ATTR_FIELD_THREAD_MODE = 2 UCP_ATTR_FIELD_MEMORY_TYPES = 4 UCP_ATTR_FIELD_NAME = 8 end @cenum ucp_worker_attr_field::UInt32 begin UCP_WORKER_ATTR_FIELD_THREAD_MODE = 1 UCP_WORKER_ATTR_FIELD_ADDRESS = 2 UCP_WORKER_ATTR_FIELD_ADDRESS_FLAGS = 4 UCP_WORKER_ATTR_FIELD_MAX_AM_HEADER = 8 UCP_WORKER_ATTR_FIELD_NAME = 16 UCP_WORKER_ATTR_FIELD_MAX_INFO_STRING = 32 end @cenum ucp_listener_attr_field::UInt32 begin UCP_LISTENER_ATTR_FIELD_SOCKADDR = 1 end @cenum ucp_conn_request_attr_field::UInt32 begin UCP_CONN_REQUEST_ATTR_FIELD_CLIENT_ADDR = 1 end @cenum ucp_dt_type::UInt32 begin UCP_DATATYPE_CONTIG = 0 UCP_DATATYPE_STRIDED = 1 UCP_DATATYPE_IOV = 2 UCP_DATATYPE_GENERIC = 7 UCP_DATATYPE_SHIFT = 3 UCP_DATATYPE_CLASS_MASK = 7 end @cenum __JL_Ctag_34::UInt32 begin UCP_MEM_MAP_NONBLOCK = 1 UCP_MEM_MAP_ALLOCATE = 2 UCP_MEM_MAP_FIXED = 4 end @cenum __JL_Ctag_35::UInt32 begin UCP_MEM_MAP_PROT_LOCAL_READ = 1 UCP_MEM_MAP_PROT_LOCAL_WRITE = 2 UCP_MEM_MAP_PROT_REMOTE_READ = 256 UCP_MEM_MAP_PROT_REMOTE_WRITE = 512 end @cenum ucp_am_cb_flags::UInt32 begin UCP_AM_FLAG_WHOLE_MSG = 1 UCP_AM_FLAG_PERSISTENT_DATA = 2 end @cenum ucp_send_am_flags::UInt32 begin UCP_AM_SEND_FLAG_REPLY = 1 UCP_AM_SEND_FLAG_EAGER = 2 UCP_AM_SEND_FLAG_RNDV = 4 UCP_AM_SEND_REPLY = 1 end @cenum ucp_cb_param_flags::UInt32 begin UCP_CB_PARAM_FLAG_DATA = 1 end @cenum ucp_atomic_post_op_t::UInt32 begin UCP_ATOMIC_POST_OP_ADD = 0 UCP_ATOMIC_POST_OP_AND = 1 UCP_ATOMIC_POST_OP_OR = 2 UCP_ATOMIC_POST_OP_XOR = 3 UCP_ATOMIC_POST_OP_LAST = 4 end @cenum ucp_atomic_fetch_op_t::UInt32 begin UCP_ATOMIC_FETCH_OP_FADD = 0 UCP_ATOMIC_FETCH_OP_SWAP = 1 UCP_ATOMIC_FETCH_OP_CSWAP = 2 UCP_ATOMIC_FETCH_OP_FAND = 3 UCP_ATOMIC_FETCH_OP_FOR = 4 UCP_ATOMIC_FETCH_OP_FXOR = 5 UCP_ATOMIC_FETCH_OP_LAST = 6 end @cenum ucp_atomic_op_t::UInt32 begin UCP_ATOMIC_OP_ADD = 0 UCP_ATOMIC_OP_SWAP = 1 UCP_ATOMIC_OP_CSWAP = 2 UCP_ATOMIC_OP_AND = 3 UCP_ATOMIC_OP_OR = 4 UCP_ATOMIC_OP_XOR = 5 UCP_ATOMIC_OP_LAST = 6 end @cenum ucp_stream_recv_flags_t::UInt32 begin UCP_STREAM_RECV_FLAG_WAITALL = 1 end @cenum ucp_op_attr_t::UInt32 begin UCP_OP_ATTR_FIELD_REQUEST = 1 UCP_OP_ATTR_FIELD_CALLBACK = 2 UCP_OP_ATTR_FIELD_USER_DATA = 4 UCP_OP_ATTR_FIELD_DATATYPE = 8 UCP_OP_ATTR_FIELD_FLAGS = 16 UCP_OP_ATTR_FIELD_REPLY_BUFFER = 32 UCP_OP_ATTR_FIELD_MEMORY_TYPE = 64 UCP_OP_ATTR_FIELD_RECV_INFO = 128 UCP_OP_ATTR_FLAG_NO_IMM_CMPL = 65536 UCP_OP_ATTR_FLAG_FAST_CMPL = 131072 UCP_OP_ATTR_FLAG_FORCE_IMM_CMPL = 262144 end @cenum ucp_req_attr_field::UInt32 begin UCP_REQUEST_ATTR_FIELD_INFO_STRING = 1 UCP_REQUEST_ATTR_FIELD_INFO_STRING_SIZE = 2 UCP_REQUEST_ATTR_FIELD_STATUS = 4 UCP_REQUEST_ATTR_FIELD_MEM_TYPE = 8 end @cenum ucp_am_recv_attr_t::UInt32 begin UCP_AM_RECV_ATTR_FIELD_REPLY_EP = 1 UCP_AM_RECV_ATTR_FLAG_DATA = 65536 UCP_AM_RECV_ATTR_FLAG_RNDV = 131072 end @cenum ucp_am_handler_param_field::UInt32 begin UCP_AM_HANDLER_PARAM_FIELD_ID = 1 UCP_AM_HANDLER_PARAM_FIELD_FLAGS = 2 UCP_AM_HANDLER_PARAM_FIELD_CB = 4 UCP_AM_HANDLER_PARAM_FIELD_ARG = 8 end struct ucp_dt_iov buffer::Ptr{Cvoid} length::Csize_t end const ucp_dt_iov_t = ucp_dt_iov struct ucp_generic_dt_ops start_pack::Ptr{Cvoid} start_unpack::Ptr{Cvoid} packed_size::Ptr{Cvoid} pack::Ptr{Cvoid} unpack::Ptr{Cvoid} finish::Ptr{Cvoid} end const ucp_generic_dt_ops_t = ucp_generic_dt_ops struct ucp_params field_mask::UInt64 features::UInt64 request_size::Csize_t request_init::ucp_request_init_callback_t request_cleanup::ucp_request_cleanup_callback_t tag_sender_mask::UInt64 mt_workers_shared::Cint estimated_num_eps::Csize_t estimated_num_ppn::Csize_t name::Ptr{Cchar} end const ucp_params_t = ucp_params struct ucp_lib_attr field_mask::UInt64 max_thread_level::ucs_thread_mode_t end const ucp_lib_attr_t = ucp_lib_attr struct ucp_context_attr field_mask::UInt64 request_size::Csize_t thread_mode::ucs_thread_mode_t memory_types::UInt64 name::NTuple{32, Cchar} end const ucp_context_attr_t = ucp_context_attr struct ucp_worker_attr field_mask::UInt64 thread_mode::ucs_thread_mode_t address_flags::UInt32 address::Ptr{ucp_address_t} address_length::Csize_t max_am_header::Csize_t name::NTuple{32, Cchar} max_debug_string::Csize_t end const ucp_worker_attr_t = ucp_worker_attr struct ucp_worker_params field_mask::UInt64 thread_mode::ucs_thread_mode_t cpu_mask::ucs_cpu_set_t events::Cuint user_data::Ptr{Cvoid} event_fd::Cint flags::UInt64 name::Ptr{Cchar} end const ucp_worker_params_t = ucp_worker_params struct ucp_ep_evaluate_perf_param_t field_mask::UInt64 message_size::Csize_t end struct ucp_ep_evaluate_perf_attr_t field_mask::UInt64 estimated_time::Cdouble end struct sockaddr_storage ss_family::sa_family_t __ss_align::Culong __ss_padding::NTuple{112, Cchar} end struct ucp_listener_attr field_mask::UInt64 sockaddr::sockaddr_storage end const ucp_listener_attr_t = ucp_listener_attr struct ucp_conn_request_attr field_mask::UInt64 client_address::sockaddr_storage end const ucp_conn_request_attr_t = ucp_conn_request_attr struct ucp_listener_params field_mask::UInt64 sockaddr::ucs_sock_addr_t accept_handler::ucp_listener_accept_handler_t conn_handler::ucp_listener_conn_handler_t end const ucp_listener_params_t = ucp_listener_params struct ucp_stream_poll_ep ep::ucp_ep_h user_data::Ptr{Cvoid} flags::Cuint reserved::NTuple{16, UInt8} end const ucp_stream_poll_ep_t = ucp_stream_poll_ep struct ucp_mem_map_params field_mask::UInt64 address::Ptr{Cvoid} length::Csize_t flags::Cuint prot::Cuint memory_type::ucs_memory_type_t end const ucp_mem_map_params_t = ucp_mem_map_params struct __JL_Ctag_47 data::NTuple{8, UInt8} end function Base.getproperty(x::Ptr{__JL_Ctag_47}, f::Symbol) f === :send && return Ptr{ucp_send_nbx_callback_t}(x + 0) f === :recv && return Ptr{ucp_tag_recv_nbx_callback_t}(x + 0) f === :recv_stream && return Ptr{ucp_stream_recv_nbx_callback_t}(x + 0) f === :recv_am && return Ptr{ucp_am_recv_data_nbx_callback_t}(x + 0) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_47, f::Symbol) r = Ref{__JL_Ctag_47}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_47}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_47}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct __JL_Ctag_48 data::NTuple{8, UInt8} end function Base.getproperty(x::Ptr{__JL_Ctag_48}, f::Symbol) f === :length && return Ptr{Ptr{Csize_t}}(x + 0) f === :tag_info && return Ptr{Ptr{ucp_tag_recv_info_t}}(x + 0) return getfield(x, f) end function Base.getproperty(x::__JL_Ctag_48, f::Symbol) r = Ref{__JL_Ctag_48}(x) ptr = Base.unsafe_convert(Ptr{__JL_Ctag_48}, r) fptr = getproperty(ptr, f) GC.@preserve r unsafe_load(fptr) end function Base.setproperty!(x::Ptr{__JL_Ctag_48}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct ucp_request_param_t op_attr_mask::UInt32 flags::UInt32 request::Ptr{Cvoid} cb::__JL_Ctag_47 datatype::ucp_datatype_t user_data::Ptr{Cvoid} reply_buffer::Ptr{Cvoid} memory_type::ucs_memory_type_t recv_info::__JL_Ctag_48 end struct ucp_request_attr_t field_mask::UInt64 debug_string::Ptr{Cchar} debug_string_size::Csize_t status::ucs_status_t mem_type::ucs_memory_type_t end struct ucp_am_handler_param field_mask::UInt64 id::Cuint flags::UInt32 cb::ucp_am_recv_callback_t arg::Ptr{Cvoid} end const ucp_am_handler_param_t = ucp_am_handler_param function ucp_lib_query(attr) ccall((:ucp_lib_query, libucp), ucs_status_t, (Ptr{ucp_lib_attr_t},), attr) end function ucp_config_read(env_prefix, filename, config_p) ccall((:ucp_config_read, libucp), ucs_status_t, (Ptr{Cchar}, Ptr{Cchar}, Ptr{Ptr{ucp_config_t}}), env_prefix, filename, config_p) end function ucp_config_release(config) ccall((:ucp_config_release, libucp), Cvoid, (Ptr{ucp_config_t},), config) end function ucp_config_modify(config, name, value) ccall((:ucp_config_modify, libucp), ucs_status_t, (Ptr{ucp_config_t}, Ptr{Cchar}, Ptr{Cchar}), config, name, value) end function ucp_config_print(config, stream, title, print_flags) ccall((:ucp_config_print, libucp), Cvoid, (Ptr{ucp_config_t}, Ptr{FILE}, Ptr{Cchar}, ucs_config_print_flags_t), config, stream, title, print_flags) end function ucp_get_version(major_version, minor_version, release_number) ccall((:ucp_get_version, libucp), Cvoid, (Ptr{Cuint}, Ptr{Cuint}, Ptr{Cuint}), major_version, minor_version, release_number) end function ucp_get_version_string() ccall((:ucp_get_version_string, libucp), Ptr{Cchar}, ()) end function ucp_init_version(api_major_version, api_minor_version, params, config, context_p) ccall((:ucp_init_version, libucp), ucs_status_t, (Cuint, Cuint, Ptr{ucp_params_t}, Ptr{ucp_config_t}, Ptr{ucp_context_h}), api_major_version, api_minor_version, params, config, context_p) end function ucp_init(params, config, context_p) ccall((:ucp_init, libucp), ucs_status_t, (Ptr{ucp_params_t}, Ptr{ucp_config_t}, Ptr{ucp_context_h}), params, config, context_p) end function ucp_cleanup(context_p) ccall((:ucp_cleanup, libucp), Cvoid, (ucp_context_h,), context_p) end function ucp_context_query(context_p, attr) ccall((:ucp_context_query, libucp), ucs_status_t, (ucp_context_h, Ptr{ucp_context_attr_t}), context_p, attr) end function ucp_context_print_info(context, stream) ccall((:ucp_context_print_info, libucp), Cvoid, (ucp_context_h, Ptr{FILE}), context, stream) end function ucp_worker_create(context, params, worker_p) ccall((:ucp_worker_create, libucp), ucs_status_t, (ucp_context_h, Ptr{ucp_worker_params_t}, Ptr{ucp_worker_h}), context, params, worker_p) end function ucp_worker_destroy(worker) ccall((:ucp_worker_destroy, libucp), Cvoid, (ucp_worker_h,), worker) end function ucp_worker_query(worker, attr) ccall((:ucp_worker_query, libucp), ucs_status_t, (ucp_worker_h, Ptr{ucp_worker_attr_t}), worker, attr) end function ucp_worker_print_info(worker, stream) ccall((:ucp_worker_print_info, libucp), Cvoid, (ucp_worker_h, Ptr{FILE}), worker, stream) end function ucp_worker_get_address(worker, address_p, address_length_p) ccall((:ucp_worker_get_address, libucp), ucs_status_t, (ucp_worker_h, Ptr{Ptr{ucp_address_t}}, Ptr{Csize_t}), worker, address_p, address_length_p) end function ucp_worker_release_address(worker, address) ccall((:ucp_worker_release_address, libucp), Cvoid, (ucp_worker_h, Ptr{ucp_address_t}), worker, address) end function ucp_worker_progress(worker) ccall((:ucp_worker_progress, libucp), Cuint, (ucp_worker_h,), worker) end function ucp_stream_worker_poll(worker, poll_eps, max_eps, flags) ccall((:ucp_stream_worker_poll, libucp), Cssize_t, (ucp_worker_h, Ptr{ucp_stream_poll_ep_t}, Csize_t, Cuint), worker, poll_eps, max_eps, flags) end function ucp_worker_get_efd(worker, fd) ccall((:ucp_worker_get_efd, libucp), ucs_status_t, (ucp_worker_h, Ptr{Cint}), worker, fd) end function ucp_worker_wait(worker) ccall((:ucp_worker_wait, libucp), ucs_status_t, (ucp_worker_h,), worker) end function ucp_worker_wait_mem(worker, address) ccall((:ucp_worker_wait_mem, libucp), Cvoid, (ucp_worker_h, Ptr{Cvoid}), worker, address) end function ucp_worker_arm(worker) ccall((:ucp_worker_arm, libucp), ucs_status_t, (ucp_worker_h,), worker) end function ucp_worker_signal(worker) ccall((:ucp_worker_signal, libucp), ucs_status_t, (ucp_worker_h,), worker) end function ucp_listener_create(worker, params, listener_p) ccall((:ucp_listener_create, libucp), ucs_status_t, (ucp_worker_h, Ptr{ucp_listener_params_t}, Ptr{ucp_listener_h}), worker, params, listener_p) end function ucp_listener_destroy(listener) ccall((:ucp_listener_destroy, libucp), Cvoid, (ucp_listener_h,), listener) end function ucp_listener_query(listener, attr) ccall((:ucp_listener_query, libucp), ucs_status_t, (ucp_listener_h, Ptr{ucp_listener_attr_t}), listener, attr) end function ucp_conn_request_query(conn_request, attr) ccall((:ucp_conn_request_query, libucp), ucs_status_t, (ucp_conn_request_h, Ptr{ucp_conn_request_attr_t}), conn_request, attr) end function ucp_request_query(request, attr) ccall((:ucp_request_query, libucp), ucs_status_t, (Ptr{Cvoid}, Ptr{ucp_request_attr_t}), request, attr) end function ucp_ep_create(worker, params, ep_p) ccall((:ucp_ep_create, libucp), ucs_status_t, (ucp_worker_h, Ptr{ucp_ep_params_t}, Ptr{ucp_ep_h}), worker, params, ep_p) end function ucp_ep_close_nb(ep, mode) ccall((:ucp_ep_close_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Cuint), ep, mode) end function ucp_ep_close_nbx(ep, param) ccall((:ucp_ep_close_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{ucp_request_param_t}), ep, param) end function ucp_listener_reject(listener, conn_request) ccall((:ucp_listener_reject, libucp), ucs_status_t, (ucp_listener_h, ucp_conn_request_h), listener, conn_request) end function ucp_ep_print_info(ep, stream) ccall((:ucp_ep_print_info, libucp), Cvoid, (ucp_ep_h, Ptr{FILE}), ep, stream) end function ucp_ep_flush_nb(ep, flags, cb) ccall((:ucp_ep_flush_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Cuint, ucp_send_callback_t), ep, flags, cb) end function ucp_ep_flush_nbx(ep, param) ccall((:ucp_ep_flush_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{ucp_request_param_t}), ep, param) end function ucp_ep_evaluate_perf(ep, param, attr) ccall((:ucp_ep_evaluate_perf, libucp), ucs_status_t, (ucp_ep_h, Ptr{ucp_ep_evaluate_perf_param_t}, Ptr{ucp_ep_evaluate_perf_attr_t}), ep, param, attr) end function ucp_mem_map(context, params, memh_p) ccall((:ucp_mem_map, libucp), ucs_status_t, (ucp_context_h, Ptr{ucp_mem_map_params_t}, Ptr{ucp_mem_h}), context, params, memh_p) end function ucp_mem_unmap(context, memh) ccall((:ucp_mem_unmap, libucp), ucs_status_t, (ucp_context_h, ucp_mem_h), context, memh) end function ucp_mem_query(memh, attr) ccall((:ucp_mem_query, libucp), ucs_status_t, (ucp_mem_h, Ptr{ucp_mem_attr_t}), memh, attr) end function ucp_mem_print_info(mem_size, context, stream) ccall((:ucp_mem_print_info, libucp), Cvoid, (Ptr{Cchar}, ucp_context_h, Ptr{FILE}), mem_size, context, stream) end @cenum ucp_mem_advice::UInt32 begin UCP_MADV_NORMAL = 0 UCP_MADV_WILLNEED = 1 end const ucp_mem_advice_t = ucp_mem_advice struct ucp_mem_advise_params field_mask::UInt64 address::Ptr{Cvoid} length::Csize_t advice::ucp_mem_advice_t end const ucp_mem_advise_params_t = ucp_mem_advise_params function ucp_mem_advise(context, memh, params) ccall((:ucp_mem_advise, libucp), ucs_status_t, (ucp_context_h, ucp_mem_h, Ptr{ucp_mem_advise_params_t}), context, memh, params) end function ucp_rkey_pack(context, memh, rkey_buffer_p, size_p) ccall((:ucp_rkey_pack, libucp), ucs_status_t, (ucp_context_h, ucp_mem_h, Ptr{Ptr{Cvoid}}, Ptr{Csize_t}), context, memh, rkey_buffer_p, size_p) end function ucp_rkey_buffer_release(rkey_buffer) ccall((:ucp_rkey_buffer_release, libucp), Cvoid, (Ptr{Cvoid},), rkey_buffer) end function ucp_ep_rkey_unpack(ep, rkey_buffer, rkey_p) ccall((:ucp_ep_rkey_unpack, libucp), ucs_status_t, (ucp_ep_h, Ptr{Cvoid}, Ptr{ucp_rkey_h}), ep, rkey_buffer, rkey_p) end function ucp_rkey_ptr(rkey, raddr, addr_p) ccall((:ucp_rkey_ptr, libucp), ucs_status_t, (ucp_rkey_h, UInt64, Ptr{Ptr{Cvoid}}), rkey, raddr, addr_p) end function ucp_rkey_destroy(rkey) ccall((:ucp_rkey_destroy, libucp), Cvoid, (ucp_rkey_h,), rkey) end function ucp_worker_set_am_handler(worker, id, cb, arg, flags) ccall((:ucp_worker_set_am_handler, libucp), ucs_status_t, (ucp_worker_h, UInt16, ucp_am_callback_t, Ptr{Cvoid}, UInt32), worker, id, cb, arg, flags) end function ucp_worker_set_am_recv_handler(worker, param) ccall((:ucp_worker_set_am_recv_handler, libucp), ucs_status_t, (ucp_worker_h, Ptr{ucp_am_handler_param_t}), worker, param) end function ucp_am_send_nb(ep, id, buffer, count, datatype, cb, flags) ccall((:ucp_am_send_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, UInt16, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_send_callback_t, Cuint), ep, id, buffer, count, datatype, cb, flags) end function ucp_am_send_nbx(ep, id, header, header_length, buffer, count, param) ccall((:ucp_am_send_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Cuint, Ptr{Cvoid}, Csize_t, Ptr{Cvoid}, Csize_t, Ptr{ucp_request_param_t}), ep, id, header, header_length, buffer, count, param) end function ucp_am_recv_data_nbx(worker, data_desc, buffer, count, param) ccall((:ucp_am_recv_data_nbx, libucp), ucs_status_ptr_t, (ucp_worker_h, Ptr{Cvoid}, Ptr{Cvoid}, Csize_t, Ptr{ucp_request_param_t}), worker, data_desc, buffer, count, param) end function ucp_am_data_release(worker, data) ccall((:ucp_am_data_release, libucp), Cvoid, (ucp_worker_h, Ptr{Cvoid}), worker, data) end function ucp_stream_send_nb(ep, buffer, count, datatype, cb, flags) ccall((:ucp_stream_send_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_send_callback_t, Cuint), ep, buffer, count, datatype, cb, flags) end function ucp_stream_send_nbx(ep, buffer, count, param) ccall((:ucp_stream_send_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, Ptr{ucp_request_param_t}), ep, buffer, count, param) end function ucp_tag_send_nb(ep, buffer, count, datatype, tag, cb) ccall((:ucp_tag_send_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_tag_t, ucp_send_callback_t), ep, buffer, count, datatype, tag, cb) end function ucp_tag_send_nbr(ep, buffer, count, datatype, tag, req) ccall((:ucp_tag_send_nbr, libucp), ucs_status_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_tag_t, Ptr{Cvoid}), ep, buffer, count, datatype, tag, req) end function ucp_tag_send_sync_nb(ep, buffer, count, datatype, tag, cb) ccall((:ucp_tag_send_sync_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_tag_t, ucp_send_callback_t), ep, buffer, count, datatype, tag, cb) end function ucp_tag_send_nbx(ep, buffer, count, tag, param) ccall((:ucp_tag_send_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, ucp_tag_t, Ptr{ucp_request_param_t}), ep, buffer, count, tag, param) end function ucp_tag_send_sync_nbx(ep, buffer, count, tag, param) ccall((:ucp_tag_send_sync_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, ucp_tag_t, Ptr{ucp_request_param_t}), ep, buffer, count, tag, param) end function ucp_stream_recv_nb(ep, buffer, count, datatype, cb, length, flags) ccall((:ucp_stream_recv_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_stream_recv_callback_t, Ptr{Csize_t}, Cuint), ep, buffer, count, datatype, cb, length, flags) end function ucp_stream_recv_nbx(ep, buffer, count, length, param) ccall((:ucp_stream_recv_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, Ptr{Csize_t}, Ptr{ucp_request_param_t}), ep, buffer, count, length, param) end function ucp_stream_recv_data_nb(ep, length) ccall((:ucp_stream_recv_data_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Csize_t}), ep, length) end function ucp_tag_recv_nb(worker, buffer, count, datatype, tag, tag_mask, cb) ccall((:ucp_tag_recv_nb, libucp), ucs_status_ptr_t, (ucp_worker_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_tag_t, ucp_tag_t, ucp_tag_recv_callback_t), worker, buffer, count, datatype, tag, tag_mask, cb) end function ucp_tag_recv_nbr(worker, buffer, count, datatype, tag, tag_mask, req) ccall((:ucp_tag_recv_nbr, libucp), ucs_status_t, (ucp_worker_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_tag_t, ucp_tag_t, Ptr{Cvoid}), worker, buffer, count, datatype, tag, tag_mask, req) end function ucp_tag_recv_nbx(worker, buffer, count, tag, tag_mask, param) ccall((:ucp_tag_recv_nbx, libucp), ucs_status_ptr_t, (ucp_worker_h, Ptr{Cvoid}, Csize_t, ucp_tag_t, ucp_tag_t, Ptr{ucp_request_param_t}), worker, buffer, count, tag, tag_mask, param) end function ucp_tag_probe_nb(worker, tag, tag_mask, remove, info) ccall((:ucp_tag_probe_nb, libucp), ucp_tag_message_h, (ucp_worker_h, ucp_tag_t, ucp_tag_t, Cint, Ptr{ucp_tag_recv_info_t}), worker, tag, tag_mask, remove, info) end function ucp_tag_msg_recv_nb(worker, buffer, count, datatype, message, cb) ccall((:ucp_tag_msg_recv_nb, libucp), ucs_status_ptr_t, (ucp_worker_h, Ptr{Cvoid}, Csize_t, ucp_datatype_t, ucp_tag_message_h, ucp_tag_recv_callback_t), worker, buffer, count, datatype, message, cb) end function ucp_tag_msg_recv_nbx(worker, buffer, count, message, param) ccall((:ucp_tag_msg_recv_nbx, libucp), ucs_status_ptr_t, (ucp_worker_h, Ptr{Cvoid}, Csize_t, ucp_tag_message_h, Ptr{ucp_request_param_t}), worker, buffer, count, message, param) end function ucp_put_nbi(ep, buffer, length, remote_addr, rkey) ccall((:ucp_put_nbi, libucp), ucs_status_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h), ep, buffer, length, remote_addr, rkey) end function ucp_put_nb(ep, buffer, length, remote_addr, rkey, cb) ccall((:ucp_put_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h, ucp_send_callback_t), ep, buffer, length, remote_addr, rkey, cb) end function ucp_put_nbx(ep, buffer, count, remote_addr, rkey, param) ccall((:ucp_put_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h, Ptr{ucp_request_param_t}), ep, buffer, count, remote_addr, rkey, param) end function ucp_get_nbi(ep, buffer, length, remote_addr, rkey) ccall((:ucp_get_nbi, libucp), ucs_status_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h), ep, buffer, length, remote_addr, rkey) end function ucp_get_nb(ep, buffer, length, remote_addr, rkey, cb) ccall((:ucp_get_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h, ucp_send_callback_t), ep, buffer, length, remote_addr, rkey, cb) end function ucp_get_nbx(ep, buffer, count, remote_addr, rkey, param) ccall((:ucp_get_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h, Ptr{ucp_request_param_t}), ep, buffer, count, remote_addr, rkey, param) end function ucp_atomic_post(ep, opcode, value, op_size, remote_addr, rkey) ccall((:ucp_atomic_post, libucp), ucs_status_t, (ucp_ep_h, ucp_atomic_post_op_t, UInt64, Csize_t, UInt64, ucp_rkey_h), ep, opcode, value, op_size, remote_addr, rkey) end function ucp_atomic_fetch_nb(ep, opcode, value, result, op_size, remote_addr, rkey, cb) ccall((:ucp_atomic_fetch_nb, libucp), ucs_status_ptr_t, (ucp_ep_h, ucp_atomic_fetch_op_t, UInt64, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h, ucp_send_callback_t), ep, opcode, value, result, op_size, remote_addr, rkey, cb) end function ucp_atomic_op_nbx(ep, opcode, buffer, count, remote_addr, rkey, param) ccall((:ucp_atomic_op_nbx, libucp), ucs_status_ptr_t, (ucp_ep_h, ucp_atomic_op_t, Ptr{Cvoid}, Csize_t, UInt64, ucp_rkey_h, Ptr{ucp_request_param_t}), ep, opcode, buffer, count, remote_addr, rkey, param) end function ucp_request_check_status(request) ccall((:ucp_request_check_status, libucp), ucs_status_t, (Ptr{Cvoid},), request) end function ucp_tag_recv_request_test(request, info) ccall((:ucp_tag_recv_request_test, libucp), ucs_status_t, (Ptr{Cvoid}, Ptr{ucp_tag_recv_info_t}), request, info) end function ucp_stream_recv_request_test(request, length_p) ccall((:ucp_stream_recv_request_test, libucp), ucs_status_t, (Ptr{Cvoid}, Ptr{Csize_t}), request, length_p) end function ucp_request_cancel(worker, request) ccall((:ucp_request_cancel, libucp), Cvoid, (ucp_worker_h, Ptr{Cvoid}), worker, request) end function ucp_stream_data_release(ep, data) ccall((:ucp_stream_data_release, libucp), Cvoid, (ucp_ep_h, Ptr{Cvoid}), ep, data) end function ucp_request_free(request) ccall((:ucp_request_free, libucp), Cvoid, (Ptr{Cvoid},), request) end function ucp_request_alloc(worker) ccall((:ucp_request_alloc, libucp), Ptr{Cvoid}, (ucp_worker_h,), worker) end function ucp_dt_create_generic(ops, context, datatype_p) ccall((:ucp_dt_create_generic, libucp), ucs_status_t, (Ptr{ucp_generic_dt_ops_t}, Ptr{Cvoid}, Ptr{ucp_datatype_t}), ops, context, datatype_p) end function ucp_dt_destroy(datatype) ccall((:ucp_dt_destroy, libucp), Cvoid, (ucp_datatype_t,), datatype) end function ucp_worker_fence(worker) ccall((:ucp_worker_fence, libucp), ucs_status_t, (ucp_worker_h,), worker) end function ucp_worker_flush_nb(worker, flags, cb) ccall((:ucp_worker_flush_nb, libucp), ucs_status_ptr_t, (ucp_worker_h, Cuint, ucp_send_callback_t), worker, flags, cb) end function ucp_worker_flush_nbx(worker, param) ccall((:ucp_worker_flush_nbx, libucp), ucs_status_ptr_t, (ucp_worker_h, Ptr{ucp_request_param_t}), worker, param) end @cenum ucp_ep_attr_field::UInt32 begin UCP_EP_ATTR_FIELD_NAME = 1 end struct ucp_ep_attr field_mask::UInt64 name::NTuple{32, Cchar} end const ucp_ep_attr_t = ucp_ep_attr function ucp_ep_query(ep, attr) ccall((:ucp_ep_query, libucp), ucs_status_t, (ucp_ep_h, Ptr{ucp_ep_attr_t}), ep, attr) end const UCS_ALLOCA_MAX_SIZE = 1200 # const UCS_EMPTY_STATEMENT = {} const UCS_MEMORY_TYPES_CPU_ACCESSIBLE = (UCS_BIT(UCS_MEMORY_TYPE_HOST) | UCS_BIT(UCS_MEMORY_TYPE_CUDA_MANAGED)) | UCS_BIT(UCS_MEMORY_TYPE_ROCM_MANAGED) const UCP_ENTITY_NAME_MAX = 32 const UCP_VERSION_MAJOR_SHIFT = 24 const UCP_VERSION_MINOR_SHIFT = 16 const UCP_API_MAJOR = 1 const UCP_API_MINOR = 11 const UCP_API_VERSION = UCP_VERSION(1, 11) const UCS_CPU_SETSIZE = 1024 end # module
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
2185
function idle_callback(handle) idle = @Base.handle_as handle UvWorkerIdle if isopen(idle.worker) progress(idle.worker, #=yield=#false) else close(idle) end nothing end mutable struct UvWorkerIdle handle::Ptr{Cvoid} cond::Base.ThreadSynchronizer worker::UCXWorker isopen::Bool function UvWorkerIdle(worker::UCXWorker) this = new(Libc.malloc(Base._sizeof_uv_idle), Base.ThreadSynchronizer(), worker, true) Base.iolock_begin() Base.associate_julia_struct(this.handle, this) err = ccall(:uv_idle_init, Cint, (Ptr{Cvoid}, Ptr{Cvoid}), Base.eventloop(), this.handle) if err != 0 Libc.free(this.handle) this.handle = C_NULL throw(_UVError("uv_idle_init", err)) end err = ccall(:uv_idle_start, Cint, (Ptr{Cvoid}, Ptr{Cvoid}), this.handle, @cfunction(idle_callback, Cvoid, (Ptr{Cvoid},))) if err != 0 Libc.free(this.handle) this.handle = C_NULL throw(_UVError("uv_idle_start", err)) end finalizer(Base.uvfinalize, this) Base.iolock_end() return this end end Base.unsafe_convert(::Type{Ptr{Cvoid}}, idle::UvWorkerIdle) = idle.handle function Base.uvfinalize(t::UvWorkerIdle) Base.iolock_begin() Base.lock(t.cond) try if t.handle != C_NULL Base.disassociate_julia_struct(t.handle) # not going to call the usual close hooks if t.isopen t.isopen = false ccall(:jl_close_uv, Cvoid, (Ptr{Cvoid},), t) end t.handle = C_NULL notify(t.cond, false) end finally unlock(t.cond) end Base.iolock_end() nothing end function Base.close(idle::UvWorkerIdle) Base.uvfinalize(idle) end function Base.wait(idle::UvWorkerIdle) Base.iolock_begin() Base.preserve_handle(idle) Base.lock(idle.cond) try Base.iolock_end() wait(idle.cond) finally Base.unlock(idle.cond) Base.iolock_begin() Base.unpreserve_handle(idle) Base.iolock_end() end end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
780
module IP using Sockets: InetAddr, IPv4 const AF_INET = Cshort(2) const INADDR_ANY = Culong(0x00000000) const INADDR_LOOPBACK = Culong(0x7f000001) const INADDR_NONE = Culong(0xffffffff) struct in_addr s_addr::Cuint end struct sockaddr_in sin_family::Cshort sin_port::Cushort sin_addr::in_addr sin_zero::NTuple{8, Cchar} function sockaddr_in(port, addr) new(AF_INET, port, addr, ntuple(_-> Cchar(0), 8)) end end function sockaddr_in(addr::InetAddr{IPv4}) host_in = in_addr(hton(addr.host.host)) sockaddr_in(hton(convert(Cushort, addr.port)), host_in) end struct sockaddr_storage data::NTuple{128, UInt8} # _SS_SIZE end end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
2188
using Test # Assumes wireup has already happened, see setup.jl # Test for https://github.com/openucx/ucx/issues/6394 @everywhere const REPLY_EP = parse(Bool, get(ENV, "AM_TEST_REPLY_EP", "false")) @everywhere using UCX @everywhere begin const AM_RECEIVE = 1 function am_receive(worker, header, header_length, data, length, _param) param = Base.unsafe_load(_param)::UCX.API.ucp_am_recv_param_t @static if REPLY_EP @assert (param.recv_attr & UCX.API.UCP_AM_RECV_ATTR_FIELD_REPLY_EP) != 0 ep = UCX.UCXEndpoint(worker, param.reply_ep) else @assert (param.recv_attr & UCX.API.UCP_AM_RECV_ATTR_FIELD_REPLY_EP) == 0 ep = proc_to_endpoint(1) end @assert header_length == sizeof(Int) id = Base.unsafe_load(Base.unsafe_convert(Ptr{Int}, header)) UCX.@async_showerr begin header = Ref{Int}(id) req = UCX.am_send(ep, AM_ANSWER, header) wait(req) end return UCX.API.UCS_OK end UCX.AMHandler(UCX_WORKER, am_receive, AM_RECEIVE) const reply_ch = Channel{Int}(0) # unbuffered const AM_ANSWER = 2 function am_answer(worker, header, header_length, data, length, param) @assert header_length == sizeof(Int) id = Base.unsafe_load(Base.unsafe_convert(Ptr{Int}, header)) UCX.@async_showerr put!(reply_ch, id) return UCX.API.UCS_OK end UCX.AMHandler(UCX_WORKER, am_answer, AM_ANSWER) end #@everywhere const msg_counter = Ref{Int}(0) function send() ep = proc_to_endpoint(2) # Get the next message id id = msg_counter[] time_start = Base.time_ns() @static if REPLY_EP flags = UCX.API.UCP_AM_SEND_FLAG_REPLY else flags = nothing end req = UCX.am_send(ep, AM_RECEIVE, msg_counter, nothing, flags) wait(req) # wait on request to be send before suspending in `take!` msg_counter[] += 1 oid = take!(reply_ch) time_end = Base.time_ns() # We are timing the round-trip time intentionally # E.g. how long it takes for us to be notified @assert oid == id time_end - time_start end function bench(n) start_times = UInt64[] for i in 1:n push!(start_times, send()) end start_times end bench(10)
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
2538
using Test using UCX @testset "config" begin config = UCX.UCXConfig(TLS="tcp") @test parse(Dict, config)[:TLS] == "tcp" config[:TLS] = "all" @test parse(Dict, config)[:TLS] == "all" ctx = UCX.UCXContext(TLS="tcp") @test ctx.config[:TLS] == "tcp" end @testset "progress" begin using UCX UCX.PROGRESS_MODE[] = :polling ctx = UCX.UCXContext() worker = UCX.UCXWorker(ctx) flag = Ref(false) T = UCX.@async_showerr begin wait(worker) flag[] = true end while !flag[] notify(worker) yield() end wait(T) @test flag[] end @testset "address" begin ctx = UCX.UCXContext() worker = UCX.UCXWorker(ctx) addr = UCX.UCXAddress(worker) @test addr.len > 0 end @testset "Active Messages" begin cmd = Base.julia_cmd() if Base.JLOptions().project != C_NULL cmd = `$cmd --project=$(unsafe_string(Base.JLOptions().project))` end setup = joinpath(@__DIR__, "setup.jl") script = joinpath(@__DIR__, "am.jl") @test success(pipeline(`$cmd -L setup.jl $script`, stderr=stderr, stdout=stdout)) withenv("JLUCX_PROGRESS_MODE" => "busy") do @test success(pipeline(`$cmd -L setup.jl $script`, stderr=stderr, stdout=stdout)) # @test success(pipeline(`$cmd -t 2 -L setup.jl $script`, stderr=stderr, stdout=stdout)) end withenv("JLUCX_PROGRESS_MODE" => "polling") do @test success(pipeline(`$cmd -L setup.jl $script`, stderr=stderr, stdout=stdout)) end withenv("JLUCX_PROGRESS_MODE" => "unknown") do @test !success(pipeline(`$cmd -L setup.jl $script`, stderr=Base.DevNull(), stdout=Base.DevNull())) end withenv("AM_TEST_REPLY_EP" => "true") do @test success(pipeline(`$cmd -L setup.jl $script`, stderr=stderr, stdout=stdout)) end end @testset "examples" begin examples_dir = joinpath(@__DIR__, "..", "examples") cmd = Base.julia_cmd() if Base.JLOptions().project != C_NULL cmd = `$cmd --project=$(unsafe_string(Base.JLOptions().project))` end @testset "Client-Server" begin script = joinpath(examples_dir, "client_server.jl") for i in 0:2 @test success(pipeline(`$cmd $script test $(2^i)`, stderr=stderr, stdout=stdout)) end end @testset "Client-Server Stream" begin script = joinpath(examples_dir, "client_server_stream.jl") for i in 0:2 @test success(pipeline(`$cmd $script test $(2^i)`, stderr=stderr, stdout=stdout)) end end end
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
code
1461
using Distributed addprocs(1) @everywhere using UCX @everywhere begin function start() ctx = UCX.UCXContext() worker = UCX.UCXWorker(ctx) global UCX_WORKER = worker atexit() do close(worker) end UCX.@spawn_showerr begin while isopen(worker) wait(worker) end close(worker) end addr = UCX.UCXAddress(worker) GC.@preserve addr begin ptr = Base.unsafe_convert(Ptr{UInt8}, addr.handle) addr_buf = Base.unsafe_wrap(Array, ptr, addr.len; own=false) bind_addr = similar(addr_buf) copyto!(bind_addr, addr_buf) end return bind_addr end const UCX_PROC_ENDPOINT = Dict{Int, UCX.UCXEndpoint}() const UCX_ADDR_LISTING = Dict{Int, Vector{UInt8}}() function wireup(procs=Distributed.procs()) # Ideally we would use FluxRM or PMI and use their # distributed KVS. ucx_addr = Dict{Int, Vector{UInt8}}() @sync for p in procs @async begin ucx_addr[p] = Distributed.remotecall_fetch(start, p) end end @sync for p in procs @async begin Distributed.remotecall_wait(p, ucx_addr) do ucx_addr merge!(UCX_ADDR_LISTING, ucx_addr) end end end end function proc_to_endpoint(p) get!(UCX_PROC_ENDPOINT, p) do worker = UCX_WORKER::UCX.UCXWorker UCX.UCXEndpoint(worker, UCX_ADDR_LISTING[p]) end end end # @everywhere wireup()
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
0.3.1
8c8f3ec32008f0527c9d1836a16b0b6d34eca6b7
docs
265
# UCX.jl Contributions welcome! Please reach out to @vchuravy on the JuliaLang slack. ## Getting started In one terminal do: ``` julia --project=. examples/client_server.jl server ``` In the another: ``` julia --project=. examples/client_server.jl client ```
UCX
https://github.com/JuliaParallel/UCX.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
361
using StaticArrayInterface using Documenter makedocs(; modules=[StaticArrayInterface], sitename="StaticArrayInterface.jl", pages=[ "StaticArrayInterface.jl: Static Compile-Time Enforced Array Interface Functionality" => "index.md", "API" => "api.md" ] ) deploydocs(; repo="github.com/JuliaArrays/StaticArrayInterface.jl" )
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
2662
module StaticArrayInterfaceOffsetArraysExt using StaticArrayInterface using StaticArrayInterface.Static if isdefined(Base, :get_extension) using OffsetArrays else using ..OffsetArrays end relative_offsets(r::OffsetArrays.IdOffsetRange) = (getfield(r, :offset),) relative_offsets(A::OffsetArrays.OffsetArray) = getfield(A, :offsets) function relative_offsets(A::OffsetArrays.OffsetArray, ::StaticInt{dim}) where {dim} if dim > ndims(A) return static(0) else return getfield(relative_offsets(A), dim) end end function relative_offsets(A::OffsetArrays.OffsetArray, dim::Int) if dim > ndims(A) return 0 else return getfield(relative_offsets(A), dim) end end StaticArrayInterface.parent_type(::Type{<:OffsetArrays.OffsetArray{T,N,A}}) where {T,N,A} = A function _offset_axis_type(::Type{T}, dim::StaticInt{D}) where {T,D} OffsetArrays.IdOffsetRange{Int,StaticArrayInterface.axes_types(T, dim)} end function StaticArrayInterface.axes_types(::Type{T}) where {T<:OffsetArrays.OffsetArray} Static.eachop_tuple( _offset_axis_type, ntuple(static, StaticInt(ndims(T))), StaticArrayInterface.parent_type(T) ) end StaticArrayInterface.static_strides(A::OffsetArray) = StaticArrayInterface.static_strides(parent(A)) function StaticArrayInterface.known_offsets(::Type{A}) where {A<:OffsetArrays.OffsetArray} ntuple(identity -> nothing, Val(ndims(A))) end function StaticArrayInterface.offsets(A::OffsetArrays.OffsetArray) map(+, StaticArrayInterface.offsets(parent(A)), relative_offsets(A)) end @inline function StaticArrayInterface.offsets(A::OffsetArrays.OffsetArray, dim) d = StaticArrayInterface.to_dims(A, dim) StaticArrayInterface.offsets(parent(A), d) + relative_offsets(A, d) end @inline function StaticArrayInterface.static_axes(A::OffsetArrays.OffsetArray) map(OffsetArrays.IdOffsetRange, StaticArrayInterface.static_axes(parent(A)), relative_offsets(A)) end @inline function StaticArrayInterface.static_axes(A::OffsetArrays.OffsetArray, dim) d = StaticArrayInterface.to_dims(A, dim) OffsetArrays.IdOffsetRange(StaticArrayInterface.static_axes(parent(A), d), relative_offsets(A, d)) end function StaticArrayInterface.stride_rank(T::Type{<:OffsetArray}) StaticArrayInterface.stride_rank(StaticArrayInterface.parent_type(T)) end function StaticArrayInterface.dense_dims(T::Type{<:OffsetArray}) StaticArrayInterface.dense_dims(StaticArrayInterface.parent_type(T)) end function StaticArrayInterface.contiguous_axis(T::Type{<:OffsetArray}) StaticArrayInterface.contiguous_axis(StaticArrayInterface.parent_type(T)) end end # module
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
3068
module StaticArrayInterfaceStaticArraysExt using StaticArrayInterface using StaticArrayInterface.Static using Static: StaticInt if isdefined(Base, :get_extension) using StaticArrays using LinearAlgebra else using ..StaticArrays using ..LinearAlgebra end const CanonicalInt = Union{Int,StaticInt} function Static.OptionallyStaticUnitRange(::StaticArrays.SOneTo{N}) where {N} Static.OptionallyStaticUnitRange(StaticInt(1), StaticInt(N)) end StaticArrayInterface.known_first(::Type{<:StaticArrays.SOneTo}) = 1 StaticArrayInterface.known_last(::Type{StaticArrays.SOneTo{N}}) where {N} = N StaticArrayInterface.known_length(::Type{StaticArrays.SOneTo{N}}) where {N} = N StaticArrayInterface.known_length(::Type{StaticArrays.Length{L}}) where {L} = L function StaticArrayInterface.known_length(::Type{A}) where {A<:StaticArrays.StaticArray} StaticArrayInterface.known_length(StaticArrays.Length(A)) end @inline StaticArrayInterface.static_length(x::StaticArrays.StaticArray) = Static.maybe_static(StaticArrayInterface.known_length, Base.length, x) StaticArrayInterface.device(::Type{<:StaticArrays.MArray}) = StaticArrayInterface.CPUPointer() StaticArrayInterface.device(::Type{<:StaticArrays.SArray}) = StaticArrayInterface.CPUTuple() StaticArrayInterface.contiguous_axis(::Type{<:StaticArrays.StaticArray}) = StaticInt{1}() StaticArrayInterface.contiguous_batch_size(::Type{<:StaticArrays.StaticArray}) = StaticInt{0}() function StaticArrayInterface.stride_rank(::Type{T}) where {N,T<:StaticArray{<:Any,<:Any,N}} ntuple(static, StaticInt(N)) end function StaticArrayInterface.dense_dims(::Type{<:StaticArray{S,T,N}}) where {S,T,N} StaticArrayInterface._all_dense(Val(N)) end StaticArrayInterface.defines_strides(::Type{<:StaticArrays.SArray}) = true StaticArrayInterface.defines_strides(::Type{<:StaticArrays.MArray}) = true @generated function StaticArrayInterface.axes_types(::Type{<:StaticArrays.StaticArray{S}}) where {S} Tuple{[StaticArrays.SOneTo{s} for s in S.parameters]...} end @generated function StaticArrayInterface.static_size(A::StaticArrays.StaticArray{S}) where {S} t = Expr(:tuple) Sp = S.parameters for n = 1:length(Sp) push!(t.args, Expr(:call, Expr(:curly, :StaticInt, Sp[n]))) end return t end @generated function StaticArrayInterface.static_strides(A::StaticArrays.StaticArray{S}) where {S} t = Expr(:tuple, Expr(:call, Expr(:curly, :StaticInt, 1))) Sp = S.parameters x = 1 for n = 1:(length(Sp)-1) push!(t.args, Expr(:call, Expr(:curly, :StaticInt, (x *= Sp[n])))) end return t end if StaticArrays.SizedArray{Tuple{8,8},Float64,2,2} isa UnionAll @inline StaticArrayInterface.static_strides(B::StaticArrays.SizedArray{S,T,M,N,A}) where {S,T,M,N,A<:SubArray} = StaticArrayInterface.static_strides(B.data) StaticArrayInterface.parent_type(::Type{<:StaticArrays.SizedArray{S,T,M,N,A}}) where {S,T,M,N,A} = A else StaticArrayInterface.parent_type(::Type{<:StaticArrays.SizedArray{S,T,M,N}}) where {S,T,M,N} = Array{T,N} end end # module
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
16522
module StaticArrayInterface @static if isdefined(Base, Symbol("@assume_effects")) using Base: @assume_effects else macro assume_effects(args...) n = nfields(args) call = getfield(args, n) if n === 2 && getfield(args, 1) === QuoteNode(:total) return esc(:(Base.@pure $(call))) else return esc(call) end end end using PrecompileTools @recompile_invalidations begin using ArrayInterface import ArrayInterface: allowed_getindex, allowed_setindex!, aos_to_soa, buffer, parent_type, fast_matrix_colors, findstructralnz, has_sparsestruct, issingular, isstructured, matrix_colors, restructure, lu_instance, safevec, zeromatrix, undefmatrix, ColoringAlgorithm, fast_scalar_indexing, parameterless_type, is_forwarding_wrapper, map_tuple_type, flatten_tuples, GetIndex, SetIndex!, defines_strides, ndims_index, ndims_shape, stride_preserving_index # ArrayIndex subtypes and methods import ArrayInterface: ArrayIndex, MatrixIndex, VectorIndex, BidiagonalIndex, TridiagonalIndex # managing immutables import ArrayInterface: ismutable, can_change_size, can_setindex # constants import ArrayInterface: MatAdjTrans, VecAdjTrans, UpTri, LoTri # device pieces import ArrayInterface: AbstractDevice, AbstractCPU, CPUPointer, CPUTuple, CheckParent, CPUIndex, GPU, can_avx, device using Static using Static: Zero, One, nstatic, eq, ne, gt, ge, lt, le, eachop, eachop_tuple, permute, invariant_permutation, field_type, reduce_tup, find_first_eq, OptionallyStaticUnitRange, OptionallyStaticStepRange, OptionallyStaticRange, IntType, SOneTo, SUnitRange using IfElse using Base.Cartesian using Base: @propagate_inbounds, tail, OneTo, LogicalIndex, Slice, ReinterpretArray, ReshapedArray, AbstractCartesianIndex using Base.Iterators: Pairs using LinearAlgebra import Compat end """ StrideIndex(x) Subtype of `ArrayIndex` that transforms and index using stride layout information derived from `x`. """ struct StrideIndex{N,R,C,S,O} <: ArrayIndex{N} strides::S offsets::O @inline function StrideIndex{N,R,C}(s::S, o::O) where {N,R,C,S,O} return new{N,R::NTuple{N,Int},C,S,O}(s, o) end end """ LazyAxis{N}(parent::AbstractArray) A lazy representation of `axes(parent, N)`. """ struct LazyAxis{N,P} <: AbstractUnitRange{Int} parent::P function LazyAxis{N}(parent::P) where {N,P} N > 0 && return new{N::Int,P}(parent) throw_dim_error(parent, N) end @inline LazyAxis{:}(parent::P) where {P} = new{ifelse(ndims(P) === 1, 1, :),P}(parent) end function throw_dim_error(@nospecialize(x), @nospecialize(dim)) throw(DimensionMismatch("$x does not have dimension corresponding to $dim")) end abstract type AbstractArray2{T, N} <: AbstractArray{T, N} end """ BroadcastAxis An abstract trait that is used to determine how axes are combined when calling `broadcast_axis`. """ abstract type BroadcastAxis end @assume_effects :total function _find_first_true(isi::Tuple{Vararg{Union{Bool, Static.StaticBool}, N}}) where {N} for i in 1:N x = getfield(isi, i) if (x isa Bool && x === true) || x isa Static.True return i end end return nothing end """ IndicesInfo{N}(inds::Tuple) -> IndicesInfo{N}(typeof(inds)) IndicesInfo{N}(T::Type{<:Tuple}) -> IndicesInfo{N,pdims,cdims}() IndicesInfo(inds::Tuple) -> IndicesInfo(typeof(inds)) IndicesInfo(T::Type{<:Tuple}) -> IndicesInfo{maximum(pdims),pdims,cdims}() Maps a tuple of indices to `N` dimensions. The resulting `pdims` is a tuple where each field in `inds` (or field type in `T`) corresponds to the parent dimensions accessed. `cdims` similarly maps indices to the resulting child array produced after indexing with `inds`. If `N` is not provided then it is assumed that all indices are represented by parent dimensions and there are no trailing dimensions accessed. These may be accessed by through `parentdims(info::IndicesInfo)` and `childdims(info::IndicesInfo)`. If `N` is not provided, it is assumed that no indices are accessing trailing dimensions (which are represented as `0` in `parentdims(info)[index_position]`). The the fields and types of `IndicesInfo` should not be accessed directly. Instead [`parentdims`](@ref), [`childdims`](@ref), [`ndims_index`](@ref), and [`ndims_shape`](@ref) should be used to extract relevant information. # Examples ```julia julia> using StaticArrayInterface: IndicesInfo, parentdims, childdims, ndims_index, ndims_shape julia> info = IndicesInfo{5}(typeof((:,[CartesianIndex(1,1),CartesianIndex(1,1)], 1, ones(Int, 2, 2), :, 1))); julia> parentdims(info) # the last two indices access trailing dimensions (1, (2, 3), 4, 5, 0, 0) julia> childdims(info) (1, 2, 0, (3, 4), 5, 0) julia> childdims(info)[3] # index 3 accesses a parent dimension but is dropped in the child array 0 julia> ndims_index(info) 5 julia> ndims_shape(info) 5 julia> info = IndicesInfo(typeof((:,[CartesianIndex(1,1),CartesianIndex(1,1)], 1, ones(Int, 2, 2), :, 1))); julia> parentdims(info) # assumed no trailing dimensions (1, (2, 3), 4, 5, 6, 7) julia> ndims_index(info) # assumed no trailing dimensions 7 ``` """ struct IndicesInfo{Np, pdims, cdims, Nc} function IndicesInfo{N}(@nospecialize(T::Type{<:Tuple})) where {N} SI = _find_first_true(map_tuple_type(is_splat_index, T)) NI = map_tuple_type(ndims_index, T) NS = map_tuple_type(ndims_shape, T) if SI === nothing ndi = NI nds = NS else nsplat = N - sum(NI) if nsplat === 0 ndi = NI nds = NS else splatmul = max(0, nsplat + 1) ndi = _map_splats(splatmul, SI, NI) nds = _map_splats(splatmul, SI, NS) end end if ndi === (1,) && N !== 1 ns1 = getfield(nds, 1) new{N, (:,), (ns1 > 1 ? ntuple(identity, ns1) : ns1,), ns1}() else nds_cumsum = cumsum(nds) if sum(ndi) > N init_pdims = _accum_dims(cumsum(ndi), ndi) pdims = ntuple(nfields(init_pdims)) do i dim_i = getfield(init_pdims, i) if dim_i isa Tuple ntuple(length(dim_i)) do j dim_i_j = getfield(dim_i, j) dim_i_j > N ? 0 : dim_i_j end else dim_i > N ? 0 : dim_i end end new{N, pdims, _accum_dims(nds_cumsum, nds), last(nds_cumsum)}() else new{N, _accum_dims(cumsum(ndi), ndi), _accum_dims(nds_cumsum, nds), last(nds_cumsum)}() end end end IndicesInfo{N}(@nospecialize(t::Tuple)) where {N} = IndicesInfo{N}(typeof(t)) function IndicesInfo(@nospecialize(T::Type{<:Tuple})) ndi = map_tuple_type(ndims_index, T) nds = map_tuple_type(ndims_shape, T) ndi_sum = cumsum(ndi) nds_sum = cumsum(nds) nf = nfields(ndi_sum) pdims = _accum_dims(ndi_sum, ndi) cdims = _accum_dims(nds_sum, nds) new{getfield(ndi_sum, nf), pdims, cdims, getfield(nds_sum, nf)}() end IndicesInfo(@nospecialize t::Tuple) = IndicesInfo(typeof(t)) @inline function IndicesInfo(@nospecialize T::Type{<:SubArray}) IndicesInfo{ndims(parent_type(T))}(fieldtype(T, :indices)) end IndicesInfo(x::SubArray) = IndicesInfo{ndims(parent(x))}(typeof(x.indices)) end @inline function _map_splats(nsplat::Int, splat_index::Int, dims::Tuple{Vararg{Union{Int,StaticInt}}}) ntuple(length(dims)) do i i === splat_index ? (nsplat * getfield(dims, i)) : getfield(dims, i) end end @inline function _accum_dims(csdims::NTuple{N, Int}, nd::NTuple{N, Int}) where {N} ntuple(N) do i nd_i = getfield(nd, i) if nd_i === 0 0 elseif nd_i === 1 getfield(csdims, i) else ntuple(Base.Fix1(+, getfield(csdims, i) - nd_i), nd_i) end end end function _lower_info(::IndicesInfo{Np, pdims, cdims, Nc}) where {Np, pdims, cdims, Nc} Np, pdims, cdims, Nc end ndims_index(@nospecialize(info::IndicesInfo)) = getfield(_lower_info(info), 1) ndims_shape(@nospecialize(info::IndicesInfo)) = getfield(_lower_info(info), 4) """ parentdims(::IndicesInfo) -> Tuple Returns the parent dimension mapping from `IndicesInfo`. See also: [`IndicesInfo`](@ref), [`childdims`](@ref) """ parentdims(@nospecialize info::IndicesInfo) = getfield(_lower_info(info), 2) """ childdims(::IndicesInfo) -> Tuple Returns the child dimension mapping from `IndicesInfo`. See also: [`IndicesInfo`](@ref), [`parentdims`](@ref) """ childdims(@nospecialize info::IndicesInfo) = getfield(_lower_info(info), 3) @generated function merge_tuple_type(::Type{X}, ::Type{Y}) where {X <: Tuple, Y <: Tuple} Tuple{X.parameters..., Y.parameters...} end Base.size(A::AbstractArray2) = map(Int, static_size(A)) Base.size(A::AbstractArray2, dim) = Int(static_size(A, dim)) function Base.axes(A::AbstractArray2) is_forwarding_wrapper(A) && return static_axes(parent(A)) throw(ArgumentError("Subtypes of `AbstractArray2` must define an axes method")) end function Base.axes(A::AbstractArray2, dim::Union{Symbol, StaticSymbol}) static_axes(A, to_dims(A, dim)) end function Base.strides(A::AbstractArray2) defines_strides(A) && return map(Int, static_strides(A)) throw(MethodError(Base.strides, (A,))) end Base.strides(A::AbstractArray2, dim) = Int(static_strides(A, dim)) function Base.IndexStyle(::Type{T}) where {T <: AbstractArray2} is_forwarding_wrapper(T) ? IndexStyle(parent_type(T)) : IndexCartesian() end function Base.length(A::AbstractArray2) len = known_length(A) if len === nothing return Int(prod(static_size(A))) else return Int(len) end end @propagate_inbounds Base.getindex(A::AbstractArray2, args...) = static_getindex(A, args...) @propagate_inbounds Base.getindex(A::AbstractArray2; kwargs...) = static_getindex(A; kwargs...) @propagate_inbounds function Base.setindex!(A::AbstractArray2, val, args...) return setindex!(A, val, args...) end @propagate_inbounds function Base.setindex!(A::AbstractArray2, val; kwargs...) return setindex!(A, val; kwargs...) end @inline static_first(x) = Static.maybe_static(known_first, first, x) @inline static_last(x) = Static.maybe_static(known_last, last, x) @inline static_step(x) = Static.maybe_static(known_step, step, x) @inline function _to_cartesian(a, i::IntType) @inbounds(CartesianIndices(ntuple(dim -> indices(a, dim), Val(ndims(a))))[i]) end @inline function _to_linear(a, i::Tuple{IntType, Vararg{IntType}}) _strides2int(offsets(a), size_to_strides(static_size(a), static(1)), i) + static(1) end """ has_parent(::Type{T}) -> StaticBool Returns `static(true)` if `parent_type(T)` a type unique to `T`. """ has_parent(x) = has_parent(typeof(x)) has_parent(::Type{T}) where {T} = _has_parent(parent_type(T), T) _has_parent(::Type{T}, ::Type{T}) where {T} = False() _has_parent(::Type{T1}, ::Type{T2}) where {T1, T2} = True() """ is_lazy_conjugate(::AbstractArray) -> Bool Determine if a given array will lazyily take complex conjugates, such as with `Adjoint`. This will work with nested wrappers, so long as there is no type in the chain of wrappers such that `parent_type(T) == T` Examples julia> a = transpose([1 + im, 1-im]') 2×1 transpose(adjoint(::Vector{Complex{Int64}})) with eltype Complex{Int64}: 1 - 1im 1 + 1im julia> is_lazy_conjugate(a) True() julia> b = a' 1×2 adjoint(transpose(adjoint(::Vector{Complex{Int64}}))) with eltype Complex{Int64}: 1+1im 1-1im julia> is_lazy_conjugate(b) False() """ is_lazy_conjugate(::T) where {T <: AbstractArray} = _is_lazy_conjugate(T, False()) is_lazy_conjugate(::AbstractArray{<:Real}) = False() function _is_lazy_conjugate(::Type{T}, isconj) where {T <: AbstractArray} Tp = parent_type(T) if T !== Tp _is_lazy_conjugate(Tp, isconj) else isconj end end function _is_lazy_conjugate(::Type{T}, isconj) where {T <: Adjoint} Tp = parent_type(T) if T !== Tp _is_lazy_conjugate(Tp, !isconj) else !isconj end end """ insert(collection, index, item) Returns a new instance of `collection` with `item` inserted into at the given `index`. """ Base.@propagate_inbounds function insert(collection, index, item) @boundscheck checkbounds(collection, index) ret = similar(collection, static_length(collection) + 1) @inbounds for i in firstindex(ret):(index - 1) ret[i] = collection[i] end @inbounds ret[index] = item @inbounds for i in (index + 1):lastindex(ret) ret[i] = collection[i - 1] end return ret end function insert(x::Tuple{Vararg{Any, N}}, index, item) where {N} @boundscheck if !checkindex(Bool, StaticInt{1}():StaticInt{N}(), index) throw(BoundsError(x, index)) end return unsafe_insert(x, Int(index), item) end @inline function unsafe_insert(x::Tuple, i::Int, item) if i === 1 return (item, x...) else return (first(x), unsafe_insert(tail(x), i - 1, item)...) end end """ deleteat(collection, index) Returns a new instance of `collection` with the item at the given `index` removed. """ Base.@propagate_inbounds function deleteat(collection::AbstractVector, index) @boundscheck if !checkindex(Bool, eachindex(collection), index) throw(BoundsError(collection, index)) end return unsafe_deleteat(collection, index) end Base.@propagate_inbounds function deleteat(collection::Tuple{Vararg{Any, N}}, index) where {N} @boundscheck if !checkindex(Bool, StaticInt{1}():StaticInt{N}(), index) throw(BoundsError(collection, index)) end return unsafe_deleteat(collection, index) end function unsafe_deleteat(src::AbstractVector, index) dst = similar(src, static_length(src) - 1) @inbounds for i in indices(dst) if i < index dst[i] = src[i] else dst[i] = src[i + 1] end end return dst end @inline function unsafe_deleteat(src::AbstractVector, inds::AbstractVector) dst = similar(src, static_length(src) - static_length(inds)) dst_index = firstindex(dst) @inbounds for src_index in indices(src) if !in(src_index, inds) dst[dst_index] = src[src_index] dst_index += one(dst_index) end end return dst end @inline function unsafe_deleteat(src::Tuple, inds::AbstractVector) dst = Vector{eltype(src)}(undef, static_length(src) - static_length(inds)) dst_index = firstindex(dst) @inbounds for src_index in static(1):static_length(src) if !in(src_index, inds) dst[dst_index] = src[src_index] dst_index += one(dst_index) end end return Tuple(dst) end @inline unsafe_deleteat(x::Tuple{T}, i) where {T} = () @inline unsafe_deleteat(x::Tuple{T1, T2}, i) where {T1, T2} = isone(i) ? (x[2],) : (x[1],) @inline function unsafe_deleteat(x::Tuple, i) if i === one(i) return tail(x) elseif i == static_length(x) return Base.front(x) else return (first(x), unsafe_deleteat(tail(x), i - one(i))...) end end include("array_index.jl") include("ranges.jl") include("axes.jl") include("size.jl") include("dimensions.jl") include("indexing.jl") include("stridelayout.jl") include("broadcast.jl") ## Precompilation @setup_workload begin # Putting some things in `setup` can reduce the size of the # precompile file and potentially make loading faster. arrays = [rand(4), Base.oneto(5)] @compile_workload begin for x in arrays known_first(x) known_step(x) known_last(x) end end end end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
697
@inline function StrideIndex{N,R,C}(a::A) where {N,R,C,A} return StrideIndex{N,R,C}(static_strides(a), offsets(a)) end @inline function StrideIndex(a::A) where {A} return StrideIndex{ndims(A),known(stride_rank(A)),known(contiguous_axis(A))}(a) end ## getindex @propagate_inbounds Base.getindex(x::ArrayIndex, i::IntType, ii::IntType...) = x[NDIndex(i, ii...)] @inline function Base.getindex(x::StrideIndex{N}, i::AbstractCartesianIndex) where {N} return _strides2int(offsets(x), static_strides(x), Tuple(i)) + static(1) end function _strides2int(o::O, s::S, i::I) where {O,S,I} N = known_length(S) sum(ntuple(x->(getfield(i, x) - getfield(o, x)) * getfield(s, x),N)) end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
10448
""" axes_types(::Type{T}) -> Type{Tuple{Vararg{AbstractUnitRange{Int}}}} axes_types(::Type{T}, dim) -> Type{AbstractUnitRange{Int}} Returns the type of each axis for the `T`, or the type of of the axis along dimension `dim`. """ @inline axes_types(x, dim) = axes_types(x, to_dims(x, dim)) @inline function axes_types(x, dim::StaticInt{D}) where {D} if D > ndims(x) return SOneTo{1} else return field_type(axes_types(x), dim) end end @inline function axes_types(x, dim::Int) if dim > ndims(x) return SOneTo{1} else return fieldtype(axes_types(x), dim) end end axes_types(x) = axes_types(typeof(x)) axes_types(::Type{T}) where {T<:Array} = NTuple{ndims(T),OneTo{Int}} @inline function axes_types(::Type{T}) where {T} if is_forwarding_wrapper(T) return axes_types(parent_type(T)) else return NTuple{ndims(T),OptionallyStaticUnitRange{One,Int}} end end axes_types(::Type{<:LinearIndices{N,R}}) where {N,R} = R axes_types(::Type{<:CartesianIndices{N,R}}) where {N,R} = R function axes_types(@nospecialize T::Type{<:VecAdjTrans}) Tuple{SOneTo{1}, fieldtype(axes_types(parent_type(T)), 1)} end function axes_types(@nospecialize T::Type{<:MatAdjTrans}) Ax = axes_types(parent_type(T)) Tuple{fieldtype(Ax, 2), fieldtype(Ax, 1)} end function axes_types(::Type{T}) where {T<:PermutedDimsArray} eachop_tuple(field_type, to_parent_dims(T), axes_types(parent_type(T))) end axes_types(T::Type{<:Base.IdentityUnitRange}) = Tuple{T} axes_types(::Type{<:Base.Slice{I}}) where {I} = Tuple{Base.IdentityUnitRange{I}} axes_types(::Type{<:Base.Slice{I}}) where {I<:Base.IdentityUnitRange} = Tuple{I} function axes_types(::Type{T}) where {T<:AbstractRange} if known_length(T) === nothing return Tuple{OneTo{Int}} else return Tuple{SOneTo{known_length(T)}} end end axes_types(::Type{T}) where {T<:ReshapedArray} = NTuple{ndims(T),OneTo{Int}} function _sub_axis_type(::Type{PA}, ::Type{I}, dim::StaticInt{D}) where {I<:Tuple,PA,D} IT = field_type(I, dim) if IT <: Base.Slice{Base.OneTo{Int}} # this helps workaround slices over statically sized dimensions axes_types(field_type(PA, dim), static(1)) else axes_types(IT, static(1)) end end @inline function axes_types(@nospecialize T::Type{<:SubArray}) return eachop_tuple(_sub_axis_type, to_parent_dims(T), axes_types(parent_type(T)), fieldtype(T, :indices)) end function axes_types(::Type{T}) where {T<:ReinterpretArray} eachop_tuple(_non_reshaped_axis_type, ntuple(static, StaticInt(ndims(T))), T) end function _non_reshaped_axis_type(::Type{A}, d::StaticInt{D}) where {A,D} paxis = axes_types(parent_type(A), d) if D === 1 if known_length(paxis) === nothing return paxis else return SOneTo{div(known_length(paxis) * sizeof(eltype(parent_type(A))), sizeof(eltype(A)))} end else return paxis end end function axes_types(::Type{A}) where {T,N,S,A<:Base.ReshapedReinterpretArray{T,N,S}} if sizeof(S) > sizeof(T) return merge_tuple_type(Tuple{SOneTo{div(sizeof(S), sizeof(T))}}, axes_types(parent_type(A))) elseif sizeof(S) < sizeof(T) P = parent_type(A) return eachop_tuple(field_type, tail(ntuple(static, StaticInt(ndims(P)))), axes_types(P)) else return axes_types(parent_type(A)) end end # FUTURE NOTE: we avoid `SOneTo(1)` when `axis(A, dim::Int)``. This is inended to decreases # breaking changes for this adopting this method to situations where they clearly benefit # from the propagation of static axes. This creates the somewhat awkward situation of # conditionally typed (but inferrable) axes. It also means we can't depend on constant # propagation to preserve statically sized axes. This should probably be addressed before # merging into Base Julia. """ static_axes(A) -> Tuple{Vararg{AbstractUnitRange{Int}}} static_axes(A, dim) -> AbstractUnitRange{Int} Returns the axis associated with each dimension of `A` or dimension `dim`. `static_axes(::AbstractArray)` behaves nearly identical to `Base.axes` with the exception of a handful of types replace `Base.OneTo{Int}` with `SOneTo`. For example, the axis along the first dimension of `Transpose{T,<:AbstractVector{T}}` and `Adjoint{T,<:AbstractVector{T}}` can be represented by `SOneTo(1)`. Similarly, `Base.ReinterpretArray`'s first axis may be statically sized. """ @inline static_axes(A) = Base.axes(A) static_axes(A::ReshapedArray) = Base.axes(A) @inline function static_axes(x::Union{MatAdjTrans,PermutedDimsArray}) map(GetIndex{false}(static_axes(parent(x))), to_parent_dims(x)) end static_axes(A::VecAdjTrans) = (SOneTo{1}(), static_axes(parent(A), 1)) @inline static_axes(x::SubArray) = flatten_tuples(map(Base.Fix1(_sub_axes, x), sub_axes_map(typeof(x)))) @inline _sub_axes(x::SubArray, axis::SOneTo) = axis _sub_axes(x::SubArray, ::StaticInt{index}) where {index} = static_axes(getfield(x.indices, index)) @inline static_axes(A, dim) = _axes(A, to_dims(A, dim)) @inline _axes(A, dim::Int) = dim > ndims(A) ? OneTo(1) : getfield(static_axes(A), dim) @inline function _axes(A, ::StaticInt{dim}) where {dim} dim > ndims(A) ? SOneTo{1}() : getfield(static_axes(A), dim) end @inline function static_axes(A::Base.ReshapedReinterpretArray{T,N,S}) where {T,N,S} if sizeof(S) > sizeof(T) return (SOneTo(div(sizeof(S), sizeof(T))), static_axes(parent(A))...) elseif sizeof(S) < sizeof(T) return tail(static_axes(parent(A))) else return static_axes(parent(A)) end end @inline function static_axes(A::Base.ReshapedReinterpretArray{T,N,S}, dim) where {T,N,S} d = to_dims(A, dim) if sizeof(S) > sizeof(T) if d == 1 return SOneTo(div(sizeof(S), sizeof(T))) else return static_axes(parent(A), d - static(1)) end elseif sizeof(S) < sizeof(T) return static_axes(parent(A), d - static(1)) else return static_axes(parent(A), d) end end @inline Base.parent(x::LazyAxis{N,P}) where {N,P} = static_axes(getfield(x, :parent), static(N)) @inline Base.parent(x::LazyAxis{:,P}) where {P} = eachindex(IndexLinear(), getfield(x, :parent)) @inline parent_type(::Type{LazyAxis{N,P}}) where {N,P} = axes_types(P, static(N)) # TODO this approach to parent_type(::Type{LazyAxis{:}}) is a bit hacky. Something like # LabelledArrays has a linear set of symbolic keys, which could be propagated through # `to_indices` for key based indexing. However, there currently isn't a good way of handling # that when the linear indices aren't linearly accessible through a child array (e.g, adjoint) # For now we just make sure the linear elements are accurate. parent_type(::Type{LazyAxis{:,P}}) where {P<:Array} = OneTo{Int} @inline function parent_type(::Type{LazyAxis{:,P}}) where {P} if known_length(P) === nothing return OptionallyStaticUnitRange{StaticInt{1},Int} else return SOneTo{known_length(P)} end end Base.keys(x::LazyAxis) = keys(parent(x)) Base.IndexStyle(T::Type{<:LazyAxis}) = IndexStyle(parent_type(T)) function Static.OptionallyStaticUnitRange(x::LazyAxis) OptionallyStaticUnitRange(static_first(x), static_last(x)) end can_change_size(@nospecialize T::Type{<:LazyAxis}) = can_change_size(fieldtype(T, :parent)) known_first(::Type{<:LazyAxis{N,P}}) where {N,P} = known_offsets(P, static(N)) known_first(::Type{<:LazyAxis{:,P}}) where {P} = 1 @inline function Base.first(x::LazyAxis{N})::Int where {N} if known_first(x) === nothing return Int(offsets(getfield(x, :parent), StaticInt(N))) else return Int(known_first(x)) end end @inline Base.first(x::LazyAxis{:})::Int = Int(offset1(getfield(x, :parent))) known_last(::Type{LazyAxis{N,P}}) where {N,P} = known_last(axes_types(P, static(N))) known_last(::Type{LazyAxis{:,P}}) where {P} = known_length(P) Base.last(x::LazyAxis) = _last(known_last(x), x) _last(::Nothing, x::LazyAxis{:}) = lastindex(getfield(x, :parent)) _last(::Nothing, x::LazyAxis{N}) where {N} = lastindex(getfield(x, :parent), N) _last(N::Int, x) = N known_length(::Type{<:LazyAxis{:,P}}) where {P} = known_length(P) known_length(::Type{<:LazyAxis{N,P}}) where {N,P} = known_size(P, static(N)) @inline Base.length(x::LazyAxis{:}) = Base.length(getfield(x, :parent)) @inline Base.length(x::LazyAxis{N}) where {N} = Base.size(getfield(x, :parent), N) Base.axes(x::LazyAxis) = (Base.axes1(x),) Base.axes1(x::LazyAxis) = x Base.axes(x::Slice{<:LazyAxis}) = (Base.axes1(x),) # assuming that lazy loaded params like dynamic length from `size(::Array, dim)` are going # be used again later with `Slice{LazyAxis}`, we quickly load indices Base.axes1(x::Slice{LazyAxis{N,A}}) where {N,A} = indices(getfield(x.indices, :parent), StaticInt(N)) Base.axes1(x::Slice{LazyAxis{:,A}}) where {A} = indices(getfield(x.indices, :parent)) Base.to_shape(x::LazyAxis) = Base.length(x) @propagate_inbounds function Base.getindex(x::LazyAxis, i::IntType) @boundscheck checkindex(Bool, x, i) || throw(BoundsError(x, i)) return Int(i) end @propagate_inbounds function Base.getindex(x::LazyAxis, s::StepRange{<:Integer}) @boundscheck checkbounds(x, s) range(Int(first(x) + s.start-1), step=Int(step(s)), length=Int(static_length(s))) end @propagate_inbounds Base.getindex(x::LazyAxis, i::AbstractUnitRange{<:Integer}) = parent(x)[i] Base.show(io::IO, x::LazyAxis{N}) where {N} = print(io, "LazyAxis{$N}($(parent(x))))") """ lazy_axes(x) Produces a tuple of axes where each axis is constructed lazily. If an axis of `x` is already constructed or it is simply retrieved. """ @inline lazy_axes(x) = lazy_axes(x, ntuple(static, StaticInt(ndims(x)))) lazy_axes(x::Union{LinearIndices,CartesianIndices,AbstractRange}) = static_axes(x) @inline function lazy_axes(x::PermutedDimsArray, ::StaticInt{N}) where {N} N <= ndims(x) ? lazy_axes(parent(x), getfield(to_parent_dims(x), N)) : SOneTo{1}() end lazy_axes(x::Union{Adjoint,Transpose}, ::StaticInt{1}) = lazy_axes(parent(x), StaticInt(2)) lazy_axes(x::Union{Adjoint,Transpose}, ::StaticInt{2}) = lazy_axes(parent(x), StaticInt(1)) lazy_axes(x::AbstractRange, ::StaticInt{1}) = Base.axes1(x) lazy_axes(x, ::Colon) = LazyAxis{:}(x) lazy_axes(x, ::StaticInt{dim}) where {dim} = ndims(x) < dim ? SOneTo{1}() : LazyAxis{dim}(x) @inline lazy_axes(x, dims::Tuple) = map(Base.Fix1(lazy_axes, x), dims)
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
1872
struct BroadcastAxisDefault <: BroadcastAxis end BroadcastAxis(x) = BroadcastAxis(typeof(x)) BroadcastAxis(::Type{T}) where {T} = BroadcastAxisDefault() """ broadcast_axis(x, y) Broadcast axis `x` and `y` into a common space. The resulting axis should be equal in length to both `x` and `y` unless one has a length of `1`, in which case the longest axis will be equal to the output. ```julia julia> broadcast_axis(1:10, 1:10) julia> broadcast_axis(1:10, 1) 1:10 ``` """ broadcast_axis(x, y) = broadcast_axis(BroadcastAxis(x), x, y) # stagger default broadcasting in case y has something other than default broadcast_axis(::BroadcastAxisDefault, x, y) = _broadcast_axis(BroadcastAxis(y), x, y) function _broadcast_axis(::BroadcastAxisDefault, x, y) return One():_combine_length(static_length(x), static_length(y)) end _broadcast_axis(s::BroadcastAxis, x, y) = broadcast_axis(s, x, y) # we can use a similar trick as we do with `indices` where unequal sizes error and we just # keep the static value. However, axes can be unequal if one of them is `1` so we have to # fall back to dynamic values in those cases _combine_length(x::StaticInt{X}, y::StaticInt{Y}) where {X,Y} = static(_combine_length(X, Y)) _combine_length(x::StaticInt{X}, ::Int) where {X} = x _combine_length(x::StaticInt{1}, y::Int) = y _combine_length(x::StaticInt{1}, y::StaticInt{1}) = y _combine_length(x::Int, y::StaticInt{Y}) where {Y} = y _combine_length(x::Int, y::StaticInt{1}) = x @inline function _combine_length(x::Int, y::Int) if x === y return x elseif y === 1 return x elseif x === 1 return y else _dimerr(x, y) end end function _dimerr(@nospecialize(x), @nospecialize(y)) throw(DimensionMismatch("axes could not be broadcast to a common size; " * "got axes with lengths $(x) and $(y)")) end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
10443
_init_dimsmap(x) = _init_dimsmap(IndicesInfo(x)) function _init_dimsmap(@nospecialize info::IndicesInfo) pdims = parentdims(info) cdims = childdims(info) ntuple(i -> static(getfield(pdims, i)), static_length(pdims)), ntuple(i -> static(getfield(cdims, i)), static_length(pdims)) end """ to_parent_dims(::Type{T}) -> Tuple{Vararg{Union{StaticInt,Tuple{Vararg{StaticInt}}}}} Returns the mapping from child dimensions to parent dimensions. !!! Warning This method is still experimental and may change without notice. """ to_parent_dims(@nospecialize x) = to_parent_dims(typeof(x)) @inline function to_parent_dims(@nospecialize T::Type{<:SubArray}) to_parent_dims(IndicesInfo{ndims(parent_type(T))}(fieldtype(T, :indices))) end to_parent_dims(info::IndicesInfo) = flatten_tuples(map(_to_pdim, map_indices_info(info))) _to_pdim(::Tuple{StaticInt,Any,StaticInt{0}}) = () _to_pdim(x::Tuple{StaticInt,Any,StaticInt{cdim}}) where {cdim} = getfield(x, 2) _to_pdim(x::Tuple{StaticInt,Any,Tuple}) = (ntuple(Compat.Returns(getfield(x, 2)), static_length(getfield(x, 3))),) to_parent_dims(@nospecialize T::Type{<:MatAdjTrans}) = (StaticInt(2), StaticInt(1)) to_parent_dims(@nospecialize T::Type{<:PermutedDimsArray}) = getfield(_permdims(T), 1) function _permdims(::Type{<:PermutedDimsArray{<:Any,<:Any,I1,I2}}) where {I1,I2} (map(static, I1), map(static, I2)) end # Base will sometimes demote statically known slices in `SubArray` to `OneTo{Int}` so we # provide the parent mapping to check for static size info @inline function sub_axes_map(@nospecialize(T::Type{<:SubArray})) map(Base.Fix1(_sub_axis_map, T), map_indices_info(IndicesInfo(T))) end function _sub_axis_map(@nospecialize(T::Type{<:SubArray}), x::Tuple{StaticInt{index},Any,Any}) where {index} if fieldtype(fieldtype(T, :indices), index) <: Base.Slice{OneTo{Int}} sz = known_size(parent_type(T), getfield(x, 2)) return sz === nothing ? StaticInt(index) : StaticInt(1):StaticInt(sz) else return StaticInt(index) end end function map_indices_info(@nospecialize info::IndicesInfo) pdims = parentdims(info) cdims = childdims(info) ntuple(i -> (static(i), static(getfield(pdims, i)), static(getfield(cdims, i))), static_length(pdims)) end function sub_dimnames_map(dnames::Tuple, imap::Tuple) flatten_tuples(map(Base.Fix1(_to_dimname, dnames), imap)) end @inline function _to_dimname(dnames::Tuple, x::Tuple{StaticInt,PD,CD}) where {PD,CD} if CD <: StaticInt{0} return () elseif CD <: Tuple return ntuple(Compat.Returns(static(:_)), StaticInt(known_length(CD))) elseif PD <: StaticInt{0} || PD <: Tuple return static(:_) else return getfield(dnames, known(PD)) end end """ from_parent_dims(::Type{T}) -> Tuple{Vararg{Union{StaticInt,Tuple{Vararg{StaticInt}}}}} Returns the mapping from parent dimensions to child dimensions. !!! Warning This method is still experimental and may change without notice. """ from_parent_dims(@nospecialize x) = from_parent_dims(typeof(x)) from_parent_dims(@nospecialize T::Type{<:PermutedDimsArray}) = getfield(_permdims(T), 2) from_parent_dims(@nospecialize T::Type{<:MatAdjTrans}) = (StaticInt(2), StaticInt(1)) @inline function from_parent_dims(@nospecialize T::Type{<:SubArray}) from_parent_dims(IndicesInfo{ndims(parent_type(T))}(fieldtype(T, :indices))) end # TODO do I need to flatten_tuples here? function from_parent_dims(@nospecialize(info::IndicesInfo)) pdims = parentdims(info) cdims = childdims(info) ntuple(static_length(cdims)) do i pdim_i = getfield(pdims, i) cdim_i = static(getfield(cdims, i)) pdim_i isa Int ? cdim_i : ntuple(Compat.Returns(cdim_i), static_length(pdim_i)) end end """ has_dimnames(::Type{T}) -> Bool Returns `true` if `x` has on or more named dimensions. If all dimensions correspond to `:_`, then `false` is returned. """ @inline has_dimnames(x) = static(known_dimnames(x) !== ntuple(Compat.Returns(:_), Val(ndims(x)))) """ known_dimnames(::Type{T}) -> Tuple{Vararg{Union{Symbol,Nothing}}} known_dimnames(::Type{T}, dim::Union{Int,StaticInt}) -> Union{Symbol,Nothing} Return the names of the dimensions for `x`. `:_` is used to indicate a dimension does not have a name. """ @inline known_dimnames(x, dim) = _known_dimname(known_dimnames(x), IntType(dim)) known_dimnames(x) = known_dimnames(typeof(x)) function known_dimnames(@nospecialize T::Type{<:VecAdjTrans}) (:_, getfield(known_dimnames(parent_type(T)), 1)) end function known_dimnames(@nospecialize T::Type{<:Union{MatAdjTrans,PermutedDimsArray}}) map(GetIndex{false}(known_dimnames(parent_type(T))), to_parent_dims(T)) end function known_dimnames(@nospecialize T::Type{<:SubArray}) dynamic(sub_dimnames_map(known_dimnames(parent_type(T)), map_indices_info(IndicesInfo(T)))) end function known_dimnames(::Type{<:ReinterpretArray{T,N,S,A,IsReshaped}}) where {T,N,S,A,IsReshaped} pnames = known_dimnames(A) if IsReshaped if sizeof(S) === sizeof(T) return pnames elseif sizeof(S) > sizeof(T) return (:_, pnames...) else return tail(pnames) end else return pnames end end @inline function known_dimnames(@nospecialize T::Type{<:Base.ReshapedArray}) if ndims(T) === ndims(parent_type(T)) return known_dimnames(parent_type(T)) elseif ndims(T) > ndims(parent_type(T)) return flatten_tuples((known_dimnames(parent_type(T)), ntuple(Compat.Returns(:_), StaticInt(ndims(T) - ndims(parent_type(T)))))) else return ntuple(Compat.Returns(:_), StaticInt(ndims(T))) end end @inline function known_dimnames(::Type{T}) where {T} if is_forwarding_wrapper(T) return known_dimnames(parent_type(T)) else return _unknown_dimnames(Base.IteratorSize(T)) end end _unknown_dimnames(::Base.HasShape{N}) where {N} = ntuple(Compat.Returns(:_), StaticInt(N)) _unknown_dimnames(::Any) = (:_,) @inline function _known_dimname(x::Tuple{Vararg{Any,N}}, dim::IntType) where {N} # we cannot have `@boundscheck`, else this will depend on bounds checking being enabled (dim > N || dim < 1) && return :_ return @inbounds(x[dim]) end @inline _inbounds_known_dimname(x, dim) = @inbounds(_known_dimname(x, dim)) """ dimnames(x) -> Tuple{Vararg{Union{Symbol,StaticSymbol}}} dimnames(x, dim::Union{Int,StaticInt}) -> Union{Symbol,StaticSymbol} Return the names of the dimensions for `x`. `:_` is used to indicate a dimension does not have a name. """ @inline dimnames(x, dim) = _dimname(dimnames(x), IntType(dim)) @inline function dimnames(x::Union{PermutedDimsArray,MatAdjTrans}) map(GetIndex{false}(dimnames(parent(x))), to_parent_dims(x)) end function dimnames(x::SubArray) sub_dimnames_map(dimnames(parent(x)), map_indices_info(IndicesInfo(typeof(x)))) end dimnames(x::VecAdjTrans) = (static(:_), getfield(dimnames(parent(x)), 1)) @inline function dimnames(x::ReinterpretArray{T,N,S,A,IsReshaped}) where {T,N,S,A,IsReshaped} pnames = dimnames(parent(x)) if IsReshaped if sizeof(S) === sizeof(T) return pnames elseif sizeof(S) > sizeof(T) return flatten_tuples((static(:_), pnames)) else return tail(pnames) end else return pnames end end @inline function dimnames(x::Base.ReshapedArray) p = parent(x) if ndims(x) === ndims(p) return dimnames(p) elseif ndims(x) > ndims(p) return flatten_tuples((dimnames(p), ntuple(Compat.Returns(static(:_)), StaticInt(ndims(x) - ndims(p))))) else return ntuple(Compat.Returns(static(:_)), StaticInt(ndims(x))) end end @inline function dimnames(x::X) where {X} if is_forwarding_wrapper(X) return dimnames(parent(x)) else return ntuple(Compat.Returns(static(:_)), StaticInt(ndims(x))) end end @inline function _dimname(x::Tuple{Vararg{Any,N}}, dim::IntType) where {N} # we cannot have `@boundscheck`, else this will depend on bounds checking being enabled # for calls such as `dimnames(view(x, :, 1, :))` (dim > N || dim < 1) && return static(:_) return @inbounds(x[dim]) end @inline _inbounds_dimname(x, dim) = @inbounds(_dimname(x, dim)) """ to_dims(x, dim) -> Union{Int,StaticInt} This returns the dimension(s) of `x` corresponding to `dim`. """ to_dims(x, dim::Colon) = dim to_dims(x, @nospecialize(dim::IntType)) = dim to_dims(x, dim::Integer) = Int(dim) to_dims(x, dim::Union{StaticSymbol,Symbol}) = _to_dim(dimnames(x), dim) function to_dims(x, dims::Tuple{Vararg{Any,N}}) where {N} eachop(_to_dims, ntuple(static, StaticInt(N)), dimnames(x), dims) end @inline _to_dims(x::Tuple, d::Tuple, n::StaticInt{N}) where {N} = _to_dim(x, getfield(d, N)) @inline function _to_dim(x::Tuple, d::Union{Symbol,StaticSymbol}) i = find_first_eq(d, x) i === nothing && throw(DimensionMismatch("dimension name $(d) not found")) return i end #= order_named_inds(names, namedtuple) order_named_inds(names, subnames, inds) Returns the tuple of index values for an array with `names`, when indexed by keywords. Any dimensions not fixed are given as `:`, to make a slice. An error is thrown if any keywords are used which do not occur in `nda`'s names. 1. parse into static dimnension names and key words. 2. find each dimnames in key words 3. if nothing is found use Colon() 4. if (ndims - ncolon) === nkwargs then all were found, else error =# @generated function find_all_dimnames(x::Tuple{Vararg{Any,ND}}, nd::Tuple{Vararg{Any,NI}}, inds::Tuple, default) where {ND,NI} if NI === 0 return :(()) else out = Expr(:block, Expr(:(=), :names_found, 0)) t = Expr(:tuple) for i in 1:ND index_i = Symbol(:index_, i) val_i = Symbol(:val_, i) push!(t.args, val_i) push!(out.args, quote $index_i = find_first_eq(getfield(x, $i), nd) if $index_i === nothing $val_i = default else $val_i = @inbounds(inds[$index_i]) names_found += 1 end end) end return quote $out @boundscheck names_found === $NI || error("Not all keywords matched dimension names.") return $t end end end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
19312
""" static_to_indices(A, I::Tuple) -> Tuple Converts the tuple of indexing arguments, `I`, into an appropriate form for indexing into `A`. Typically, each index should be an `Int`, `StaticInt`, a collection with values of `Int`, or a collection with values of `CartesianIndex` This is accomplished in three steps after the initial call to `static_to_indices`: # Extended help This implementation differs from that of `Base.to_indices` in the following ways: * `static_to_indices(A, I)` never results in recursive processing of `I` through `static_to_indices(A, static_axes(A), I)`. This is avoided through the use of an internal `@generated` method that aligns calls of `static_to_indices` and `to_index` based on the return values of `ndims_index`. This is beneficial because the compiler currently does not optimize away the increased time spent recursing through each additional argument that needs converting. For example: ```julia julia> x = rand(4,4,4,4,4,4,4,4,4,4); julia> inds1 = (1, 2, 1, 2, 1, 2, 1, 2, 1, 2); julia> inds2 = (1, CartesianIndex(1, 2), 1, CartesianIndex(1, 2), 1, CartesianIndex(1, 2), 1); julia> inds3 = (fill(true, 4, 4), 2, fill(true, 4, 4), 2, 1, fill(true, 4, 4), 1); julia> @btime Base.to_indices(\$x, \$inds2) 1.105 μs (12 allocations: 672 bytes) (1, 1, 2, 1, 1, 2, 1, 1, 2, 1) julia> @btime static_to_indices(\$x, \$inds2) 0.041 ns (0 allocations: 0 bytes) (1, 1, 2, 1, 1, 2, 1, 1, 2, 1) julia> @btime Base.to_indices(\$x, \$inds3); 340.629 ns (14 allocations: 768 bytes) julia> @btime static_to_indices(\$x, \$inds3); 11.614 ns (0 allocations: 0 bytes) ``` * Recursing through `static_to_indices(A, axes, I::Tuple{I1,Vararg{Any}})` is intended to provide context for processing `I1`. However, this doesn't tell use how many dimensions are consumed by what is in `Vararg{Any}`. Using `ndims_index` to directly align the axes of `A` with each value in `I` ensures that a `CartesiaIndex{3}` at the tail of `I` isn't incorrectly assumed to only consume one dimension. * `Base.to_indices` may fail to infer the returned type. This is the case for `inds2` and `inds3` in the first bullet on Julia 1.6.4. * Specializing by dispatch through method definitions like this: `static_to_indices(::ArrayType, ::Tuple{AxisType,Vararg{Any}}, ::Tuple{::IndexType,Vararg{Any}})` require an excessive number of hand written methods to avoid ambiguities. Furthermore, if `AxisType` is wrapping another axis that should have unique behavior, then unique parametric types need to also be explicitly defined. * `to_index(static_axes(A, dim), index)` is called, as opposed to `Base.to_index(A, index)`. The `IndexStyle` of the resulting axis is used to allow indirect dispatch on nested axis types within `to_index`. """ static_to_indices(A, ::Tuple{}) = () @inline function static_to_indices(a::A, inds::I) where {A,I} flatten_tuples(map(IndexedMappedArray(a), inds, getfield(_init_dimsmap(IndicesInfo{ndims(A)}(I)), 1))) end struct IndexedMappedArray{A} a::A end @inline (ima::IndexedMappedArray{A})(idx::I, ::StaticInt{0}) where {A,I} = to_index(StaticInt(1):StaticInt(1), idx) @inline (ima::IndexedMappedArray{A})(idx::I, ::Colon) where {A,I} = to_index(lazy_axes(ima.a, :), idx) @inline (ima::IndexedMappedArray{A})(idx::I, d::StaticInt{D}) where {A,I,D} = to_index(lazy_axes(ima.a, d), idx) @inline function (ima::IndexedMappedArray{A})(idx::AbstractArray{Bool}, dims::Tuple) where {A} if (last(dims) == ndims(A)) && (IndexStyle(A) isa IndexLinear) return LogicalIndex{Int}(idx) else return LogicalIndex(idx) end end @inline (ima::IndexedMappedArray{A})(idx::CartesianIndex, ::Tuple) where {A} = getfield(idx, 1) @inline function (ima::IndexedMappedArray{A})(idx::I, dims::Tuple) where {A,I} to_index(CartesianIndices(lazy_axes(ima.a, dims)), idx) end """ to_index([::IndexStyle, ]axis, arg) -> index Convert the argument `arg` that was originally passed to `static_getindex` for the dimension corresponding to `axis` into a form for native indexing (`Int`, Vector{Int}, etc.). `to_index` supports passing a function as an index. This function-index is transformed into a proper index. ```julia julia> using ArrayInterface, Static julia> to_index(static(1):static(10), 5) 5 julia> to_index(static(1):static(10), <(5)) static(1):4 julia> to_index(static(1):static(10), <=(5)) static(1):5 julia> to_index(static(1):static(10), >(5)) 6:static(10) julia> to_index(static(1):static(10), >=(5)) 5:static(10) ``` Use of a function-index helps ensure that indices are inbounds ```julia julia> to_index(static(1):static(10), <(12)) static(1):10 julia> to_index(static(1):static(10), >(-1)) 1:static(10) ``` New axis types with unique behavior should use an `IndexStyle` trait: ```julia to_index(axis::MyAxisType, arg) = to_index(IndexStyle(axis), axis, arg) to_index(::MyIndexStyle, axis, arg) = ... ``` """ to_index(x, i::Slice) = i to_index(x, ::Colon) = indices(x) to_index(::LinearIndices{0,Tuple{}}, ::Colon) = Slice(static(1):static(1)) to_index(::CartesianIndices{0,Tuple{}}, ::Colon) = Slice(static(1):static(1)) # logical indexing to_index(x, i::AbstractArray{Bool}) = LogicalIndex(i) to_index(::LinearIndices, i::AbstractArray{Bool}) = LogicalIndex{Int}(i) # cartesian indexing @inline to_index(x, i::CartesianIndices{0}) = i @inline to_index(x, i::CartesianIndices) = getfield(i, :indices) @inline to_index(x, i::CartesianIndex) = getfield(i, 1) @inline to_index(x, i::NDIndex) = getfield(i, 1) @inline to_index(x, i::AbstractArray{<:AbstractCartesianIndex}) = i @inline function to_index(x, i::Base.Fix2{<:Union{typeof(<),typeof(isless)},<:Union{Base.BitInteger,StaticInt}}) static_first(x):min(_sub1(IntType(i.x)), static_last(x)) end @inline function to_index(x, i::Base.Fix2{typeof(<=),<:Union{Base.BitInteger,StaticInt}}) static_first(x):min(IntType(i.x), static_last(x)) end @inline function to_index(x, i::Base.Fix2{typeof(>=),<:Union{Base.BitInteger,StaticInt}}) max(IntType(i.x), static_first(x)):static_last(x) end @inline function to_index(x, i::Base.Fix2{typeof(>),<:Union{Base.BitInteger,StaticInt}}) max(_add1(IntType(i.x)), static_first(x)):static_last(x) end # integer indexing to_index(x, i::AbstractArray{<:Integer}) = i to_index(x, @nospecialize(i::StaticInt)) = i to_index(x, i::Integer) = Int(i) @inline to_index(x, i) = to_index(IndexStyle(x), x, i) function to_index(S::IndexStyle, x, i) throw(ArgumentError( "invalid index: $S does not support indices of type $(typeof(i)) for instances of type $(typeof(x))." )) end """ unsafe_reconstruct(A, data; kwargs...) Reconstruct `A` given the values in `data`. New methods using `unsafe_reconstruct` should only dispatch on `A`. """ function unsafe_reconstruct(axis::OneTo, data; kwargs...) if axis === data return axis else return OneTo(data) end end function unsafe_reconstruct(axis::UnitRange, data; kwargs...) if axis === data return axis else return UnitRange(first(data), last(data)) end end function unsafe_reconstruct(axis::OptionallyStaticUnitRange, data; kwargs...) if axis === data return axis else return OptionallyStaticUnitRange(static_first(data), static_last(data)) end end function unsafe_reconstruct(A::AbstractUnitRange, data; kwargs...) return static_first(data):static_last(data) end """ to_axes(A, inds) -> Tuple Construct new axes given the corresponding `inds` constructed after `to_indices(A, args) -> inds`. This method iterates through each pair of axes and indices calling [`to_axis`](@ref). """ @inline function to_axes(A, inds::Tuple) if ndims(A) === 1 return (to_axis(static_axes(A, 1), first(inds)),) elseif Base.length(inds) === 1 return (to_axis(eachindex(IndexLinear(), A), first(inds)),) else return to_axes(A, static_axes(A), inds) end end # drop this dimension to_axes(A, a::Tuple, i::Tuple{<:IntType,Vararg{Any}}) = to_axes(A, _maybe_tail(a), tail(i)) to_axes(A, a::Tuple, i::Tuple{I,Vararg{Any}}) where {I} = _to_axes(StaticInt(ndims_index(I)), A, a, i) function _to_axes(::StaticInt{1}, A, axs::Tuple, inds::Tuple) return (to_axis(_maybe_first(axs), first(inds)), to_axes(A, _maybe_tail(axs), tail(inds))...) end @propagate_inbounds function _to_axes(::StaticInt{N}, A, axs::Tuple, inds::Tuple) where {N} axes_front, axes_tail = Base.IteratorsMD.split(axs, Val(N)) if IndexStyle(A) === IndexLinear() axis = to_axis(LinearIndices(axes_front), getfield(inds, 1)) else axis = to_axis(CartesianIndices(axes_front), getfield(inds, 1)) end return (axis, to_axes(A, axes_tail, tail(inds))...) end to_axes(A, ::Tuple{Ax,Vararg{Any}}, ::Tuple{}) where {Ax} = () to_axes(A, ::Tuple{}, ::Tuple{}) = () _maybe_first(::Tuple{}) = static(1):static(1) _maybe_first(t::Tuple) = first(t) _maybe_tail(::Tuple{}) = () _maybe_tail(t::Tuple) = tail(t) """ to_axis(old_axis, index) -> new_axis Construct an `new_axis` for a newly constructed array that corresponds to the previously executed `to_index(old_axis, arg) -> index`. `to_axis` assumes that `index` has already been confirmed to be in bounds. The underlying indices of `new_axis` begins at one and extends the length of `index` (i.e., one-based indexing). """ @inline function to_axis(axis, inds) if !can_change_size(axis) && (known_length(inds) !== nothing && known_length(axis) === known_length(inds)) return axis else return to_axis(IndexStyle(axis), axis, inds) end end # don't need to check size b/c slice means it's the entire axis @inline function to_axis(axis, inds::Slice) if can_change_size(axis) return copy(axis) else return axis end end to_axis(S::IndexLinear, axis, inds) = StaticInt(1):static_length(inds) """ static_getindex(A, args...) Retrieve the value(s) stored at the given key or index within a collection. Creating another instance of `static_getindex` should only be done by overloading `A`. Changing indexing based on a given argument from `args` should be done through, [`to_index`](@ref), or [`to_axis`](@ref). """ function static_getindex(A, args...) inds = static_to_indices(A, args) @boundscheck checkbounds(A, inds...) unsafe_getindex(A, inds...) end @propagate_inbounds function static_getindex(A; kwargs...) inds = static_to_indices(A, find_all_dimnames(dimnames(A), static(keys(kwargs)), Tuple(values(kwargs)), :)) @boundscheck checkbounds(A, inds...) unsafe_getindex(A, inds...) end @propagate_inbounds static_getindex(x::Tuple, i::Int) = getfield(x, i) @propagate_inbounds static_getindex(x::Tuple, ::StaticInt{i}) where {i} = getfield(x, i) ## unsafe_getindex ## function unsafe_getindex(a::A) where {A} is_forwarding_wrapper(A) || throw(MethodError(unsafe_getindex, (A,))) unsafe_getindex(parent(a)) end # TODO Need to manage index transformations between nested layers of arrays function unsafe_getindex(a::A, i::IntType) where {A} if IndexStyle(A) === IndexLinear() is_forwarding_wrapper(A) || throw(MethodError(unsafe_getindex, (A, i))) return unsafe_getindex(parent(a), i) else return unsafe_getindex(a, _to_cartesian(a, i)...) end end function unsafe_getindex(a::A, i::IntType, ii::Vararg{IntType}) where {A} if IndexStyle(A) === IndexLinear() return unsafe_getindex(a, _to_linear(a, (i, ii...))) else is_forwarding_wrapper(A) || throw(MethodError(unsafe_getindex, (A, i))) return unsafe_getindex(parent(a), i, ii...) end end unsafe_getindex(a, i::Vararg{Any}) = unsafe_get_collection(a, i) unsafe_getindex(A::Array) = Base.arrayref(false, A, 1) unsafe_getindex(A::Array, i::IntType) = Base.arrayref(false, A, Int(i)) @inline function unsafe_getindex(A::Array, i::IntType, ii::Vararg{IntType}) unsafe_getindex(A, _to_linear(A, (i, ii...))) end unsafe_getindex(A::LinearIndices, i::IntType) = Int(i) unsafe_getindex(A::CartesianIndices{N}, ii::Vararg{IntType,N}) where {N} = CartesianIndex(ii...) unsafe_getindex(A::CartesianIndices, ii::Vararg{IntType}) = unsafe_getindex(A, Base.front(ii)...) unsafe_getindex(A::CartesianIndices, i::IntType) = @inbounds(A[i]) unsafe_getindex(A::ReshapedArray, i::IntType) = @inbounds(parent(A)[i]) function unsafe_getindex(A::ReshapedArray, i::IntType, ii::Vararg{IntType}) @inbounds(parent(A)[_to_linear(A, (i, ii...))]) end unsafe_getindex(A::SubArray, i::IntType) = @inbounds(A[i]) unsafe_getindex(A::SubArray, i::IntType, ii::Vararg{IntType}) = @inbounds(A[i, ii...]) # This is based on Base._unsafe_getindex from https://github.com/JuliaLang/julia/blob/c5ede45829bf8eb09f2145bfd6f089459d77b2b1/base/multidimensional.jl#L755. #= unsafe_get_collection(A, inds) Returns a collection of `A` given `inds`. `inds` is assumed to have been bounds-checked. =# function unsafe_get_collection(A, inds) axs = to_axes(A, inds) dest = similar(A, axs) if map(static_length, static_axes(dest)) == map(static_length, axs) Base._unsafe_getindex!(dest, A, inds...) else Base.throw_checksize_error(dest, axs) end return dest end _ints2range(x::IntType) = x:x _ints2range(x::AbstractRange) = x # apply _ints2range to front N elements _ints2range_front(::Val{N}, ind, inds...) where {N} = (_ints2range(ind), _ints2range_front(Val(N - 1), inds...)...) _ints2range_front(::Val{0}, ind, inds...) = () _ints2range_front(::Val{0}) = () # get output shape with given indices _output_shape(::IntType, inds...) = _output_shape(inds...) _output_shape(ind::AbstractRange, inds...) = (Base.length(ind), _output_shape(inds...)...) _output_shape(::IntType) = () _output_shape(x::AbstractRange) = (Base.length(x),) @inline function unsafe_get_collection(A::CartesianIndices{N}, inds) where {N} if (Base.length(inds) === 1 && N > 1) || stride_preserving_index(typeof(inds)) === False() return Base._getindex(IndexStyle(A), A, inds...) else return reshape( CartesianIndices(_ints2range_front(Val(N), inds...)), _output_shape(inds...) ) end end _known_first_isone(ind) = known_first(ind) !== nothing && isone(known_first(ind)) @inline function unsafe_get_collection(A::LinearIndices{N}, inds) where {N} if Base.length(inds) === 1 && ndims_index(typeof(first(inds))) === 1 return @inbounds(eachindex(A)[first(inds)]) elseif stride_preserving_index(typeof(inds)) === True() && reduce_tup(&, map(_known_first_isone, inds)) # create a LinearIndices when first(ind) != 1 is imposable return reshape( LinearIndices(_ints2range_front(Val(N), inds...)), _output_shape(inds...) ) else return Base._getindex(IndexStyle(A), A, inds...) end end """ setindex!(A, args...) Store the given values at the given key or index within a collection. """ @propagate_inbounds function setindex!(A, val, args...) can_setindex(A) || error("Instance of type $(typeof(A)) are not mutable and cannot change elements after construction.") inds = static_to_indices(A, args) @boundscheck checkbounds(A, inds...) unsafe_setindex!(A, val, inds...) end @propagate_inbounds function setindex!(A, val; kwargs...) can_setindex(A) || error("Instance of type $(typeof(A)) are not mutable and cannot change elements after construction.") inds = static_to_indices(A, find_all_dimnames(dimnames(A), static(keys(kwargs)), Tuple(values(kwargs)), :)) @boundscheck checkbounds(A, inds...) unsafe_setindex!(A, val, inds...) end ## unsafe_setindex! ## function unsafe_setindex!(a::A, v) where {A} is_forwarding_wrapper(A) || throw(MethodError(unsafe_setindex!, (A, v))) return unsafe_setindex!(parent(a), v) end # TODO Need to manage index transformations between nested layers of arrays function unsafe_setindex!(a::A, v, i::IntType) where {A} if IndexStyle(A) === IndexLinear() is_forwarding_wrapper(A) || throw(MethodError(unsafe_setindex!, (A, v, i))) return unsafe_setindex!(parent(a), v, i) else return unsafe_setindex!(a, v, _to_cartesian(a, i)...) end end function unsafe_setindex!(a::A, v, i::IntType, ii::Vararg{IntType}) where {A} if IndexStyle(A) === IndexLinear() return unsafe_setindex!(a, v, _to_linear(a, (i, ii...))) else is_forwarding_wrapper(A) || throw(MethodError(unsafe_setindex!, (A, v, i, ii...))) return unsafe_setindex!(parent(a), v, i, ii...) end end function unsafe_setindex!(A::Array{T}, v) where {T} Base.arrayset(false, A, convert(T, v)::T, 1) end function unsafe_setindex!(A::Array{T}, v, i::IntType) where {T} return Base.arrayset(false, A, convert(T, v)::T, Int(i)) end unsafe_setindex!(a, v, i::Vararg{Any}) = unsafe_set_collection!(a, v, i) # This is based on Base._unsafe_setindex!. #= unsafe_set_collection!(A, val, inds) Sets `inds` of `A` to `val`. `inds` is assumed to have been bounds-checked. =# unsafe_set_collection!(A, v, i) = Base._unsafe_setindex!(IndexStyle(A), A, v, i...) ## Index Information """ known_first(::Type{T}) -> Union{Int,Nothing} If `first` of an instance of type `T` is known at compile time, return it. Otherwise, return `nothing`. ```julia julia> known_first(typeof(1:4)) nothing julia> known_first(typeof(Base.OneTo(4))) 1 ``` """ known_first(x) = known_first(typeof(x)) known_first(T::Type) = is_forwarding_wrapper(T) ? known_first(parent_type(T)) : nothing known_first(::Type{<:Base.OneTo}) = 1 known_first(@nospecialize T::Type{<:LinearIndices}) = 1 known_first(@nospecialize T::Type{<:Base.IdentityUnitRange}) = known_first(parent_type(T)) function known_first(::Type{<:CartesianIndices{N, R}}) where {N, R} _cartesian_index(ntuple(i -> known_first(R.parameters[i]), Val(N))) end _cartesian_index(i::Tuple{Vararg{Int}}) = CartesianIndex(i) _cartesian_index(::Any) = nothing """ known_last(::Type{T}) -> Union{Int,Nothing} If `last` of an instance of type `T` is known at compile time, return it. Otherwise, return `nothing`. ```julia julia> known_last(typeof(1:4)) nothing julia> known_first(typeof(static(1):static(4))) 4 ``` """ known_last(x) = known_last(typeof(x)) known_last(T::Type) = is_forwarding_wrapper(T) ? known_last(parent_type(T)) : nothing function known_last(::Type{<:CartesianIndices{N, R}}) where {N, R} _cartesian_index(ntuple(i -> known_last(R.parameters[i]), Val(N))) end """ known_step(::Type{T}) -> Union{Int,Nothing} If `step` of an instance of type `T` is known at compile time, return it. Otherwise, return `nothing`. ```julia julia> known_step(typeof(1:2:8)) nothing julia> known_step(typeof(1:4)) 1 ``` """ known_step(x) = known_step(typeof(x)) known_step(T::Type) = is_forwarding_wrapper(T) ? known_step(parent_type(T)) : nothing known_step(@nospecialize T::Type{<:AbstractUnitRange}) = 1 """ is_splat_index(::Type{T}) -> Bool Returns `static(true)` if `T` is a type that splats across multiple dimensions. """ is_splat_index(T::Type) = false is_splat_index(@nospecialize(x)) = is_splat_index(typeof(x)) _add1(@nospecialize x) = x + oneunit(x) _sub1(@nospecialize x) = x - oneunit(x)
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
2172
known_first(::Type{<:OptionallyStaticUnitRange{StaticInt{F}}}) where {F} = F::Int known_first(::Type{<:OptionallyStaticStepRange{StaticInt{F}}}) where {F} = F::Int known_step(::Type{<:OptionallyStaticStepRange{<:Any,StaticInt{S}}}) where {S} = S::Int known_last(::Type{<:OptionallyStaticUnitRange{<:Any,StaticInt{L}}}) where {L} = L::Int known_last(::Type{<:OptionallyStaticStepRange{<:Any,<:Any,StaticInt{L}}}) where {L} = L::Int """ indices(x, dim) -> AbstractUnitRange{Int} Given an array `x`, this returns the indices along dimension `dim`. """ @inline indices(x, d) = indices(static_axes(x, d)) """ indices(x) -> AbstractUnitRange{Int} Returns valid indices for the entire length of `x`. """ @inline function indices(x) inds = eachindex(x) if inds isa AbstractUnitRange && eltype(inds) <: Integer return Base.Slice(OptionallyStaticUnitRange(inds)) else return inds end end @inline indices(x::AbstractUnitRange{<:Integer}) = Base.Slice(OptionallyStaticUnitRange(x)) """ indices(x::Tuple) -> AbstractUnitRange{Int} Returns valid indices for the entire length of each array in `x`. """ @propagate_inbounds function indices(x::Tuple) inds = map(eachindex, x) return reduce_tup(static_promote, inds) end """ indices(x::Tuple, dim) -> AbstractUnitRange{Int} Returns valid indices for each array in `x` along dimension `dim` """ @propagate_inbounds function indices(x::Tuple, dim) inds = map(Base.Fix2(indices, dim), x) return reduce_tup(static_promote, inds) end """ indices(x::Tuple, dim::Tuple) -> AbstractUnitRange{Int} Returns valid indices given a tuple of arrays `x` and tuple of dimesions for each respective array (`dim`). """ @propagate_inbounds function indices(x::Tuple, dim::Tuple) inds = map(indices, x, dim) return reduce_tup(static_promote, inds) end """ indices(x, dim::Tuple) -> Tuple{Vararg{AbstractUnitRange{Int}}} Returns valid indices for array `x` along each dimension specified in `dim`. """ @inline indices(x, dims::Tuple) = _indices(x, dims) _indices(x, dims::Tuple) = (indices(x, first(dims)), _indices(x, tail(dims))...) _indices(x, ::Tuple{}) = ()
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
9245
""" static_size(A) -> Tuple static_size(A, dim) -> Union{Int,StaticInt} Returns the size of each dimension of `A` or along dimension `dim` of `A`. If the size of any axes are known at compile time, these should be returned as `Static` numbers. Otherwise, `static_size(A)` is identical to `Base.size(A)` ```julia julia> using StaticArrays, ArrayInterface julia> A = @SMatrix rand(3,4); julia> static_size(A) (static(3), static(4)) ``` """ @inline function static_size(a::A) where {A} if is_forwarding_wrapper(A) return static_size(parent(a)) else return _maybe_size(Base.IteratorSize(A), a) end end static_size(a::Base.Broadcast.Broadcasted) = map(static_length, static_axes(a)) _maybe_size(::Base.HasShape{N}, a::A) where {N,A} = map(static_length, static_axes(a)) _maybe_size(::Base.HasLength, a::A) where {A} = (static_length(a),) @inline static_size(x::SubArray) = flatten_tuples(map(Base.Fix1(_sub_size, x), sub_axes_map(typeof(x)))) @inline _sub_size(::SubArray, ::SOneTo{S}) where {S} = StaticInt(S) _sub_size(x::SubArray, ::StaticInt{index}) where {index} = static_size(getfield(x.indices, index)) @inline static_size(B::VecAdjTrans) = (One(), static_length(parent(B))) @inline function static_size(x::Union{PermutedDimsArray,MatAdjTrans}) map(GetIndex{false}(static_size(parent(x))), to_parent_dims(x)) end function static_size(a::ReinterpretArray{T,N,S,A,IsReshaped}) where {T,N,S,A,IsReshaped} psize = static_size(parent(a)) if IsReshaped if sizeof(S) === sizeof(T) return psize elseif sizeof(S) > sizeof(T) return flatten_tuples((static(div(sizeof(S), sizeof(T))), psize)) else return tail(psize) end else return flatten_tuples((div(first(psize) * static(sizeof(S)), static(sizeof(T))), tail(psize))) end end static_size(A::ReshapedArray) = Base.size(A) static_size(A::AbstractRange) = (static_length(A),) static_size(x::Base.Generator) = static_size(getfield(x, :iter)) static_size(x::Iterators.Reverse) = static_size(getfield(x, :itr)) static_size(x::Iterators.Enumerate) = static_size(getfield(x, :itr)) static_size(x::Iterators.Accumulate) = static_size(getfield(x, :itr)) static_size(x::Iterators.Pairs) = static_size(getfield(x, :itr)) # TODO couldn't this just be map(length, getfield(x, :iterators)) @inline function static_size(x::Iterators.ProductIterator) eachop(_sub_size, ntuple(static, StaticInt(ndims(x))), getfield(x, :iterators)) end _sub_size(x::Tuple, ::StaticInt{dim}) where {dim} = static_length(getfield(x, dim)) static_size(a, dim) = static_size(a, to_dims(a, dim)) static_size(a::Array, dim::IntType) = Base.arraysize(a, convert(Int, dim)) function static_size(a::A, dim::IntType) where {A} if is_forwarding_wrapper(A) return static_size(parent(a), dim) else len = known_size(A, dim) if len === nothing return Int(static_length(static_axes(a, dim))) else return StaticInt(len) end end end static_size(x::Iterators.Zip) = Static.reduce_tup(promote_shape, map(static_size, getfield(x, :is))) """ known_size(::Type{T}) -> Tuple known_size(::Type{T}, dim) -> Union{Int,Nothing} Returns the size of each dimension of `A` or along dimension `dim` of `A` that is known at compile time. If a dimension does not have a known size along a dimension then `nothing` is returned in its position. """ known_size(x) = known_size(typeof(x)) @inline known_size(@nospecialize T::Type{<:Number}) = () @inline known_size(@nospecialize T::Type{<:VecAdjTrans}) = (1, known_length(parent_type(T))) @inline function known_size(@nospecialize T::Type{<:Union{PermutedDimsArray,MatAdjTrans}}) map(GetIndex{false}(known_size(parent_type(T))), to_parent_dims(T)) end function known_size(@nospecialize T::Type{<:Diagonal}) s = known_length(parent_type(T)) (s, s) end known_size(@nospecialize T::Type{<:Union{Symmetric,Hermitian}}) = known_size(parent_type(T)) @inline function known_size(::Type{<:Base.ReinterpretArray{T,N,S,A,IsReshaped}}) where {T,N,S,A,IsReshaped} psize = known_size(A) if IsReshaped if sizeof(S) > sizeof(T) return (div(sizeof(S), sizeof(T)), psize...) elseif sizeof(S) < sizeof(T) return Base.tail(psize) else return psize end else if Base.issingletontype(T) || first(psize) === nothing return psize else return (div(first(psize) * sizeof(S), sizeof(T)), Base.tail(psize)...) end end end @inline function known_size(::Type{T}) where {T} if is_forwarding_wrapper(T) return known_size(parent_type(T)) else return _maybe_known_size(Base.IteratorSize(T), T) end end function _maybe_known_size(::Base.HasShape{N}, ::Type{T}) where {N,T} eachop(_known_size, ntuple(static, StaticInt(N)), axes_types(T)) end _maybe_known_size(::Base.IteratorSize, ::Type{T}) where {T} = (known_length(T),) known_size(::Type{<:Base.IdentityUnitRange{I}}) where {I} = known_size(I) known_size(::Type{<:Base.Generator{I}}) where {I} = known_size(I) known_size(::Type{<:Iterators.Reverse{I}}) where {I} = known_size(I) known_size(::Type{<:Iterators.Enumerate{I}}) where {I} = known_size(I) known_size(::Type{<:Iterators.Accumulate{<:Any,I}}) where {I} = known_size(I) known_size(::Type{<:Iterators.Pairs{<:Any,<:Any,I}}) where {I} = known_size(I) @inline function known_size(::Type{<:Iterators.ProductIterator{T}}) where {T} ntuple(i -> known_length(T.parameters[i]), Val(known_length(T))) end @inline function known_size(@nospecialize T::Type{<:AbstractRange}) if is_forwarding_wrapper(T) return known_size(parent_type(T)) else start = known_first(T) s = known_step(T) stop = known_last(T) if stop !== nothing && s !== nothing && start !== nothing if s > 0 return (stop < start ? 0 : div(stop - start, s) + 1,) else return (stop > start ? 0 : div(start - stop, -s) + 1,) end else return (nothing,) end end end @inline function known_size(@nospecialize T::Type{<:Union{LinearIndices,CartesianIndices}}) I = fieldtype(T, :indices) ntuple(i -> known_length(I.parameters[i]), Val(ndims(T))) end @inline function known_size(@nospecialize T::Type{<:SubArray}) flatten_tuples(map(Base.Fix1(_known_sub_size, T), sub_axes_map(T))) end _known_sub_size(@nospecialize(T::Type{<:SubArray}), ::SOneTo{S}) where {S} = S function _known_sub_size(@nospecialize(T::Type{<:SubArray}), ::StaticInt{index}) where {index} known_size(fieldtype(fieldtype(T, :indices), index)) end # 1. `Zip` doesn't check that its collections are compatible (same size) at construction, # but we assume as much b/c otherwise it will error while iterating. So we promote to the # known size if matching a `Nothing` and `Int` size. # 2. `promote_shape(::Tuple{Vararg{IntType}}, ::Tuple{Vararg{IntType}})` promotes # trailing dimensions (which must be of size 1), to `static(1)`. We want to stick to # `Nothing` and `Int` types, so we do one last pass to ensure everything is dynamic @inline function known_size(::Type{<:Iterators.Zip{T}}) where {T} dynamic(reduce_tup(Static._promote_shape, eachop(_unzip_size, ntuple(static, StaticInt(known_length(T))), T))) end _unzip_size(::Type{T}, n::StaticInt{N}) where {T,N} = known_size(field_type(T, n)) _known_size(::Type{T}, dim::StaticInt) where {T} = known_length(field_type(T, dim)) @inline known_size(x, dim) = known_size(typeof(x), dim) @inline known_size(::Type{T}, dim) where {T} = known_size(T, to_dims(T, dim)) known_size(T::Type, dim::IntType) = ndims(T) < dim ? 1 : known_size(T)[dim] """ static_length(A) -> Union{Int,StaticInt} Returns the length of `A`. If the length is known at compile time, it is returned as `Static` number. Otherwise, `static_length(A)` is identical to `Base.length(A)`. ```julia julia> using StaticArrays, ArrayInterface julia> A = @SMatrix rand(3,4); julia> static_length(A) static(12) ``` """ @inline static_length(a::UnitRange{T}) where {T} = last(a) - first(a) + oneunit(T) @inline static_length(x) = Static.maybe_static(known_length, Base.length, x) """ known_length(::Type{T}) -> Union{Int,Nothing} If `length` of an instance of type `T` is known at compile time, return it. Otherwise, return `nothing`. """ known_length(x) = known_length(typeof(x)) known_length(::Type{<:NamedTuple{L}}) where {L} = static_length(L) known_length(::Type{T}) where {T<:Slice} = known_length(parent_type(T)) known_length(::Type{<:Tuple{Vararg{Any,N}}}) where {N} = N known_length(::Type{<:Number}) = 1 known_length(::Type{<:AbstractCartesianIndex{N}}) where {N} = N known_length(::Type{T}) where {T} = _maybe_known_length(Base.IteratorSize(T), T) function known_length(::Type{<:Iterators.Flatten{I}}) where {I} _prod_or_nothing((known_length(I),known_length(eltype(I)))) end _prod_or_nothing(x::Tuple{Vararg{Int}}) = prod(x) _prod_or_nothing(_) = nothing _maybe_known_length(::Base.HasShape, ::Type{T}) where {T} = _prod_or_nothing(known_size(T)) _maybe_known_length(::Base.IteratorSize, ::Type) = nothing
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
25399
""" known_offsets(::Type{T}) -> Tuple known_offsets(::Type{T}, dim) -> Union{Int,Nothing} Returns a tuple of offset values known at compile time. If the offset of a given axis is not known at compile time `nothing` is returned its position. """ known_offsets(x, dim) = known_offsets(typeof(x), dim) known_offsets(::Type{T}, dim) where {T} = known_offsets(T, to_dims(T, dim)) known_offsets(@nospecialize T::Type{<:Number}) = () # Int has no dimensions @inline function known_offsets(@nospecialize T::Type{<:SubArray}) flatten_tuples(map_tuple_type(known_offsets, fieldtype(T, :indices))) end function known_offsets(::Type{T}, dim::IntType) where {T} if ndims(T) < dim return 1 else return known_offsets(T)[dim] end end known_offsets(x) = known_offsets(typeof(x)) function known_offsets(::Type{T}) where {T} eachop(_known_offsets, ntuple(static, StaticInt(ndims(T))), axes_types(T)) end _known_offsets(::Type{T}, dim::StaticInt) where {T} = known_first(field_type(T, dim)) known_offsets(::Type{<:StrideIndex{N,R,C,S,O}}) where {N,R,C,S,O} = known(O) """ offsets(A) -> Tuple offsets(A, dim) -> Union{Int,StaticInt} Returns offsets of indices with respect to 0. If values are known at compile time, it should return them as `Static` numbers. For example, if `A isa Base.Matrix`, `offsets(A) === (StaticInt(1), StaticInt(1))`. """ @inline offsets(x, i) = static_first(indices(x, i)) offsets(::Tuple) = (One(),) offsets(x::StrideIndex) = getfield(x, :offsets) @inline offsets(x::SubArray) = flatten_tuples(map(offsets, x.indices)) offsets(x) = eachop(_offsets, ntuple(static, StaticInt(ndims(x))), x) function _offsets(x::X, dim::StaticInt{D}) where {X,D} start = known_first(axes_types(X, dim)) if start === nothing return first(static_axes(x, dim)) else return static(start) end end # we can't generate an axis for `StrideIndex` so this is performed manually here @inline offsets(x::StrideIndex, dim::Int) = getfield(offsets(x), dim) @inline offsets(x::StrideIndex, ::StaticInt{dim}) where {dim} = getfield(offsets(x), dim) """ known_offset1(::Type{T}) -> Union{Int,Nothing} Returns the linear offset of array `x` if known at compile time. """ @inline known_offset1(x) = known_offset1(typeof(x)) @inline function known_offset1(::Type{T}) where {T} if ndims(T) === 0 return 1 else return known_offsets(T, 1) end end """ offset1(x) -> Union{Int,StaticInt} Returns the offset of the linear indices for `x`. """ @inline function offset1(x::X) where {X} o1 = known_offset1(X) if o1 === nothing if ndims(X) === 0 return 1 else return offsets(x, 1) end else return static(o1) end end """ contiguous_axis(::Type{T}) -> StaticInt{N} Returns the axis of an array of type `T` containing contiguous data. If no axis is contiguous, it returns a `StaticInt{-1}`. If unknown, it returns `nothing`. """ contiguous_axis(x) = contiguous_axis(typeof(x)) contiguous_axis(::Type{<:StrideIndex{N,R,C}}) where {N,R,C} = static(C) contiguous_axis(::Type{<:StrideIndex{N,R,nothing}}) where {N,R} = nothing function contiguous_axis(::Type{T}) where {T} is_forwarding_wrapper(T) ? contiguous_axis(parent_type(T)) : nothing end contiguous_axis(@nospecialize T::Type{<:DenseArray}) = One() contiguous_axis(::Type{<:BitArray}) = One() contiguous_axis(@nospecialize T::Type{<:AbstractRange}) = One() contiguous_axis(@nospecialize T::Type{<:Tuple}) = One() function contiguous_axis(@nospecialize T::Type{<:VecAdjTrans}) c = contiguous_axis(parent_type(T)) if c === nothing return nothing elseif c === One() return StaticInt{2}() else return -One() end end function contiguous_axis(@nospecialize T::Type{<:MatAdjTrans}) c = contiguous_axis(parent_type(T)) if c === nothing return nothing elseif isone(-c) return c else return StaticInt(3) - c end end function contiguous_axis(@nospecialize T::Type{<:PermutedDimsArray}) c = contiguous_axis(parent_type(T)) if c === nothing return nothing elseif isone(-c) return c else return from_parent_dims(T)[c] end end function contiguous_axis(::Type{<:Base.ReshapedArray{T, N, A, Tuple{}}}) where {T, N, A} c = contiguous_axis(A) if c !== nothing && isone(-c) return StaticInt(-1) elseif dynamic(is_column_major(A) & is_dense(A)) return StaticInt(1) else return nothing end end # we're actually looking at the original vector indices before transpose/adjoint function contiguous_axis(::Type{<:Base.ReshapedArray{T, 1, A, Tuple{}}}) where {T, A <: VecAdjTrans} contiguous_axis(parent_type(A)) end @inline function contiguous_axis(@nospecialize T::Type{<:SubArray}) c = contiguous_axis(parent_type(T)) if c === nothing return nothing elseif c == -1 return c else I = field_type(fieldtype(T, :indices), c) if I <: AbstractUnitRange return from_parent_dims(T)[c] # FIXME get rid of from_parent_dims elseif I <: AbstractArray || I <: IntType return StaticInt(-1) else return nothing end end end function contiguous_axis(::Type{R}) where {T,N,S,A<:Array{S},R<:ReinterpretArray{T,N,S,A}} if isbitstype(S) return One() else return nothing end end """ contiguous_axis_indicator(::Type{T}) -> Tuple{Vararg{StaticBool}} Returns a tuple boolean `Val`s indicating whether that axis is contiguous. """ function contiguous_axis_indicator(::Type{A}) where {D,A<:AbstractArray{<:Any,D}} return contiguous_axis_indicator(contiguous_axis(A), Val(D)) end contiguous_axis_indicator(::A) where {A<:AbstractArray} = contiguous_axis_indicator(A) contiguous_axis_indicator(::Nothing, ::Val) = nothing function contiguous_axis_indicator(c::StaticInt{N}, dim::Val{D}) where {N,D} map(eq(c), ntuple(static, dim)) end function rank_to_sortperm(R::Tuple{Vararg{StaticInt,N}}) where {N} sp = ntuple(zero, Val{N}()) r = ntuple(n -> sum(R[n] .≥ R), Val{N}()) @inbounds for n = 1:N sp = Base.setindex(sp, n, r[n]) end return sp end stride_rank(::Type{<:StrideIndex{N,R}}) where {N,R} = static(R) stride_rank(x) = stride_rank(typeof(x)) function stride_rank(::Type{T}) where {T} is_forwarding_wrapper(T) ? stride_rank(parent_type(T)) : nothing end stride_rank(::Type{BitArray{N}}) where {N} = ntuple(static, StaticInt(N)) stride_rank(@nospecialize T::Type{<:DenseArray}) = ntuple(static, StaticInt(ndims(T))) stride_rank(@nospecialize T::Type{<:AbstractRange}) = (One(),) stride_rank(@nospecialize T::Type{<:Tuple}) = (One(),) stride_rank(@nospecialize T::Type{<:VecAdjTrans}) = (StaticInt(2), StaticInt(1)) @inline function stride_rank(@nospecialize T::Type{<:Union{MatAdjTrans,PermutedDimsArray}}) rank = stride_rank(parent_type(T)) if rank === nothing return nothing else return map(GetIndex{false}(rank), to_parent_dims(T)) end end function stride_rank(@nospecialize T::Type{<:SubArray}) rank = stride_rank(parent_type(T)) if rank === nothing return nothing else return map(GetIndex{false}(rank), to_parent_dims(T)) end end stride_rank(x, i) = stride_rank(x)[i] function stride_rank(::Type{R}) where {T,N,S,A<:Array{S},R<:Base.ReinterpretArray{T,N,S,A}} return ntuple(static, StaticInt(N)) end @inline function stride_rank(::Type{A}) where {NB,NA,B<:AbstractArray{<:Any,NB},A<:Base.ReinterpretArray{<:Any,NA,<:Any,B,true}} NA == NB ? stride_rank(B) : _stride_rank_reinterpret(stride_rank(B), gt(StaticInt{NB}(), StaticInt{NA}())) end @inline function stride_rank(::Type{A}) where {N,B<:AbstractArray{<:Any,N},A<:Base.ReinterpretArray{<:Any,N,<:Any,B,false}} stride_rank(B) end @inline _stride_rank_reinterpret(sr, ::False) = (One(), map(Base.Fix2(+, One()), sr)...) @inline _stride_rank_reinterpret(sr::Tuple{One,Vararg}, ::True) = map(Base.Fix2(-, One()), tail(sr)) function contiguous_axis(::Type{R}) where {T,N,S,B<:AbstractArray{S,N},R<:ReinterpretArray{T,N,S,B,false}} contiguous_axis(B) end # if the leading dim's `stride_rank` is not one, then that means the individual elements are split across an axis, which ArrayInterface # doesn't currently have a means of representing. @inline function contiguous_axis(::Type{A}) where {NB,NA,B<:AbstractArray{<:Any,NB},A<:Base.ReinterpretArray{<:Any,NA,<:Any,B,true}} _reinterpret_contiguous_axis(stride_rank(B), dense_dims(B), contiguous_axis(B), gt(StaticInt{NB}(), StaticInt{NA}())) end @inline _reinterpret_contiguous_axis(::Any, ::Any, ::Any, ::False) = One() @inline _reinterpret_contiguous_axis(::Any, ::Any, ::Any, ::True) = Zero() @generated function _reinterpret_contiguous_axis(t::Tuple{One,Vararg{StaticInt,N}}, d::Tuple{True,Vararg{StaticBool,N}}, ::One, ::True) where {N} for n in 1:N if t.parameters[n+1].parameters[1] === 2 if d.parameters[n+1] === True return :(StaticInt{$n}()) else return :(Zero()) end end end :(Zero()) end function stride_rank(::Type{Base.ReshapedArray{T, N, P, Tuple{Vararg{Base.SignedMultiplicativeInverse{Int},M}}}}) where {T,N,P,M} _reshaped_striderank(is_column_major(P), Val{N}(), Val{M}()) end function stride_rank(::Type{Base.ReshapedArray{T, 1, A, Tuple{}}}) where {T, A} IfElse.ifelse(is_column_major(A) & is_dense(A), (static(1),), nothing) end function stride_rank(::Type{Base.ReshapedArray{T, 1, LinearAlgebra.Adjoint{T, A}, Tuple{}}}) where {T, A <: AbstractVector{T}} IfElse.ifelse(is_dense(A), (static(1),), nothing) end function stride_rank(::Type{Base.ReshapedArray{T, 1, LinearAlgebra.Transpose{T, A}, Tuple{}}}) where {T, A <: AbstractVector{T}} IfElse.ifelse(is_dense(A), (static(1),), nothing) end _reshaped_striderank(::True, ::Val{N}, ::Val{0}) where {N} = ntuple(static, StaticInt(N)) _reshaped_striderank(_, __, ___) = nothing """ contiguous_batch_size(::Type{T}) -> StaticInt{N} Returns the Base.size of contiguous batches if `!isone(stride_rank(T, contiguous_axis(T)))`. If `isone(stride_rank(T, contiguous_axis(T)))`, then it will return `StaticInt{0}()`. If `contiguous_axis(T) == -1`, it will return `StaticInt{-1}()`. If unknown, it will return `nothing`. """ contiguous_batch_size(x) = contiguous_batch_size(typeof(x)) contiguous_batch_size(::Type{T}) where {T} = _contiguous_batch_size(contiguous_axis(T), stride_rank(T)) _contiguous_batch_size(_, __) = nothing function _contiguous_batch_size(::StaticInt{D}, ::R) where {D,R<:Tuple} if R.parameters[D].parameters[1] === 1 return Zero() else return nothing end end _contiguous_batch_size(::StaticInt{-1}, ::R) where {R<:Tuple} = -One() contiguous_batch_size(::Type{Array{T,N}}) where {T,N} = Zero() contiguous_batch_size(::Type{BitArray{N}}) where {N} = Zero() contiguous_batch_size(@nospecialize T::Type{<:AbstractRange}) = Zero() contiguous_batch_size(@nospecialize T::Type{<:Tuple}) = Zero() @inline function contiguous_batch_size(@nospecialize T::Type{<:Union{PermutedDimsArray,Transpose,Adjoint}}) contiguous_batch_size(parent_type(T)) end function contiguous_batch_size(::Type{S}) where {N,NP,T,A<:AbstractArray{T,NP},I,S<:SubArray{T,N,A,I}} return _contiguous_batch_size(S, contiguous_batch_size(A), contiguous_axis(A)) end _contiguous_batch_size(::Any, ::Any, ::Any) = nothing function _contiguous_batch_size(::Type{<:SubArray{T,N,A,I}}, b::StaticInt{B}, c::StaticInt{C}) where {T,N,A,I,B,C} if I.parameters[C] <: AbstractUnitRange return b else return -One() end end contiguous_batch_size(::Type{<:Base.ReinterpretArray{T,N,S,A}}) where {T,N,S,A} = Zero() """ is_column_major(A) -> StaticBool Returns `True()` if elements of `A` are stored in column major order. Otherwise returns `False()`. """ is_column_major(A) = is_column_major(stride_rank(A), contiguous_batch_size(A)) is_column_major(sr::Nothing, cbs) = False() is_column_major(sr::R, cbs) where {R} = _is_column_major(sr, cbs) is_column_major(::AbstractRange) = False() # cbs > 0 _is_column_major(sr::R, cbs::StaticInt) where {R} = False() # cbs <= 0 _is_column_major(sr::R, cbs::Union{StaticInt{0},StaticInt{-1}}) where {R} = is_increasing(sr) function is_increasing(perm::Tuple{StaticInt{X},StaticInt{Y},Vararg}) where {X, Y} X <= Y ? is_increasing(tail(perm)) : False() end is_increasing(::Tuple{StaticInt{X},StaticInt{Y}}) where {X, Y} = X <= Y ? True() : False() is_increasing(::Tuple{StaticInt{X}}) where {X} = True() is_increasing(::Tuple{}) = True() """ dense_dims(::Type{<:AbstractArray{N}}) -> Tuple{Vararg{StaticBool,N}} Returns a tuple of indicators for whether each axis is dense. An axis `i` of array `A` is dense if `stride(A, i) * Base.size(A, i) == stride(A, j)` where `stride_rank(A)[i] + 1 == stride_rank(A)[j]`. """ dense_dims(x) = dense_dims(typeof(x)) function dense_dims(::Type{T}) where {T} is_forwarding_wrapper(T) ? dense_dims(parent_type(T)) : nothing end _all_dense(::Val{N}) where {N} = ntuple(_ -> True(), Val{N}()) function dense_dims(@nospecialize T::Type{<:DenseArray}) ntuple(Compat.Returns(True()), StaticInt(ndims(T))) end dense_dims(::Type{BitArray{N}}) where {N} = ntuple(Compat.Returns(True()), StaticInt(N)) dense_dims(@nospecialize T::Type{<:AbstractRange}) = (True(),) dense_dims(@nospecialize T::Type{<:Tuple}) = (True(),) function dense_dims(@nospecialize T::Type{<:VecAdjTrans}) dense = dense_dims(parent_type(T)) if dense === nothing return nothing else return (True(), first(dense)) end end @inline function dense_dims(@nospecialize T::Type{<:Union{MatAdjTrans,PermutedDimsArray}}) dense = dense_dims(parent_type(T)) if dense === nothing return nothing else return map(GetIndex{false}(dense), to_parent_dims(T)) end end @inline function dense_dims(@nospecialize T::Type{<:Base.ReshapedReinterpretArray}) ddb = dense_dims(parent_type(T)) IfElse.ifelse(Static.le(StaticInt(ndims(parent_type(T))), StaticInt(ndims(T))), (True(), ddb...), Base.tail(ddb)) end @inline dense_dims(@nospecialize T::Type{<:Base.NonReshapedReinterpretArray}) = dense_dims(parent_type(T)) @inline function dense_dims(@nospecialize T::Type{<:SubArray}) dd = dense_dims(parent_type(T)) if dd === nothing return nothing else return _dense_dims(T, dd, Val(stride_rank(parent_type(T)))) end end @generated function _dense_dims( ::Type{S}, ::D, ::Val{R}, ) where {D,R,N,NP,T,A<:AbstractArray{T,NP},I,S<:SubArray{T,N,A,I}} still_dense = true sp = rank_to_sortperm(R) densev = Vector{Bool}(undef, NP) for np = 1:NP spₙ = sp[np] if still_dense still_dense = D.parameters[spₙ] <: True end densev[spₙ] = still_dense # a dim not being complete makes later dims not dense still_dense &= (I.parameters[spₙ] <: Base.Slice)::Bool end dense_tup = Expr(:tuple) for np = 1:NP Iₙₚ = I.parameters[np] if Iₙₚ <: AbstractUnitRange if densev[np] push!(dense_tup.args, :(True())) else push!(dense_tup.args, :(False())) end elseif Iₙₚ <: AbstractVector push!(dense_tup.args, :(False())) end end # If n != N, then an axis was indexed by something other than an integer or `AbstractUnitRange`, so we return `nothing`. if static_length(dense_tup.args) === N return dense_tup else return nothing end end function dense_dims(@nospecialize T::Type{<:Base.ReshapedArray}) d = dense_dims(parent_type(T)) if d === nothing return nothing elseif all(d) return ntuple(Compat.Returns(True()), StaticInt(ndims(T))) else return ntuple(Compat.Returns(False()), StaticInt(ndims(T))) end end is_dense(A) = all(dense_dims(A)) ? True() : False() """ known_strides(::Type{T}) -> Tuple known_strides(::Type{T}, dim) -> Union{Int,Nothing} Returns the strides of array `A` known at compile time. Any strides that are not known at compile time are represented by `nothing`. """ known_strides(x, dim) = known_strides(typeof(x), dim) known_strides(::Type{T}, dim) where {T} = known_strides(T, to_dims(T, dim)) function known_strides(::Type{T}, dim::IntType) where {T} # see https://github.com/JuliaLang/julia/blob/6468dcb04ea2947f43a11f556da9a5588de512a0/base/reinterpretarray.jl#L148 if ndims(T) < dim return known_length(T) else return known_strides(T)[dim] end end known_strides(::Type{<:StrideIndex{N,R,C,S,O}}) where {N,R,C,S,O} = known(S) known_strides(x) = known_strides(typeof(x)) known_strides(::Type{T}) where {T<:Vector} = (1,) @inline function known_strides(::Type{T}) where {T<:VecAdjTrans} strd = first(known_strides(parent_type(T))) return (strd, strd) end @inline function known_strides(@nospecialize T::Type{<:Union{MatAdjTrans,PermutedDimsArray}}) map(GetIndex{false}(known_strides(parent_type(T))), to_parent_dims(T)) end @inline function known_strides(::Type{T}) where {T<:SubArray} map(GetIndex{false}(known_strides(parent_type(T))), to_parent_dims(T)) end function known_strides(::Type{T}) where {T} if ndims(T) === 1 return (1,) else return size_to_strides(known_size(T), 1) end end """ static_strides(A) -> Tuple{Vararg{Union{Int,StaticInt}}} static_strides(A, dim) -> Union{Int,StaticInt} Returns the strides of array `A`. If any strides are known at compile time, these should be returned as `Static` numbers. For example: ```julia julia> A = rand(3,4); julia> static_strides(A) (static(1), 3) ``` Additionally, the behavior differs from `Base.strides` for adjoint vectors: ```julia julia> x = rand(5); julia> static_strides(x') (static(1), static(1)) ``` This is to support the pattern of using just the first stride for linear indexing, `x[i]`, while still producing correct behavior when using valid cartesian indices, such as `x[1,i]`. ``` """ static_strides(A::StrideIndex) = getfield(A, :strides) @inline static_strides(A::Vector{<:Any}) = (StaticInt(1),) @inline static_strides(A::Array{<:Any,N}) where {N} = (StaticInt(1), Base.tail(Base.strides(A))...) @inline function static_strides(x::X) where {X} if is_forwarding_wrapper(X) return static_strides(parent(x)) elseif defines_strides(X) return size_to_strides(static_size(x), One()) else return Base.strides(x) end end _is_column_dense(::A) where {A<:AbstractArray} = defines_strides(A) && (ndims(A) == 0 || Bool(is_dense(A)) && Bool(is_column_major(A))) # Fixes the example of https://github.com/JuliaArrays/jl/issues/160 function static_strides(A::ReshapedArray) if _is_column_dense(parent(A)) return size_to_strides(static_size(A), One()) else pst = static_strides(parent(A)) psz = static_size(parent(A)) # Try dimension merging in order (starting from dim1). # `sz1` and `st1` are the `size`/`stride` of dim1 after dimension merging. # `n` indicates the last merged dimension. # note: `st1` should be static if possible sz1, st1, n = merge_adjacent_dim(psz, pst) n == ndims(A.parent) && return size_to_strides(static_size(A), st1) return _reshaped_strides(static_size(A), One(), sz1, st1, n, Dims(psz), Dims(pst)) end end @inline function _reshaped_strides(::Dims{0}, reshaped, msz::Int, _, ::Int, ::Dims, ::Dims) reshaped == msz && return () throw(ArgumentError("Input is not strided.")) end function _reshaped_strides(asz::Dims, reshaped, msz::Int, mst, n::Int, apsz::Dims, apst::Dims) st = reshaped * mst reshaped = reshaped * asz[1] if static_length(asz) > 1 && reshaped == msz && asz[2] != 1 msz, mst′, n = merge_adjacent_dim(apsz, apst, n + 1) reshaped = 1 else mst′ = Int(mst) end sts = _reshaped_strides(tail(asz), reshaped, msz, mst′, n, apsz, apst) return (st, sts...) end merge_adjacent_dim(::Tuple{}, ::Tuple{}) = 1, One(), 0 merge_adjacent_dim(szs::Tuple{Any}, sts::Tuple{Any}) = Int(szs[1]), sts[1], 1 function merge_adjacent_dim(szs::Tuple, sts::Tuple) if szs[1] isa One # Just ignore dimension with size 1 sz, st, n = merge_adjacent_dim(tail(szs), tail(sts)) return sz, st, n + 1 elseif szs[2] isa One # Just ignore dimension with size 1 sz, st, n = merge_adjacent_dim((szs[1], tail(tail(szs))...), (sts[1], tail(tail(sts))...)) return sz, st, n + 1 elseif (szs[1], szs[2], sts[1], sts[2]) isa NTuple{4,StaticInt} # the check could be done during compiling. if sts[2] == sts[1] * szs[1] szs′ = (szs[1] * szs[2], tail(tail(szs))...) sts′ = (sts[1], tail(tail(sts))...) sz, st, n = merge_adjacent_dim(szs′, sts′) return sz, st, n + 1 else return Int(szs[1]), sts[1], 1 end else # the check can't be done during compiling. sz, st, n = merge_adjacent_dim(Dims(szs), Dims(sts), 1) if (szs[1], sts[1]) isa NTuple{2,StaticInt} && szs[1] != 1 # But the 1st stride might still be static. return sz, sts[1], n else return sz, st, n end end end function merge_adjacent_dim(psz::Dims{N}, pst::Dims{N}, n::Int) where {N} sz, st = psz[n], pst[n] while n < N szₙ, stₙ = psz[n+1], pst[n+1] if sz == 1 sz, st = szₙ, stₙ elseif stₙ == st * sz sz *= szₙ elseif szₙ != 1 break end n += 1 end return sz, st, n end # `static_strides` for `Base.ReinterpretArray` function static_strides(A::Base.ReinterpretArray{T,<:Any,S,<:AbstractArray{S},IsReshaped}) where {T,S,IsReshaped} _is_column_dense(parent(A)) && return size_to_strides(static_size(A), One()) stp = static_strides(parent(A)) ET, ES = static(sizeof(T)), static(sizeof(S)) ET === ES && return stp IsReshaped && ET < ES && return (One(), _reinterp_strides(stp, ET, ES)...) first(stp) == 1 || throw(ArgumentError("Parent must be contiguous in the 1st dimension!")) if IsReshaped # The wrapper tell us `A`'s parent has static size in dim1. # We can make the next stride static if the following dim is still dense. sr = stride_rank(parent(A)) dd = dense_dims(parent(A)) stp′ = _new_static(stp, sr, dd, ET ÷ ES) return _reinterp_strides(tail(stp′), ET, ES) else return (One(), _reinterp_strides(tail(stp), ET, ES)...) end end _new_static(P,_,_,_) = P # This should never be called, just in case. @generated function _new_static(p::P, ::SR, ::DD, ::StaticInt{S}) where {S,N,P<:NTuple{N,Union{Int,StaticInt}},SR<:NTuple{N,StaticInt},DD<:NTuple{N,StaticBool}} sr = fieldtypes(SR) j = findfirst(T -> T() == sr[1]()+1, sr) if !isnothing(j) && !(fieldtype(P, j) <: StaticInt) && fieldtype(DD, j) === True return :(tuple($((i == j ? :(static($S)) : :(p[$i]) for i in 1:N)...))) else return :(p) end end @inline function _reinterp_strides(stp::Tuple, els::StaticInt, elp::StaticInt) if elp % els == 0 N = elp ÷ els return map(Base.Fix2(*, N), stp) else return map(stp) do i d, r = divrem(elp * i, els) iszero(r) || throw(ArgumentError("Parent's strides could not be exactly divided!")) d end end end static_strides(@nospecialize x::AbstractRange) = (One(),) function static_strides(x::VecAdjTrans) st = first(static_strides(parent(x))) return (st, st) end @inline function static_strides(x::Union{MatAdjTrans,PermutedDimsArray}) map(GetIndex{false}(static_strides(parent(x))), to_parent_dims(x)) end getmul(x::Tuple, y::Tuple, ::StaticInt{i}) where {i} = getfield(x, i) * getfield(y, i) function static_strides(A::SubArray) eachop(getmul, to_parent_dims(typeof(A)), map(maybe_static_step, A.indices), static_strides(parent(A))) end maybe_static_step(x::AbstractRange) = static_step(x) maybe_static_step(_) = nothing @generated function size_to_strides(sz::S, init) where {N,S<:Tuple{Vararg{Any,N}}} out = Expr(:block, Expr(:meta, :inline)) t = Expr(:tuple, :init) prev = :init i = 1 while i <= (N - 1) if S.parameters[i] <: Nothing || (i > 1 && t.args[i - 1] === :nothing) push!(t.args, :nothing) else next = Symbol(:val_, i) push!(out.args, :($next = $prev * getfield(sz, $i))) push!(t.args, next) prev = next end i += 1 end push!(out.args, t) return out end static_strides(a, dim) = static_strides(a, to_dims(a, dim)) function static_strides(a::A, dim::IntType) where {A} if is_forwarding_wrapper(A) return static_strides(parent(a), dim) else return Base.stride(a, Int(dim)) end end @inline static_stride(A::AbstractArray, ::StaticInt{N}) where {N} = static_strides(A)[N] @inline static_stride(A::AbstractArray, ::Val{N}) where {N} = static_strides(A)[N] static_stride(A, i) = Base.stride(A, i) # for type stability
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
3168
A = zeros(3, 4, 5); A[:] = 1:60 Ap = @view(PermutedDimsArray(A,(3,1,2))[:,1:2,1])'; ap_index = StaticArrayInterface.StrideIndex(Ap) for x_i in axes(Ap, 1) for y_i in axes(Ap, 2) @test ap_index[x_i, y_i] == ap_index[x_i, y_i] end end @test @inferred(StaticArrayInterface.known_offsets(ap_index)) === StaticArrayInterface.known_offsets(Ap) @test @inferred(StaticArrayInterface.known_offset1(ap_index)) === StaticArrayInterface.known_offset1(Ap) @test @inferred(StaticArrayInterface.offsets(ap_index, 1)) === StaticArrayInterface.offset1(Ap) @test @inferred(StaticArrayInterface.offsets(ap_index, static(1))) === StaticArrayInterface.offset1(Ap) @test @inferred(StaticArrayInterface.known_strides(ap_index)) === StaticArrayInterface.known_strides(Ap) @test @inferred(StaticArrayInterface.contiguous_axis(ap_index)) == 1 @test @inferred(StaticArrayInterface.contiguous_axis(StaticArrayInterface.StrideIndex{2,(1,2),nothing,NTuple{2,Int},NTuple{2,Int}})) === nothing @test @inferred(StaticArrayInterface.stride_rank(ap_index)) == (1, 3) let v = Float64.(1:10)', v2 = transpose(parent(v)) sv = @view(v[1:5])' sv2 = @view(v2[1:5])' @test @inferred(StaticArrayInterface.StrideIndex(sv)) === @inferred(StaticArrayInterface.StrideIndex(sv2)) === StaticArrayInterface.StrideIndex{2, (2, 1), 2}((StaticInt(1), StaticInt(1)), (StaticInt(1), StaticInt(1))) @test @inferred(StaticArrayInterface.stride_rank(parent(sv))) === @inferred(StaticArrayInterface.stride_rank(parent(sv2))) === (StaticInt(1),) end @testset "IndicesInfo" begin struct SplatFirst end import StaticArrayInterface: IndicesInfo StaticArrayInterface.is_splat_index(::Type{SplatFirst}) = true @test @inferred(IndicesInfo(SubArray{Float64, 2, Vector{Float64}, Tuple{Base.ReshapedArray{Int64, 2, UnitRange{Int64}, Tuple{}}}, true})) isa IndicesInfo{1,(1,),((1,2),)} @test @inferred(IndicesInfo{1}((Tuple{Vector{Int}}))) isa IndicesInfo{1, (1,), (1,)} @test @inferred(IndicesInfo{2}(Tuple{Vector{Int}})) isa IndicesInfo{2, (:,), (1,)} @test @inferred(IndicesInfo{1}(Tuple{SplatFirst})) isa IndicesInfo{1, (1,), (1,)} @test @inferred(IndicesInfo{2}(Tuple{SplatFirst})) isa IndicesInfo{2, ((1,2),), ((1, 2),)} @test @inferred(IndicesInfo{5}(typeof((:,[CartesianIndex(1,1),CartesianIndex(1,1)], 1, ones(Int, 2, 2), :, 1)))) isa IndicesInfo{5, (1, (2, 3), 4, 5, 0, 0), (1, 2, 0, (3, 4), 5, 0)} @test @inferred(IndicesInfo{10}(Tuple{Vararg{Int,10}})) isa IndicesInfo{10, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)} @test @inferred(IndicesInfo{10}(typeof((1, CartesianIndex(2, 1), 2, CartesianIndex(1, 2), 1, CartesianIndex(2, 1), 2)))) isa IndicesInfo{10, (1, (2, 3), 4, (5, 6), 7, (8, 9), 10), (0, 0, 0, 0, 0, 0, 0)} @test @inferred(IndicesInfo{10}(typeof((fill(true, 4, 4), 2, fill(true, 4, 4), 2, 1, fill(true, 4, 4), 1)))) isa IndicesInfo{10, ((1, 2), 3, (4, 5), 6, 7, (8, 9), 10), (1, 0, 2, 0, 0, 3, 0)} @test @inferred(IndicesInfo{10}(typeof((1, SplatFirst(), 2, SplatFirst(), CartesianIndex(1, 1))))) isa IndicesInfo{10, (1, (2, 3, 4, 5, 6), 7, 8, (9, 10)), (0, (1, 2, 3, 4, 5), 0, 6, 0)} end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
5805
v = Array{Float64}(undef, 4) m = Array{Float64}(undef, 4, 3) @test @inferred(StaticArrayInterface.static_axes(v')) === (StaticInt(1):StaticInt(1),Base.OneTo(4)) @test @inferred(StaticArrayInterface.static_axes(m')) === (Base.OneTo(3),Base.OneTo(4)) @test StaticArrayInterface.static_axes(v', StaticInt(1)) === StaticInt(1):StaticInt(1) @test StaticArrayInterface.static_axes(v, StaticInt(2)) === StaticInt(1):StaticInt(1) @test StaticArrayInterface.axes_types(view(CartesianIndices(map(Base.Slice, (0:3, 3:5))), 0, :), 1) <: Base.IdentityUnitRange @testset "LazyAxis" begin A = zeros(3,4,5); SA = MArray(zeros(3,4,5)) DA = MArray(zeros(3,4,5), LinearIndices((Base.Slice(1:3), 1:4, 1:5))) lz1 = StaticArrayInterface.LazyAxis{1}(A) slz1 = StaticArrayInterface.LazyAxis{1}(SA) dlz1 = StaticArrayInterface.LazyAxis{1}(DA) lzc = StaticArrayInterface.LazyAxis{:}(A) slzc = StaticArrayInterface.LazyAxis{:}(SA) dlzc = StaticArrayInterface.LazyAxis{:}(DA) @test @inferred(first(lz1)) === @inferred(first(slz1)) === @inferred(first(dlz1)) @test @inferred(first(lzc)) === @inferred(first(slzc)) === @inferred(first(dlzc)) @test @inferred(last(lz1)) === @inferred(last(slz1)) === @inferred(last(dlz1)) @test @inferred(last(lzc)) === @inferred(last(slzc)) === @inferred(last(dlzc)) @test @inferred(length(lz1)) === @inferred(length(slz1)) === @inferred(length(dlz1)) @test @inferred(length(lzc)) === @inferred(length(slzc)) === @inferred(length(dlzc)) @test @inferred(Base.to_shape(lzc)) == length(slzc) == length(dlzc) @test @inferred(Base.checkindex(Bool, lzc, 1)) & @inferred(Base.checkindex(Bool, slzc, 1)) @test axes(lzc)[1] == Base.axes1(lzc) == axes(Base.Slice(lzc))[1] == Base.axes1(Base.Slice(lzc)) @test keys(axes(A, 1)) == @inferred(keys(lz1)) @test @inferred(StaticArrayInterface.known_first(slzc)) === 1 @test @inferred(StaticArrayInterface.known_length(slz1)) === 3 @test @inferred(getindex(lz1, 2)) == 2 @test @inferred(getindex(lz1, 1:2)) == 1:2 @test @inferred(getindex(lz1, 1:1:3)) == 1:1:3 @test @inferred(StaticArrayInterface.parent_type(StaticArrayInterface.LazyAxis{:}(A))) <: Base.OneTo{Int} @test @inferred(StaticArrayInterface.parent_type(StaticArrayInterface.LazyAxis{4}(SA))) <: Static.SOneTo{1} @test @inferred(StaticArrayInterface.parent_type(StaticArrayInterface.LazyAxis{:}(SA))) <: Static.SOneTo{60} @test @inferred(IndexStyle(SA)) isa IndexLinear @test @inferred(IndexStyle(DA)) isa IndexLinear @test StaticArrayInterface.can_change_size(StaticArrayInterface.LazyAxis{1,Vector{Any}}) Aperm = PermutedDimsArray(A, (3,1,2)) Aview = @view(Aperm[:,1:2,1]) @test map(parent, @inferred(StaticArrayInterface.lazy_axes(Aperm))) === @inferred(StaticArrayInterface.static_axes(Aperm)) @test map(parent, @inferred(StaticArrayInterface.lazy_axes(Aview))) === @inferred(StaticArrayInterface.static_axes(Aview)) @test map(parent, @inferred(StaticArrayInterface.lazy_axes(Aview'))) === @inferred(StaticArrayInterface.static_axes(Aview')) @test map(parent, @inferred(StaticArrayInterface.lazy_axes((1:2)'))) === @inferred(StaticArrayInterface.static_axes((1:2)')) @test_throws DimensionMismatch StaticArrayInterface.LazyAxis{0}(A) end @testset "`axes(A, dim)`` with `dim > ndims(A)` (#224)" begin m = 2 n = 3 B = Array{Float64, 2}(undef, m, n) b = view(B, :, 1) @test @inferred(StaticArrayInterface.static_axes(B, 1)) == 1:m @test @inferred(StaticArrayInterface.static_axes(B, 2)) == 1:n @test @inferred(StaticArrayInterface.static_axes(B, 3)) == 1:1 @test @inferred(StaticArrayInterface.static_axes(B, static(1))) == 1:m @test @inferred(StaticArrayInterface.static_axes(B, static(2))) == 1:n @test @inferred(StaticArrayInterface.static_axes(B, static(3))) == 1:1 @test @inferred(StaticArrayInterface.static_axes(b, 1)) == 1:m @test @inferred(StaticArrayInterface.static_axes(b, 2)) == 1:1 @test @inferred(StaticArrayInterface.static_axes(b, 3)) == 1:1 @test @inferred(StaticArrayInterface.static_axes(b, static(1))) == 1:m @test @inferred(StaticArrayInterface.static_axes(b, static(2))) == 1:1 @test @inferred(StaticArrayInterface.static_axes(b, static(3))) == 1:1 # multidimensional subindices vx = view(rand(4), reshape(1:4, 2, 2)) @test @inferred(axes(vx)) == (1:2, 1:2) end @testset "SubArray Adjoint Axis" begin N = 4; d = rand(N); @test @inferred(StaticArrayInterface.axes_types(typeof(view(d',:,1:2)))) === Tuple{Static.OptionallyStaticUnitRange{StaticInt{1}, StaticInt{1}}, Base.OneTo{Int64}} === typeof(@inferred(StaticArrayInterface.static_axes(view(d',:,1:2)))) === typeof((StaticArrayInterface.static_axes(view(d',:,1:2),1),StaticArrayInterface.static_axes(view(d',:,1:2),2))) end if isdefined(Base, :ReshapedReinterpretArray) @testset "ReshapedReinterpretArray" begin a = rand(3, 5) ua = reinterpret(reshape, UInt64, a) @test StaticArrayInterface.static_axes(ua) === StaticArrayInterface.static_axes(a) @test StaticArrayInterface.static_axes(ua, 1) === StaticArrayInterface.static_axes(a, 1) @test @inferred(StaticArrayInterface.static_axes(ua)) isa StaticArrayInterface.axes_types(ua) u8a = reinterpret(reshape, UInt8, a) @test @inferred(StaticArrayInterface.static_axes(u8a)) isa StaticArrayInterface.axes_types(u8a) @test @inferred(StaticArrayInterface.static_axes(u8a, static(1))) isa StaticArrayInterface.axes_types(u8a, 1) @test @inferred(StaticArrayInterface.static_axes(u8a, static(2))) isa StaticArrayInterface.axes_types(u8a, 2) fa = reinterpret(reshape, Float64, copy(u8a)) @inferred(StaticArrayInterface.static_axes(fa)) isa StaticArrayInterface.axes_types(fa) end end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
1138
s5 = static(1):static(5) s4 = static(1):static(4) s1 = static(1):static(1) d5 = static(1):5 d4 = static(1):static(4) d1 = static(1):static(1) struct DummyBroadcast <: StaticArrayInterface.BroadcastAxis end struct DummyAxis end StaticArrayInterface.BroadcastAxis(::Type{DummyAxis}) = DummyBroadcast() StaticArrayInterface.broadcast_axis(::DummyBroadcast, x, y) = y @inferred(StaticArrayInterface.broadcast_axis(s1, s1)) === s1 @inferred(StaticArrayInterface.broadcast_axis(s5, s5)) === s5 @inferred(StaticArrayInterface.broadcast_axis(s5, s1)) === s5 @inferred(StaticArrayInterface.broadcast_axis(s1, s5)) === s5 @inferred(StaticArrayInterface.broadcast_axis(s5, d5)) === s5 @inferred(StaticArrayInterface.broadcast_axis(d5, s5)) === s5 @inferred(StaticArrayInterface.broadcast_axis(d5, d1)) === d5 @inferred(StaticArrayInterface.broadcast_axis(d1, d5)) === d5 @inferred(StaticArrayInterface.broadcast_axis(s1, d5)) === d5 @inferred(StaticArrayInterface.broadcast_axis(d5, s1)) === d5 @inferred(StaticArrayInterface.broadcast_axis(s5, DummyAxis())) === s5 @test_throws DimensionMismatch StaticArrayInterface.broadcast_axis(s5, s4)
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
7256
### ### define wrapper with StaticArrayInterface.dimnames ### @testset "order_named_inds" begin n1 = (static(:x),) n2 = (n1..., static(:y)) n3 = (n2..., static(:z)) @test @inferred(StaticArrayInterface.find_all_dimnames(n1, (), (), :)) == () @test @inferred(StaticArrayInterface.find_all_dimnames(n1, (static(:x),), (2,), :)) == (2,) @test @inferred(StaticArrayInterface.find_all_dimnames(n2, (static(:x),), (2,), :)) == (2, :) @test @inferred(StaticArrayInterface.find_all_dimnames(n2, (static(:y),), (2,), :)) == (:, 2) @test @inferred(StaticArrayInterface.find_all_dimnames(n2, (static(:y), static(:x)), (20, 30), :)) == (30, 20) @test @inferred(StaticArrayInterface.find_all_dimnames(n2, (static(:x), static(:y)), (30, 20), :)) == (30, 20) @test @inferred(StaticArrayInterface.find_all_dimnames(n3, (static(:x), static(:y)), (30, 20), :)) == (30, 20, :) @test_throws ErrorException StaticArrayInterface.find_all_dimnames(n2, (static(:x), static(:y), static(:z)), (30, 20, 40), :) end @testset "StaticArrayInterface.dimnames" begin d = (static(:x), static(:y)) x = NamedDimsWrapper(d, ones(Int64, 2, 2)) y = NamedDimsWrapper((static(:x),), ones(2)) z = NamedDimsWrapper((:x, static(:y)), ones(2)) r1 = reinterpret(Int8, x) r2 = reinterpret(reshape, Int8, x) r3 = reinterpret(reshape, Complex{Int}, x) r4 = reinterpret(reshape, Float64, x) w = Wrapper(x) dnums = ntuple(+, length(d)) @test @inferred(StaticArrayInterface.has_dimnames(x)) == true @test @inferred(StaticArrayInterface.has_dimnames(z)) == true @test @inferred(StaticArrayInterface.has_dimnames(ones(2, 2))) == false @test @inferred(StaticArrayInterface.has_dimnames(Array{Int,2})) == false @test @inferred(StaticArrayInterface.has_dimnames(typeof(x))) == true @test @inferred(StaticArrayInterface.has_dimnames(typeof(view(x, :, 1, :)))) == true @test @inferred(StaticArrayInterface.dimnames(x)) === d @test @inferred(StaticArrayInterface.dimnames(w)) === d @test @inferred(StaticArrayInterface.dimnames(r1)) === d @test @inferred(StaticArrayInterface.dimnames(r2)) === (static(:_), d...) @test @inferred(StaticArrayInterface.dimnames(r3)) === Base.tail(d) @test @inferred(StaticArrayInterface.dimnames(r4)) === d @test @inferred(StaticArrayInterface.StaticArrayInterface.dimnames(z)) === (:x, static(:y)) @test @inferred(StaticArrayInterface.dimnames(parent(x))) === (static(:_), static(:_)) @test @inferred(StaticArrayInterface.dimnames(reshape(x, (1, 4)))) === d @test @inferred(StaticArrayInterface.dimnames(reshape(x, :))) === (static(:_),) @test @inferred(StaticArrayInterface.dimnames(x')) === reverse(d) @test @inferred(StaticArrayInterface.dimnames(y')) === (static(:_), static(:x)) @test @inferred(StaticArrayInterface.dimnames(PermutedDimsArray(x, (2, 1)))) === reverse(d) @test @inferred(StaticArrayInterface.dimnames(PermutedDimsArray(x', (2, 1)))) === d @test @inferred(StaticArrayInterface.dimnames(view(x, :, 1))) === (static(:x),) @test @inferred(StaticArrayInterface.dimnames(view(x, :, 1)')) === (static(:_), static(:x)) @test @inferred(StaticArrayInterface.dimnames(view(x, :, :, :))) === (static(:x), static(:y), static(:_)) @test @inferred(StaticArrayInterface.dimnames(view(x, :, 1, :))) === (static(:x), static(:_)) # multidmensional indices @test @inferred(StaticArrayInterface.dimnames(view(x, ones(Int, 2, 2), 1))) === (static(:_), static(:_)) @test @inferred(StaticArrayInterface.dimnames(view(x, [CartesianIndex(1,1), CartesianIndex(1,1)]))) === (static(:_),) @test @inferred(StaticArrayInterface.dimnames(x, Static.One())) === static(:x) @test @inferred(StaticArrayInterface.dimnames(parent(x), Static.One())) === static(:_) @test @inferred(StaticArrayInterface.known_dimnames(Iterators.flatten(1:10))) === (:_,) @test @inferred(StaticArrayInterface.known_dimnames(Iterators.flatten(1:10), static(1))) === :_ # multidmensional indices @test @inferred(StaticArrayInterface.known_dimnames(view(x, ones(Int, 2, 2), 1))) === (:_, :_) @test @inferred(StaticArrayInterface.known_dimnames(view(x, [CartesianIndex(1,1), CartesianIndex(1,1)]))) === (:_,) @test @inferred(StaticArrayInterface.known_dimnames(z)) === (nothing, :y) @test @inferred(StaticArrayInterface.known_dimnames(reshape(x, (1, 4)))) === (:x, :y) @test @inferred(StaticArrayInterface.known_dimnames(r1)) === (:x, :y) @test @inferred(StaticArrayInterface.known_dimnames(r2)) === (:_, :x, :y) @test @inferred(StaticArrayInterface.known_dimnames(r3)) === (:y,) @test @inferred(StaticArrayInterface.known_dimnames(r4)) === (:x, :y) @test @inferred(StaticArrayInterface.known_dimnames(w)) === (:x, :y) @test @inferred(StaticArrayInterface.known_dimnames(reshape(x, :))) === (:_,) @test @inferred(StaticArrayInterface.known_dimnames(view(x, :, 1)')) === (:_, :x) end @testset "to_dims" begin x = NamedDimsWrapper(static((:x, :y)), ones(2, 2)) y = NamedDimsWrapper(static((:x, :y, :a, :b, :c, :d)), ones(6)) @test @inferred(StaticArrayInterface.to_dims(x, :)) == Colon() @test @inferred(StaticArrayInterface.to_dims(x, 1)) == 1 @testset "small case" begin @test @inferred(StaticArrayInterface.to_dims(x, (:x, :y))) == (1, 2) @test @inferred(StaticArrayInterface.to_dims(x, (:y, :x))) == (2, 1) @test @inferred(StaticArrayInterface.to_dims(x, :x)) == 1 @test @inferred(StaticArrayInterface.to_dims(x, :y)) == 2 @test_throws DimensionMismatch StaticArrayInterface.to_dims(x, static(:z)) # not found @test_throws DimensionMismatch StaticArrayInterface.to_dims(x, :z) # not found end @testset "large case" begin @test @inferred(StaticArrayInterface.to_dims(y, :x)) == 1 @test @inferred(StaticArrayInterface.to_dims(y, :a)) == 3 @test @inferred(StaticArrayInterface.to_dims(y, :d)) == 6 @test_throws DimensionMismatch StaticArrayInterface.to_dims(y, :z) # not found end end @testset "methods accepting StaticArrayInterface.dimnames" begin d = (static(:x), static(:y)) x = NamedDimsWrapper(d, ones(2, 2)) y = NamedDimsWrapper((static(:x),), ones(2)) @test @inferred(size(x, first(d))) == size(parent(x), 1) @test @inferred(StaticArrayInterface.static_axes(y')) == (static(1):static(1), Base.OneTo(2)) @test @inferred(axes(x, first(d))) == axes(parent(x), 1) @test strides(x, :x) == StaticArrayInterface.static_strides(parent(x))[1] @test @inferred(StaticArrayInterface.axes_types(x, static(:x))) <: Base.OneTo{Int} @test StaticArrayInterface.axes_types(x, :x) <: Base.OneTo{Int} @test @inferred(StaticArrayInterface.axes_types(LinearIndices{2,NTuple{2,Base.OneTo{Int}}})) <: NTuple{2,Base.OneTo{Int}} CI = CartesianIndices{2,Tuple{Base.OneTo{Int},UnitRange{Int}}} @test @inferred(StaticArrayInterface.axes_types(CI, static(1))) <: Base.OneTo{Int} x[x=1] = [2, 3] @test @inferred(getindex(x, x=1)) == [2, 3] y = NamedDimsWrapper((:x, static(:y)), ones(2, 2)) # FIXME this doesn't correctly infer the output because it can't infer @test getindex(y, x=1) == [1, 1] end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
16350
@testset "to_index" begin axis = 1:3 @test @inferred(StaticArrayInterface.to_index(axis, 1)) === 1 @test @inferred(StaticArrayInterface.to_index(axis, static(1))) === static(1) @test @inferred(StaticArrayInterface.to_index(axis, CartesianIndex(1))) === (1,) @test @inferred(StaticArrayInterface.to_index(axis, 1:2)) === 1:2 @test @inferred(StaticArrayInterface.to_index(axis, CartesianIndices((1:2,)))) == (1:2,) @test @inferred(StaticArrayInterface.to_index(axis, CartesianIndices((2:3,)))) == (2:3,) @test @inferred(StaticArrayInterface.to_index(axis, [1, 2])) == [1, 2] @test @inferred(StaticArrayInterface.to_index(axis, [true, false, false])) == [1] index = @inferred(StaticArrayInterface.to_index(axis, :)) @test @inferred(StaticArrayInterface.to_index(axis, index)) == index == StaticArrayInterface.indices(axis) x = LinearIndices((static(0):static(3), static(3):static(5), static(-2):static(0))) @test_throws ArgumentError StaticArrayInterface.to_index(axis, error) end @testset "unsafe_reconstruct" begin one_to = Base.OneTo(10) opt_ur = StaticInt(1):10 ur = 1:10 @test @inferred(StaticArrayInterface.unsafe_reconstruct(one_to, opt_ur)) === one_to @test @inferred(StaticArrayInterface.unsafe_reconstruct(one_to, one_to)) === one_to @test @inferred(StaticArrayInterface.unsafe_reconstruct(opt_ur, opt_ur)) === opt_ur @test @inferred(StaticArrayInterface.unsafe_reconstruct(opt_ur, one_to)) === opt_ur @test @inferred(StaticArrayInterface.unsafe_reconstruct(ur, ur)) === ur @test @inferred(StaticArrayInterface.unsafe_reconstruct(ur, one_to)) === ur end @testset "to_indices" begin a = ones(2, 2, 1) v = ones(2) @testset "linear indexing" begin @test @inferred(StaticArrayInterface.static_to_indices(a, (1,))) == (1,) @test @inferred(StaticArrayInterface.static_to_indices(a, (1:2,))) == (1:2,) @testset "Linear indexing doesn't ruin vector indexing" begin @test @inferred(StaticArrayInterface.static_to_indices(v, (1:2,))) == (1:2,) @test @inferred(StaticArrayInterface.static_to_indices(v, (1,))) == (1,) end end #@test @inferred(StaticArrayInterface.static_to_indices(a, (CartesianIndices(()),))) == (CartesianIndices(()),) inds = @inferred(StaticArrayInterface.static_to_indices(a, (:,))) @test @inferred(StaticArrayInterface.static_to_indices(a, inds)) == inds == (StaticArrayInterface.indices(a),) @test @inferred(StaticArrayInterface.static_to_indices(ones(2, 2, 2), ([true, true], CartesianIndex(1, 1)))) == ([1, 2], 1, 1) @test @inferred(StaticArrayInterface.static_to_indices(a, (1, 1))) == (1, 1) @test @inferred(StaticArrayInterface.static_to_indices(a, (1, CartesianIndex(1)))) == (1, 1) @test @inferred(StaticArrayInterface.static_to_indices(a, (1, false))) == (1, 0) @test @inferred(StaticArrayInterface.static_to_indices(a, (1, 1:2))) == (1, 1:2) @test @inferred(StaticArrayInterface.static_to_indices(a, (1:2, 1))) == (1:2, 1) @test @inferred(StaticArrayInterface.static_to_indices(a, (1, :))) == (1, Base.Slice(1:2)) @test @inferred(StaticArrayInterface.static_to_indices(a, (:, 1))) == (Base.Slice(1:2), 1) @test @inferred(StaticArrayInterface.static_to_indices(a, ([true, true], :))) == (Base.LogicalIndex(Bool[1, 1]), Base.Slice(1:2)) @test @inferred(StaticArrayInterface.static_to_indices(a, (CartesianIndices((1,)), 1))) == (1:1, 1) @test @inferred(StaticArrayInterface.static_to_indices(a, (1, 1, 1))) == (1, 1, 1) @test @inferred(StaticArrayInterface.static_to_indices(a, (1, fill(true, 2, 2)))) == Base.to_indices(a, (1, fill(true, 2, 2))) inds = @inferred(StaticArrayInterface.static_to_indices(a, (fill(true, 2, 2, 1),))) # Conversion to LogicalIndex doesn't change @test @inferred(StaticArrayInterface.static_to_indices(a, inds)) == inds @test @inferred(StaticArrayInterface.static_to_indices(a, (fill(true, 2, 1), 1))) == Base.to_indices(a, (fill(true, 2, 1), 1)) @test @inferred(StaticArrayInterface.static_to_indices(a, (fill(true, 2), 1, 1))) == Base.to_indices(a, (fill(true, 2), 1, 1)) @test @inferred(StaticArrayInterface.static_to_indices(a, ([CartesianIndex(1, 1, 1), CartesianIndex(1, 2, 1)],))) == (CartesianIndex{3}[CartesianIndex(1, 1, 1), CartesianIndex(1, 2, 1)],) @test @inferred(StaticArrayInterface.static_to_indices(a, ([CartesianIndex(1, 1), CartesianIndex(1, 2)], 1:1))) == (CartesianIndex{2}[CartesianIndex(1, 1), CartesianIndex(1, 2)], 1:1) @test @inferred(first(StaticArrayInterface.static_to_indices(a, (fill(true, 2, 2, 1),)))) isa Base.LogicalIndex end @testset "splat indexing" begin struct SplatFirst end StaticArrayInterface.to_index(x, ::SplatFirst) = map(first, axes(x)) StaticArrayInterface.is_splat_index(::Type{SplatFirst}) = true x = rand(4, 4, 4, 4, 4, 4, 4, 4, 4, 4); i = (1, SplatFirst(), 2, SplatFirst(), CartesianIndex(1, 1)) @test @inferred(StaticArrayInterface.static_to_indices(x, i)) == (1, 1, 1, 1, 1, 1, 2, 1, 1, 1) end @testset "to_axes" begin A = ones(3, 3) axis = StaticInt(1):StaticInt(3) inds = StaticInt(1):StaticInt(2) multi_inds = [CartesianIndex(1, 1), CartesianIndex(1, 2)] @test @inferred(StaticArrayInterface.to_axes(A, (axis, axis), (inds, inds))) === (inds, inds) # vector indexing @test @inferred(StaticArrayInterface.to_axes(ones(3), (axis,), (inds,))) === (inds,) # linear indexing @test @inferred(StaticArrayInterface.to_axes(A, (axis, axis), (inds,))) === (inds,) # multidim arg @test @inferred(StaticArrayInterface.to_axes(A, (axis, axis), (multi_inds,))) === (static(1):2,) @test StaticArrayInterface.to_axis(axis, axis) === axis @test StaticArrayInterface.to_axis(axis, StaticArrayInterface.indices(axis)) === axis @test @inferred(StaticArrayInterface.to_axes(A, (), (inds,))) === (inds,) end @testset "getindex with additional inds" begin A = reshape(1:12, (3, 4)) subA = view(A, :, :) LA = LinearIndices(A) CA = CartesianIndices(A) @test @inferred(StaticArrayInterface.static_getindex(A, 1, 1, 1)) == 1 @test @inferred(StaticArrayInterface.static_getindex(A, 1, 1, :)) == [1] @test @inferred(StaticArrayInterface.static_getindex(A, 1, 1, 1:1)) == [1] @test @inferred(StaticArrayInterface.static_getindex(A, 1, 1, :, :)) == ones(1, 1) @test @inferred(StaticArrayInterface.static_getindex(A, :, 1, 1)) == 1:3 @test @inferred(StaticArrayInterface.static_getindex(A, 2:3, 1, 1)) == 2:3 @test @inferred(StaticArrayInterface.static_getindex(A, static(1):2, 1, 1)) == 1:2 @test @inferred(StaticArrayInterface.static_getindex(A, :, 1, :)) == reshape(1:3, 3, 1) @test @inferred(StaticArrayInterface.static_getindex(subA, 1, 1, 1)) == 1 @test @inferred(StaticArrayInterface.static_getindex(subA, 1, 1, :)) == [1] @test @inferred(StaticArrayInterface.static_getindex(subA, 1, 1, 1:1)) == [1] @test @inferred(StaticArrayInterface.static_getindex(subA, 1, 1, :, :)) == ones(1, 1) @test @inferred(StaticArrayInterface.static_getindex(subA, :, 1, 1)) == 1:3 @test @inferred(StaticArrayInterface.static_getindex(subA, 2:3, 1, 1)) == 2:3 @test @inferred(StaticArrayInterface.static_getindex(subA, static(1):2, 1, 1)) == 1:2 @test @inferred(StaticArrayInterface.static_getindex(subA, :, 1, :)) == reshape(1:3, 3, 1) @test @inferred(StaticArrayInterface.static_getindex(LA, 1, 1, 1)) == 1 @test @inferred(StaticArrayInterface.static_getindex(LA, 1, 1, :)) == [1] @test @inferred(StaticArrayInterface.static_getindex(LA, 1, 1, 1:1)) == [1] @test @inferred(StaticArrayInterface.static_getindex(LA, 1, 1, :, :)) == ones(1, 1) @test @inferred(StaticArrayInterface.static_getindex(LA, :, 1, 1)) == 1:3 @test @inferred(StaticArrayInterface.static_getindex(LA, 2:3, 1, 1)) == 2:3 @test @inferred(StaticArrayInterface.static_getindex(LA, static(1):2, 1, 1)) == 1:2 @test @inferred(StaticArrayInterface.static_getindex(LA, :, 1, :)) == reshape(1:3, 3, 1) @test @inferred(StaticArrayInterface.static_getindex(CA, 1, 1, 1)) == CartesianIndex(1, 1) @test @inferred(StaticArrayInterface.static_getindex(CA, 1, 1, :)) == [CartesianIndex(1, 1)] @test @inferred(StaticArrayInterface.static_getindex(CA, 1, 1, 1:1)) == [CartesianIndex(1, 1)] @test @inferred(StaticArrayInterface.static_getindex(CA, 1, 1, :, :)) == fill(CartesianIndex(1, 1), 1, 1) @test @inferred(StaticArrayInterface.static_getindex(CA, :, 1, 1)) == reshape(CartesianIndex(1, 1):CartesianIndex(3, 1), 3) @test @inferred(StaticArrayInterface.static_getindex(CA, 2:3, 1, 1)) == reshape(CartesianIndex(2, 1):CartesianIndex(3, 1), 2) @test @inferred(StaticArrayInterface.static_getindex(CA, static(1):2, 1, 1)) == reshape(CartesianIndex(1, 1):CartesianIndex(2, 1), 2) @test @inferred(StaticArrayInterface.static_getindex(CA, :, 1, :)) == reshape(CartesianIndex(1, 1):CartesianIndex(3, 1), 3, 1) end @testset "0-dimensional" begin x = Array{Int,0}(undef) StaticArrayInterface.setindex!(x, 1) @test @inferred(StaticArrayInterface.static_getindex(x)) == 1 end @testset "1-dimensional" begin for i = 1:3 @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((3,)), i)) == i @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices((3,)), i)) == CartesianIndex(i,) end @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((3,)), 2, 1)) == 2 @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((3,)), [1])) == [1] # !!NOTE!! this is different than Base.getindex(::LinearIndices, ::AbstractUnitRange) # which returns a UnitRange. Instead we try to preserve axes if at all possible so the # values are the same but it's still wrapped in LinearIndices struct @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((3,)), 1:2)) == 1:2 @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((3,)), 1:2:3)) === 1:2:3 @test_throws BoundsError StaticArrayInterface.static_getindex(LinearIndices((3,)), 2:4) @test_throws BoundsError StaticArrayInterface.static_getindex(CartesianIndices((3,)), 2, 2) # ambiguity btw cartesian indexing and linear indexing in 1d when # indices may be nontraditional # TODO should this be implemented in ArrayInterface with vectorization? #@test_throws ArgumentError Base._sub2ind((1:3,), 2) #@test_throws ArgumentError Base._ind2sub((1:3,), 2) x = Array{Int,2}(undef, (2, 2)) StaticArrayInterface.unsafe_setindex!(x, 1, 2, 2) @test StaticArrayInterface.unsafe_getindex(x, 2, 2) === 1 # FIXME @test_throws MethodError StaticArrayInterface.unsafe_set_element!(x, 1, (:x, :x)) # FIXME @test_throws MethodError StaticArrayInterface.unsafe_get_element(x, (:x, :x)) end @testset "2-dimensional" begin k = 0 cartesian = CartesianIndices((4, 3)) linear = LinearIndices(cartesian) for j = 1:3, i = 1:4 k += 1 @test @inferred(StaticArrayInterface.static_getindex(linear, i, j)) == StaticArrayInterface.static_getindex(linear, k) == k @test @inferred(StaticArrayInterface.static_getindex(cartesian, k)) == CartesianIndex(i, j) @test @inferred(StaticArrayInterface.static_getindex(LinearIndices(map(Base.Slice, (0:3, 3:5))), i - 1, j + 2)) == k @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices(map(Base.Slice, (0:3, 3:5))), k)) == CartesianIndex(i - 1, j + 2) end x = LinearIndices(map(Base.Slice, (static(0):static(3), static(3):static(5), static(-2):static(0)))) if VERSION >= v"1.7" @test @inferred(StaticArrayInterface.static_getindex(x, 0, 3, -2)) === 1 else @test StaticArrayInterface.static_getindex(x, 0, 3, -2) === 1 end @test @inferred(StaticArrayInterface.static_getindex(x, static(0), static(3), static(-2))) === 1 @test @inferred(StaticArrayInterface.static_getindex(linear, linear)) == linear @test @inferred(StaticArrayInterface.static_getindex(linear, vec(linear))) == vec(linear) @test @inferred(StaticArrayInterface.static_getindex(linear, cartesian)) == linear @test @inferred(StaticArrayInterface.static_getindex(linear, vec(cartesian))) == vec(linear) @test @inferred(StaticArrayInterface.static_getindex(cartesian, linear)) == cartesian @test @inferred(StaticArrayInterface.static_getindex(cartesian, vec(linear))) == vec(cartesian) @test @inferred(StaticArrayInterface.static_getindex(cartesian, cartesian)) == cartesian @test @inferred(StaticArrayInterface.static_getindex(cartesian, vec(cartesian))) == vec(cartesian) @test @inferred(StaticArrayInterface.static_getindex(linear, 2:3)) === 2:3 @test @inferred(StaticArrayInterface.static_getindex(linear, 3:-1:1)) === 3:-1:1 @test @inferred(StaticArrayInterface.static_getindex(linear, >(1), <(3))) == linear[(begin+1):end, 1:(end-1)] @test @inferred(StaticArrayInterface.static_getindex(linear, >=(1), <=(3))) == linear[begin:end, 1:end] @test_throws BoundsError StaticArrayInterface.static_getindex(linear, 4:13) end @testset "3-dimensional" begin l = 0 for k = 1:2, j = 1:3, i = 1:4 l += 1 @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((4, 3, 2)), i, j, k)) == l @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((4, 3, 2)), l)) == l @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices((4, 3, 2)), i, j, k)) == CartesianIndex(i, j, k) @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices((4, 3, 2)), l)) == CartesianIndex(i, j, k) @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((1:4, 1:3, 1:2)), i, j, k)) == l @test @inferred(StaticArrayInterface.static_getindex(LinearIndices((1:4, 1:3, 1:2)), l)) == l @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices((1:4, 1:3, 1:2)), i, j, k)) == CartesianIndex(i, j, k) @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices((1:4, 1:3, 1:2)), l)) == CartesianIndex(i, j, k) end l = 0 for k = -101:-100, j = 3:5, i = 0:3 l += 1 @test @inferred(StaticArrayInterface.static_getindex(LinearIndices(map(Base.Slice, (0:3, 3:5, -101:-100))), i, j, k)) == l @test @inferred(StaticArrayInterface.static_getindex(LinearIndices(map(Base.Slice, (0:3, 3:5, -101:-100))), l)) == l @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices(map(Base.Slice, (0:3, 3:5, -101:-100))), i, j, k)) == CartesianIndex(i, j, k) @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices(map(Base.Slice, (0:3, 3:5, -101:-100))), l)) == CartesianIndex(i, j, k) end local A = reshape(Vector(1:9), (3, 3)) @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices(size(A)), 6)) == CartesianIndex(3, 2) @test @inferred(StaticArrayInterface.static_getindex(LinearIndices(size(A)), 3, 2)) == 6 @test @inferred(StaticArrayInterface.static_getindex(CartesianIndices(A), 6)) == CartesianIndex(3, 2) @test @inferred(StaticArrayInterface.static_getindex(LinearIndices(A), 3, 2)) == 6 for i in 1:length(A) @test @inferred(StaticArrayInterface.static_getindex(LinearIndices(A), StaticArrayInterface.static_getindex(CartesianIndices(A), i))) == i end end A = zeros(3, 4, 5); A[:] = 1:60 Ap = @view(PermutedDimsArray(A, (3, 1, 2))[:, 1:2, 1])'; S = MArray(zeros(2, 3, 4)) A_trailingdim = zeros(2, 3, 4, 1) Sp = @view(PermutedDimsArray(S, (3, 1, 2))[2:3, 1:2, :]); Sp2 = @view(PermutedDimsArray(S, (3, 2, 1))[2:3, :, :]); Mp = @view(PermutedDimsArray(S, (3, 1, 2))[:, 2, :])'; Mp2 = @view(PermutedDimsArray(S, (3, 1, 2))[2:3, :, 2])'; D = @view(A[:, 2:2:4, :]); R = StaticInt(1):StaticInt(2); Rnr = reinterpret(Int32, R); Ar = reinterpret(Float32, A); A2 = zeros(4, 3, 5) A2r = reinterpret(ComplexF64, A2) irev = Iterators.reverse(S) igen = Iterators.map(identity, S) iacc = Iterators.accumulate(+, S) iprod = Iterators.product(axes(S)...) iflat = Iterators.flatten(iprod) ienum = enumerate(S) ipairs = pairs(S) izip = zip(S, S) sv5 = MArray(zeros(5)); v5 = Vector{Float64}(undef, 5);
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
1099
@testset "known values" begin CI = CartesianIndices((2, 2)) @test isnothing(@inferred(StaticArrayInterface.known_first(typeof(1:4)))) @test isone(@inferred(StaticArrayInterface.known_first(Base.OneTo(4)))) @test isone(@inferred(StaticArrayInterface.known_first(typeof(Base.OneTo(4))))) @test @inferred(StaticArrayInterface.known_first(typeof(CI))) == CartesianIndex(1, 1) @test @inferred(StaticArrayInterface.known_first(typeof(CI))) == CartesianIndex(1, 1) @test isnothing(@inferred(StaticArrayInterface.known_last(1:4))) @test isnothing(@inferred(StaticArrayInterface.known_last(typeof(1:4)))) @test @inferred(StaticArrayInterface.known_last(typeof(CI))) === nothing @test isnothing(@inferred(StaticArrayInterface.known_step(typeof(1:0.2:4)))) @test isone(@inferred(StaticArrayInterface.known_step(1:4))) @test isone(@inferred(StaticArrayInterface.known_step(typeof(1:4)))) @test isone(@inferred(StaticArrayInterface.known_step(typeof(Base.Slice(1:4))))) @test isone(@inferred(StaticArrayInterface.known_step(typeof(view(1:4, 1:2))))) end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
965
@testset "insert/deleteat" begin @test @inferred(StaticArrayInterface.insert([1,2,3], 2, -2)) == [1, -2, 2, 3] @test @inferred(StaticArrayInterface.deleteat([1, 2, 3], 2)) == [1, 3] @test @inferred(StaticArrayInterface.deleteat([1, 2, 3], [1, 2])) == [3] @test @inferred(StaticArrayInterface.deleteat([1, 2, 3], [1, 3])) == [2] @test @inferred(StaticArrayInterface.deleteat([1, 2, 3], [2, 3])) == [1] @test @inferred(StaticArrayInterface.insert((2,3,4), 1, -2)) == (-2, 2, 3, 4) @test @inferred(StaticArrayInterface.insert((2,3,4), 2, -2)) == (2, -2, 3, 4) @test @inferred(StaticArrayInterface.insert((2,3,4), 3, -2)) == (2, 3, -2, 4) @test @inferred(StaticArrayInterface.deleteat((2, 3, 4), 1)) == (3, 4) @test @inferred(StaticArrayInterface.deleteat((2, 3, 4), 2)) == (2, 4) @test @inferred(StaticArrayInterface.deleteat((2, 3, 4), 3)) == (2, 3) @test StaticArrayInterface.deleteat((1, 2, 3), [1, 2]) == (3,) end
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git
[ "MIT" ]
1.8.0
96381d50f1ce85f2663584c8e886a6ca97e60554
code
2120
using StaticArrayInterface using OffsetArrays using Static using Test A = zeros(3, 4, 5); O = OffsetArray(A, 3, 7, 10); Op = PermutedDimsArray(O,(3,1,2)); @test @inferred(StaticArrayInterface.offsets(O)) === (4, 8, 11) @test @inferred(StaticArrayInterface.offsets(Op)) === (11, 4, 8) @test @inferred(StaticArrayInterface.static_to_indices(O, (:, :, :))) == (4:6, 8:11, 11:15) @test @inferred(StaticArrayInterface.static_to_indices(Op, (:, :, :))) == (11:15, 4:6, 8:11) @test @inferred(StaticArrayInterface.offsets((1,2,3))) === (StaticInt(1),) o = OffsetArray(vec(A), 8); @test @inferred(StaticArrayInterface.offset1(o)) === 9 @test @inferred(StaticArrayInterface.device(OffsetArray(view(PermutedDimsArray(A, (3,1,2)), 1, :, 2:4)', 3, -173))) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.device(view(OffsetArray(A,2,3,-12), 4, :, -11:-9))) === StaticArrayInterface.CPUPointer() @test @inferred(StaticArrayInterface.device(view(OffsetArray(A,2,3,-12), 3, :, [-11,-10,-9])')) === StaticArrayInterface.CPUIndex() @test @inferred(StaticArrayInterface.indices(OffsetArray(view(PermutedDimsArray(A, (3,1,2)), 1, :, 2:4)', 3, -173),1)) === Base.Slice(Static.OptionallyStaticUnitRange(4,6)) @test @inferred(StaticArrayInterface.indices(OffsetArray(view(PermutedDimsArray(A, (3,1,2)), 1, :, 2:4)', 3, -173),2)) === Base.Slice(Static.OptionallyStaticUnitRange(-172,-170)) @test @inferred(StaticArrayInterface.device(OffsetArray(1:10))) === StaticArrayInterface.CPUIndex() @test @inferred(StaticArrayInterface.device(OffsetArray(@view(reshape(1:8, 2,2,2)[1,1:2,:]),-3,4))) === StaticArrayInterface.CPUIndex() @test @inferred(StaticArrayInterface.device(OffsetArray(zeros(2,2,2),8,-2,-5))) === StaticArrayInterface.CPUPointer() offset_view = @view OffsetArrays.centered(zeros(eltype(A), 5, 5))[:, begin]; # SubArray of OffsetArray @test @inferred(StaticArrayInterface.offsets(offset_view)) == (-2,) B = OffsetArray(PermutedDimsArray(rand(2,3,4), (2,3,1))); @test @inferred(StaticArrayInterface.StrideIndex(B)) === StaticArrayInterface.StrideIndex{3, (2, 3, 1), 3}((2, 6, static(1)), (1, 1, 1))
StaticArrayInterface
https://github.com/JuliaArrays/StaticArrayInterface.jl.git