Skip to content

Commit 04655dc

Browse files
committed
inference: inter-procedural conditional constraint back-propagation
This PR propagates `Conditional`s inter-procedurally when a `Conditional` at return site imposes a constraint on the call arguments. When inference exits local frame and the return type is annotated as `Conditional`, it will be converted into `InterConditional` object, which is implemented in `Core` and can be directly put into the global cache. Finally after going back to caller frame, `InterConditional` will be re-converted into `Conditional` in the context of the caller frame. So now some simple "is-wrapper" functions will propagate its constraint as expected, e.g.: ```julia isaint(a) = isa(a, Int) @test Base.return_types((Any,)) do a isaint(a) && return a # a::Int return 0 end == [Int] ``` This PR also tweaks `isnothing` and `ismissing` so that there is no longer any inferrability penalties to use them instead of `x === nothing` or `x === missing` e.g.: ```julia @test Base.return_types((Union{Nothing,Int},)) do a isnothing(a) && return 0 return a # a::Int end == [Int] ``` (and now we don't need something like #38636) There're certain limitations around. One of the biggest ones would be that it can propagate constrains only on a single argument, and it fails to back-propagate constrains when there're multiple conditions on different slots, e.g. `Meta.isexpr` can't still propagate its type constraint to the caller: ```julia @test_broken Base.return_types((Any,)) do x Meta.isexpr(x, :call) && return x # still x::Any but ideally x::Expr return nothing end == [Nothing,Expr] ``` (and because of this reason, this PR can't close #37342)
1 parent 3853060 commit 04655dc

File tree

14 files changed

+161
-36
lines changed

14 files changed

+161
-36
lines changed

base/boot.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,7 @@ eval(Core, :(CodeInstance(mi::MethodInstance, @nospecialize(rettype), @nospecial
424424
mi, rettype, inferred_const, inferred, const_flags, min_world, max_world)))
425425
eval(Core, :(Const(@nospecialize(v)) = $(Expr(:new, :Const, :v))))
426426
eval(Core, :(PartialStruct(@nospecialize(typ), fields::Array{Any, 1}) = $(Expr(:new, :PartialStruct, :typ, :fields))))
427+
eval(Core, :(InterConditional(slot::Int, @nospecialize(vtype), @nospecialize(elsetype)) = $(Expr(:new, :InterConditional, :slot, :vtype, :elsetype))))
427428
eval(Core, :(MethodMatch(@nospecialize(spec_types), sparams::SimpleVector, method::Method, fully_covers::Bool) =
428429
$(Expr(:new, :MethodMatch, :spec_types, :sparams, :method, :fully_covers))))
429430

base/compiler/abstractinterpretation.jl

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ function is_improvable(@nospecialize(rtype))
2424
# already at Bottom
2525
return rtype !== Union{}
2626
end
27-
# Could be improved to `Const` or a more precise PartialStruct
28-
return isa(rtype, PartialStruct)
27+
# Could be improved to `Const` or a more precise wrapper
28+
return isa(rtype, PartialStruct) || isa(rtype, InterConditional)
2929
end
3030

3131
function abstract_call_gf_by_type(interp::AbstractInterpreter, @nospecialize(f), argtypes::Vector{Any}, @nospecialize(atype), sv::InferenceState,
@@ -1144,7 +1144,10 @@ function abstract_eval_statement(interp::AbstractInterpreter, @nospecialize(e),
11441144
end
11451145
callinfo = abstract_call(interp, ea, argtypes, sv)
11461146
sv.stmt_info[sv.currpc] = callinfo.info
1147-
t = callinfo.rt
1147+
rt = callinfo.rt
1148+
t = isa(rt, InterConditional) ?
1149+
transform_from_interconditional(rt, ea) :
1150+
rt
11481151
elseif e.head === :new
11491152
t = instanceof_tfunc(abstract_eval_value(interp, e.args[1], vtypes, sv))[1]
11501153
if isconcretetype(t) && !t.mutable
@@ -1255,6 +1258,19 @@ function abstract_eval_statement(interp::AbstractInterpreter, @nospecialize(e),
12551258
return t
12561259
end
12571260

1261+
# try to convert interprocedural-conditional constraint from callee into constraints for
1262+
# the current frame
1263+
function transform_from_interconditional(rt::InterConditional, ea::Vector{Any})
1264+
i = rt.slot
1265+
if checkbounds(Bool, ea, i)
1266+
e = @inbounds ea[i]
1267+
if isa(e, Slot)
1268+
return Conditional(e, rt.vtype, rt.elsetype)
1269+
end
1270+
end
1271+
return widenconditional(rt)
1272+
end
1273+
12581274
function abstract_eval_global(M::Module, s::Symbol)
12591275
if isdefined(M,s) && isconst(M,s)
12601276
return Const(getfield(M,s))
@@ -1338,10 +1354,15 @@ function typeinf_local(interp::AbstractInterpreter, frame::InferenceState)
13381354
end
13391355
elseif isa(stmt, ReturnNode)
13401356
pc´ = n + 1
1341-
rt = widenconditional(abstract_eval_value(interp, stmt.val, s[pc], frame))
1342-
if !isa(rt, Const) && !isa(rt, Type) && !isa(rt, PartialStruct)
1357+
rt = abstract_eval_value(interp, stmt.val, s[pc], frame)
1358+
if !isa(rt, Const) &&
1359+
!isa(rt, Type) &&
1360+
!isa(rt, PartialStruct) &&
1361+
!isa(rt, Conditional)
13431362
# only propagate information we know we can store
13441363
# and is valid inter-procedurally
1364+
# some of them will further be transformed by `bestguess_to_interprocedural`
1365+
# in `finish(::InferenceState, ::AbstractInterpreter)`
13451366
rt = widenconst(rt)
13461367
end
13471368
if tchanged(rt, frame.bestguess)

base/compiler/tfuncs.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1649,6 +1649,9 @@ function return_type_tfunc(interp::AbstractInterpreter, argtypes::Vector{Any}, s
16491649
return Const(Union{})
16501650
end
16511651
rt = abstract_call(interp, nothing, argtypes_vec, sv, -1).rt
1652+
if isa(rt, InterConditional)
1653+
rt = widenconditional(rt)
1654+
end
16521655
if isa(rt, Const)
16531656
# output was computed to be constant
16541657
return Const(typeof(rt.val))

base/compiler/typeinfer.jl

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -286,28 +286,32 @@ end
286286
function CodeInstance(result::InferenceResult, @nospecialize(inferred_result::Any),
287287
valid_worlds::WorldRange)
288288
local const_flags::Int32
289+
res = result.result
289290
if inferred_result isa Const
290291
# use constant calling convention
291292
rettype_const = (result.src::Const).val
292293
const_flags = 0x3
293294
inferred_result = nothing
294295
else
295-
if isa(result.result, Const)
296-
rettype_const = (result.result::Const).val
296+
if isa(res, Const)
297+
rettype_const = res.val
297298
const_flags = 0x2
298-
elseif isconstType(result.result)
299-
rettype_const = result.result.parameters[1]
299+
elseif isconstType(res)
300+
rettype_const = res.parameters[1]
300301
const_flags = 0x2
301-
elseif isa(result.result, PartialStruct)
302-
rettype_const = (result.result::PartialStruct).fields
302+
elseif isa(res, PartialStruct)
303+
rettype_const = res.fields
304+
const_flags = 0x2
305+
elseif isa(res, InterConditional)
306+
rettype_const = res
303307
const_flags = 0x2
304308
else
305309
rettype_const = nothing
306310
const_flags = 0x00
307311
end
308312
end
309313
return CodeInstance(result.linfo,
310-
widenconst(result.result), rettype_const, inferred_result,
314+
widenconst(res), rettype_const, inferred_result,
311315
const_flags, first(valid_worlds), last(valid_worlds))
312316
end
313317

@@ -412,10 +416,22 @@ function finish(me::InferenceState, interp::AbstractInterpreter)
412416
me.result.src = OptimizationState(me, OptimizationParams(interp), interp)
413417
end
414418
me.result.valid_worlds = me.valid_worlds
415-
me.result.result = me.bestguess
419+
me.result.result = me.bestguess =
420+
bestguess_to_interprocedural(me.bestguess, length(me.result.argtypes))
416421
nothing
417422
end
418423

424+
bestguess_to_interprocedural(@nospecialize(bestguess), _) = bestguess
425+
function bestguess_to_interprocedural(bestguess::Conditional, nargs::Int)
426+
# keep `Conditional` return type only when it constrains any of call argument
427+
i = slot_id(bestguess.var)
428+
if 1 < i nargs
429+
return InterConditional(i, bestguess.vtype, bestguess.elsetype)
430+
else
431+
return widenconditional(bestguess)
432+
end
433+
end
434+
419435
function finish(src::CodeInfo, interp::AbstractInterpreter)
420436
# convert all type information into the form consumed by the cache for inlining and code-generation
421437
widen_all_consts!(src)
@@ -724,14 +740,18 @@ function typeinf_edge(interp::AbstractInterpreter, method::Method, @nospecialize
724740
code = get(code_cache(interp), mi, nothing)
725741
if code isa CodeInstance # return existing rettype if the code is already inferred
726742
update_valid_age!(caller, WorldRange(min_world(code), max_world(code)))
743+
rettype = code.rettype
727744
if isdefined(code, :rettype_const)
728-
if isa(code.rettype_const, Vector{Any}) && !(Vector{Any} <: code.rettype)
729-
return PartialStruct(code.rettype, code.rettype_const), mi
745+
rettype_const = code.rettype_const
746+
if isa(rettype_const, InterConditional)
747+
return rettype_const, mi
748+
elseif isa(rettype_const, Vector{Any}) && !(Vector{Any} <: rettype)
749+
return PartialStruct(rettype, rettype_const), mi
730750
else
731-
return Const(code.rettype_const), mi
751+
return Const(rettype_const), mi
732752
end
733753
else
734-
return code.rettype, mi
754+
return rettype, mi
735755
end
736756
end
737757
if ccall(:jl_get_module_infer, Cint, (Any,), method.module) == 0
@@ -802,7 +822,8 @@ function typeinf_ext(interp::AbstractInterpreter, mi::MethodInstance)
802822
if invoke_api(code) == 2
803823
i == 2 && ccall(:jl_typeinf_end, Cvoid, ())
804824
tree = ccall(:jl_new_code_info_uninit, Ref{CodeInfo}, ())
805-
tree.code = Any[ ReturnNode(quoted(code.rettype_const)) ]
825+
rettype_const = code.rettype_const
826+
tree.code = Any[ ReturnNode(quoted(rettype_const)) ]
806827
nargs = Int(method.nargs)
807828
tree.slotnames = ccall(:jl_uncompress_argnames, Vector{Symbol}, (Any,), method.slot_syms)
808829
tree.slotflags = fill(0x00, nargs)
@@ -814,7 +835,7 @@ function typeinf_ext(interp::AbstractInterpreter, mi::MethodInstance)
814835
tree.pure = true
815836
tree.inlineable = true
816837
tree.parent = mi
817-
tree.rettype = Core.Typeof(code.rettype_const)
838+
tree.rettype = Core.Typeof(widenconditional(rettype_const))
818839
tree.min_world = code.min_world
819840
tree.max_world = code.max_world
820841
return tree

base/compiler/typelattice.jl

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# structs/constants #
55
#####################
66

7-
# N.B.: Const/PartialStruct are defined in Core, to allow them to be used
7+
# N.B.: Const/PartialStruct/InterConditional are defined in Core, to allow them to be used
88
# inside the global code cache.
99
#
1010
# # The type of a value might be constant
@@ -18,7 +18,6 @@
1818
# end
1919
import Core: Const, PartialStruct
2020

21-
2221
# The type of this value might be Bool.
2322
# However, to enable a limited amount of back-propagagation,
2423
# we also keep some information about how this Bool value was created.
@@ -45,6 +44,15 @@ struct Conditional
4544
end
4645
end
4746

47+
# # similar to `Conditional`, but conveys inter-procedural constrains imposed on call arguments
48+
# struct InterConditional
49+
# slot::Int
50+
# vtype
51+
# elsetype
52+
# end
53+
import Core: InterConditional
54+
const AnyConditional = Union{Conditional,InterConditional}
55+
4856
struct PartialTypeVar
4957
tv::TypeVar
5058
# N.B.: Currently unused, but would allow turning something back
@@ -90,11 +98,8 @@ const CompilerTypes = Union{MaybeUndef, Const, Conditional, NotFound, PartialStr
9098
# lattice logic #
9199
#################
92100

93-
function issubconditional(a::Conditional, b::Conditional)
94-
avar = a.var
95-
bvar = b.var
96-
if (isa(avar, Slot) && isa(bvar, Slot) && slot_id(avar) === slot_id(bvar)) ||
97-
(isa(avar, SSAValue) && isa(bvar, SSAValue) && avar === bvar)
101+
function issubconditional(a::AnyConditional, b::AnyConditional)
102+
if is_same_conditionals(a, b)
98103
if a.vtype b.vtype
99104
if a.elsetype b.elsetype
100105
return true
@@ -103,9 +108,13 @@ function issubconditional(a::Conditional, b::Conditional)
103108
end
104109
return false
105110
end
111+
is_same_conditionals(a::Conditional, b::Conditional) = slot_id(a.var) === slot_id(b.var)
112+
is_same_conditionals(a::Conditional, b::InterConditional) = slot_id(a.var) === b.slot
113+
is_same_conditionals(a::InterConditional, b::Conditional) = is_same_conditionals(b, a)
114+
is_same_conditionals(a::InterConditional, b::InterConditional) = a.slot === b.slot
106115

107116
maybe_extract_const_bool(c::Const) = isa(c.val, Bool) ? c.val : nothing
108-
function maybe_extract_const_bool(c::Conditional)
117+
function maybe_extract_const_bool(c::AnyConditional)
109118
(c.vtype === Bottom && !(c.elsetype === Bottom)) && return false
110119
(c.elsetype === Bottom && !(c.vtype === Bottom)) && return true
111120
nothing
@@ -122,14 +131,14 @@ function ⊑(@nospecialize(a), @nospecialize(b))
122131
(a === Any || b === NOT_FOUND) && return false
123132
a === Union{} && return true
124133
b === Union{} && return false
125-
if isa(a, Conditional)
126-
if isa(b, Conditional)
134+
if isa(a, AnyConditional)
135+
if isa(b, AnyConditional)
127136
return issubconditional(a, b)
128137
elseif isa(b, Const) && isa(b.val, Bool)
129138
return maybe_extract_const_bool(a) === b.val
130139
end
131140
a = Bool
132-
elseif isa(b, Conditional)
141+
elseif isa(b, AnyConditional)
133142
return false
134143
end
135144
if isa(a, PartialStruct)
@@ -204,7 +213,7 @@ function is_lattice_equal(@nospecialize(a), @nospecialize(b))
204213
return a b && b a
205214
end
206215

207-
widenconst(c::Conditional) = Bool
216+
widenconst(c::AnyConditional) = Bool
208217
function widenconst(c::Const)
209218
if isa(c.val, Type)
210219
if isvarargtype(c.val)
@@ -237,7 +246,7 @@ end
237246
@inline schanged(@nospecialize(n), @nospecialize(o)) = (n !== o) && (o === NOT_FOUND || (n !== NOT_FOUND && !issubstate(n, o)))
238247

239248
widenconditional(@nospecialize typ) = typ
240-
function widenconditional(typ::Conditional)
249+
function widenconditional(typ::AnyConditional)
241250
if typ.vtype === Union{}
242251
return Const(false)
243252
elseif typ.elsetype === Union{}

base/compiler/typelimits.jl

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,35 @@ function tmerge(@nospecialize(typea), @nospecialize(typeb))
327327
end
328328
return Bool
329329
end
330+
# type-lattice for InterConditional wrapper, InterConditional won't be merged with Conditional
331+
if isa(typea, InterConditional) && isa(typeb, Const)
332+
if typeb.val === true
333+
typeb = InterConditional(typea.slot, Any, Union{})
334+
elseif typeb.val === false
335+
typeb = InterConditional(typea.slot, Union{}, Any)
336+
end
337+
end
338+
if isa(typeb, InterConditional) && isa(typea, Const)
339+
if typea.val === true
340+
typea = InterConditional(typeb.slot, Any, Union{})
341+
elseif typea.val === false
342+
typea = InterConditional(typeb.slot, Union{}, Any)
343+
end
344+
end
345+
if isa(typea, InterConditional) && isa(typeb, InterConditional)
346+
if typea.slot === typeb.slot
347+
vtype = tmerge(typea.vtype, typeb.vtype)
348+
elsetype = tmerge(typea.elsetype, typeb.elsetype)
349+
if vtype != elsetype
350+
return InterConditional(typea.slot, vtype, elsetype)
351+
end
352+
end
353+
val = maybe_extract_const_bool(typea)
354+
if val isa Bool && val === maybe_extract_const_bool(typeb)
355+
return Const(val)
356+
end
357+
return Bool
358+
end
330359
if (isa(typea, PartialStruct) || isa(typea, Const)) &&
331360
(isa(typeb, PartialStruct) || isa(typeb, Const)) &&
332361
widenconst(typea) === widenconst(typeb)

base/essentials.jl

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -813,8 +813,7 @@ const missing = Missing()
813813
814814
Indicate whether `x` is [`missing`](@ref).
815815
"""
816-
ismissing(::Any) = false
817-
ismissing(::Missing) = true
816+
ismissing(x) = x === missing
818817

819818
function popfirst! end
820819

base/some.jl

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,7 @@ Return `true` if `x === nothing`, and return `false` if not.
6363
!!! compat "Julia 1.1"
6464
This function requires at least Julia 1.1.
6565
"""
66-
isnothing(::Any) = false
67-
isnothing(::Nothing) = true
66+
isnothing(x) = x === nothing
6867

6968

7069
"""

src/builtins.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1622,6 +1622,7 @@ void jl_init_primitives(void) JL_GC_DISABLED
16221622
add_builtin("Argument", (jl_value_t*)jl_argument_type);
16231623
add_builtin("Const", (jl_value_t*)jl_const_type);
16241624
add_builtin("PartialStruct", (jl_value_t*)jl_partial_struct_type);
1625+
add_builtin("InterConditional", (jl_value_t*)jl_interconditional_type);
16251626
add_builtin("MethodMatch", (jl_value_t*)jl_method_match_type);
16261627
add_builtin("IntrinsicFunction", (jl_value_t*)jl_intrinsic_type);
16271628
add_builtin("Function", (jl_value_t*)jl_function_type);

src/jl_exported_data.inc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070
XX(jl_nothing_type) \
7171
XX(jl_number_type) \
7272
XX(jl_partial_struct_type) \
73+
XX(jl_interconditional_type) \
7374
XX(jl_phicnode_type) \
7475
XX(jl_phinode_type) \
7576
XX(jl_pinode_type) \

src/jltypes.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2302,6 +2302,10 @@ void jl_init_types(void) JL_GC_DISABLED
23022302
jl_perm_symsvec(2, "typ", "fields"),
23032303
jl_svec2(jl_any_type, jl_array_any_type), 0, 0, 2);
23042304

2305+
jl_interconditional_type = jl_new_datatype(jl_symbol("InterConditional"), core, jl_any_type, jl_emptysvec,
2306+
jl_perm_symsvec(3, "slot", "vtype", "elsetype"),
2307+
jl_svec(3, jl_long_type, jl_any_type, jl_any_type), 0, 0, 3);
2308+
23052309
jl_method_match_type = jl_new_datatype(jl_symbol("MethodMatch"), core, jl_any_type, jl_emptysvec,
23062310
jl_perm_symsvec(4, "spec_types", "sparams", "method", "fully_covers"),
23072311
jl_svec(4, jl_type_type, jl_simplevector_type, jl_method_type, jl_bool_type), 0, 0, 4);

src/julia.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,7 @@ extern JL_DLLIMPORT jl_datatype_t *jl_typedslot_type JL_GLOBALLY_ROOTED;
619619
extern JL_DLLIMPORT jl_datatype_t *jl_argument_type JL_GLOBALLY_ROOTED;
620620
extern JL_DLLIMPORT jl_datatype_t *jl_const_type JL_GLOBALLY_ROOTED;
621621
extern JL_DLLIMPORT jl_datatype_t *jl_partial_struct_type JL_GLOBALLY_ROOTED;
622+
extern JL_DLLIMPORT jl_datatype_t *jl_interconditional_type JL_GLOBALLY_ROOTED;
622623
extern JL_DLLIMPORT jl_datatype_t *jl_method_match_type JL_GLOBALLY_ROOTED;
623624
extern JL_DLLIMPORT jl_datatype_t *jl_simplevector_type JL_GLOBALLY_ROOTED;
624625
extern JL_DLLIMPORT jl_typename_t *jl_tuple_typename JL_GLOBALLY_ROOTED;

src/staticdata.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ jl_value_t **const*const get_tags(void) {
6868
INSERT_TAG(jl_returnnode_type);
6969
INSERT_TAG(jl_const_type);
7070
INSERT_TAG(jl_partial_struct_type);
71+
INSERT_TAG(jl_interconditional_type);
7172
INSERT_TAG(jl_method_match_type);
7273
INSERT_TAG(jl_pinode_type);
7374
INSERT_TAG(jl_phinode_type);

0 commit comments

Comments
 (0)