-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathreflection.jl
1468 lines (1268 loc) · 53.7 KB
/
reflection.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: https://julialang.org/license
const Compiler = Core.Compiler
"""
code_lowered(f, types; generated=true, debuginfo=:default)
Return an array of the lowered forms (IR) for the methods matching the given generic function
and type signature.
If `generated` is `false`, the returned `CodeInfo` instances will correspond to fallback
implementations. An error is thrown if no fallback implementation exists.
If `generated` is `true`, these `CodeInfo` instances will correspond to the method bodies
yielded by expanding the generators.
The keyword `debuginfo` controls the amount of code metadata present in the output.
Note that an error will be thrown if `types` are not leaf types when `generated` is
`true` and any of the corresponding methods are an `@generated` method.
"""
function code_lowered(@nospecialize(f), @nospecialize(t=Tuple); generated::Bool=true, debuginfo::Symbol=:default)
if @isdefined(IRShow)
debuginfo = IRShow.debuginfo(debuginfo)
elseif debuginfo === :default
debuginfo = :source
end
if debuginfo !== :source && debuginfo !== :none
throw(ArgumentError("'debuginfo' must be either :source or :none"))
end
world = get_world_counter()
world == typemax(UInt) && error("code reflection cannot be used from generated functions")
ret = CodeInfo[]
for m in method_instances(f, t, world)
if generated && hasgenerator(m)
if may_invoke_generator(m)
code = ccall(:jl_code_for_staged, Ref{CodeInfo}, (Any, UInt, Ptr{Cvoid}), m, world, C_NULL)
else
error("Could not expand generator for `@generated` method ", m, ". ",
"This can happen if the provided argument types (", t, ") are ",
"not leaf types, but the `generated` argument is `true`.")
end
else
code = uncompressed_ir(m.def::Method)
debuginfo === :none && remove_linenums!(code)
end
push!(ret, code)
end
return ret
end
# high-level, more convenient method lookup functions
function visit(f, mt::Core.MethodTable)
mt.defs !== nothing && visit(f, mt.defs)
nothing
end
function visit(f, mc::Core.TypeMapLevel)
function avisit(f, e::Memory{Any})
for i in 2:2:length(e)
isassigned(e, i) || continue
ei = e[i]
if ei isa Memory{Any}
for j in 2:2:length(ei)
isassigned(ei, j) || continue
visit(f, ei[j])
end
else
visit(f, ei)
end
end
end
if mc.targ !== nothing
avisit(f, mc.targ::Memory{Any})
end
if mc.arg1 !== nothing
avisit(f, mc.arg1::Memory{Any})
end
if mc.tname !== nothing
avisit(f, mc.tname::Memory{Any})
end
if mc.name1 !== nothing
avisit(f, mc.name1::Memory{Any})
end
mc.list !== nothing && visit(f, mc.list)
mc.any !== nothing && visit(f, mc.any)
nothing
end
function visit(f, d::Core.TypeMapEntry)
while d !== nothing
f(d.func)
d = d.next
end
nothing
end
struct MethodSpecializations
specializations::Union{Nothing, Core.MethodInstance, Core.SimpleVector}
end
"""
specializations(m::Method) → itr
Return an iterator `itr` of all compiler-generated specializations of `m`.
"""
specializations(m::Method) = MethodSpecializations(isdefined(m, :specializations) ? m.specializations : nothing)
function iterate(specs::MethodSpecializations)
s = specs.specializations
s === nothing && return nothing
isa(s, Core.MethodInstance) && return (s, nothing)
return iterate(specs, 0)
end
iterate(specs::MethodSpecializations, ::Nothing) = nothing
function iterate(specs::MethodSpecializations, i::Int)
s = specs.specializations::Core.SimpleVector
n = length(s)
i >= n && return nothing
item = nothing
while i < n && item === nothing
item = s[i+=1]
end
item === nothing && return nothing
return (item, i)
end
length(specs::MethodSpecializations) = count(Returns(true), specs)
function length(mt::Core.MethodTable)
n = 0
visit(mt) do m
n += 1
end
return n::Int
end
isempty(mt::Core.MethodTable) = (mt.defs === nothing)
uncompressed_ir(m::Method) = isdefined(m, :source) ? _uncompressed_ir(m) :
isdefined(m, :generator) ? error("Method is @generated; try `code_lowered` instead.") :
error("Code for this Method is not available.")
function _uncompressed_ir(m::Method)
s = m.source
if s isa String
s = ccall(:jl_uncompress_ir, Ref{CodeInfo}, (Any, Ptr{Cvoid}, Any), m, C_NULL, s)
end
return s::CodeInfo
end
# for backwards compat
const uncompressed_ast = uncompressed_ir
const _uncompressed_ast = _uncompressed_ir
function method_instances(@nospecialize(f), @nospecialize(t), world::UInt)
tt = signature_type(f, t)
results = Core.MethodInstance[]
# this make a better error message than the typeassert that follows
world == typemax(UInt) && error("code reflection cannot be used from generated functions")
for match in _methods_by_ftype(tt, -1, world)::Vector
instance = Core.Compiler.specialize_method(match::Core.MethodMatch)
push!(results, instance)
end
return results
end
function method_instance(@nospecialize(f), @nospecialize(t);
world=Base.get_world_counter(), method_table=nothing)
tt = signature_type(f, t)
mi = ccall(:jl_method_lookup_by_tt, Any,
(Any, Csize_t, Any),
tt, world, method_table)
return mi::Union{Nothing, MethodInstance}
end
default_debug_info_kind() = unsafe_load(cglobal(:jl_default_debug_info_kind, Cint))
# this type mirrors jl_cgparams_t (documented in julia.h)
struct CodegenParams
"""
If enabled, generate the necessary code to support the --track-allocations
command line flag to julia itself. Note that the option itself does not enable
allocation tracking. Rather, it merely generates the support code necessary
to perform allocation tracking if requested by the command line option.
"""
track_allocations::Cint
"""
If enabled, generate the necessary code to support the --code-coverage
command line flag to julia itself. Note that the option itself does not enable
code coverage. Rather, it merely generates the support code necessary
to code coverage if requested by the command line option.
"""
code_coverage::Cint
"""
If enabled, force the compiler to use the specialized signature
for all generated functions, whenever legal. If disabled, the choice is made
heuristically and specsig is only used when deemed profitable.
"""
prefer_specsig::Cint
"""
If enabled, enable emission of `.debug_names` sections.
"""
gnu_pubnames::Cint
"""
Controls what level of debug info to emit. Currently supported values are:
- 0: no debug info
- 1: full debug info
- 2: Line tables only
- 3: Debug directives only
The integer values currently match the llvm::DICompilerUnit::DebugEmissionKind enum,
although this is not guaranteed.
"""
debug_info_kind::Cint
"""
Controls the debug_info_level parameter, equivalent to the -g command line option.
"""
debug_info_level::Cint
"""
If enabled, generate a GC safepoint at the entry to every function. Emitting
these extra safepoints can reduce the amount of time that other threads are
waiting for the currently running thread to reach a safepoint. The cost for
a safepoint is small, but non-zero. The option is enabled by default.
"""
safepoint_on_entry::Cint
"""
If enabled, add an implicit argument to each function call that is used to
pass down the current task local state pointer. This argument is passed
using the `swiftself` convention, which in the ordinary case means that the
pointer is kept in a register and accesses are thus very fast. If this option
is disabled, the task local state pointer must be loaded from thread local
storage, which incurs a small amount of additional overhead. The option is enabled by
default.
"""
gcstack_arg::Cint
"""
If enabled, use the Julia PLT mechanism to support lazy-resolution of `ccall`
targets. The option may be disabled for use in environments where the julia
runtime is unavailable, but is otherwise recommended to be enabled, even if
lazy resolution is not required, as the Julia PLT mechanism may have superior
performance compared to the native platform mechanism. The options is enabled by default.
"""
use_jlplt::Cint
"""
If enabled, only provably reachable code (from functions marked with `entrypoint`) is included
in the output system image. Errors or warnings can be given for call sites too dynamic to handle.
The option is disabled by default. (0=>disabled, 1=>safe (static errors), 2=>unsafe, 3=>unsafe plus warnings)
"""
trim::Cint
"""
A pointer of type
typedef jl_value_t *(*jl_codeinstance_lookup_t)(jl_method_instance_t *mi JL_PROPAGATES_ROOT,
size_t min_world, size_t max_world);
that may be used by external compilers as a callback to look up the code instance corresponding
to a particular method instance.
"""
lookup::Ptr{Cvoid}
function CodegenParams(; track_allocations::Bool=true, code_coverage::Bool=true,
prefer_specsig::Bool=false,
gnu_pubnames::Bool=true, debug_info_kind::Cint = default_debug_info_kind(),
debug_info_level::Cint = Cint(JLOptions().debug_level), safepoint_on_entry::Bool=true,
gcstack_arg::Bool=true, use_jlplt::Bool=true, trim::Cint=Cint(0),
lookup::Ptr{Cvoid}=unsafe_load(cglobal(:jl_rettype_inferred_addr, Ptr{Cvoid})))
return new(
Cint(track_allocations), Cint(code_coverage),
Cint(prefer_specsig),
Cint(gnu_pubnames), debug_info_kind,
debug_info_level, Cint(safepoint_on_entry),
Cint(gcstack_arg), Cint(use_jlplt), Cint(trim),
lookup)
end
end
# this type mirrors jl_emission_params_t (documented in julia.h)
struct EmissionParams
emit_metadata::Cint
function EmissionParams(; emit_metadata::Bool=true)
return new(Cint(emit_metadata))
end
end
"""
code_typed(f, types; kw...)
Returns an array of type-inferred lowered form (IR) for the methods matching the given
generic function and type signature.
# Keyword Arguments
- `optimize::Bool = true`: optional, controls whether additional optimizations,
such as inlining, are also applied.
- `debuginfo::Symbol = :default`: optional, controls the amount of code metadata present
in the output, possible options are `:source` or `:none`.
# Internal Keyword Arguments
This section should be considered internal, and is only for who understands Julia compiler
internals.
- `world::UInt = Base.get_world_counter()`: optional, controls the world age to use
when looking up methods, use current world age if not specified.
- `interp::Core.Compiler.AbstractInterpreter = Core.Compiler.NativeInterpreter(world)`:
optional, controls the abstract interpreter to use, use the native interpreter if not specified.
# Examples
One can put the argument types in a tuple to get the corresponding `code_typed`.
```julia
julia> code_typed(+, (Float64, Float64))
1-element Vector{Any}:
CodeInfo(
1 ─ %1 = Base.add_float(x, y)::Float64
└── return %1
) => Float64
```
"""
function code_typed(@nospecialize(f), @nospecialize(types=default_tt(f)); kwargs...)
if isa(f, Core.OpaqueClosure)
return code_typed_opaque_closure(f, types; kwargs...)
end
tt = signature_type(f, types)
return code_typed_by_type(tt; kwargs...)
end
# returns argument tuple type which is supposed to be used for `code_typed` and its family;
# if there is a single method this functions returns the method argument signature,
# otherwise returns `Tuple` that doesn't match with any signature
function default_tt(@nospecialize(f))
ms = methods(f)
if length(ms) == 1
return tuple_type_tail(only(ms).sig)
else
return Tuple
end
end
function raise_match_failure(name::Symbol, @nospecialize(tt))
@noinline
sig_str = sprint(Base.show_tuple_as_call, Symbol(""), tt)
error("$name: unanalyzable call given $sig_str")
end
"""
code_typed_by_type(types::Type{<:Tuple}; ...)
Similar to [`code_typed`](@ref), except the argument is a tuple type describing
a full signature to query.
"""
function code_typed_by_type(@nospecialize(tt::Type);
optimize::Bool=true,
debuginfo::Symbol=:default,
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world))
(ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
error("code reflection cannot be used from generated functions")
if @isdefined(IRShow)
debuginfo = IRShow.debuginfo(debuginfo)
elseif debuginfo === :default
debuginfo = :source
end
if debuginfo !== :source && debuginfo !== :none
throw(ArgumentError("'debuginfo' must be either :source or :none"))
end
tt = to_tuple_type(tt)
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:code_typed, tt)
asts = []
for match in matches.matches
match = match::Core.MethodMatch
code = Compiler.typeinf_code(interp, match, optimize)
if code === nothing
push!(asts, match.method => Any)
else
debuginfo === :none && remove_linenums!(code)
push!(asts, code => code.rettype)
end
end
return asts
end
function get_oc_code_rt(oc::Core.OpaqueClosure, types, optimize::Bool)
@nospecialize oc types
ccall(:jl_is_in_pure_context, Bool, ()) &&
error("code reflection cannot be used from generated functions")
m = oc.source
if isa(m, Method)
if isdefined(m, :source)
if optimize
tt = Tuple{typeof(oc.captures), to_tuple_type(types).parameters...}
mi = Compiler.specialize_method(m, tt, Core.svec())
interp = Compiler.NativeInterpreter(m.primary_world)
code = Compiler.typeinf_code(interp, mi, optimize)
if code isa CodeInfo
return Pair{CodeInfo, Any}(code, code.rettype)
end
error("inference not successful")
else
code = _uncompressed_ir(m)
return Pair{CodeInfo, Any}(code, typeof(oc).parameters[2])
end
else
# OC constructed from optimized IR
codeinst = m.specializations.cache
# XXX: the inferred field is not normally a CodeInfo, but this assumes it is guaranteed to be always
return Pair{CodeInfo, Any}(codeinst.inferred, codeinst.rettype)
end
else
error("encountered invalid Core.OpaqueClosure object")
end
end
function code_typed_opaque_closure(oc::Core.OpaqueClosure, types;
debuginfo::Symbol=:default,
optimize::Bool=true,
_...)
@nospecialize oc types
(code, rt) = get_oc_code_rt(oc, types, optimize)
debuginfo === :none && remove_linenums!(code)
return Any[Pair{CodeInfo,Any}(code, rt)]
end
"""
code_ircode(f, [types])
Return an array of pairs of `IRCode` and inferred return type if type inference succeeds.
The `Method` is included instead of `IRCode` otherwise.
See also: [`code_typed`](@ref)
# Internal Keyword Arguments
This section should be considered internal, and is only for who understands Julia compiler
internals.
- `world::UInt = Base.get_world_counter()`: optional, controls the world age to use
when looking up methods, use current world age if not specified.
- `interp::Core.Compiler.AbstractInterpreter = Core.Compiler.NativeInterpreter(world)`:
optional, controls the abstract interpreter to use, use the native interpreter if not specified.
- `optimize_until::Union{Integer,AbstractString,Nothing} = nothing`: optional,
controls the optimization passes to run.
If it is a string, it specifies the name of the pass up to which the optimizer is run.
If it is an integer, it specifies the number of passes to run.
If it is `nothing` (default), all passes are run.
# Examples
One can put the argument types in a tuple to get the corresponding `code_ircode`.
```julia
julia> Base.code_ircode(+, (Float64, Int64))
1-element Vector{Any}:
388 1 ─ %1 = Base.sitofp(Float64, _3)::Float64
│ %2 = Base.add_float(_2, %1)::Float64
└── return %2
=> Float64
julia> Base.code_ircode(+, (Float64, Int64); optimize_until = "compact 1")
1-element Vector{Any}:
388 1 ─ %1 = Base.promote(_2, _3)::Tuple{Float64, Float64}
│ %2 = Core._apply_iterate(Base.iterate, Base.:+, %1)::Float64
└── return %2
=> Float64
```
"""
function code_ircode(@nospecialize(f), @nospecialize(types = default_tt(f)); kwargs...)
if isa(f, Core.OpaqueClosure)
error("OpaqueClosure not supported")
end
tt = signature_type(f, types)
return code_ircode_by_type(tt; kwargs...)
end
"""
code_ircode_by_type(types::Type{<:Tuple}; ...)
Similar to [`code_ircode`](@ref), except the argument is a tuple type describing
a full signature to query.
"""
function code_ircode_by_type(
@nospecialize(tt::Type);
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world),
optimize_until::Union{Integer,AbstractString,Nothing}=nothing,
)
(ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
error("code reflection cannot be used from generated functions")
tt = to_tuple_type(tt)
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:code_ircode, tt)
asts = []
for match in matches.matches
match = match::Core.MethodMatch
(code, ty) = Compiler.typeinf_ircode(interp, match, optimize_until)
if code === nothing
push!(asts, match.method => Any)
else
push!(asts, code => ty)
end
end
return asts
end
function _builtin_return_type(interp::Compiler.AbstractInterpreter,
@nospecialize(f::Core.Builtin), @nospecialize(types))
argtypes = Any[to_tuple_type(types).parameters...]
rt = Compiler.builtin_tfunction(interp, f, argtypes, nothing)
return Compiler.widenconst(rt)
end
function _builtin_effects(interp::Compiler.AbstractInterpreter,
@nospecialize(f::Core.Builtin), @nospecialize(types))
argtypes = Any[to_tuple_type(types).parameters...]
rt = Compiler.builtin_tfunction(interp, f, argtypes, nothing)
return Compiler.builtin_effects(Compiler.typeinf_lattice(interp), f, argtypes, rt)
end
function _builtin_exception_type(interp::Compiler.AbstractInterpreter,
@nospecialize(f::Core.Builtin), @nospecialize(types))
effects = _builtin_effects(interp, f, types)
return Compiler.is_nothrow(effects) ? Union{} : Any
end
check_generated_context(world::UInt) =
(ccall(:jl_is_in_pure_context, Bool, ()) || world == typemax(UInt)) &&
error("code reflection cannot be used from generated functions")
# TODO rename `Base.return_types` to `Base.infer_return_types`
"""
Base.return_types(
f, types=default_tt(f);
world::UInt=get_world_counter(),
interp::NativeInterpreter=Core.Compiler.NativeInterpreter(world)) -> rts::Vector{Any}
Return a list of possible return types for a given function `f` and argument types `types`.
The list corresponds to the results of type inference on all the possible method match
candidates for `f` and `types` (see also [`methods(f, types)`](@ref methods).
# Arguments
- `f`: The function to analyze.
- `types` (optional): The argument types of the function. Defaults to the default tuple type of `f`.
- `world` (optional): The world counter to use for the analysis. Defaults to the current world counter.
- `interp` (optional): The abstract interpreter to use for the analysis. Defaults to a new `Core.Compiler.NativeInterpreter` with the specified `world`.
# Returns
- `rts::Vector{Any}`: The list of return types that are figured out by inference on
methods matching with the given `f` and `types`. The list's order matches the order
returned by `methods(f, types)`.
# Examples
```julia
julia> Base.return_types(sum, Tuple{Vector{Int}})
1-element Vector{Any}:
Int64
julia> methods(sum, (Union{Vector{Int},UnitRange{Int}},))
# 2 methods for generic function "sum" from Base:
[1] sum(r::AbstractRange{<:Real})
@ range.jl:1399
[2] sum(a::AbstractArray; dims, kw...)
@ reducedim.jl:1010
julia> Base.return_types(sum, (Union{Vector{Int},UnitRange{Int}},))
2-element Vector{Any}:
Int64 # the result of inference on sum(r::AbstractRange{<:Real})
Int64 # the result of inference on sum(a::AbstractArray; dims, kw...)
```
!!! warning
The `Base.return_types` function should not be used from generated functions;
doing so will result in an error.
"""
function return_types(@nospecialize(f), @nospecialize(types=default_tt(f));
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world))
check_generated_context(world)
if isa(f, Core.OpaqueClosure)
_, rt = only(code_typed_opaque_closure(f, types))
return Any[rt]
elseif isa(f, Core.Builtin)
return Any[_builtin_return_type(interp, f, types)]
end
tt = signature_type(f, types)
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:return_types, tt)
rts = Any[]
for match in matches.matches
ty = Compiler.typeinf_type(interp, match::Core.MethodMatch)
push!(rts, something(ty, Any))
end
return rts
end
"""
Base.infer_return_type(
f, types=default_tt(f);
world::UInt=get_world_counter(),
interp::Core.Compiler.AbstractInterpreter=Core.Compiler.NativeInterpreter(world)) -> rt::Type
Returns an inferred return type of the function call specified by `f` and `types`.
# Arguments
- `f`: The function to analyze.
- `types` (optional): The argument types of the function. Defaults to the default tuple type of `f`.
- `world` (optional): The world counter to use for the analysis. Defaults to the current world counter.
- `interp` (optional): The abstract interpreter to use for the analysis. Defaults to a new `Core.Compiler.NativeInterpreter` with the specified `world`.
# Returns
- `rt::Type`: An inferred return type of the function call specified by the given call signature.
!!! note
Note that, different from [`Base.return_types`](@ref), this doesn't give you the list
return types of every possible method matching with the given `f` and `types`.
It returns a single return type, taking into account all potential outcomes of
any function call entailed by the given signature type.
# Examples
```julia
julia> checksym(::Symbol) = :symbol;
julia> checksym(x::Any) = x;
julia> Base.infer_return_type(checksym, (Union{Symbol,String},))
Union{String, Symbol}
julia> Base.return_types(checksym, (Union{Symbol,String},))
2-element Vector{Any}:
Symbol
Union{String, Symbol}
```
It's important to note the difference here: `Base.return_types` gives back inferred results
for each method that matches the given signature `checksum(::Union{Symbol,String})`.
On the other hand `Base.infer_return_type` returns one collective result that sums up all those possibilities.
!!! warning
The `Base.infer_return_type` function should not be used from generated functions;
doing so will result in an error.
"""
function infer_return_type(@nospecialize(f), @nospecialize(types=default_tt(f));
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world))
check_generated_context(world)
if isa(f, Core.OpaqueClosure)
return last(only(code_typed_opaque_closure(f, types)))
elseif isa(f, Core.Builtin)
return _builtin_return_type(interp, f, types)
end
tt = signature_type(f, types)
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:infer_return_type, tt)
rt = Union{}
for match in matches.matches
ty = Compiler.typeinf_type(interp, match::Core.MethodMatch)
rt = Compiler.tmerge(rt, something(ty, Any))
end
return rt
end
"""
Base.infer_exception_types(
f, types=default_tt(f);
world::UInt=get_world_counter(),
interp::NativeInterpreter=Core.Compiler.NativeInterpreter(world)) -> excts::Vector{Any}
Return a list of possible exception types for a given function `f` and argument types `types`.
The list corresponds to the results of type inference on all the possible method match
candidates for `f` and `types` (see also [`methods(f, types)`](@ref methods).
It works like [`Base.return_types`](@ref), but it infers the exception types instead of the return types.
# Arguments
- `f`: The function to analyze.
- `types` (optional): The argument types of the function. Defaults to the default tuple type of `f`.
- `world` (optional): The world counter to use for the analysis. Defaults to the current world counter.
- `interp` (optional): The abstract interpreter to use for the analysis. Defaults to a new `Core.Compiler.NativeInterpreter` with the specified `world`.
# Returns
- `excts::Vector{Any}`: The list of exception types that are figured out by inference on
methods matching with the given `f` and `types`. The list's order matches the order
returned by `methods(f, types)`.
# Examples
```julia
julia> throw_if_number(::Number) = error("number is given");
julia> throw_if_number(::Any) = nothing;
julia> Base.infer_exception_types(throw_if_number, (Int,))
1-element Vector{Any}:
ErrorException
julia> methods(throw_if_number, (Any,))
# 2 methods for generic function "throw_if_number" from Main:
[1] throw_if_number(x::Number)
@ REPL[1]:1
[2] throw_if_number(::Any)
@ REPL[2]:1
julia> Base.infer_exception_types(throw_if_number, (Any,))
2-element Vector{Any}:
ErrorException # the result of inference on `throw_if_number(::Number)`
Union{} # the result of inference on `throw_if_number(::Any)`
```
!!! warning
The `Base.infer_exception_types` function should not be used from generated functions;
doing so will result in an error.
"""
function infer_exception_types(@nospecialize(f), @nospecialize(types=default_tt(f));
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world))
check_generated_context(world)
if isa(f, Core.OpaqueClosure)
return Any[Any] # TODO
elseif isa(f, Core.Builtin)
return Any[_builtin_exception_type(interp, f, types)]
end
tt = signature_type(f, types)
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:infer_exception_types, tt)
excts = Any[]
for match in matches.matches
frame = Compiler.typeinf_frame(interp, match::Core.MethodMatch, #=run_optimizer=#false)
if frame === nothing
exct = Any
else
exct = Compiler.widenconst(frame.result.exc_result)
end
push!(excts, exct)
end
return excts
end
_may_throw_methoderror(matches#=::Core.Compiler.MethodLookupResult=#) =
matches.ambig || !any(match::Core.MethodMatch->match.fully_covers, matches.matches)
"""
Base.infer_exception_type(
f, types=default_tt(f);
world::UInt=get_world_counter(),
interp::Core.Compiler.AbstractInterpreter=Core.Compiler.NativeInterpreter(world)) -> exct::Type
Returns the type of exception potentially thrown by the function call specified by `f` and `types`.
# Arguments
- `f`: The function to analyze.
- `types` (optional): The argument types of the function. Defaults to the default tuple type of `f`.
- `world` (optional): The world counter to use for the analysis. Defaults to the current world counter.
- `interp` (optional): The abstract interpreter to use for the analysis. Defaults to a new `Core.Compiler.NativeInterpreter` with the specified `world`.
# Returns
- `exct::Type`: The inferred type of exception that can be thrown by the function call
specified by the given call signature.
!!! note
Note that, different from [`Base.infer_exception_types`](@ref), this doesn't give you the list
exception types for every possible matching method with the given `f` and `types`.
It returns a single exception type, taking into account all potential outcomes of
any function call entailed by the given signature type.
# Examples
```julia
julia> f1(x) = x * 2;
julia> Base.infer_exception_type(f1, (Int,))
Union{}
```
The exception inferred as `Union{}` indicates that `f1(::Int)` will not throw any exception.
```julia
julia> f2(x::Int) = x * 2;
julia> Base.infer_exception_type(f2, (Integer,))
MethodError
```
This case is pretty much the same as with `f1`, but there's a key difference to note. For
`f2`, the argument type is limited to `Int`, while the argument type is given as `Tuple{Integer}`.
Because of this, taking into account the chance of the method error entailed by the call
signature, the exception type is widened to `MethodError`.
!!! warning
The `Base.infer_exception_type` function should not be used from generated functions;
doing so will result in an error.
"""
function infer_exception_type(@nospecialize(f), @nospecialize(types=default_tt(f));
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world))
check_generated_context(world)
if isa(f, Core.OpaqueClosure)
return Any # TODO
elseif isa(f, Core.Builtin)
return _builtin_exception_type(interp, f, types)
end
tt = signature_type(f, types)
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:infer_exception_type, tt)
exct = Union{}
if _may_throw_methoderror(matches)
# account for the fact that we may encounter a MethodError with a non-covered or ambiguous signature.
exct = Compiler.tmerge(exct, MethodError)
end
for match in matches.matches
match = match::Core.MethodMatch
frame = Compiler.typeinf_frame(interp, match, #=run_optimizer=#false)
frame === nothing && return Any
exct = Compiler.tmerge(exct, Compiler.widenconst(frame.result.exc_result))
end
return exct
end
"""
Base.infer_effects(
f, types=default_tt(f);
optimize::Bool=true,
world::UInt=get_world_counter(),
interp::Core.Compiler.AbstractInterpreter=Core.Compiler.NativeInterpreter(world)) -> effects::Effects
Returns the possible computation effects of the function call specified by `f` and `types`.
# Arguments
- `f`: The function to analyze.
- `types` (optional): The argument types of the function. Defaults to the default tuple type of `f`.
- `optimize` (optional): Whether to run additional effects refinements based on post-optimization analysis.
- `world` (optional): The world counter to use for the analysis. Defaults to the current world counter.
- `interp` (optional): The abstract interpreter to use for the analysis. Defaults to a new `Core.Compiler.NativeInterpreter` with the specified `world`.
# Returns
- `effects::Effects`: The computed effects of the function call specified by the given call signature.
See the documentation of [`Effects`](@ref Core.Compiler.Effects) or [`Base.@assume_effects`](@ref)
for more information on the various effect properties.
!!! note
Note that, different from [`Base.return_types`](@ref), this doesn't give you the list
effect analysis results for every possible matching method with the given `f` and `types`.
It returns a single effect, taking into account all potential outcomes of any function
call entailed by the given signature type.
# Examples
```julia
julia> f1(x) = x * 2;
julia> Base.infer_effects(f1, (Int,))
(+c,+e,+n,+t,+s,+m,+i)
```
This function will return an `Effects` object with information about the computational
effects of the function `f1` when called with an `Int` argument.
```julia
julia> f2(x::Int) = x * 2;
julia> Base.infer_effects(f2, (Integer,))
(+c,+e,!n,+t,+s,+m,+i)
```
This case is pretty much the same as with `f1`, but there's a key difference to note. For
`f2`, the argument type is limited to `Int`, while the argument type is given as `Tuple{Integer}`.
Because of this, taking into account the chance of the method error entailed by the call
signature, the `:nothrow` bit gets tainted.
!!! warning
The `Base.infer_effects` function should not be used from generated functions;
doing so will result in an error.
$(Core.Compiler.effects_key_string)
# See Also
- [`Core.Compiler.Effects`](@ref): A type representing the computational effects of a method call.
- [`Base.@assume_effects`](@ref): A macro for making assumptions about the effects of a method.
"""
function infer_effects(@nospecialize(f), @nospecialize(types=default_tt(f));
optimize::Bool=true,
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world))
check_generated_context(world)
if isa(f, Core.Builtin)
return _builtin_effects(interp, f, types)
end
tt = signature_type(f, types)
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:infer_effects, tt)
effects = Compiler.EFFECTS_TOTAL
if _may_throw_methoderror(matches)
# account for the fact that we may encounter a MethodError with a non-covered or ambiguous signature.
effects = Compiler.Effects(effects; nothrow=false)
end
for match in matches.matches
match = match::Core.MethodMatch
frame = Compiler.typeinf_frame(interp, match, #=run_optimizer=#optimize)
frame === nothing && return Compiler.Effects()
effects = Compiler.merge_effects(effects, frame.result.ipo_effects)
end
return effects
end
"""
print_statement_costs(io::IO, f, types)
Print type-inferred and optimized code for `f` given argument types `types`,
prepending each line with its cost as estimated by the compiler's inlining engine.
"""
function print_statement_costs(io::IO, @nospecialize(f), @nospecialize(t); kwargs...)
tt = signature_type(f, t)
print_statement_costs(io, tt; kwargs...)
end
function print_statement_costs(io::IO, @nospecialize(tt::Type);
world::UInt=get_world_counter(),
interp::Compiler.AbstractInterpreter=Compiler.NativeInterpreter(world))
tt = to_tuple_type(tt)
world == typemax(UInt) && error("code reflection cannot be used from generated functions")
matches = Compiler.findall(tt, Compiler.method_table(interp))
matches === nothing && raise_match_failure(:print_statement_costs, tt)
params = Compiler.OptimizationParams(interp)
cst = Int[]
for match in matches.matches
match = match::Core.MethodMatch
println(io, match.method)
code = Compiler.typeinf_code(interp, match, true)
if code === nothing
println(io, " inference not successful")
else
empty!(cst)
resize!(cst, length(code.code))
sptypes = Compiler.VarState[Compiler.VarState(sp, false) for sp in match.sparams]
maxcost = Compiler.statement_costs!(cst, code.code, code, sptypes, params)
nd = ndigits(maxcost)
irshow_config = IRShow.IRShowConfig() do io, linestart, idx
print(io, idx > 0 ? lpad(cst[idx], nd+1) : " "^(nd+1), " ")
return ""
end
IRShow.show_ir(io, code, irshow_config)
end
println(io)
end
end
print_statement_costs(args...; kwargs...) = print_statement_costs(stdout, args...; kwargs...)
function _which(@nospecialize(tt::Type);
method_table::Union{Nothing,Core.MethodTable,Compiler.MethodTableView}=nothing,
world::UInt=get_world_counter(),
raise::Bool=true)
world == typemax(UInt) && error("code reflection cannot be used from generated functions")
if method_table === nothing
table = Compiler.InternalMethodTable(world)
elseif method_table isa Core.MethodTable
table = Compiler.OverlayMethodTable(world, method_table)
else
table = method_table
end
match, = Compiler.findsup(tt, table)
if match === nothing
raise && error("no unique matching method found for the specified argument types")
return nothing
end
return match
end
"""
which(f, types)
Returns the method of `f` (a `Method` object) that would be called for arguments of the given `types`.
If `types` is an abstract type, then the method that would be called by `invoke` is returned.
See also: [`parentmodule`](@ref), [`@which`](@ref Main.InteractiveUtils.@which), and [`@edit`](@ref Main.InteractiveUtils.@edit).
"""
function which(@nospecialize(f), @nospecialize(t))
tt = signature_type(f, t)
world = get_world_counter()
match, _ = Compiler._findsup(tt, nothing, world)
if match === nothing
me = MethodError(f, t, world)
ee = ErrorException(sprint(io -> begin
println(io, "Calling invoke(f, t, args...) would throw:");
Base.showerror(io, me);
end))
throw(ee)
end
return match.method
end
"""
which(types::Type{<:Tuple})