forked from JamesWrigley/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprecompile.jl
2096 lines (1908 loc) · 73.9 KB
/
precompile.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
using Test, Distributed, Random, Logging
using REPL # doc lookup function
include("precompile_utils.jl")
Foo_module = :Foo4b3a94a1a081a8cb
foo_incl_dep = :foo4b3a94a1a081a8cb
bar_incl_dep = :bar4b3a94a1a081a8cb
Foo2_module = :F2oo4b3a94a1a081a8cb
FooBase_module = :FooBase4b3a94a1a081a8cb
@eval module ConflictingBindings
export $Foo_module, $FooBase_module
$Foo_module = 232
$FooBase_module = 9134
end
using .ConflictingBindings
@testset "object_build_id" begin
@test Base.object_build_id([1]) === nothing
@test Base.object_build_id(Base) == Base.module_build_id(Base)
end
# method root provenance
rootid(m::Module) = Base.module_build_id(Base.parentmodule(m)) % UInt64
rootid(m::Method) = rootid(m.module)
function root_provenance(m::Method, i::Int)
mid = rootid(m)
isdefined(m, :root_blocks) || return mid
idxs = view(m.root_blocks, 2:2:length(m.root_blocks))
j = searchsortedfirst(idxs, i) - 1 # RLE roots are 0-indexed
j == 0 && return mid
return m.root_blocks[2*j-1]
end
struct RLEIterator{T} # for method roots, T = UInt64 (even on 32-bit)
items::Vector{Any}
blocks::Vector{T}
defaultid::T
end
function RLEIterator(roots, blocks, defaultid)
T = promote_type(eltype(blocks), typeof(defaultid))
return RLEIterator{T}(convert(Vector{Any}, roots), blocks, defaultid)
end
RLEIterator(m::Method) = RLEIterator(m.roots, m.root_blocks, rootid(m))
Base.iterate(iter::RLEIterator) = iterate(iter, (0, 0, iter.defaultid))
function Base.iterate(iter::RLEIterator, (i, j, cid))
i += 1
i > length(iter.items) && return nothing
r = iter.items[i]
while (j + 1 < length(iter.blocks) && i > iter.blocks[j+2])
cid = iter.blocks[j+1]
j += 2
end
return cid => r, (i, j, cid)
end
function group_roots(m::Method)
mid = rootid(m)
isdefined(m, :root_blocks) || return Dict(mid => m.roots)
group_roots(RLEIterator(m.roots, m.root_blocks, mid))
end
function group_roots(iter::RLEIterator)
rootsby = Dict{typeof(iter.defaultid),Vector{Any}}()
for (id, r) in iter
list = get!(valtype(rootsby), rootsby, id)
push!(list, r)
end
return rootsby
end
precompile_test_harness("basic precompile functionality") do dir2
precompile_test_harness(false) do dir
Foo_file = joinpath(dir, "$Foo_module.jl")
Foo2_file = joinpath(dir, "$Foo2_module.jl")
FooBase_file = joinpath(dir, "$FooBase_module.jl")
foo_file = joinpath(dir, "$foo_incl_dep.jl")
bar_file = joinpath(dir, "$bar_incl_dep.jl")
write(FooBase_file,
"""
false && __precompile__(false)
module $FooBase_module
import Base: hash, >
struct fmpz end
struct typeA end
>(x::fmpz, y::Int) = Base.cmp(x, y) > 0
function hash(a::typeA, h::UInt)
d = den(a)
return h
end
abstract type AbstractAlgebraMap{A} end
struct GAPGroupHomomorphism{A, B} <: AbstractAlgebraMap{GAPGroupHomomorphism{B, A}} end
end
""")
write(Foo2_file,
"""
module $Foo2_module
export override, overridenc
override(x::Integer) = 2
override(x::AbstractFloat) = Float64(override(1))
overridenc(x::Integer) = rand()+1
overridenc(x::AbstractFloat) = Float64(overridenc(1))
end
""")
write(Foo_file,
"""
module $Foo_module
import $FooBase_module, $FooBase_module.typeA, $FooBase_module.GAPGroupHomomorphism
import $Foo2_module: $Foo2_module, override, overridenc
import $FooBase_module.hash
import Test
public foo, Bar
module Inner
import $FooBase_module.hash
using ..$Foo_module
import ..$Foo2_module
end
struct typeB
y::typeA
end
hash(x::typeB) = hash(x.y)
# test that docs get reconnected
@doc "foo function" foo(x) = x + 1
include_dependency("$foo_incl_dep.jl")
include_dependency("$foo_incl_dep.jl")
module Bar
public bar
include_dependency("$bar_incl_dep.jl")
end
@doc "Bar module" Bar # this needs to define the META dictionary via eval
@eval Bar @doc "bar function" bar(x) = x + 2
# test for creation of some reasonably complicated type
struct MyType{T} end
const t17809s = Any[
Tuple{
Type{Ptr{MyType{i}}},
Ptr{Type{MyType{i}}},
Array{Ptr{MyType{MyType{:sym}()}}(0), 0},
Val{Complex{Int}(1, 2)},
Val{3},
Val{nothing}}
for i = 0:25]
# test that types and methods get reconnected correctly
# issue 16529 (adding a method to a type with no instances)
(::Task)(::UInt8, ::UInt16, ::UInt32) = 2
# issue 16471
Base.sin(::UInt8, ::UInt16, ::UInt32; x = 52) = x
const sinkw = Core.kwcall
# issue 16908 (some complicated types and external method definitions)
abstract type CategoricalPool{T, R <: Integer, V} end
abstract type CategoricalValue{T, R <: Integer} end
struct NominalPool{T, R <: Integer, V} <: CategoricalPool{T, R, V}
index::Vector{T}
invindex::Dict{T, R}
order::Vector{R}
ordered::Vector{T}
valindex::Vector{V}
end
struct NominalValue{T, R <: Integer} <: CategoricalValue{T, R}
level::R
pool::NominalPool{T, R, NominalValue{T, R}}
end
struct OrdinalValue{T, R <: Integer} <: CategoricalValue{T, R}
level::R
pool::NominalPool{T, R, NominalValue{T, R}}
end
(::Union{Type{NominalValue}, Type{OrdinalValue}})() = 1
(::Union{Type{NominalValue{T}}, Type{OrdinalValue{T}}})() where {T} = 2
(::Type{Vector{NominalValue{T, R}}})() where {T, R} = 3
(::Type{Vector{NominalValue{T, T}}})() where {T} = 4
(::Type{Vector{NominalValue{Int, Int}}})() = 5
# more tests for method signature involving a complicated type
# issue 18343
struct Pool18343{R, V}
valindex::Vector{V}
end
struct Value18343{T, R}
pool::Pool18343{R, Value18343{T, R}}
end
Base.convert(::Type{Some{S}}, ::Value18343{Some}) where {S} = 2
Base.convert(::Type{Some{Value18343}}, ::Value18343{Some}) = 2
Base.convert(::Type{Ref}, ::Value18343{T}) where {T} = 3
const GAPType1 = GAPGroupHomomorphism{Nothing, Nothing}
const GAPType2 = GAPGroupHomomorphism{1, 2}
# issue #28297
mutable struct Result
result::Union{Int,Missing}
end
const x28297 = Result(missing)
const d29936a = UnionAll(Dict.var, UnionAll(Dict.body.var, Dict.body.body))
const d29936b = UnionAll(Dict.body.var, UnionAll(Dict.var, Dict.body.body))
# issue #28998
const x28998 = [missing, 2, missing, 6, missing,
missing, missing, missing,
missing, missing, missing,
missing, missing, 6]
let some_method = which(Base.include, (Module, String,))
# global const some_method // FIXME: support for serializing a direct reference to an external Method not implemented
global const some_linfo = Core.Compiler.specialize_method(some_method,
Tuple{typeof(Base.include), Module, String}, Core.svec())
end
g() = override(1.0)
Test.@test g() === 2.0 # compile this
gnc() = overridenc(1.0)
Test.@test 1 < gnc() < 5 # compile this
abigfloat_f() = big"12.34"
const abigfloat_x = big"43.21"
abigint_f() = big"123"
const abigint_x = big"124"
# issue #51111
abigfloat_to_f32() = Float32(big"1.5")
# issue #31488
_v31488 = Base.StringVector(2)
resize!(_v31488, 0)
const a31488 = fill(String(_v31488), 100)
const ptr1 = Ptr{UInt8}(1)
ptr2 = Ptr{UInt8}(1)
const ptr3 = Ptr{UInt8}(-1)
const layout1 = Ptr{Int8}[Ptr{Int8}(0), Ptr{Int8}(1), Ptr{Int8}(-1)]
const layout2 = Any[Ptr{Int8}(0), Ptr{Int16}(1), Ptr{Int32}(-1)]
const layout3 = collect(x.match for x in eachmatch(r"..", "abcdefghijk"))::Vector{SubString{String}}
# create a backedge that includes Type{Union{}}, to ensure lookup can handle that
call_bottom() = show(stdout, Union{})
Core.Compiler.return_type(call_bottom, Tuple{})
# check that @ccallable works from precompiled modules
Base.@ccallable Cint f35014(x::Cint) = x+Cint(1)
# check that Tasks work from serialized state
ch1 = Channel(x -> nothing)
ch2 = Channel(x -> (push!(x, 2); nothing), Inf)
# check that Memory aliasing is respected
a_vec_int = Int[]
push!(a_vec_int, 1, 2)
a_mat_int = reshape(a_vec_int, (1, 2))
a_vec_any = Any[]
push!(a_vec_any, 1, 2)
a_mat_any = reshape(a_vec_any, (1, 2))
a_vec_union = Union{Int,Nothing}[]
push!(a_vec_union, 1, 2)
a_mat_union = reshape(a_vec_union, (1, 2))
a_vec_inline = Pair{Int,Any}[]
push!(a_vec_inline, 1=>2, 3=>4)
a_mat_inline = reshape(a_vec_inline, (1, 2))
oid_vec_int = objectid(a_vec_int)
oid_mat_int = objectid(a_mat_int)
end
""")
# Issue #52063
touch(foo_file); touch(bar_file)
# Issue #12623
@test __precompile__(false) === nothing
# Issue #21307
Foo2 = Base.require(Main, Foo2_module)
@eval $Foo2.override(::Int) = 'a'
@eval $Foo2.override(::Float32) = 'b'
@eval $Foo2.overridenc(::Int) = rand() + 97.0
@eval $Foo2.overridenc(::Float32) = rand() + 100.0
Foo = Base.require(Main, Foo_module)
Base.invokelatest() do # use invokelatest to see the results of loading the compile
@test Foo.foo(17) == 18
@test Foo.Bar.bar(17) == 19
# Issue #21307
@test Foo.g() === 97.0
@test 96 < Foo.gnc() < 99
@test Foo.override(1.0e0) == Float64('a')
@test Foo.override(1.0f0) == 'b'
@test Foo.override(UInt(1)) == 2
@test 96 < Foo.overridenc(1.0e0) < 99
@test 99 < Foo.overridenc(1.0f0) < 102
@test 0 < Foo.overridenc(UInt(1)) < 3
# Issue #15722
@test Foo.abigfloat_f()::BigFloat == big"12.34"
@test (Foo.abigfloat_x::BigFloat + 21) == big"64.21"
@test Foo.abigint_f()::BigInt == big"123"
@test Foo.abigint_x::BigInt + 1 == big"125"
# Issue #51111
@test Foo.abigfloat_to_f32() == 1.5f0
@test Foo.x28297.result === missing
@test Foo.d29936a === Dict
@test Foo.d29936b === Dict{K,V} where {V,K}
@test Foo.x28998[end] == 6
@test Foo.a31488 == fill("", 100)
@test Foo.ptr1 === Ptr{UInt8}(1)
@test Foo.ptr2 === Ptr{UInt8}(0)
@test Foo.ptr3 === Ptr{UInt8}(-1)
@test Foo.layout1::Vector{Ptr{Int8}} == Ptr{Int8}[Ptr{Int8}(0), Ptr{Int8}(0), Ptr{Int8}(-1)]
@test Foo.layout2 == Any[Ptr{Int8}(0), Ptr{Int16}(0), Ptr{Int32}(-1)]
@test typeof.(Foo.layout2) == [Ptr{Int8}, Ptr{Int16}, Ptr{Int32}]
@test Foo.layout3 == ["ab", "cd", "ef", "gh", "ij"]
@test !isopen(Foo.ch1)
@test !isopen(Foo.ch2)
@test !isready(Foo.ch1)
@test isready(Foo.ch2)
@test take!(Foo.ch2) === 2
@test !isready(Foo.ch2)
end
let
@test Foo.a_vec_int == Int[1, 2]
@test Foo.a_mat_int == Int[1 2]
Foo.a_mat_int[1, 2] = 3
@test Foo.a_vec_int[2] === 3
@test Foo.a_vec_any == Int[1, 2]
@test Foo.a_mat_any == Int[1 2]
Foo.a_mat_any[1, 2] = 3
@test Foo.a_vec_any[2] === 3
@test Foo.a_vec_union == Union{Int,Nothing}[1, 2]
@test Foo.a_mat_union == Union{Int,Nothing}[1 2]
Foo.a_mat_union[1, 2] = 3
@test Foo.a_vec_union[2] === 3
Foo.a_mat_union[1, 2] = nothing
@test Foo.a_vec_union[2] === nothing
@test Foo.a_vec_inline == Pair{Int,Any}[1=>2, 3=>4]
@test Foo.a_mat_inline == Pair{Int,Any}[1=>2 3=>4]
Foo.a_mat_inline[1, 2] = 5=>6
@test Foo.a_vec_inline[2] === Pair{Int,Any}(5, 6)
@test objectid(Foo.a_vec_int) === Foo.oid_vec_int
@test objectid(Foo.a_mat_int) === Foo.oid_mat_int
@test Foo.oid_vec_int !== Foo.oid_mat_int
@test Base.object_build_id(Foo.a_vec_int) == Base.object_build_id(Foo.a_mat_int)
@test Base.object_build_id(Foo) == Base.module_build_id(Foo)
@test Base.object_build_id(Foo.a_vec_int) == Base.module_build_id(Foo)
end
@eval begin function ccallable_test()
Base.llvmcall(
("""declare i32 @f35014(i32)
define i32 @entry() {
0:
%1 = call i32 @f35014(i32 3)
ret i32 %1
}""", "entry"
), Cint, Tuple{})
end
@test ccallable_test() == 4
end
cachedir = joinpath(dir, "compiled", "v$(VERSION.major).$(VERSION.minor)")
cachedir2 = joinpath(dir2, "compiled", "v$(VERSION.major).$(VERSION.minor)")
cachefile = joinpath(cachedir, "$Foo_module.ji")
do_pkgimg = Base.JLOptions().use_pkgimages == 1 && Base.JLOptions().permalloc_pkgimg == 1
if do_pkgimg || Base.JLOptions().use_pkgimages == 0
if do_pkgimg
ocachefile = Base.ocachefile_from_cachefile(cachefile)
else
ocachefile = nothing
end
# use _require_from_serialized to ensure that the test fails if
# the module doesn't reload from the image:
@test_warn "@ccallable was already defined for this method name" begin
@test_logs (:warn, "Replacing module `$Foo_module`") begin
m = Base._require_from_serialized(Base.PkgId(Foo), cachefile, ocachefile, Foo_file)
@test isa(m, Module)
end
end
end
@test_throws MethodError Foo.foo(17) # world shouldn't be visible yet
Base.invokelatest() do # use invokelatest to see the results of loading the compile
@test Foo.foo(17) == 18
@test Foo.Bar.bar(17) == 19
# Issue #21307
@test Foo.g() === 97.0
@test Foo.override(1.0e0) == Float64('a')
@test Foo.override(1.0f0) == 'b'
@test Foo.override(UInt(1)) == 2
# issue #12284:
@test string(Base.Docs.doc(Foo.foo)) == "foo function\n"
@test string(Base.Docs.doc(Foo.Bar.bar)) == "bar function\n"
@test string(Base.Docs.doc(Foo.Bar)) == "Bar module\n"
modules, (deps, _, requires), required_modules, _... = Base.parse_cache_header(cachefile)
discard_module = mod_fl_mt -> mod_fl_mt.filename
@test modules == [ Base.PkgId(Foo) => Base.module_build_id(Foo) % UInt64 ]
@test map(x -> x.filename, deps) == [ Foo_file, joinpath("@depot", foo_file), joinpath("@depot", bar_file) ]
@test requires == [ Base.PkgId(Foo) => Base.PkgId(string(FooBase_module)),
Base.PkgId(Foo) => Base.PkgId(Foo2),
Base.PkgId(Foo) => Base.PkgId(Test),
Base.PkgId(Foo) => Base.PkgId(string(FooBase_module)) ]
srctxt = Base.read_dependency_src(cachefile, Foo_file)
@test !isempty(srctxt) && srctxt == read(Foo_file, String)
@test_throws ErrorException Base.read_dependency_src(cachefile, "/tmp/nonexistent.txt")
# dependencies declared with `include_dependency` should not be stored
@test_throws ErrorException Base.read_dependency_src(cachefile, joinpath(dir, foo_file))
modules, deps1 = Base.cache_dependencies(cachefile)
modules_ok = merge(
Dict(let m = Base.PkgId(s)
m => Base.module_build_id(Base.root_module(m))
end for s in
[ "Base", "Core", "Main",
string(Foo2_module), string(FooBase_module),]),
# plus modules included in the system image
Dict(let m = Base.root_module(Base, s)
Base.PkgId(m) => Base.module_build_id(m)
end for s in [Symbol(x.name) for x in Base._sysimage_modules if !(x.name in ["Base", "Core", "Main"])]),
# plus test module,
Dict(Base.PkgId(Base.root_module(Base, :Test)) => Base.module_build_id(Base.root_module(Base, :Test))),
# plus dependencies of test module
Dict(Base.PkgId(Base.root_module(Base, :InteractiveUtils)) => Base.module_build_id(Base.root_module(Base, :InteractiveUtils))),
Dict(Base.PkgId(Base.root_module(Base, :Logging)) => Base.module_build_id(Base.root_module(Base, :Logging))),
Dict(Base.PkgId(Base.root_module(Base, :Random)) => Base.module_build_id(Base.root_module(Base, :Random))),
Dict(Base.PkgId(Base.root_module(Base, :Serialization)) => Base.module_build_id(Base.root_module(Base, :Serialization))),
# and their dependencies
Dict(Base.PkgId(Base.root_module(Base, :SHA)) => Base.module_build_id(Base.root_module(Base, :SHA))),
Dict(Base.PkgId(Base.root_module(Base, :Markdown)) => Base.module_build_id(Base.root_module(Base, :Markdown))),
Dict(Base.PkgId(Base.root_module(Base, :JuliaSyntaxHighlighting)) => Base.module_build_id(Base.root_module(Base, :JuliaSyntaxHighlighting))),
Dict(Base.PkgId(Base.root_module(Base, :StyledStrings)) => Base.module_build_id(Base.root_module(Base, :StyledStrings))),
# and their dependencies
Dict(Base.PkgId(Base.root_module(Base, :Base64)) => Base.module_build_id(Base.root_module(Base, :Base64))),
)
@test Dict(modules) == modules_ok
@test discard_module.(deps) == deps1
modules, (_, deps, requires), required_modules, _... = Base.parse_cache_header(cachefile)
@test map(x -> x.filename, deps) == [Foo_file]
@test current_task()(0x01, 0x4000, 0x30031234) == 2
@test sin(0x01, 0x4000, 0x30031234) == 52
@test sin(0x01, 0x4000, 0x30031234; x = 9142) == 9142
@test Foo.sinkw === Core.kwcall
@test Foo.NominalValue() == 1
@test Foo.OrdinalValue() == 1
@test Foo.NominalValue{Int}() == 2
@test Foo.OrdinalValue{Int}() == 2
let T = Vector{Foo.NominalValue{Int}}
@test isa(T(), T)
end
@test Vector{Foo.NominalValue{Int32, Int64}}() == 3
@test Vector{Foo.NominalValue{UInt, UInt}}() == 4
@test Vector{Foo.NominalValue{Int, Int}}() == 5
@test all(i -> Foo.t17809s[i + 1] ===
Tuple{
Type{Ptr{Foo.MyType{i}}},
Ptr{Type{Foo.MyType{i}}},
Array{Ptr{Foo.MyType{Foo.MyType{:sym}()}}(0), 0},
Val{Complex{Int}(1, 2)},
Val{3},
Val{nothing}},
0:25)
some_method = which(Base.include, (Module, String,))
some_linfo = Core.Compiler.specialize_method(some_method, Tuple{typeof(Base.include), Module, String}, Core.svec())
@test Foo.some_linfo::Core.MethodInstance === some_linfo
ft = Base.datatype_fieldtypes
PV = ft(Foo.Value18343{Some}.body)[1]
VR = ft(PV)[1].parameters[1]
@test ft(PV)[1] === Array{VR,1}
@test pointer_from_objref(ft(PV)[1]) ===
pointer_from_objref(ft(ft(ft(PV)[1].parameters[1])[1])[1])
@test PV === ft(ft(PV)[1].parameters[1])[1]
@test pointer_from_objref(PV) === pointer_from_objref(ft(ft(PV)[1].parameters[1])[1])
end
Nest_module = :Nest4b3a94a1a081a8cb
Nest_file = joinpath(dir, "$Nest_module.jl")
NestInner_file = joinpath(dir, "$(Nest_module)Inner.jl")
NestInner2_file = joinpath(dir, "$(Nest_module)Inner2.jl")
write(Nest_file,
"""
module $Nest_module
include("$(escape_string(NestInner_file))")
end
""")
write(NestInner_file,
"""
module NestInner
include("$(escape_string(NestInner2_file))")
end
""")
write(NestInner2_file,
"""
f() = 22
""")
Nest = Base.require(Main, Nest_module)
cachefile = joinpath(cachedir, "$Nest_module.ji")
modules, (deps, _, requires), required_modules, _... = Base.parse_cache_header(cachefile)
@test last(deps).modpath == ["NestInner"]
UsesB_module = :UsesB4b3a94a1a081a8cb
B_module = :UsesB4b3a94a1a081a8cb_B
UsesB_file = joinpath(dir, "$UsesB_module.jl")
B_file = joinpath(dir, "$(B_module).jl")
write(UsesB_file,
"""
module $UsesB_module
using $B_module
end
""")
write(B_file,
"""
module $B_module
export bfunc
bfunc() = 33
end
""")
UsesB = Base.require(Main, UsesB_module)
cachefile = joinpath(cachedir, "$UsesB_module.ji")
modules, (deps, _, requires), required_modules, _... = Base.parse_cache_header(cachefile)
id1, id2 = only(requires)
@test Base.pkgorigins[id1].cachepath == cachefile
@test Base.pkgorigins[id2].cachepath == joinpath(cachedir, "$B_module.ji")
Baz_file = joinpath(dir, "Baz.jl")
write(Baz_file,
"""
haskey(Base.loaded_modules, Base.PkgId("UseBaz")) || __precompile__(false)
module Baz
baz() = 1
end
""")
@test Base.compilecache(Base.PkgId("Baz")) == Base.PrecompilableError() # due to __precompile__(false)
OverwriteMethodError_file = joinpath(dir, "OverwriteMethodError.jl")
write(OverwriteMethodError_file,
"""
module OverwriteMethodError
Base.:(+)(x::Bool, y::Bool) = false
end
""")
@test (@test_warn "overwritten in module OverwriteMethodError" Base.compilecache(Base.PkgId("OverwriteMethodError"))) == Base.PrecompilableError() # due to piracy
UseBaz_file = joinpath(dir, "UseBaz.jl")
write(UseBaz_file,
"""
module UseBaz
biz() = 1
@assert haskey(Base.loaded_modules, Base.PkgId("UseBaz"))
@assert !haskey(Base.loaded_modules, Base.PkgId("Baz"))
using Baz
@assert haskey(Base.loaded_modules, Base.PkgId("Baz"))
buz() = 2
const generating = ccall(:jl_generating_output, Cint, ())
const incremental = Base.JLOptions().incremental
end
""")
@test Base.compilecache(Base.PkgId("UseBaz")) == Base.PrecompilableError() # due to __precompile__(false)
@eval using UseBaz
@test haskey(Base.loaded_modules, Base.PkgId("UseBaz"))
@test haskey(Base.loaded_modules, Base.PkgId("Baz"))
@test Base.invokelatest(UseBaz.biz) === 1
@test Base.invokelatest(UseBaz.buz) === 2
@test UseBaz.generating == 0
@test UseBaz.incremental == 0
@eval using Baz
@test Base.invokelatest(Baz.baz) === 1
@test Baz === UseBaz.Baz
# should not throw if the cachefile does not exist
@test !isfile("DoesNotExist.ji")
@test Base.stale_cachefile("", "DoesNotExist.ji") === true
# Issue #12720
FooBar1_file = joinpath(dir, "FooBar1.jl")
write(FooBar1_file,
"""
module FooBar1
using FooBar
end
""")
sleep(2) # give FooBar and FooBar1 different timestamps, in reverse order too
FooBar_file = joinpath(dir, "FooBar.jl")
write(FooBar_file,
"""
module FooBar
end
""")
cachefile, _ = @test_logs (:debug, r"Precompiling FooBar") min_level=Logging.Debug match_mode=:any Base.compilecache(Base.PkgId("FooBar"))
empty_prefs_hash = Base.get_preferences_hash(nothing, String[])
@test cachefile == Base.compilecache_path(Base.PkgId("FooBar"), empty_prefs_hash)
@test isfile(joinpath(cachedir, "FooBar.ji"))
Tsc = Bool(Base.JLOptions().use_pkgimages) ? Tuple{<:Vector, String, UInt128} : Tuple{<:Vector, Nothing, UInt128}
@test Base.stale_cachefile(FooBar_file, joinpath(cachedir, "FooBar.ji")) isa Tsc
@test !isdefined(Main, :FooBar)
@test !isdefined(Main, :FooBar1)
relFooBar_file = joinpath(dir, "subfolder", "..", "FooBar.jl")
@test Base.stale_cachefile(relFooBar_file, joinpath(cachedir, "FooBar.ji")) isa (Sys.iswindows() ? Tuple{<:Vector, String, UInt128} : Bool) # `..` is not a symlink on Windows
mkdir(joinpath(dir, "subfolder"))
@test Base.stale_cachefile(relFooBar_file, joinpath(cachedir, "FooBar.ji")) isa Tsc
@eval using FooBar
fb_uuid = Base.module_build_id(FooBar)
sleep(2); touch(FooBar_file)
insert!(DEPOT_PATH, 1, dir2)
@test Base.stale_cachefile(FooBar_file, joinpath(cachedir, "FooBar.ji")) isa Tsc
@eval using FooBar1
@test !isfile(joinpath(cachedir2, "FooBar.ji"))
@test !isfile(joinpath(cachedir, "FooBar1.ji"))
@test isfile(joinpath(cachedir2, "FooBar1.ji"))
@test Base.stale_cachefile(FooBar_file, joinpath(cachedir, "FooBar.ji")) isa Tsc
@test Base.stale_cachefile(FooBar1_file, joinpath(cachedir2, "FooBar1.ji")) isa Tsc
@test fb_uuid == Base.module_build_id(FooBar)
fb_uuid1 = Base.module_build_id(FooBar1)
@test fb_uuid != fb_uuid1
# test checksum
open(joinpath(cachedir2, "FooBar1.ji"), "a") do f
write(f, 0x076cac96) # append 4 random bytes
end
@test Base.stale_cachefile(FooBar1_file, joinpath(cachedir2, "FooBar1.ji")) === true
# test behavior of precompile modules that throw errors
FooBar2_file = joinpath(dir, "FooBar2.jl")
write(FooBar2_file,
"""
module FooBar2
error("break me")
end
""")
@test_warn r"LoadError: break me\nStacktrace:\n[ ]*\[1\] [\e01m\[]*error" try
Base.require(Main, :FooBar2)
error("the \"break me\" test failed")
catch exc
isa(exc, ErrorException) || rethrow()
occursin("ERROR: LoadError: break me", exc.msg) && rethrow()
end
# Test that trying to eval into closed modules during precompilation is an error
FooBar3_file = joinpath(dir, "FooBar3.jl")
FooBar3_inc = joinpath(dir, "FooBar3_inc.jl")
write(FooBar3_inc, "x=1\n")
for code in ["Core.eval(Base, :(x=1))", "Base.include(Base, \"FooBar3_inc.jl\")"]
write(FooBar3_file, """
module FooBar3
$code
end
""")
@test_warn "Evaluation into the closed module `Base` breaks incremental compilation" try
Base.require(Main, :FooBar3)
catch exc
isa(exc, ErrorException) || rethrow()
end
end
# Test transitive dependency for #21266
FooBarT_file = joinpath(dir, "FooBarT.jl")
write(FooBarT_file,
"""
module FooBarT
end
""")
FooBarT1_file = joinpath(dir, "FooBarT1.jl")
write(FooBarT1_file,
"""
module FooBarT1
using FooBarT
end
""")
FooBarT2_file = joinpath(dir, "FooBarT2.jl")
write(FooBarT2_file,
"""
module FooBarT2
using FooBarT1
end
""")
Base.compilecache(Base.PkgId("FooBarT2"))
write(FooBarT1_file,
"""
module FooBarT1
end
""")
rm(FooBarT_file)
@test Base.stale_cachefile(FooBarT2_file, joinpath(cachedir2, "FooBarT2.ji")) === true
@test Base.require(Main, :FooBarT2) isa Module
end
end
# method root provenance & external code caching
precompile_test_harness("code caching") do dir
Bid = rootid(Base)
Cache_module = :Cacheb8321416e8a3e2f1
# Note: calling setindex!(::Dict{K,V}, ::Any, ::K) adds both compression and codegen roots
write(joinpath(dir, "$Cache_module.jl"),
"""
module $Cache_module
struct X end
struct X2 end
@noinline function f(d)
@noinline
d[X()] = nothing
end
@noinline fpush(dest) = push!(dest, X())
function callboth()
f(Dict{X,Any}())
fpush(X[])
nothing
end
function getelsize(list::Vector{T}) where T
n = 0
for item in list
n += sizeof(T)
end
return n
end
precompile(callboth, ())
precompile(getelsize, (Vector{Int32},))
end
""")
pkgid = Base.PkgId(string(Cache_module))
@test !Base.isprecompiled(pkgid)
Base.compilecache(pkgid)
@test Base.isprecompiled(pkgid)
@eval using $Cache_module
M = getfield(@__MODULE__, Cache_module)
# Test that this cache file "owns" all the roots
Mid = rootid(M)
for name in (:f, :fpush, :callboth)
func = getfield(M, name)
m = only(collect(methods(func)))
@test all(i -> root_provenance(m, i) == Mid, 1:length(m.roots))
end
# Check that we can cache external CodeInstances:
# length(::Vector) has an inferred specialization for `Vector{X}`
msize = which(length, (Vector{<:Any},))
hasspec = false
for mi in Base.specializations(msize)
if mi.specTypes == Tuple{typeof(length),Vector{Cacheb8321416e8a3e2f1.X}}
if (isdefined(mi, :cache) && isa(mi.cache, Core.CodeInstance) &&
mi.cache.max_world == typemax(UInt) && mi.cache.inferred !== nothing)
hasspec = true
break
end
end
end
@test hasspec
# Test that compilation adds to method roots with appropriate provenance
m = which(setindex!, (Dict{M.X,Any}, Any, M.X))
@test Memory{M.X} ∈ m.roots
# Check that roots added outside of incremental builds get attributed to a moduleid of 0
Base.invokelatest() do
Dict{M.X2,Any}()[M.X2()] = nothing
end
@test Memory{M.X2} ∈ m.roots
groups = group_roots(m)
@test Memory{M.X} ∈ groups[Mid] # attributed to M
@test Memory{M.X2} ∈ groups[0] # activate module is not known
@test !isempty(groups[Bid])
# Check that internal methods and their roots are accounted appropriately
minternal = which(M.getelsize, (Vector,))
mi = minternal.specializations::Core.MethodInstance
@test mi.specTypes == Tuple{typeof(M.getelsize),Vector{Int32}}
ci = mi.cache
@test ci.relocatability == 0
@test ci.inferred !== nothing
# ...and that we can add "untracked" roots & non-relocatable CodeInstances to them too
Base.invokelatest() do
M.getelsize(M.X2[])
end
mispecs = minternal.specializations::Core.SimpleVector
@test mispecs[1] === mi
mi = mispecs[2]::Core.MethodInstance
ci = mi.cache
@test ci.relocatability == 0
# PkgA loads PkgB, and both add roots to the same `push!` method (both before and after loading B)
Cache_module2 = :Cachea1544c83560f0c99
write(joinpath(dir, "$Cache_module2.jl"),
"""
module $Cache_module2
struct Y end
@noinline f(dest) = push!(dest, Y())
callf() = f(Y[])
callf()
using $(Cache_module)
struct Z end
@noinline g(dest) = push!(dest, Z())
callg() = g(Z[])
callg()
end
""")
Base.compilecache(Base.PkgId(string(Cache_module2)))
@eval using $Cache_module2
M2 = getfield(@__MODULE__, Cache_module2)
M2id = rootid(M2)
dest = []
Base.invokelatest() do # use invokelatest to see the results of loading the compile
M2.f(dest)
M.fpush(dest)
M2.g(dest)
@test dest == [M2.Y(), M.X(), M2.Z()]
@test M2.callf() == [M2.Y()]
@test M2.callg() == [M2.Z()]
@test M.fpush(M.X[]) == [M.X()]
end
mT = which(push!, (Vector{T} where T, Any))
groups = group_roots(mT)
@test Memory{M2.Y} ∈ groups[M2id]
@test Memory{M2.Z} ∈ groups[M2id]
@test Memory{M.X} ∈ groups[Mid]
@test Memory{M.X} ∉ groups[M2id]
# backedges of external MethodInstances
# Root gets used by RootA and RootB, and both consumers end up inferring the same MethodInstance from Root
# Do both callers get listed as backedges?
RootModule = :Root_0xab07d60518763a7e
write(joinpath(dir, "$RootModule.jl"),
"""
module $RootModule
function f(x)
while x < 10
x += oftype(x, 1)
end
return x
end
g1() = f(Int16(9))
g2() = f(Int16(9))
# all deliberately uncompiled
end
""")
RootA = :RootA_0xab07d60518763a7e
write(joinpath(dir, "$RootA.jl"),
"""
module $RootA
using $RootModule
fA() = $RootModule.f(Int8(4))
fA()
$RootModule.g1()
end
""")
RootB = :RootB_0xab07d60518763a7e
write(joinpath(dir, "$RootB.jl"),
"""
module $RootB
using $RootModule
fB() = $RootModule.f(Int8(4))
fB()
$RootModule.g2()
end
""")
Base.compilecache(Base.PkgId(string(RootA)))
Base.compilecache(Base.PkgId(string(RootB)))
@eval using $RootA
@eval using $RootB
MA = getfield(@__MODULE__, RootA)
MB = getfield(@__MODULE__, RootB)
M = getfield(MA, RootModule)
m = which(M.f, (Any,))
for mi in Base.specializations(m)
mi === nothing && continue
mi = mi::Core.MethodInstance
if mi.specTypes.parameters[2] === Int8
# external callers
mods = Module[]
for be in mi.backedges
push!(mods, be.def.module)
end
@test MA ∈ mods
@test MB ∈ mods
@test length(mods) == 2
elseif mi.specTypes.parameters[2] === Int16
# internal callers
meths = Method[]
for be in mi.backedges
push!(meths, be.def)
end
@test which(M.g1, ()) ∈ meths
@test which(M.g2, ()) ∈ meths
@test length(meths) == 2
end
end
# Invalidations (this test is adapted from SnoopCompile)
function hasvalid(mi, world)
isdefined(mi, :cache) || return false
ci = mi.cache
while true
ci.max_world >= world && return true
isdefined(ci, :next) || return false
ci = ci.next
end
end
StaleA = :StaleA_0xab07d60518763a7e
StaleB = :StaleB_0xab07d60518763a7e
StaleC = :StaleC_0xab07d60518763a7e
write(joinpath(dir, "$StaleA.jl"),
"""
module $StaleA
stale(x) = rand(1:8)
stale(x::Int) = length(digits(x))
not_stale(x::String) = first(x)
use_stale(c) = stale(c[1]) + not_stale("hello")
build_stale(x) = use_stale(Any[x])
# force precompilation
build_stale(37)
stale('c')
## Reporting tests (unrelated to the above)
nbits(::Int8) = 8
nbits(::Int16) = 16
end
"""
)
write(joinpath(dir, "$StaleB.jl"),
"""
module $StaleB
# StaleB does not know about StaleC when it is being built.
# However, if StaleC is loaded first, we get `"jl_insert_method_instance"`
# invalidations.
using $StaleA
# This will be invalidated if StaleC is loaded
useA() = $StaleA.stale("hello")
useA2() = useA()
# force precompilation
begin
Base.Experimental.@force_compile
useA2()
end
## Reporting tests
call_nbits(x::Integer) = $StaleA.nbits(x)
map_nbits() = map(call_nbits, Integer[Int8(1), Int16(1)])
map_nbits()
end
"""
)
write(joinpath(dir, "$StaleC.jl"),
"""
module $StaleC
using $StaleA
$StaleA.stale(x::String) = length(x)
call_buildstale(x) = $StaleA.build_stale(x)
call_buildstale("hey")
end # module
"""
)
for pkg in (StaleA, StaleB, StaleC)
Base.compilecache(Base.PkgId(string(pkg)))
end
@eval using $StaleA
MA = getfield(@__MODULE__, StaleA)
Base.eval(MA, :(nbits(::UInt8) = 8))
@eval using $StaleC
invalidations = ccall(:jl_debug_method_invalidation, Any, (Cint,), 1)
@eval using $StaleB
ccall(:jl_debug_method_invalidation, Any, (Cint,), 0)