Closed stevengj closed 10 years ago
On the other hand, it looks like isa
does, in fact, inline to a constant expression that gets optimized out. For example, with
f(x) = isa(x, Real) ? 1 : 2
if you do code_native(f, (Int,))
it is clear that the conditional has been optimized out.
Thanks to @carnaval for his improvements! Some things that are still not compiled statically:
g{T}(x::Array{T}) = isleaftype(T) ? 1 : 2
code_native(g, (Array{Int},))
or
g(x::Array) = isleaftype(eltype(x)) ? 1 : 2
code_native(g, (Array{Int,1},))
Another one that just bit me in #7125: type-inference is performed before dead-code elimination. Hence, for example:
julia> f(x) = isa(x, Integer) ? 1 : 1.0
f (generic function with 1 method)
julia> [f(i) for i in 1:2]
2-element Array{Union(Float64,Int64),1}:
1
1
instead of the return type being Array{Int}
.
Type inference and DCE can be iterated any number of times to improve the resulting code --- there is no one correct ordering. But doing constant prop as part of type inference would fix this case (constant prop being type inference with singleton types).
Another oddity:
f(x) = isa(x, Complex) ? 1 : 2
does not get statically evaluated, as code_native(f, (Int,))
shows, even though static evaluation worked for the isa(x, Real)
case above.
Update: Fixed by 98189bc6444898a341264bc6c02e9564b016e6db
This issue is covered by #6822 and #5560.
Right now, Julia does not seem to do a good job of partially evaluating type expressions that are known at compile time. For example:
should be compiled to
f(x) = 1
forf(3)
orf(x) = 2
forf(4+5im)
, butcode_native(f, (Int,))
reveals thatthis is not the case: in fact, the code for this function is quite involved.Fixed by #7088.It would be nice to have this work for cases where using dispatch is impractical, especially in macros. For example, as discussed in #7033, I would like to generalize the
@horner
macro to use a better algorithm for cases where the argument is complex but the coefficients are real, but it should inline to the correct code depending upon the argument type.Another example that should be possible to evaluate at compile time is:
Explicit
method_exists
checks are used, for example, inreducedim.jl
andmultimedia.jl
. (_It might be good to evaluate this statically only ifmethod_exists
returnstrue
, to preserve the current dynamic behavior._)A third example mentioned on the mailing list in the context of better type promotion for
Array*Number
forSIUnits
quantities is that it would be nice to haveisleaftype(T)
evaluated at compile time. (Partially fixed by #7088.)