-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
inference.jl
3319 lines (3127 loc) · 105 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
# parameters limiting potentially-infinite types
const MAX_TYPEUNION_LEN = 3
const MAX_TYPE_DEPTH = 4
const MAX_TUPLETYPE_LEN = 8
const MAX_TUPLE_DEPTH = 4
type NotFound
end
const NF = NotFound()
type StaticVarInfo
sp::SimpleVector # static parameters
cenv::ObjectIdDict # types of closed vars
vars::Array{Any,1} # names of args and locals
gensym_types::Array{Any,1} # types of the GenSym's in this function
vinfo::Array{Any,1} # variable properties
label_counter::Int # index of the current highest label for this function
fedbackvars::ObjectIdDict
end
type VarState
typ
undef::Bool
end
type EmptyCallStack
end
type CallStack
ast
mod::Module
types::Type
recurred::Bool
cycleid::Int
result
prev::Union(EmptyCallStack,CallStack)
sv::StaticVarInfo
CallStack(ast, mod, types::ANY, prev) = new(ast, mod, types, false, 0, Bottom, prev)
end
inference_stack = EmptyCallStack()
function is_static_parameter(sv::StaticVarInfo, s::Symbol)
sp = sv.sp
for i=1:2:length(sp)
if is(sp[i].name,s)
return true
end
end
return false
end
function contains_is(itr, x::ANY)
for y in itr
if is(y,x)
return true
end
end
return false
end
is_local(sv::StaticVarInfo, s::GenSym) = true
is_local(sv::StaticVarInfo, s::Symbol) = contains_is(sv.vars, s)
is_closed(sv::StaticVarInfo, s::Symbol) = haskey(sv.cenv, s)
function is_assigned_inner(sv::StaticVarInfo, s::Symbol)
for vi in sv.vinfo
if vi[1] === s
return (vi[3]&4) != 0
end
end
return false
end
is_global(sv::StaticVarInfo, s::Symbol) =
!is_local(sv,s) && !is_closed(sv,s) && !is_static_parameter(sv,s)
function _iisconst(s::Symbol)
m = (inference_stack::CallStack).mod
isdefined(m,s) && (ccall(:jl_is_const, Int32, (Any, Any), m, s) != 0)
end
_iisconst(s::SymbolNode) = _iisconst(s.name)
_iisconst(s::TopNode) = isconst(_topmod(), s.name)
_iisconst(x::Expr) = false
_iisconst(x::ANY) = true
_ieval(x::ANY) =
ccall(:jl_interpret_toplevel_expr_in, Any, (Any, Any, Ptr{Void}, Csize_t),
(inference_stack::CallStack).mod, x, C_NULL, 0)
_iisdefined(x::ANY) = isdefined((inference_stack::CallStack).mod, x)
function _topmod()
m = (inference_stack::CallStack).mod
return ccall(:jl_base_relative_to, Any, (Any,), m)::Module
end
function istopfunction(topmod, f, 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
cmp_tfunc = (x,y)->Bool
isType(t::ANY) = isa(t,DataType) && is((t::DataType).name,Type.name)
const IInf = typemax(Int) # integer infinity
const n_ifunc = reinterpret(Int32,llvmcall)+1
const t_ifunc = Array{Tuple{Int,Int,Function},1}(n_ifunc)
const t_ffunc_key = Array{Function,1}(0)
const t_ffunc_val = Array{Tuple{Int,Int,Function},1}(0)
function add_tfunc(f::IntrinsicFunction, minarg::Int, maxarg::Int, tfunc::Function)
t_ifunc[reinterpret(Int32,f)+1] = (minarg, maxarg, tfunc)
end
function add_tfunc(f::Function, minarg::Int, maxarg::Int, tfunc::Function)
push!(t_ffunc_key, f)
push!(t_ffunc_val, (minarg, maxarg, tfunc))
end
add_tfunc(throw, 1, 1, x->Bottom)
add_tfunc(box, 2, 2, (t,v)->(isType(t) ? t.parameters[1] : Any))
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(nan_dom_err, 2, 2, (a, b)->a)
add_tfunc(getfield(Core.Intrinsics,:ccall), 3, IInf,
function(fptr, rt, at, a...)
if !isType(rt)
return Any
end
t = rt.parameters[1]
if isa(t,DataType) && is((t::DataType).name,Ref.name)
t = t.parameters[1]
if is(t,Any)
return Union() # a return type of Box{Any} is invalid
end
return t
end
return t
end)
add_tfunc(eval(Core.Intrinsics,:llvmcall), 3, IInf,
(fptr, rt, at, a...)->(isType(rt) ? rt.parameters[1] : Any))
add_tfunc(eval(Core.Intrinsics,:cglobal), 1, 2,
(fptr, t...)->(isempty(t) ? Ptr{Void} :
isType(t[1]) ? Ptr{t[1].parameters[1]} : Ptr))
add_tfunc(eval(Core.Intrinsics,:select_value), 3, 3,
# TODO: return Bottom if cnd is definitely not a Bool
(cnd, x, y)->Union(x,y))
add_tfunc(is, 2, 2, cmp_tfunc)
add_tfunc(issubtype, 2, 2, cmp_tfunc)
add_tfunc(isa, 2, 2, cmp_tfunc)
add_tfunc(isdefined, 1, IInf, (args...)->Bool)
add_tfunc(Core.sizeof, 1, 1, x->Int)
add_tfunc(nfields, 1, 1, x->Int)
add_tfunc(Union, 0, IInf,
(args...)->(if all(isType,args)
Type{Union(map(t->t.parameters[1],args)...)}
else
Type
end))
add_tfunc(_expr, 1, IInf, (args...)->Expr)
add_tfunc(method_exists, 2, 2, cmp_tfunc)
add_tfunc(applicable, 1, IInf, (f, args...)->Bool)
add_tfunc(arraylen, 1, 1, x->Int)
#add_tfunc(arrayref, 2,IInf,(a,i...)->(isa(a,DataType) && a<:Array ?
# a.parameters[1] : Any))
#add_tfunc(arrayset, 3, IInf, (a,v,i...)->a)
add_tfunc(arraysize, 2, 2, (a,d)->Int)
add_tfunc(pointerref, 2, 2, (a,i)->(isa(a,DataType) && a<:Ptr ? a.parameters[1] : Any))
add_tfunc(pointerset, 3, 3, (a,v,i)->a)
const typeof_tfunc = function (t)
if isType(t)
t = t.parameters[1]
if isa(t,TypeVar)
Type
else
Type{typeof(t)}
end
elseif isa(t,DataType)
if isleaftype(t)
Type{t}
else
Type{TypeVar(:_,t)}
end
elseif isa(t,UnionType)
Union(map(typeof_tfunc, t.types)...)
elseif isa(t,TypeVar)
Type{t}
else
Type
end
end
add_tfunc(typeof, 1, 1, typeof_tfunc)
# involving constants: typeassert, getfield, fieldtype, apply_type
# therefore they get their arguments unevaluated
add_tfunc(typeassert, 2, 2,
(A, v, t)->(isType(t) ? typeintersect(v,t.parameters[1]) : Any))
function limit_type_depth(t::ANY, d::Int, cov::Bool, vars)
if isa(t,TypeVar) || isa(t,TypeConstructor)
return t
end
inexact = !cov && d > MAX_TYPE_DEPTH
if isa(t,UnionType)
t === Bottom && return t
if d > MAX_TYPE_DEPTH
R = Any
else
R = Union(map(x->limit_type_depth(x, d+1, cov, vars), t.types)...)
end
elseif isa(t,DataType)
P = t.parameters
length(P) == 0 && return t
if d > MAX_TYPE_DEPTH
R = t.name.primary
else
Q = map(x->limit_type_depth(x, d+1, false, vars), P)
if !cov && any(p->contains_is(vars,p), Q)
R = t.name.primary
inexact = true
else
R = t.name.primary{Q...}
end
end
else
return t
end
if inexact
R = TypeVar(:_,R)
push!(vars, R)
end
return R
end
const getfield_tfunc = function (A, s0, name)
s = s0
if isType(s)
s = typeof(s.parameters[1])
if s === TypeVar
return Any, false
end
end
if isa(s,UnionType)
return reduce(tmerge, Bottom, map(t->getfield_tfunc(A, t, name)[1], s.types)), false
end
if !isa(s,DataType)
return Any, false
end
if is(s.name,NTuple.name)
return (name == Symbol ? Bottom : s.parameters[2]), true
end
if s.abstract
return Any, false
end
if s <: Tuple && name === Symbol
return Bottom, true
end
haveargs = A !== nothing && length(A)>1
if haveargs && isa(A[2],QuoteNode) && isa(A[2].value,Symbol)
fld = A[2].value
A1 = A[1]
if isa(A1,Module) && isdefined(A1,fld) && isconst(A1, fld)
return abstract_eval_constant(eval(A1,fld)), true
end
if s === Module
return Any, false
end
if isType(s0)
sp = s0.parameters[1]
if isa(sp,DataType) && !any(x->isa(x,TypeVar), sp.parameters)
# TODO
#if fld === :parameters
# return Type{sp.parameters}, true
#end
#if fld === :types
# return Type{sp.types}, true
#end
if fld === :super
return Type{sp.super}, isleaftype(s)
end
end
end
snames = s.name.names
for i=1:length(snames)
if is(snames[i],fld)
R = s.types[i]
if length(s.parameters) == 0
return R, true
else
typ = limit_type_depth(R, 0, true,
filter!(x->isa(x,TypeVar), Any[s.parameters...]))
return typ, isleaftype(s) && typeseq(typ, R)
end
end
end
return Bottom, true
elseif haveargs && isa(A[2],Int)
if isa(A[1],Module) || s === Module
return Bottom, true
end
i::Int = A[2]
nf = s.types.length
if isvatuple(s) && i >= nf
return s.types[nf].parameters[1], false
end
if i < 1 || i > nf
return Bottom, true
end
return s.types[i], false
else
return reduce(tmerge, Bottom, map(unwrapva,s.types)) #=Union(s.types...)=#, false
end
end
add_tfunc(getfield, 2, 2, (A,s,name)->getfield_tfunc(A,s,name)[1])
add_tfunc(setfield!, 3, 3, (o, f, v)->v)
const fieldtype_tfunc = function (A, s, name)
if isType(s)
s = s.parameters[1]
else
return Type
end
t, exact = getfield_tfunc(A, s, name)
if is(t,Bottom)
return t
end
Type{exact || isleaftype(t) || isa(t,TypeVar) ? t : TypeVar(:_, t)}
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
function extract_simple_tparam(Ai)
if !isa(Ai,Symbol) && valid_tparam(Ai)
return Ai
elseif isa(Ai,QuoteNode) && valid_tparam(Ai.value)
return Ai.value
elseif isa(inference_stack,CallStack) && isa(Ai,Expr) &&
is_known_call(Ai,tuple,inference_stack.sv)
tup = ()
for arg in Ai.args[2:end]
val = extract_simple_tparam(arg)
if val === Bottom
return val
end
tup = tuple(tup...,val)
end
return tup
end
return Bottom
end
has_typevars(t::ANY) = ccall(:jl_has_typevars, Cint, (Any,), t)!=0
# TODO: handle e.g. apply_type(T, R::Union(Type{Int32},Type{Float64}))
const apply_type_tfunc = function (A, args...)
if !isType(args[1])
return Type
end
headtype = args[1].parameters[1]
if isa(headtype,UnionType) || isa(headtype,TypeVar)
return args[1]
end
istuple = (headtype === Tuple)
uncertain = false
lA = length(A)
tparams = svec()
for i=2:max(lA,length(args))
ai = args[i]
if isType(ai)
aip1 = ai.parameters[1]
uncertain |= has_typevars(aip1)
tparams = svec(tparams..., aip1)
else
if i<=lA
val = extract_simple_tparam(A[i])
if val !== Bottom
tparams = svec(tparams..., val)
continue
elseif isa(inference_stack,CallStack) && isa(A[i],Symbol)
sp = inference_stack.sv.sp
s = A[i]
found = false
for j=1:2:length(sp)
if is(sp[j].name,s)
# static parameter
val = sp[j+1]
if valid_tparam(val)
tparams = svec(tparams..., val)
found = true
break
end
end
end
if found
continue
end
end
end
if !istuple && i-1 > length(headtype.parameters)
# too many parameters for type
return Bottom
end
uncertain = true
if istuple
tparams = svec(tparams..., Any)
else
tparams = svec(tparams..., headtype.parameters[i-1])
end
end
end
local appl
# good, all arguments understood
try
appl = apply_type(headtype, tparams...)
catch
# type instantiation might fail if one of the type parameters
# doesn't match, which could happen if a type estimate is too coarse
appl = headtype
uncertain = true
end
if type_too_complex(appl,0)
return Type{TypeVar(:_,headtype)}
end
uncertain && !isa(appl,TypeVar) ? Type{TypeVar(:_,appl)} : Type{appl}
end
add_tfunc(apply_type, 1, IInf, apply_type_tfunc)
function tuple_tfunc(argtype::ANY)
if isa(argtype,DataType) && argtype.name === Tuple.name
p = map(x->(isType(x) && !isa(x.parameters[1],TypeVar) ? typeof(x.parameters[1]) : x),
argtype.parameters)
return Tuple{p...}
end
argtype
end
function builtin_tfunction(f::ANY, args::ANY, argtype::ANY)
isva = isvatuple(argtype)
argtypes = argtype.parameters
if is(f,tuple)
return tuple_tfunc(limit_tuple_depth(argtype))
elseif is(f,svec)
return SimpleVector
elseif is(f,arrayset)
if length(argtypes) < 3 && !isva
return Bottom
end
a1 = argtypes[1]
if isvarargtype(a1)
return a1.parameters[1]
end
return a1
elseif is(f,arrayref)
if length(argtypes) < 2 && !isva
return Bottom
end
a = argtypes[1]
return (isa(a,DataType) && a<:Array ?
a.parameters[1] : Any)
elseif is(f,Expr)
if length(argtypes) < 1 && !isva
return Bottom
end
return Expr
end
if isa(f, IntrinsicFunction)
iidx = Int(reinterpret(Int32, f::IntrinsicFunction))+1
if !isdefined(t_ifunc, iidx)
# unknown/unhandled intrinsic (most fall in this category since most return an unboxed value)
return Any
end
tf = t_ifunc[iidx]
else
fidx = findfirst(t_ffunc_key, f::Function)
if fidx == 0
# unknown/unhandled builtin or anonymous function
return Any
end
tf = t_ffunc_val[fidx]
end
tf = tf::Tuple{Real, Real, Function}
if isva
# only some t-funcs can handle varargs (TODO)
#if !is(f, apply_type)
return Any
#end
elseif !(tf[1] <= length(argtypes) <= tf[2])
# wrong # of args
return Bottom
end
if is(f,typeassert) || is(f,getfield) || is(f,apply_type) || is(f,fieldtype)
# TODO: case of apply(), where we do not have the args
return tf[3](args, argtypes...)
end
return tf[3](argtypes...)
end
function isconstantfunc(f::ANY, sv::StaticVarInfo)
if isa(f,TopNode)
m = _topmod()
return isconst(m, f.name) && isdefined(m, f.name) && f
end
if isa(f,GlobalRef)
M = f.mod; s = f.name
return isdefined(M,s) && isconst(M,s) && f
end
if isa(f,Expr) && (is(f.head,:call) || is(f.head,:call1))
if length(f.args) == 3 && isa(f.args[1], TopNode) &&
is(f.args[1].name,:getfield) && isa(f.args[3],QuoteNode)
s = f.args[3].value
if isa(f.args[2],Module)
M = f.args[2]
else
M = isconstantfunc(f.args[2], sv)
if M === false
return false
end
M = _ieval(M)
if !isa(M,Module)
return false
end
end
return isdefined(M,s) && isconst(M,s) && f
end
end
if isa(f,QuoteNode) && isa(f.value, Function)
return f.value
end
if isa(f,Function)
return f
end
if isa(f,SymbolNode)
f = f.name
end
return isa(f,Symbol) && is_global(sv, f) && _iisconst(f) && f
end
const isconstantref = isconstantfunc
const limit_tuple_depth = t->limit_tuple_depth_(t,0)
const limit_tuple_depth_ = function (t,d::Int)
if isa(t,UnionType)
# also limit within Union types.
# may have to recur into other stuff in the future too.
return Union(map(x->limit_tuple_depth_(x,d+1), t.types)...)
end
if !(isa(t,DataType) && t.name === Tuple.name)
return t
end
if d > MAX_TUPLE_DEPTH
return Tuple
end
p = map(x->limit_tuple_depth_(x,d+1), t.parameters)
Tuple{p...}
end
limit_tuple_type = t -> limit_tuple_type_n(t, MAX_TUPLETYPE_LEN)
const limit_tuple_type_n = function (t, lim::Int)
p = t.parameters
n = length(p)
if n > lim
tail = reduce(tmerge, Bottom, svec(p[lim:(n-1)]..., unwrapva(p[n])))
return Tuple{p[1:(lim-1)]..., Vararg{tail}}
end
return t
end
let stagedcache=Dict{Any,Any}()
global func_for_method
function func_for_method(m::Method, tt, env)
if !m.isstaged
return m.func.code
elseif haskey(stagedcache,(m,tt,env))
return stagedcache[(m,tt,env)].code
else
if !isleaftype(tt)
# don't call staged functions on abstract types.
# (see issues #8504, #10230)
# we can't guarantee that their type behavior is monotonic.
error("cannot call @generated function `", m.func.code.name, "` ",
"with abstract argument types: ", tt)
end
f = ccall(:jl_instantiate_staged,Any,(Any,Any,Any),m,tt,env)
stagedcache[(m,tt,env)] = f
return f.code
end
end
end
function abstract_call_gf(f, fargs, argtype, e)
argtypes = argtype.parameters
tm = _topmod()
if length(argtypes)>1 && (argtypes[1] <: Tuple) && argtypes[2]===Int
# allow tuple indexing functions to take advantage of constant
# index arguments.
if istopfunction(tm, f, :getindex)
isa(e,Expr) && (e.head = :call1)
return getfield_tfunc(fargs, argtypes[1], argtypes[2])[1]
elseif istopfunction(tm, f, :next)
isa(e,Expr) && (e.head = :call1)
t1 = getfield_tfunc(fargs, argtypes[1], argtypes[2])[1]
return t1===Bottom ? Bottom : Tuple{t1, Int}
elseif istopfunction(tm, f, :indexed_next)
isa(e,Expr) && (e.head = :call1)
t1 = getfield_tfunc(fargs, argtypes[1], argtypes[2])[1]
return t1===Bottom ? Bottom : Tuple{t1, Int}
end
end
if istopfunction(tm, f, :promote_type) || istopfunction(tm, f, :typejoin)
la = length(argtypes)
c = cell(la)
for i = 1:la
t = argtypes[i]
if isType(t) && !isa(t.parameters[1],TypeVar)
c[i] = t.parameters[1]
else
return Type
end
end
if istopfunction(tm, f, :promote_type)
try
RT = Type{f(c...)}
isa(e,Expr) && (e.head = :call1)
return RT
catch
end
else
isa(e,Expr) && (e.head = :call1)
return Type{f(c...)}
end
end
# don't consider more than N methods. this trades off between
# compiler performance and generated code performance.
# typically, considering many methods means spending lots of time
# obtaining poor type information.
# It is important for N to be >= the number of methods in the error()
# function, so we can still know that error() is always Bottom.
# here I picked 4.
argtype = limit_tuple_type(argtype)
argtypes = argtype.parameters
applicable = _methods(f, argtype, 4)
rettype = Bottom
if is(applicable,false)
# this means too many methods matched
isa(e,Expr) && (e.head = :call)
return Any
end
x::Array{Any,1} = applicable
if isempty(x)
# no methods match
# TODO: it would be nice to return Bottom here, but during bootstrap we
# often compile code that calls methods not defined yet, so it is much
# safer just to fall back on dynamic dispatch.
return Any
end
if isa(e,Expr)
if length(x)==1
# method match is unique; mark it
e.head = :call1
else
e.head = :call
end
end
for (m::SimpleVector) in x
local linfo
try
linfo = func_for_method(m[3],argtype,m[2])
catch
rettype = Any
break
end
sig = m[1]
lsig = length(m[3].sig.parameters)
# limit argument type tuple based on size of definition signature.
# for example, given function f(T, Any...), limit to 3 arguments
# instead of the default (MAX_TUPLETYPE_LEN)
sp = inference_stack
limit = false
# look at the stack to detect recursive calls with growing argument lists
while sp !== EmptyCallStack()
if linfo.ast === sp.ast && length(argtypes) > length(sp.types.parameters)
limit = true; break
end
sp = sp.prev
end
ls = length(sig.parameters)
if limit && ls > lsig+1
if !istopfunction(tm, f, :promote_typeof)
fst = sig.parameters[lsig+1]
allsame = true
# allow specializing on longer arglists if all the trailing
# arguments are the same, since there is no exponential
# blowup in this case.
for i = lsig+2:ls
if sig.parameters[i] != fst
allsame = false
break
end
end
if !allsame
sig = limit_tuple_type_n(sig, lsig+1)
end
end
end
#print(m,"\n")
(_tree,rt) = typeinf(linfo, sig, m[2], linfo)
rettype = tmerge(rettype, rt)
if is(rettype,Any)
break
end
end
# if rettype is Bottom we've found a method not found error
#print("=> ", rettype, "\n")
return rettype
end
function invoke_tfunc(f, types, argtype)
argtype = typeintersect(types,limit_tuple_type(argtype))
if is(argtype,Bottom)
return Bottom
end
try
meth = ccall(:jl_gf_invoke_lookup, Any, (Any, Any), f, types)
if is(meth, nothing)
return Any
end
(ti, env) = ccall(:jl_match_method, Any, (Any, Any, Any),
argtype, meth.sig, meth.tvars)::SimpleVector
linfo = func_for_method(meth, types, env)
return typeinf(linfo, ti, env, linfo)[2]
catch
return Any
end
end
# `types` is an array of inferred types for expressions in `args`.
# if an expression constructs a container (e.g. `svec(x,y,z)`),
# refine its type to an array of element types. returns an array of
# arrays of types, or `nothing`.
function precise_container_types(args, types, vtypes, sv)
n = length(args)
assert(n == length(types))
result = cell(n)
for i = 1:n
ai = args[i]; ti = types[i]
if isa(ai,Expr) && (is_known_call(ai, svec, sv) || is_known_call(ai, tuple, sv))
aa = ai.args
result[i] = Any[ (isa(aa[j],Expr) ? aa[j].typ : abstract_eval(aa[j],vtypes,sv)) for j=2:length(aa) ]
elseif ti<:Tuple && (i==n || !isvatuple(ti))
result[i] = ti.parameters
else
return nothing
end
end
return result
end
# do apply(af, fargs...), where af is a function value
function abstract_apply(af, fargs, aargtypes::Vector{Any}, vtypes, sv, e)
ctypes = precise_container_types(fargs, aargtypes, vtypes, sv)
if ctypes !== nothing
e.head = :call1
# apply with known func with known tuple types
# can be collapsed to a call to the applied func
at = append_any(ctypes...)
n = length(at)
if n > MAX_TUPLETYPE_LEN
tail = foldl((a,b)->tmerge(a,unwrapva(b)), Bottom, at[MAX_TUPLETYPE_LEN:n])
at = vcat(at[1:MAX_TUPLETYPE_LEN-1], Any[Vararg{tail}])
end
return abstract_call(af, (), at, vtypes, sv, ())
end
if is(af,tuple) && length(aargtypes)==1
# tuple(xs...)
aat = aargtypes[1]
if aat <: AbstractArray
# tuple(array...)
# TODO: > 1 array of the same type
tn = AbstractArray.name
while isa(aat, DataType)
if is(aat.name, tn)
et = aat.parameters[1]
if !isa(et,TypeVar)
return Tuple{Vararg{et}}
end
end
if is(aat, Any)
break
end
aat = aat.super
end
end
return Tuple
end
is(af,kwcall) && return Any
# apply known function with unknown args => f(Any...)
return abstract_call(af, (), Any[Vararg{Any}], vtypes, sv, ())
end
function abstract_call(f, fargs, argtypes::Vector{Any}, vtypes, sv::StaticVarInfo, e)
if is(f,_apply) && length(fargs)>1
af = isconstantfunc(fargs[2], sv)
if !is(af,false)
af = _ieval(af)
if isa(af,Function)
return abstract_apply(af, fargs[3:end], argtypes[3:end], vtypes, sv, e)
end
end
# TODO: this slows down inference a lot
a2type = argtypes[2]
if a2type !== Function && isleaftype(a2type)
# would definitely use call()
call_func = _ieval(isconstantfunc(fargs[1], sv))
if isa(call_func,Function)
aargtypes = Any[ argtypes[i] for i=2:length(argtypes) ]
aargtypes[1] = Tuple{aargtypes[1]} # don't splat "function"
fa = fargs[2:end]
fa[1] = Expr(:call, top_tuple, fa[1])
return abstract_apply(call_func, fa, aargtypes, vtypes, sv, e)
end
end
return Any
end
if isgeneric(f)
return abstract_call_gf(f, fargs, Tuple{argtypes...}, e)
end
if is(f,invoke) && length(fargs)>1
af = isconstantfunc(fargs[1], sv)
if !is(af,false) && (af=_ieval(af);isgeneric(af))
sig = argtypes[2]
if isType(sig) && sig.parameters[1] <: Tuple
return invoke_tfunc(af, sig.parameters[1], Tuple{argtypes[3:end]...})
end
end
end
if !is(f,_apply) && isa(e,Expr) && (isa(f,Function) || isa(f,IntrinsicFunction))
e.head = :call1
end
if is(f,getfield)
val = isconstantref(e, sv)
if !is(val,false)
return abstract_eval_constant(_ieval(val))
end
end
if is(f,kwcall)
if length(argtypes) < 4
return Bottom
end
if length(fargs) < 3
return Any
end
kwcount = fargs[2]
ff = isconstantfunc(fargs[3 + 2*kwcount], sv)
if !(ff===false)
ff = _ieval(ff)
if isgeneric(ff) && isdefined(ff.env,:kwsorter)
# use the fact that kwcall(...) calls ff.env.kwsorter
posargt = argtypes[(5+2*kwcount):end]
return abstract_call_gf(ff.env.kwsorter, (),
Tuple{Array{Any,1}, posargt...}, e)
end
end
# TODO: call() case
return Any
end
if !isa(f,Function) && !isa(f,IntrinsicFunction) && _iisdefined(:call)
call_func = _ieval(:call)
if isa(call_func,Function)
return abstract_call(call_func, e.args,
Any[abstract_eval_constant(f),argtypes...],
vtypes, sv, e)
else
return Any
end
end
rt = builtin_tfunction(f, fargs, Tuple{argtypes...})
#print("=> ", rt, "\n")
return rt
end
function abstract_eval_call(e, vtypes, sv::StaticVarInfo)
fargs = e.args[2:end]
argtypes = Any[abstract_eval(a, vtypes, sv) for a in fargs]
if any(x->is(x,Bottom), argtypes)
return Bottom
end
called = e.args[1]
func = isconstantfunc(called, sv)
if is(func,false)
if isa(called, LambdaStaticData)
# called lambda expression (let)
(_, result) = typeinf(called, Tuple{argtypes...}, called.sparams, called)
return result
end
ft = abstract_eval(called, vtypes, sv)
if !(Function <: ft) && _iisdefined(:call)
call_func = _ieval(:call)
if isa(call_func,Function)
return abstract_call(call_func, e.args, Any[ft,argtypes...], vtypes, sv, e)
end
end
return Any
end
#print("call ", e.args[1], argtypes, "\n\n")
f = _ieval(func)
return abstract_call(f, fargs, argtypes, vtypes, sv, e)
end
function abstract_eval(e::ANY, vtypes, sv::StaticVarInfo)
if isa(e,QuoteNode)
return typeof((e::QuoteNode).value)
elseif isa(e,TopNode)
return abstract_eval_global(_topmod(), (e::TopNode).name)
elseif isa(e,Symbol)
return abstract_eval_symbol(e::Symbol, vtypes, sv)
elseif isa(e,SymbolNode)
return abstract_eval_symbol((e::SymbolNode).name, vtypes, sv)
elseif isa(e,GenSym)
return abstract_eval_gensym(e::GenSym, sv)
elseif isa(e,LambdaStaticData)
return Function
elseif isa(e,GlobalRef)
return abstract_eval_global(e.mod, e.name)
end
if !isa(e,Expr)
return abstract_eval_constant(e)
end
e = e::Expr
# handle:
# call null new & static_typeof
if is(e.head,:call) || is(e.head,:call1)
t = abstract_eval_call(e, vtypes, sv)
elseif is(e.head,:null)
t = Void
elseif is(e.head,:new)
t = abstract_eval(e.args[1], vtypes, sv)
if isType(t)
t = t.parameters[1]
else
t = Any
end
for i = 2:length(e.args)
abstract_eval(e.args[i], vtypes, sv)
end
elseif is(e.head,:&)
abstract_eval(e.args[1], vtypes, sv)
t = Any
elseif is(e.head,:static_typeof)
var = e.args[1]
t = abstract_eval(var, vtypes, sv)
if isa(t,DataType) && typeseq(t,t.name.primary)
# remove unnecessary typevars
t = t.name.primary
end
if is(t,Bottom)
# if we haven't gotten fed-back type info yet, return Bottom. otherwise
# Bottom is the actual type of the variable, so return Type{Bottom}.
if haskey(sv.fedbackvars, var)
t = Type{Bottom}
end
elseif isleaftype(t)
t = Type{t}
elseif isleaftype(inference_stack.types)
if isa(t,TypeVar)
t = Type{t.ub}
else
t = Type{t}
end
else
# if there is any type uncertainty in the arguments, we are
# effectively predicting what static_typeof will say when
# the function is compiled with actual arguments. in that case
# abstract types yield Type{<:T} instead of Type{T}.
# this doesn't really model the situation perfectly, but