JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.4k stars 5.45k forks source link

Feature request: `isconstant` function or macro #50176

Open ojwoodford opened 1 year ago

ojwoodford commented 1 year ago

It would be useful to have an isconstant function or macro which returns true if the input is a constant, otherwise returns false. What do I mean by "constant"? I mean that if v is not a constant, then somefunc(Val(v)) will trigger a dynamic dispatch, otherwise it won't.

Having such a function/macro would enable at least two useful things:

ojwoodford commented 1 year ago

The StaticInt functionality would provide an alternative mechanism for compile-time branching to faster code if a value is constant. However, I'm not sure it would help with detecting constant propagation regressions.

MasonProtter commented 1 year ago

This thread https://discourse.julialang.org/t/branch-on-whether-a-value-is-known-to-the-compiler/34850 lays out the usecase and expecation pretty clearly. i.e.

@inline function ^(x, p::Integer)
    if @isconstant p
       literal_pow(^, x, Val(p))
    else
       power_by_squaring(x, p)
    end
end

this says that if p is a constant known to the compiler, then we do code generation based on it's value via literal_pow but if it's not a constant then we do the slower power_by_squaring.

A lot like if @generated but for values.

jishnub commented 1 year ago

I'm not sure it would help with detecting constant propagation regressions.

Would this not be possible using JET?