-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathinference.jl
5269 lines (4985 loc) · 182 KB
/
inference.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: http://julialang.org/license
import Core: _apply, svec, apply_type, Builtin, IntrinsicFunction, MethodInstance
#### parameters limiting potentially-infinite types ####
const MAX_TYPEUNION_LEN = 3
const MAX_TYPE_DEPTH = 8
struct InferenceParams
world::UInt
# optimization
inlining::Bool
# parameters limiting potentially-infinite types (configurable)
MAX_TUPLETYPE_LEN::Int
MAX_TUPLE_DEPTH::Int
MAX_TUPLE_SPLAT::Int
MAX_UNION_SPLITTING::Int
MAX_APPLY_UNION_ENUM::Int
# reasonable defaults
function InferenceParams(world::UInt;
inlining::Bool = inlining_enabled(),
tupletype_len::Int = 15,
tuple_depth::Int = 4,
tuple_splat::Int = 16,
union_splitting::Int = 4,
apply_union_enum::Int = 8)
return new(world, inlining, tupletype_len,
tuple_depth, tuple_splat, union_splitting, apply_union_enum)
end
end
const UNION_SPLIT_MISMATCH_ERROR = false
# alloc_elim_pass! relies on `Slot_AssignedOnce | Slot_UsedUndef` being
# SSA. This should be true now but can break if we start to track conditional
# constants. e.g.
#
# cond && (a = 1)
# other_code()
# cond && use(a)
# slot property bit flags
const Slot_Assigned = 2
const Slot_AssignedOnce = 16
const Slot_UsedUndef = 32
#### inference state types ####
struct NotFound end
const NF = NotFound()
const LineNum = Int
const VarTable = Array{Any,1}
# The type of a variable load is either a value or an UndefVarError
mutable struct VarState
typ
undef::Bool
VarState(typ::ANY, undef::Bool) = new(typ, undef)
end
# The type of a value might be constant
struct Const
val
Const(v::ANY) = new(v)
end
# The type of a value might be Bool,
# but where the value of the boolean can be used in back-propagation to
# limit the type of some other variable
# The Conditional type tracks the set of branches on variable type info
# that was used to create the boolean condition
mutable struct Conditional
var::Union{Slot,SSAValue}
vtype
elsetype
function Conditional(
var::ANY,
vtype::ANY,
nottype::ANY)
return new(var, vtype, nottype)
end
end
struct PartialTypeVar
tv::TypeVar
# N.B.: Currently unused, but would allow turning something back
# into Const, if the bounds are pulled out of this TypeVar
lb_certain::Bool
ub_certain::Bool
PartialTypeVar(tv::TypeVar, lb_certain::Bool, ub_certain::Bool) = new(tv, lb_certain, ub_certain)
end
function rewrap(t::ANY, u::ANY)
isa(t, Const) && return t
isa(t, Conditional) && return t
return rewrap_unionall(t, u)
end
mutable struct InferenceState
sp::SimpleVector # static parameters
label_counter::Int # index of the current highest label for this function
mod::Module
currpc::LineNum
# info on the state of inference and the linfo
params::InferenceParams
linfo::MethodInstance # used here for the tuple (specTypes, env, Method)
src::CodeInfo
min_valid::UInt
max_valid::UInt
nargs::Int
stmt_types::Vector{Any}
stmt_edges::Vector{Any}
# return type
bestguess #::Type
# current active instruction pointers
ip::IntSet
pc´´::Int
nstmts::Int
# current exception handler info
cur_hand #::Tuple{LineNum, Tuple{LineNum, ...}}
handler_at::Vector{Any}
n_handlers::Int
# ssavalue sparsity and restart info
ssavalue_uses::Vector{IntSet}
ssavalue_init::Vector{Any}
# call-graph edges connecting from a caller to a callee (and back)
# we shouldn't need to iterate edges very often, so we use it to optimize the lookup from edge -> linenum
# whereas backedges is optimized for iteration
edges::ObjectIdDict # a Dict{InferenceState, Vector{LineNum}}
backedges::Vector{Tuple{InferenceState, Vector{LineNum}}}
# iteration fixed-point detection
fixedpoint::Bool
inworkq::Bool
const_api::Bool
const_ret::Bool
# TODO: put these in InferenceParams (depends on proper multi-methodcache support)
optimize::Bool
cached::Bool
inferred::Bool
# src is assumed to be a newly-allocated CodeInfo, that can be modified in-place to contain intermediate results
function InferenceState(linfo::MethodInstance, src::CodeInfo,
optimize::Bool, cached::Bool, params::InferenceParams)
code = src.code::Array{Any,1}
nl = label_counter(code) + 1
toplevel = !isdefined(linfo, :def)
if !toplevel && isempty(linfo.sparam_vals) && !isempty(linfo.def.sparam_syms)
# linfo is unspecialized
sp = Any[]
sig = linfo.def.sig
while isa(sig,UnionAll)
push!(sp, sig.var)
sig = sig.body
end
sp = svec(sp...)
else
sp = linfo.sparam_vals
end
src.ssavaluetypes = Any[ NF for i = 1:(src.ssavaluetypes::Int) ]
n = length(code)
s_edges = Any[ () for i = 1:n ]
s_types = Any[ () for i = 1:n ]
# initial types
nslots = length(src.slotnames)
s_types[1] = Any[ VarState(Bottom, true) for i = 1:nslots ]
src.slottypes = Any[ Bottom for i = 1:nslots ]
atypes = unwrap_unionall(linfo.specTypes)
nargs::Int = toplevel ? 0 : linfo.def.nargs
la = nargs
if la > 0
if linfo.def.isva
if atypes == Tuple
if la > 1
atypes = Tuple{Any[Any for i = 1:(la - 1)]..., Tuple.parameters[1]}
end
vararg_type = Tuple
else
vararg_type = limit_tuple_depth(params, tupletype_tail(atypes, la))
vararg_type = tuple_tfunc(vararg_type) # returns a Const object, if applicable
vararg_type = rewrap(vararg_type, linfo.specTypes)
end
s_types[1][la] = VarState(vararg_type, false)
src.slottypes[la] = widenconst(vararg_type)
la -= 1
end
end
laty = length(atypes.parameters)
if laty > 0
if laty > la
laty = la
end
local lastatype
atail = laty
for i = 1:laty
atyp = atypes.parameters[i]
if i == laty && isvarargtype(atyp)
atyp = unwrap_unionall(atyp).parameters[1]
atail -= 1
end
if isa(atyp, TypeVar)
atyp = atyp.ub
end
if isa(atyp, DataType) && isdefined(atyp, :instance)
# replace singleton types with their equivalent Const object
atyp = Const(atyp.instance)
else
atyp = rewrap_unionall(atyp, linfo.specTypes)
end
i == laty && (lastatype = atyp)
s_types[1][i] = VarState(atyp, false)
src.slottypes[i] = widenconst(atyp)
end
for i = (atail + 1):la
s_types[1][i] = VarState(lastatype, false)
src.slottypes[i] = widenconst(lastatype)
end
else
@assert la == 0 # wrong number of arguments
end
ssavalue_uses = find_ssavalue_uses(code)
ssavalue_init = copy(src.ssavaluetypes::Vector{Any})
# exception handlers
cur_hand = ()
handler_at = Any[ () for i=1:n ]
n_handlers = 0
W = IntSet()
push!(W, 1) #initial pc to visit
if !toplevel
meth = linfo.def
inmodule = meth.module
else
inmodule = current_module() # toplevel thunks are inferred in the current module
end
if cached && !toplevel
min_valid = min_world(linfo.def)
max_valid = max_world(linfo.def)
else
min_valid = typemax(UInt)
max_valid = typemin(UInt)
end
frame = new(
sp, nl, inmodule, 0, params,
linfo, src, min_valid, max_valid,
nargs, s_types, s_edges,
Union{}, W, 1, n,
cur_hand, handler_at, n_handlers,
ssavalue_uses, ssavalue_init,
ObjectIdDict(), # Dict{InferenceState, Vector{LineNum}}(),
Vector{Tuple{InferenceState, Vector{LineNum}}}(),
false, false, false, false, optimize, cached, false)
push!(active, frame)
nactive[] += 1
return frame
end
end
# create copies of the CodeInfo definition, and any fields that type-inference might modify
# TODO: post-inference see if we can swap back to the original arrays
function get_source(li::MethodInstance)
src = ccall(:jl_copy_code_info, Ref{CodeInfo}, (Any,), li.def.source)
if isa(src.code, Array{UInt8,1})
src.code = ccall(:jl_uncompress_ast, Any, (Any, Any), li.def, src.code)
else
src.code = copy_exprargs(src.code)
end
src.slotnames = copy(src.slotnames)
src.slotflags = copy(src.slotflags)
return src
end
function get_staged(li::MethodInstance)
src = ccall(:jl_code_for_staged, Any, (Any,), li)::CodeInfo
if isa(src.code, Array{UInt8,1})
src.code = ccall(:jl_uncompress_ast, Any, (Any, Any), li.def, src.code)
end
return src
end
#### current global inference state ####
const active = Vector{Any}() # set of all InferenceState objects being processed
const nactive = Array{Int}(())
nactive[] = 0
const workq = Vector{InferenceState}() # set of InferenceState objects that can make immediate progress
#### helper functions ####
@inline slot_id(s) = isa(s, SlotNumber) ? (s::SlotNumber).id : (s::TypedSlot).id # using a function to ensure we can infer this
# avoid cycle due to over-specializing `any` when used by inference
function _any(f::ANY, a)
for x in a
f(x) && return true
end
return false
end
function contains_is(itr, x::ANY)
for y in itr
if y === x
return true
end
end
return false
end
_topmod(sv::InferenceState) = _topmod(sv.mod)
_topmod(m::Module) = ccall(:jl_base_relative_to, Any, (Any,), m)::Module
function istopfunction(topmod, f::ANY, sym)
if isdefined(Main, :Base) && isdefined(Main.Base, sym) && f === getfield(Main.Base, sym)
return true
elseif isdefined(topmod, sym) && f === getfield(topmod, sym)
return true
end
return false
end
isknownlength(t::DataType) = !isvatuple(t) ||
(length(t.parameters) > 0 && isa(unwrap_unionall(t.parameters[end]).parameters[2],Int))
# t[n:end]
tupletype_tail(t::ANY, n) = Tuple{t.parameters[n:end]...}
#### type-functions for builtins / intrinsics ####
const _Type_name = Type.body.name
isType(t::ANY) = isa(t, DataType) && (t::DataType).name === _Type_name
# true if Type is inlineable as constant (is a singleton)
isconstType(t::ANY) = isType(t) && (isleaftype(t.parameters[1]) || t.parameters[1] === Union{})
const IInf = typemax(Int) # integer infinity
const n_ifunc = reinterpret(Int32,arraylen)+1
const t_ifunc = Array{Tuple{Int,Int,Any},1}(n_ifunc)
const t_ffunc_key = Array{Function,1}(0)
const t_ffunc_val = Array{Tuple{Int,Int,Any},1}(0)
function add_tfunc(f::IntrinsicFunction, minarg::Int, maxarg::Int, tfunc::ANY)
t_ifunc[reinterpret(Int32,f)+1] = (minarg, maxarg, tfunc)
end
function add_tfunc(f::Function, minarg::Int, maxarg::Int, tfunc::ANY)
push!(t_ffunc_key, f)
push!(t_ffunc_val, (minarg, maxarg, tfunc))
end
add_tfunc(throw, 1, 1, (x::ANY) -> Bottom)
# the inverse of typeof_tfunc
function instanceof_tfunc(t::ANY)
# TODO improve
if t === Bottom
return t
elseif isa(t, Const)
if isa(t.val, Type)
return t.val
end
elseif isType(t)
return t.parameters[1]
elseif isa(t,UnionAll)
t′ = unwrap_unionall(t)
return rewrap_unionall(instanceof_tfunc(t′), t)
elseif isa(t,Union)
return Union{instanceof_tfunc(t.a), instanceof_tfunc(t.b)}
end
return Any
end
bitcast_tfunc(t::ANY, x::ANY) = instanceof_tfunc(t)
math_tfunc(x::ANY) = widenconst(x)
math_tfunc(x::ANY, y::ANY) = widenconst(x)
math_tfunc(x::ANY, y::ANY, z::ANY) = widenconst(x)
fptoui_tfunc(t::ANY, x::ANY) = bitcast_tfunc(t, x)
fptosi_tfunc(t::ANY, x::ANY) = bitcast_tfunc(t, x)
function fptoui_tfunc(x::ANY)
T = widenconst(x)
T === Float64 && return UInt64
T === Float32 && return UInt32
T === Float16 && return UInt16
return Any
end
function fptosi_tfunc(x::ANY)
T = widenconst(x)
T === Float64 && return Int64
T === Float32 && return Int32
T === Float16 && return Int16
return Any
end
## conversion ##
add_tfunc(bitcast, 2, 2, bitcast_tfunc)
add_tfunc(sext_int, 2, 2, bitcast_tfunc)
add_tfunc(zext_int, 2, 2, bitcast_tfunc)
add_tfunc(trunc_int, 2, 2, bitcast_tfunc)
add_tfunc(fptoui, 1, 2, fptoui_tfunc)
add_tfunc(fptosi, 1, 2, fptosi_tfunc)
add_tfunc(uitofp, 2, 2, bitcast_tfunc)
add_tfunc(sitofp, 2, 2, bitcast_tfunc)
add_tfunc(fptrunc, 2, 2, bitcast_tfunc)
add_tfunc(fpext, 2, 2, bitcast_tfunc)
## checked conversion ##
add_tfunc(checked_trunc_sint, 2, 2, bitcast_tfunc)
add_tfunc(checked_trunc_uint, 2, 2, bitcast_tfunc)
add_tfunc(check_top_bit, 1, 1, math_tfunc)
## arithmetic ##
add_tfunc(neg_int, 1, 1, math_tfunc)
add_tfunc(add_int, 2, 2, math_tfunc)
add_tfunc(sub_int, 2, 2, math_tfunc)
add_tfunc(mul_int, 2, 2, math_tfunc)
add_tfunc(sdiv_int, 2, 2, math_tfunc)
add_tfunc(udiv_int, 2, 2, math_tfunc)
add_tfunc(srem_int, 2, 2, math_tfunc)
add_tfunc(urem_int, 2, 2, math_tfunc)
add_tfunc(neg_float, 1, 1, math_tfunc)
add_tfunc(add_float, 2, 2, math_tfunc)
add_tfunc(sub_float, 2, 2, math_tfunc)
add_tfunc(mul_float, 2, 2, math_tfunc)
add_tfunc(div_float, 2, 2, math_tfunc)
add_tfunc(rem_float, 2, 2, math_tfunc)
add_tfunc(fma_float, 3, 3, math_tfunc)
add_tfunc(muladd_float, 3, 3, math_tfunc)
## fast arithmetic ##
add_tfunc(neg_float_fast, 1, 1, math_tfunc)
add_tfunc(add_float_fast, 2, 2, math_tfunc)
add_tfunc(sub_float_fast, 2, 2, math_tfunc)
add_tfunc(mul_float_fast, 2, 2, math_tfunc)
add_tfunc(div_float_fast, 2, 2, math_tfunc)
add_tfunc(rem_float_fast, 2, 2, math_tfunc)
## bitwise operators ##
add_tfunc(and_int, 2, 2, math_tfunc)
add_tfunc(or_int, 2, 2, math_tfunc)
add_tfunc(xor_int, 2, 2, math_tfunc)
add_tfunc(not_int, 1, 1, math_tfunc)
add_tfunc(shl_int, 2, 2, math_tfunc)
add_tfunc(lshr_int, 2, 2, math_tfunc)
add_tfunc(ashr_int, 2, 2, math_tfunc)
add_tfunc(bswap_int, 1, 1, math_tfunc)
add_tfunc(ctpop_int, 1, 1, math_tfunc)
add_tfunc(ctlz_int, 1, 1, math_tfunc)
add_tfunc(cttz_int, 1, 1, math_tfunc)
add_tfunc(checked_sdiv_int, 2, 2, math_tfunc)
add_tfunc(checked_udiv_int, 2, 2, math_tfunc)
add_tfunc(checked_srem_int, 2, 2, math_tfunc)
add_tfunc(checked_urem_int, 2, 2, math_tfunc)
## functions ##
add_tfunc(abs_float, 1, 1, math_tfunc)
add_tfunc(copysign_float, 2, 2, math_tfunc)
add_tfunc(flipsign_int, 2, 2, math_tfunc)
add_tfunc(ceil_llvm, 1, 1, math_tfunc)
add_tfunc(floor_llvm, 1, 1, math_tfunc)
add_tfunc(trunc_llvm, 1, 1, math_tfunc)
add_tfunc(rint_llvm, 1, 1, math_tfunc)
add_tfunc(sqrt_llvm, 1, 1, math_tfunc)
add_tfunc(powi_llvm, 2, 2, math_tfunc)
add_tfunc(sqrt_llvm_fast, 1, 1, math_tfunc)
## same-type comparisons ##
cmp_tfunc(x::ANY, y::ANY) = Bool
add_tfunc(eq_int, 2, 2, cmp_tfunc)
add_tfunc(ne_int, 2, 2, cmp_tfunc)
add_tfunc(slt_int, 2, 2, cmp_tfunc)
add_tfunc(ult_int, 2, 2, cmp_tfunc)
add_tfunc(sle_int, 2, 2, cmp_tfunc)
add_tfunc(ule_int, 2, 2, cmp_tfunc)
add_tfunc(eq_float, 2, 2, cmp_tfunc)
add_tfunc(ne_float, 2, 2, cmp_tfunc)
add_tfunc(lt_float, 2, 2, cmp_tfunc)
add_tfunc(le_float, 2, 2, cmp_tfunc)
add_tfunc(fpiseq, 2, 2, cmp_tfunc)
add_tfunc(fpislt, 2, 2, cmp_tfunc)
add_tfunc(eq_float_fast, 2, 2, cmp_tfunc)
add_tfunc(ne_float_fast, 2, 2, cmp_tfunc)
add_tfunc(lt_float_fast, 2, 2, cmp_tfunc)
add_tfunc(le_float_fast, 2, 2, cmp_tfunc)
## checked arithmetic ##
chk_tfunc(x::ANY, y::ANY) = Tuple{widenconst(x), Bool}
add_tfunc(checked_sadd_int, 2, 2, chk_tfunc)
add_tfunc(checked_uadd_int, 2, 2, chk_tfunc)
add_tfunc(checked_ssub_int, 2, 2, chk_tfunc)
add_tfunc(checked_usub_int, 2, 2, chk_tfunc)
add_tfunc(checked_smul_int, 2, 2, chk_tfunc)
add_tfunc(checked_umul_int, 2, 2, chk_tfunc)
## other, misc intrinsics ##
add_tfunc(Core.Intrinsics.llvmcall, 3, IInf,
(fptr::ANY, rt::ANY, at::ANY, a...) -> instanceof_tfunc(rt))
cglobal_tfunc(fptr::ANY) = Ptr{Void}
cglobal_tfunc(fptr::ANY, t::ANY) = (isType(t) ? Ptr{t.parameters[1]} : Ptr)
cglobal_tfunc(fptr::ANY, t::Const) = (isa(t.val, Type) ? Ptr{t.val} : Ptr)
add_tfunc(Core.Intrinsics.cglobal, 1, 2, cglobal_tfunc)
add_tfunc(Core.Intrinsics.select_value, 3, 3,
function (cnd::ANY, x::ANY, y::ANY)
if isa(cnd, Const)
if cnd.val === true
return x
elseif cnd.val === false
return y
else
return Bottom
end
end
(Bool ⊑ cnd) || return Bottom
return tmerge(x, y)
end)
add_tfunc(===, 2, 2,
function (x::ANY, y::ANY)
if isa(x, Const) && isa(y, Const)
return Const(x.val === y.val)
elseif typeintersect(widenconst(x), widenconst(y)) === Bottom
return Const(false)
elseif (isa(x, Const) && y === typeof(x.val) && isdefined(y, :instance)) ||
(isa(y, Const) && x === typeof(y.val) && isdefined(x, :instance))
return Const(true)
elseif isa(x, Conditional) && isa(y, Const)
y.val === false && return Conditional(x.var, x.elsetype, x.vtype)
y.val === true && return x
return x
elseif isa(y, Conditional) && isa(x, Const)
x.val === false && return Conditional(y.var, y.elsetype, y.vtype)
x.val === true && return y
end
return Bool
end)
add_tfunc(isdefined, 1, IInf, (args...)->Bool)
add_tfunc(Core.sizeof, 1, 1, x->Int)
add_tfunc(nfields, 1, 1,
function (x::ANY)
isa(x,Const) && return Const(nfields(x.val))
isa(x,Conditional) && return Const(nfields(Bool))
if isType(x)
isleaftype(x.parameters[1]) && return Const(nfields(x.parameters[1]))
elseif isa(x,DataType) && !x.abstract && !(x.name === Tuple.name && isvatuple(x))
return Const(length(x.types))
end
return Int
end)
add_tfunc(Core._expr, 1, IInf, (args...)->Expr)
add_tfunc(applicable, 1, IInf, (f::ANY, args...)->Bool)
add_tfunc(Core.Intrinsics.arraylen, 1, 1, x->Int)
add_tfunc(arraysize, 2, 2, (a::ANY, d::ANY)->Int)
add_tfunc(pointerref, 3, 3,
function (a::ANY, i::ANY, align::ANY)
a = widenconst(a)
if a <: Ptr
if isa(a,DataType) && isa(a.parameters[1],Type)
return a.parameters[1]
elseif isa(a,UnionAll) && !has_free_typevars(a)
unw = unwrap_unionall(a)
if isa(unw,DataType)
return rewrap_unionall(unw.parameters[1], a)
end
end
end
return Any
end)
add_tfunc(pointerset, 4, 4, (a::ANY, v::ANY, i::ANY, align::ANY) -> a)
function typeof_tfunc(t::ANY)
if isa(t, Const)
return Const(typeof(t.val))
elseif isa(t, Conditional)
return Const(Bool)
elseif isType(t)
tp = t.parameters[1]
if !isleaftype(tp)
return DataType # typeof(Kind::Type)::DataType
else
return Const(typeof(tp)) # XXX: this is not necessarily true
end
elseif isa(t, DataType)
if isleaftype(t) || isvarargtype(t)
return Const(t)
elseif t === Any
return DataType
else
return Type{<:t}
end
elseif isa(t, Union)
a = widenconst(typeof_tfunc(t.a))
b = widenconst(typeof_tfunc(t.b))
return Union{a, b}
elseif isa(t, TypeVar) && !(Any <: t.ub)
return typeof_tfunc(t.ub)
else
return DataType # typeof(anything)::DataType
end
end
add_tfunc(typeof, 1, 1, typeof_tfunc)
add_tfunc(typeassert, 2, 2,
function (v::ANY, t::ANY)
t = instanceof_tfunc(t)
t === Any && return v
if isa(v, Const)
if !has_free_typevars(t) && !isa(v.val, t)
return Bottom
end
return v
elseif isa(v, Conditional)
if !(Bool <: t)
return Bottom
end
return v
end
return typeintersect(v, t)
end)
add_tfunc(isa, 2, 2,
function (v::ANY, t::ANY)
t = instanceof_tfunc(t)
if t !== Any && !has_free_typevars(t)
if v ⊑ t
return Const(true)
elseif isa(v, Const) || isa(v, Conditional) || isleaftype(v)
return Const(false)
end
end
# TODO: handle non-leaftype(t) by testing against lower and upper bounds
return Bool
end)
add_tfunc(issubtype, 2, 2,
function (a::ANY, b::ANY)
if (isa(a,Const) || isType(a)) && (isa(b,Const) || isType(b))
a = instanceof_tfunc(a)
b = instanceof_tfunc(b)
if !has_free_typevars(a) && !has_free_typevars(b)
return Const(issubtype(a, b))
end
end
return Bool
end)
function type_depth(t::ANY)
if t === Bottom
return 0
elseif isa(t, Union)
return max(type_depth(t.a), type_depth(t.b)) + 1
elseif isa(t, DataType)
return (t::DataType).depth
elseif isa(t, UnionAll)
if t.var.ub === Any && t.var.lb === Bottom
return type_depth(t.body)
end
return max(type_depth(t.var.ub)+1, type_depth(t.var.lb)+1, type_depth(t.body))
end
return 0
end
function limit_type_depth(t::ANY, d::Int)
r = limit_type_depth(t, d, true, TypeVar[])
@assert !isa(t, Type) || t <: r
return r
end
function limit_type_depth(t::ANY, d::Int, cov::Bool, vars::Vector{TypeVar}=TypeVar[])
if isa(t,Union)
if d > MAX_TYPE_DEPTH
return Any
end
return Union{map(x->limit_type_depth(x, d+1, cov, vars), (t.a,t.b))...}
elseif isa(t,UnionAll)
v = t.var
if v.ub === Any
if v.lb === Bottom
return UnionAll(t.var, limit_type_depth(t.body, d, cov, vars))
end
ub = Any
else
ub = limit_type_depth(v.ub, d+1, true)
end
if v.lb === Bottom || type_depth(v.lb) > MAX_TYPE_DEPTH
# note: lower bounds need to be widened by making them lower
lb = Bottom
else
lb = v.lb
end
v2 = TypeVar(v.name, lb, ub)
return UnionAll(v2, limit_type_depth(t{v2}, d, cov, vars))
elseif !isa(t,DataType)
return t
end
P = t.parameters
isempty(P) && return t
if d > MAX_TYPE_DEPTH
cov && return t.name.wrapper
var = TypeVar(:_, t.name.wrapper)
push!(vars, var)
return var
end
stillcov = cov && (t.name === Tuple.name)
Q = map(x->limit_type_depth(x, d+1, stillcov, vars), P)
R = t.name.wrapper{Q...}
if cov && !stillcov
for var in vars
R = UnionAll(var, R)
end
end
return R
end
const DataType_name_fieldindex = fieldindex(DataType, :name)
const DataType_parameters_fieldindex = fieldindex(DataType, :parameters)
const DataType_types_fieldindex = fieldindex(DataType, :types)
const DataType_super_fieldindex = fieldindex(DataType, :super)
const TypeName_name_fieldindex = fieldindex(TypeName, :name)
const TypeName_module_fieldindex = fieldindex(TypeName, :module)
const TypeName_wrapper_fieldindex = fieldindex(TypeName, :wrapper)
function const_datatype_getfield_tfunc(sv, fld)
if (fld == DataType_name_fieldindex ||
fld == DataType_parameters_fieldindex ||
fld == DataType_types_fieldindex ||
fld == DataType_super_fieldindex)
return abstract_eval_constant(getfield(sv, fld))
end
return nothing
end
# returns (type, isexact)
function getfield_tfunc(s00::ANY, name)
if isa(s00, TypeVar)
s00 = s00.ub
end
s = unwrap_unionall(s00)
if isType(s)
p1 = s.parameters[1]
if !isleaftype(p1)
return Any
end
s = DataType # typeof(p1)
elseif isa(s, Union)
return tmerge(rewrap(getfield_tfunc(s.a, name),s00),
rewrap(getfield_tfunc(s.b, name),s00))
elseif isa(s, Conditional)
return Bottom # Bool has no fields
elseif isa(s, Const)
sv = s.val
if isa(name, Const)
nv = name.val
if isa(sv, UnionAll)
if nv === :var || nv === 1
return Const(sv.var)
elseif nv === :body || nv === 2
return Const(sv.body)
end
elseif isa(sv, DataType)
t = const_datatype_getfield_tfunc(sv, isa(nv, Symbol) ?
fieldindex(DataType, nv, false) : nv)
t !== nothing && return t
elseif isa(sv, TypeName)
fld = isa(nv, Symbol) ? fieldindex(TypeName, nv, false) : nv
if (fld == TypeName_name_fieldindex ||
fld == TypeName_module_fieldindex ||
fld == TypeName_wrapper_fieldindex)
return abstract_eval_constant(getfield(sv, fld))
end
end
if isa(sv, Module) && isa(nv, Symbol)
return abstract_eval_global(sv, nv)
end
if (isa(sv, SimpleVector) || isimmutable(sv)) && isdefined(sv, nv)
return abstract_eval_constant(getfield(sv, nv))
end
end
s = typeof(sv)
end
if !isa(s,DataType) || s.abstract
return Any
end
if s <: Tuple && name ⊑ Symbol
return Bottom
end
if s <: Module
if name ⊑ Int
return Bottom
end
return Any
end
if isempty(s.types)
return Bottom
end
if isa(name, Conditional)
return Bottom # can't index fields with Bool
end
if !isa(name, Const)
if !(Int <: name || Symbol <: name)
return Bottom
end
if length(s.types) == 1
return rewrap_unionall(unwrapva(s.types[1]), s00)
end
# union together types of all fields
R = reduce(tmerge, Bottom, map(t -> rewrap_unionall(unwrapva(t), s00), s.types))
# do the same limiting as the known-symbol case to preserve type-monotonicity
if isempty(s.parameters)
return R
end
return limit_type_depth(R, 0)
end
fld = name.val
if isa(fld,Symbol)
fld = fieldindex(s, fld, false)
end
if !isa(fld,Int)
return Bottom
end
nf = length(s.types)
if s <: Tuple && fld >= nf && isvarargtype(s.types[nf])
return rewrap_unionall(unwrapva(s.types[nf]), s00)
end
if fld < 1 || fld > nf
return Bottom
end
if isType(s00) && isleaftype(s00.parameters[1])
sp = s00.parameters[1]
elseif isa(s00, Const) && isa(s00.val, DataType)
sp = s00.val
else
sp = nothing
end
if sp !== nothing
t = const_datatype_getfield_tfunc(sp, fld)
t !== nothing && return t
end
R = s.types[fld]
if isempty(s.parameters)
return R
end
# TODO jb/subtype is this still necessary?
# conservatively limit the type depth here,
# since the UnionAll type bound is otherwise incorrect
# in the current type system
return rewrap_unionall(limit_type_depth(R, 0), s00)
end
add_tfunc(getfield, 2, 2, (s::ANY, name::ANY) -> getfield_tfunc(s, name))
add_tfunc(setfield!, 3, 3, (o::ANY, f::ANY, v::ANY) -> v)
function fieldtype_tfunc(s0::ANY, name::ANY)
if s0 === Any || s0 === Type || DataType ⊑ s0 || UnionAll ⊑ s0
return Type
end
# fieldtype only accepts DataType and UnionAll, errors on `Module`
if isa(s0,Const) && (!(isa(s0.val,DataType) || isa(s0.val,UnionAll)) || s0.val === Module)
return Bottom
end
if s0 == Type{Module} || s0 == Type{Union{}} || isa(s0, Conditional)
return Bottom
end
s = instanceof_tfunc(s0)
u = unwrap_unionall(s)
if isa(u,Union)
return tmerge(rewrap(fieldtype_tfunc(u.a, name),s),
rewrap(fieldtype_tfunc(u.b, name),s))
end
if !isa(u,DataType) || u.abstract
return Type
end
ftypes = u.types
if isempty(ftypes)
return Bottom
end
if !isa(name, Const)
if !(Int <: name || Symbol <: name)
return Bottom
end
return reduce(tmerge, Bottom,
Any[ fieldtype_tfunc(s0, Const(i)) for i = 1:length(ftypes) ])
end
fld = name.val
if isa(fld,Symbol)
fld = fieldindex(u, fld, false)
end
if !isa(fld, Int)
return Bottom
end
nf = length(ftypes)
if u.name === Tuple.name && fld >= nf && isvarargtype(ftypes[nf])
ft = unwrapva(ftypes[nf])
elseif fld < 1 || fld > nf
return Bottom
else
ft = ftypes[fld]
end
exact = (isa(s0, Const) || isType(s0)) && !has_free_typevars(s)
ft = rewrap_unionall(ft,s)
if exact
return Const(ft)
end
return Type{<:ft}
end
add_tfunc(fieldtype, 2, 2, fieldtype_tfunc)
function valid_tparam(x::ANY)
if isa(x,Tuple)
for t in x
!valid_tparam(t) && return false
end
return true
end
return isa(x,Int) || isa(x,Symbol) || isa(x,Bool) || (!isa(x,Type) && isbits(x))
end
has_free_typevars(t::ANY) = ccall(:jl_has_free_typevars, Cint, (Any,), t)!=0
# TODO: handle e.g. apply_type(T, R::Union{Type{Int32},Type{Float64}})
function apply_type_tfunc(headtypetype::ANY, args::ANY...)
if isa(headtypetype, Const)
headtype = headtypetype.val
elseif isType(headtypetype) && isleaftype(headtypetype.parameters[1])
headtype = headtypetype.parameters[1]
else
return Any
end
largs = length(args)
if headtype === Union
largs == 0 && return Const(Bottom)
largs == 1 && return args[1]
for i = 1:largs
ai = args[i]
if !isa(ai, Const) || !isa(ai.val, Type)
if !isType(ai)
return Any
end
end
end
ty = Union{}
allconst = true
for i = 1:largs
ai = args[i]
if isType(ai)
aty = ai.parameters[1]
isleaftype(aty) || (allconst = false)
else
aty = (ai::Const).val
end
ty = Union{ty, aty}
end
return allconst ? Const(ty) : Type{ty}
end
istuple = (headtype == Tuple)
if !istuple && !isa(headtype, UnionAll)
# TODO: return `Bottom` for trying to apply a non-UnionAll
return Any
end
uncertain = false
canconst = true
tparams = Any[]
outervars = Any[]
for i = 1:largs
ai = args[i]
if isType(ai)
aip1 = ai.parameters[1]
canconst &= isleaftype(aip1)
push!(tparams, aip1)
elseif isa(ai, Const) && (isa(ai.val, Type) || isa(ai.val, TypeVar) || valid_tparam(ai.val))
push!(tparams, ai.val)
elseif isa(ai, PartialTypeVar)
canconst = false
push!(tparams, ai.tv)
else
# TODO: return `Bottom` for trying to apply a non-UnionAll
uncertain = true
# These blocks improve type info but make compilation a bit slower.
# XXX
#unw = unwrap_unionall(ai)
#isT = isType(unw)
#if isT && isa(ai,UnionAll) && contains_is(outervars, ai.var)
# ai = rename_unionall(ai)
# unw = unwrap_unionall(ai)
#end
if istuple
if i == largs
push!(tparams, Vararg)
# XXX
#elseif isT
# push!(tparams, rewrap_unionall(unw.parameters[1], ai))
else
push!(tparams, Any)
end
# XXX