forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgf.c
4045 lines (3832 loc) · 173 KB
/
gf.c
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
/*
Generic Functions
. method table and lookup
. GF constructor
. dispatch
. static parameter inference
. method specialization and caching, invoking type inference
*/
#include <stdlib.h>
#include <string.h>
#include "julia.h"
#include "julia_internal.h"
#ifndef _OS_WINDOWS_
#include <unistd.h>
#endif
#include "julia_assert.h"
// The compilation signature is not used to cache the method if the number of overlapping methods is greater than this
#define MAX_UNSPECIALIZED_CONFLICTS 32
#ifdef __cplusplus
extern "C" {
#endif
JL_DLLEXPORT _Atomic(size_t) jl_world_counter = 1; // uses atomic acquire/release
JL_DLLEXPORT size_t jl_get_world_counter(void) JL_NOTSAFEPOINT
{
jl_task_t *ct = jl_current_task;
if (ct->ptls->in_pure_callback)
return ~(size_t)0;
return jl_atomic_load_acquire(&jl_world_counter);
}
JL_DLLEXPORT size_t jl_get_tls_world_age(void) JL_NOTSAFEPOINT
{
return jl_current_task->world_age;
}
// Compute the maximum number of times to unroll Varargs{T}, based on
// m->max_varargs (if specified) or a heuristic based on the maximum
// number of non-varargs arguments in the provided method table.
//
// If provided, `may_increase` is set to 1 if the returned value is
// heuristic-based and has a chance of increasing in the future.
static size_t get_max_varargs(
jl_method_t *m,
jl_methtable_t *kwmt,
jl_methtable_t *mt,
uint8_t *may_increase) JL_NOTSAFEPOINT
{
size_t max_varargs = 1;
if (may_increase != NULL)
*may_increase = 0;
if (m->max_varargs != UINT8_MAX)
max_varargs = m->max_varargs;
else if (kwmt != NULL && kwmt != jl_type_type_mt && kwmt != jl_nonfunction_mt && kwmt != jl_kwcall_mt) {
if (may_increase != NULL)
*may_increase = 1; // `max_args` can increase as new methods are inserted
max_varargs = jl_atomic_load_relaxed(&kwmt->max_args) + 2;
if (mt == jl_kwcall_mt)
max_varargs += 2;
max_varargs -= m->nargs;
}
return max_varargs;
}
/// ----- Handling for Julia callbacks ----- ///
JL_DLLEXPORT int8_t jl_is_in_pure_context(void)
{
jl_task_t *ct = jl_current_task;
return ct->ptls->in_pure_callback;
}
tracer_cb jl_newmeth_tracer = NULL;
JL_DLLEXPORT void jl_register_newmeth_tracer(void (*callback)(jl_method_t *tracee))
{
jl_newmeth_tracer = (tracer_cb)callback;
}
void jl_call_tracer(tracer_cb callback, jl_value_t *tracee)
{
jl_task_t *ct = jl_current_task;
int last_in = ct->ptls->in_pure_callback;
JL_TRY {
ct->ptls->in_pure_callback = 1;
callback(tracee);
ct->ptls->in_pure_callback = last_in;
}
JL_CATCH {
ct->ptls->in_pure_callback = last_in;
jl_printf((JL_STREAM*)STDERR_FILENO, "WARNING: tracer callback function threw an error:\n");
jl_static_show((JL_STREAM*)STDERR_FILENO, jl_current_exception());
jl_printf((JL_STREAM*)STDERR_FILENO, "\n");
jlbacktrace(); // written to STDERR_FILENO
}
}
/// ----- Definitions for various internal TypeMaps ----- ///
static int8_t jl_cachearg_offset(jl_methtable_t *mt)
{
return mt->offs;
}
/// ----- Insertion logic for special entries ----- ///
static uint_t speccache_hash(size_t idx, jl_svec_t *data)
{
jl_method_instance_t *ml = (jl_method_instance_t*)jl_svecref(data, idx); // This must always happen inside the lock
jl_value_t *sig = ml->specTypes;
if (jl_is_unionall(sig))
sig = jl_unwrap_unionall(sig);
return ((jl_datatype_t*)sig)->hash;
}
static int speccache_eq(size_t idx, const void *ty, jl_svec_t *data, uint_t hv)
{
if (idx >= jl_svec_len(data))
return 0; // We got a OOB access, probably due to a data race
jl_method_instance_t *ml = (jl_method_instance_t*)jl_svecref(data, idx);
jl_value_t *sig = ml->specTypes;
if (ty == sig)
return 1;
uint_t h2 = ((jl_datatype_t*)(jl_is_unionall(sig) ? jl_unwrap_unionall(sig) : sig))->hash;
if (h2 != hv)
return 0;
return jl_types_equal(sig, (jl_value_t*)ty);
}
// get or create the MethodInstance for a specialization
static jl_method_instance_t *jl_specializations_get_linfo_(jl_method_t *m JL_PROPAGATES_ROOT, jl_value_t *type, jl_svec_t *sparams, jl_method_instance_t *mi_insert)
{
if (m->sig == (jl_value_t*)jl_anytuple_type && jl_atomic_load_relaxed(&m->unspecialized) != NULL && m != jl_opaque_closure_method)
return jl_atomic_load_relaxed(&m->unspecialized); // handle builtin methods
jl_value_t *ut = jl_is_unionall(type) ? jl_unwrap_unionall(type) : type;
JL_TYPECHK(specializations, datatype, ut);
uint_t hv = ((jl_datatype_t*)ut)->hash;
jl_array_t *speckeyset = NULL;
jl_value_t *specializations = NULL;
size_t i = -1, cl = 0, lastcl;
for (int locked = 0; locked < 2; locked++) {
if (locked) {
if (!sparams) // can't insert without knowing this
return NULL;
JL_LOCK(&m->writelock);
}
lastcl = cl;
speckeyset = jl_atomic_load_acquire(&m->speckeyset);
specializations = jl_atomic_load_relaxed(&m->specializations);
if (specializations == (jl_value_t*)jl_emptysvec)
continue;
if (!jl_is_svec(specializations)) {
jl_method_instance_t *mi = (jl_method_instance_t*)specializations;
if (jl_types_equal(mi->specTypes, type)) {
if (locked)
JL_UNLOCK(&m->writelock);
return mi;
}
continue;
}
cl = jl_svec_len(specializations);
if (hv) {
ssize_t idx = jl_smallintset_lookup(speckeyset, speccache_eq, type, (jl_svec_t*)specializations, hv);
if (idx != -1) {
jl_method_instance_t *mi = (jl_method_instance_t*)jl_svecref(specializations, idx);
if (locked)
JL_UNLOCK(&m->writelock);
return mi;
}
}
else {
_Atomic(jl_method_instance_t*) *data = (_Atomic(jl_method_instance_t*)*)jl_svec_data(specializations);
JL_GC_PUSH1(&specializations); // clang-sa doesn't realize this loop uses specializations
// the last lastcl-i-1 elements are already checked when locked, so start search with the new elements only
for (i += cl - lastcl; i > 0; i--) {
jl_method_instance_t *mi = jl_atomic_load_relaxed(&data[i]);
if ((jl_value_t*)mi == jl_nothing)
break;
if (jl_types_equal(mi->specTypes, type)) {
if (locked)
JL_UNLOCK(&m->writelock);
JL_GC_POP();
return mi;
}
}
// i points to the first unchecked element, or the place to insert
JL_GC_POP();
}
}
jl_method_instance_t *mi = mi_insert ? mi_insert : jl_get_specialized(m, type, sparams);
if (specializations == (jl_value_t*)jl_emptysvec) {
jl_atomic_store_release(&m->specializations, (jl_value_t*)mi);
jl_gc_wb(m, mi);
}
else {
JL_GC_PUSH1(&mi);
if (!jl_is_svec(specializations)) {
jl_method_instance_t *mi = (jl_method_instance_t*)specializations;
jl_value_t *type = mi->specTypes;
jl_value_t *ut = jl_is_unionall(type) ? jl_unwrap_unionall(type) : type;
uint_t hv = ((jl_datatype_t*)ut)->hash;
cl = 7;
i = cl - 1;
specializations = (jl_value_t*)jl_svec_fill(cl, jl_nothing);
jl_svecset(specializations, hv ? 0 : i--, mi);
jl_atomic_store_release(&m->specializations, specializations);
jl_gc_wb(m, specializations);
if (hv)
jl_smallintset_insert(&m->speckeyset, (jl_value_t*)m, speccache_hash, 0, (jl_svec_t*)specializations);
}
if (hv) {
_Atomic(jl_method_instance_t*) *data = (_Atomic(jl_method_instance_t*)*)jl_svec_data(specializations);
for (i = 0; i < cl; i++) {
jl_method_instance_t *mi = jl_atomic_load_relaxed(&data[i]);
if ((jl_value_t*)mi == jl_nothing)
break;
assert(!jl_types_equal(mi->specTypes, type));
}
// i points at the place to insert
}
if (hv ? (i + 1 >= cl || jl_svecref(specializations, i + 1) != jl_nothing) : (i <= 1 || jl_svecref(specializations, i - 2) != jl_nothing)) {
size_t ncl = cl < 7 ? 7 : (cl*3)>>1;
jl_svec_t *nc = jl_alloc_svec_uninit(ncl);
if (i > 0)
memcpy((char*)jl_svec_data(nc), jl_svec_data(specializations), sizeof(void*) * i);
for (int j = 0; j < ncl - cl; j++)
jl_svecset(nc, j+i, jl_nothing);
if (i < cl)
memcpy((char*)jl_svec_data(nc) + sizeof(void*) * (i + ncl - cl),
(char*)jl_svec_data(specializations) + sizeof(void*) * i,
sizeof(void*) * (cl - i));
specializations = (jl_value_t*)nc;
jl_atomic_store_release(&m->specializations, specializations);
jl_gc_wb(m, specializations);
if (!hv)
i += ncl - cl;
}
assert(jl_svecref(specializations, i) == jl_nothing);
jl_svecset(specializations, i, mi);
if (hv)
jl_smallintset_insert(&m->speckeyset, (jl_value_t*)m, speccache_hash, i, (jl_svec_t*)specializations);
JL_GC_POP();
}
JL_UNLOCK(&m->writelock); // may gc
return mi;
}
JL_DLLEXPORT jl_method_instance_t *jl_specializations_get_linfo(jl_method_t *m JL_PROPAGATES_ROOT, jl_value_t *type, jl_svec_t *sparams)
{
return jl_specializations_get_linfo_(m, type, sparams, NULL);
}
jl_method_instance_t *jl_specializations_get_or_insert(jl_method_instance_t *mi)
{
jl_method_t *m = mi->def.method;
jl_value_t *type = mi->specTypes;
jl_svec_t *sparams = mi->sparam_vals;
return jl_specializations_get_linfo_(m, type, sparams, mi);
}
JL_DLLEXPORT jl_value_t *jl_specializations_lookup(jl_method_t *m, jl_value_t *type)
{
jl_value_t *mi = (jl_value_t*)jl_specializations_get_linfo(m, type, NULL);
if (mi == NULL)
return jl_nothing;
return mi;
}
JL_DLLEXPORT jl_value_t *jl_methtable_lookup(jl_methtable_t *mt, jl_value_t *type, size_t world)
{
// TODO: this is sort of an odd lookup strategy (and the only user of
// jl_typemap_assoc_by_type with subtype=0), while normally jl_gf_invoke_lookup would be
// expected to be used instead
struct jl_typemap_assoc search = {type, world, NULL, 0, ~(size_t)0};
jl_typemap_entry_t *sf = jl_typemap_assoc_by_type(jl_atomic_load_relaxed(&mt->defs), &search, jl_cachearg_offset(mt), /*subtype*/0);
if (!sf)
return jl_nothing;
return sf->func.value;
}
// ----- MethodInstance specialization instantiation ----- //
JL_DLLEXPORT jl_code_instance_t* jl_new_codeinst(
jl_method_instance_t *mi, jl_value_t *rettype,
jl_value_t *inferred_const, jl_value_t *inferred,
int32_t const_flags, size_t min_world, size_t max_world,
uint32_t ipo_effects, uint32_t effects, jl_value_t *argescapes,
uint8_t relocatability);
jl_datatype_t *jl_mk_builtin_func(jl_datatype_t *dt, const char *name, jl_fptr_args_t fptr) JL_GC_DISABLED
{
jl_sym_t *sname = jl_symbol(name);
if (dt == NULL) {
jl_value_t *f = jl_new_generic_function_with_supertype(sname, jl_core_module, jl_builtin_type);
jl_set_const(jl_core_module, sname, f);
dt = (jl_datatype_t*)jl_typeof(f);
}
jl_method_t *m = jl_new_method_uninit(jl_core_module);
m->name = sname;
m->module = jl_core_module;
m->isva = 1;
m->nargs = 2;
m->sig = (jl_value_t*)jl_anytuple_type;
m->slot_syms = jl_an_empty_string;
m->nospecialize = 0;
m->nospecialize = ~m->nospecialize;
jl_methtable_t *mt = dt->name->mt;
jl_typemap_entry_t *newentry = NULL;
JL_GC_PUSH2(&m, &newentry);
newentry = jl_typemap_alloc(jl_anytuple_type, NULL, jl_emptysvec,
(jl_value_t*)m, 1, ~(size_t)0);
jl_typemap_insert(&mt->defs, (jl_value_t*)mt, newentry, jl_cachearg_offset(mt));
jl_method_instance_t *mi = jl_get_specialized(m, (jl_value_t*)jl_anytuple_type, jl_emptysvec);
jl_atomic_store_relaxed(&m->unspecialized, mi);
jl_gc_wb(m, mi);
jl_code_instance_t *codeinst = jl_new_codeinst(mi,
(jl_value_t*)jl_any_type, jl_nothing, jl_nothing,
0, 1, ~(size_t)0, 0, 0, jl_nothing, 0);
jl_mi_cache_insert(mi, codeinst);
jl_atomic_store_relaxed(&codeinst->specptr.fptr1, fptr);
jl_atomic_store_relaxed(&codeinst->invoke, jl_fptr_args);
newentry = jl_typemap_alloc(jl_anytuple_type, NULL, jl_emptysvec,
(jl_value_t*)mi, 1, ~(size_t)0);
jl_typemap_insert(&mt->cache, (jl_value_t*)mt, newentry, 0);
mt->frozen = 1;
JL_GC_POP();
return dt;
}
// run type inference on lambda "mi" for given argument types.
// returns the inferred source, and may cache the result in mi
// if successful, also updates the mi argument to describe the validity of this src
// if inference doesn't occur (or can't finish), returns NULL instead
jl_code_info_t *jl_type_infer(jl_method_instance_t *mi, size_t world, int force)
{
if (jl_typeinf_func == NULL)
return NULL;
jl_task_t *ct = jl_current_task;
if (ct->reentrant_timing & 0b1000) {
// We must avoid attempting to re-enter inference here
assert(0 && "attempted to enter inference while writing out image");
abort();
}
// In case we use higher bits later, mask them out
if ((ct->reentrant_timing & 0b1111) >= 0b110)
return NULL;
jl_code_info_t *src = NULL;
#ifdef ENABLE_INFERENCE
if (mi->inInference && !force)
return NULL;
JL_TIMING(INFERENCE, INFERENCE);
jl_value_t **fargs;
JL_GC_PUSHARGS(fargs, 3);
fargs[0] = (jl_value_t*)jl_typeinf_func;
fargs[1] = (jl_value_t*)mi;
fargs[2] = jl_box_ulong(world);
jl_timing_show_method_instance(mi, JL_TIMING_DEFAULT_BLOCK);
#ifdef TRACE_INFERENCE
if (mi->specTypes != (jl_value_t*)jl_emptytuple_type) {
jl_printf(JL_STDERR,"inference on ");
jl_static_show_func_sig(JL_STDERR, (jl_value_t*)mi->specTypes);
jl_printf(JL_STDERR, "\n");
}
#endif
int last_errno = errno;
#ifdef _OS_WINDOWS_
DWORD last_error = GetLastError();
#endif
size_t last_age = ct->world_age;
ct->world_age = jl_typeinf_world;
mi->inInference = 1;
// first bit is for reentrant timing,
// so adding 1 to the bit above performs
// inference reentrancy counter addition.
// Note that this is only safe because
// the counter varies from 0-3; if we
// increase that limit, we'll need to
// allocate another bit for the counter.
ct->reentrant_timing += 0b10;
JL_TRY {
src = (jl_code_info_t*)jl_apply(fargs, 3);
}
JL_CATCH {
jl_value_t *e = jl_current_exception();
if (e == jl_stackovf_exception) {
jl_printf((JL_STREAM*)STDERR_FILENO, "Internal error: stack overflow in type inference of ");
jl_static_show_func_sig((JL_STREAM*)STDERR_FILENO, (jl_value_t*)mi->specTypes);
jl_printf((JL_STREAM*)STDERR_FILENO, ".\n");
jl_printf((JL_STREAM*)STDERR_FILENO, "This might be caused by recursion over very long tuples or argument lists.\n");
}
else {
jl_printf((JL_STREAM*)STDERR_FILENO, "Internal error: encountered unexpected error in runtime:\n");
jl_static_show((JL_STREAM*)STDERR_FILENO, e);
jl_printf((JL_STREAM*)STDERR_FILENO, "\n");
jlbacktrace(); // written to STDERR_FILENO
}
src = NULL;
}
ct->world_age = last_age;
ct->reentrant_timing -= 0b10;
mi->inInference = 0;
#ifdef _OS_WINDOWS_
SetLastError(last_error);
#endif
errno = last_errno;
if (src && !jl_is_code_info(src)) {
src = NULL;
}
JL_GC_POP();
#endif
return src;
}
JL_DLLEXPORT jl_value_t *jl_call_in_typeinf_world(jl_value_t **args, int nargs)
{
jl_task_t *ct = jl_current_task;
size_t last_age = ct->world_age;
ct->world_age = jl_typeinf_world;
jl_value_t *ret = jl_apply(args, nargs);
ct->world_age = last_age;
return ret;
}
JL_DLLEXPORT jl_value_t *jl_rettype_inferred(jl_method_instance_t *mi, size_t min_world, size_t max_world) JL_NOTSAFEPOINT
{
jl_code_instance_t *codeinst = jl_atomic_load_relaxed(&mi->cache);
while (codeinst) {
if (codeinst->min_world <= min_world && max_world <= codeinst->max_world) {
jl_value_t *code = jl_atomic_load_relaxed(&codeinst->inferred);
if (code && (code == jl_nothing || jl_ir_flag_inferred(code)))
return (jl_value_t*)codeinst;
}
codeinst = jl_atomic_load_relaxed(&codeinst->next);
}
return (jl_value_t*)jl_nothing;
}
JL_DLLEXPORT jl_value_t *(*const jl_rettype_inferred_addr)(jl_method_instance_t *mi, size_t min_world, size_t max_world) JL_NOTSAFEPOINT = jl_rettype_inferred;
JL_DLLEXPORT jl_code_instance_t *jl_get_method_inferred(
jl_method_instance_t *mi JL_PROPAGATES_ROOT, jl_value_t *rettype,
size_t min_world, size_t max_world)
{
jl_code_instance_t *codeinst = jl_atomic_load_relaxed(&mi->cache);
while (codeinst) {
if (codeinst->min_world == min_world &&
codeinst->max_world == max_world &&
jl_egal(codeinst->rettype, rettype)) {
return codeinst;
}
codeinst = jl_atomic_load_relaxed(&codeinst->next);
}
codeinst = jl_new_codeinst(
mi, rettype, NULL, NULL,
0, min_world, max_world, 0, 0, jl_nothing, 0);
jl_mi_cache_insert(mi, codeinst);
return codeinst;
}
JL_DLLEXPORT jl_code_instance_t *jl_new_codeinst(
jl_method_instance_t *mi, jl_value_t *rettype,
jl_value_t *inferred_const, jl_value_t *inferred,
int32_t const_flags, size_t min_world, size_t max_world,
uint32_t ipo_effects, uint32_t effects, jl_value_t *argescapes,
uint8_t relocatability
/*, jl_array_t *edges, int absolute_max*/)
{
jl_task_t *ct = jl_current_task;
assert(min_world <= max_world && "attempting to set invalid world constraints");
jl_code_instance_t *codeinst = (jl_code_instance_t*)jl_gc_alloc(ct->ptls, sizeof(jl_code_instance_t),
jl_code_instance_type);
codeinst->def = mi;
codeinst->min_world = min_world;
codeinst->max_world = max_world;
codeinst->rettype = rettype;
jl_atomic_store_release(&codeinst->inferred, inferred);
//codeinst->edges = NULL;
if ((const_flags & 2) == 0)
inferred_const = NULL;
codeinst->rettype_const = inferred_const;
jl_atomic_store_relaxed(&codeinst->specptr.fptr, NULL);
jl_atomic_store_relaxed(&codeinst->invoke, NULL);
if ((const_flags & 1) != 0) {
assert(const_flags & 2);
jl_atomic_store_relaxed(&codeinst->invoke, jl_fptr_const_return);
}
jl_atomic_store_relaxed(&codeinst->specsigflags, 0);
jl_atomic_store_relaxed(&codeinst->precompile, 0);
jl_atomic_store_relaxed(&codeinst->next, NULL);
codeinst->ipo_purity_bits = ipo_effects;
jl_atomic_store_relaxed(&codeinst->purity_bits, effects);
codeinst->argescapes = argescapes;
codeinst->relocatability = relocatability;
return codeinst;
}
JL_DLLEXPORT void jl_mi_cache_insert(jl_method_instance_t *mi JL_ROOTING_ARGUMENT,
jl_code_instance_t *ci JL_ROOTED_ARGUMENT JL_MAYBE_UNROOTED)
{
JL_GC_PUSH1(&ci);
if (jl_is_method(mi->def.method))
JL_LOCK(&mi->def.method->writelock);
jl_code_instance_t *oldci = jl_atomic_load_relaxed(&mi->cache);
jl_atomic_store_relaxed(&ci->next, oldci);
if (oldci)
jl_gc_wb(ci, oldci);
jl_atomic_store_release(&mi->cache, ci);
jl_gc_wb(mi, ci);
if (jl_is_method(mi->def.method))
JL_UNLOCK(&mi->def.method->writelock);
JL_GC_POP();
return;
}
static int get_method_unspec_list(jl_typemap_entry_t *def, void *closure)
{
size_t world = jl_atomic_load_acquire(&jl_world_counter);
jl_value_t *specializations = jl_atomic_load_relaxed(&def->func.method->specializations);
if (specializations == (jl_value_t*)jl_emptysvec)
return 1;
if (!jl_is_svec(specializations)) {
jl_method_instance_t *mi = (jl_method_instance_t*)specializations;
assert(jl_is_method_instance(mi));
if (jl_rettype_inferred(mi, world, world) == jl_nothing)
jl_array_ptr_1d_push((jl_array_t*)closure, (jl_value_t*)mi);
return 1;
}
size_t i, l = jl_svec_len(specializations);
JL_GC_PUSH1(&specializations);
for (i = 0; i < l; i++) {
jl_method_instance_t *mi = (jl_method_instance_t*)jl_svecref(specializations, i);
if ((jl_value_t*)mi != jl_nothing) {
assert(jl_is_method_instance(mi));
if (jl_rettype_inferred(mi, world, world) == jl_nothing)
jl_array_ptr_1d_push((jl_array_t*)closure, (jl_value_t*)mi);
}
}
JL_GC_POP();
return 1;
}
int foreach_mtable_in_module(
jl_module_t *m,
int (*visit)(jl_methtable_t *mt, void *env),
void *env)
{
jl_svec_t *table = jl_atomic_load_relaxed(&m->bindings);
for (size_t i = 0; i < jl_svec_len(table); i++) {
jl_binding_t *b = (jl_binding_t*)jl_svec_ref(table, i);
if ((void*)b == jl_nothing)
break;
jl_sym_t *name = b->globalref->name;
if (jl_atomic_load_relaxed(&b->owner) == b && b->constp) {
jl_value_t *v = jl_atomic_load_relaxed(&b->value);
if (v) {
jl_value_t *uw = jl_unwrap_unionall(v);
if (jl_is_datatype(uw)) {
jl_typename_t *tn = ((jl_datatype_t*)uw)->name;
if (tn->module == m && tn->name == name && tn->wrapper == v) {
// this is the original/primary binding for the type (name/wrapper)
jl_methtable_t *mt = tn->mt;
if (mt != NULL && (jl_value_t*)mt != jl_nothing && mt != jl_type_type_mt && mt != jl_nonfunction_mt) {
assert(mt->module == m);
if (!visit(mt, env))
return 0;
}
}
}
else if (jl_is_module(v)) {
jl_module_t *child = (jl_module_t*)v;
if (child != m && child->parent == m && child->name == name) {
// this is the original/primary binding for the submodule
if (!foreach_mtable_in_module(child, visit, env))
return 0;
}
}
else if (jl_is_mtable(v)) {
jl_methtable_t *mt = (jl_methtable_t*)v;
if (mt->module == m && mt->name == name) {
// this is probably an external method table here, so let's
// assume so as there is no way to precisely distinguish them
if (!visit(mt, env))
return 0;
}
}
}
}
table = jl_atomic_load_relaxed(&m->bindings);
}
return 1;
}
int jl_foreach_reachable_mtable(int (*visit)(jl_methtable_t *mt, void *env), void *env)
{
if (!visit(jl_type_type_mt, env))
return 0;
if (!visit(jl_nonfunction_mt, env))
return 0;
jl_array_t *mod_array = jl_get_loaded_modules();
if (mod_array) {
JL_GC_PUSH1(&mod_array);
int i;
for (i = 0; i < jl_array_len(mod_array); i++) {
jl_module_t *m = (jl_module_t*)jl_array_ptr_ref(mod_array, i);
assert(jl_is_module(m));
if (m->parent == m) // some toplevel modules (really just Base) aren't actually
if (!foreach_mtable_in_module(m, visit, env)) {
JL_GC_POP();
return 0;
}
}
JL_GC_POP();
}
else {
if (!foreach_mtable_in_module(jl_main_module, visit, env))
return 0;
if (!foreach_mtable_in_module(jl_core_module, visit, env))
return 0;
}
return 1;
}
static int reset_mt_caches(jl_methtable_t *mt, void *env)
{
// removes all method caches
// this might not be entirely safe (GC or MT), thus we only do it very early in bootstrapping
if (!mt->frozen) { // make sure not to reset builtin functions
jl_atomic_store_release(&mt->leafcache, (jl_array_t*)jl_an_empty_vec_any);
jl_atomic_store_release(&mt->cache, jl_nothing);
}
jl_typemap_visitor(jl_atomic_load_relaxed(&mt->defs), get_method_unspec_list, env);
return 1;
}
jl_function_t *jl_typeinf_func JL_GLOBALLY_ROOTED = NULL;
JL_DLLEXPORT size_t jl_typeinf_world = 1;
JL_DLLEXPORT void jl_set_typeinf_func(jl_value_t *f)
{
size_t newfunc = jl_typeinf_world == 1 && jl_typeinf_func == NULL;
jl_typeinf_func = (jl_function_t*)f;
jl_typeinf_world = jl_get_tls_world_age();
int world = jl_atomic_fetch_add(&jl_world_counter, 1) + 1; // make type-inference the only thing in this world
if (newfunc) {
// give type inference a chance to see all of these
// TODO: also reinfer if max_world != ~(size_t)0
jl_array_t *unspec = jl_alloc_vec_any(0);
JL_GC_PUSH1(&unspec);
jl_foreach_reachable_mtable(reset_mt_caches, (void*)unspec);
size_t i, l;
for (i = 0, l = jl_array_len(unspec); i < l; i++) {
jl_method_instance_t *mi = (jl_method_instance_t*)jl_array_ptr_ref(unspec, i);
if (jl_rettype_inferred(mi, world, world) == jl_nothing)
jl_type_infer(mi, world, 1);
}
JL_GC_POP();
}
}
static int very_general_type(jl_value_t *t)
{
return (t == (jl_value_t*)jl_any_type || jl_types_equal(t, (jl_value_t*)jl_type_type));
}
jl_value_t *jl_nth_slot_type(jl_value_t *sig, size_t i) JL_NOTSAFEPOINT
{
sig = jl_unwrap_unionall(sig);
size_t len = jl_nparams(sig);
if (i < len-1)
return jl_tparam(sig, i);
jl_value_t *p = jl_tparam(sig, len-1);
if (jl_is_vararg(p))
p = jl_unwrap_vararg(p);
return p;
}
// if concrete_match returns false, the sig may specify `Type{T::DataType}`, while the `tt` contained DataType
// in this case, subtyping is wrong, and this may not actually match at runtime
// since it may instead match any kind of `Type{T::Type}`
//static int concrete_match(jl_tupletype_t *tt, jl_value_t *sig)
//{
// size_t i, np;
// for (i = 0, np = jl_nparams(tt); i < np; i++) {
// jl_value_t *elt = jl_tparam(tt, i);
// jl_value_t *decl_i = jl_nth_slot_type((jl_value_t*)sig, i);
// if (jl_is_kind(elt)) {
// // check whether this match may be exact at runtime
// if (!jl_subtype(elt, decl_i))
// return 0;
// }
// }
// return 1;
//}
static jl_value_t *inst_varargp_in_env(jl_value_t *decl, jl_svec_t *sparams)
{
jl_value_t *unw = jl_unwrap_unionall(decl);
jl_value_t *vm = jl_tparam(unw, jl_nparams(unw) - 1);
assert(jl_is_vararg(vm));
int nsp = jl_svec_len(sparams);
if (nsp > 0 && jl_has_free_typevars(vm)) {
JL_GC_PUSH1(&vm);
assert(jl_subtype_env_size(decl) == nsp);
vm = jl_instantiate_type_in_env(vm, (jl_unionall_t*)decl, jl_svec_data(sparams));
assert(jl_is_vararg(vm));
// rewrap_unionall(lastdeclt, sparams) if any sparams isa TypeVar
// for example, `Tuple{Vararg{Union{Nothing,Int,Val{T}}}} where T`
// and the user called it with `Tuple{Vararg{Union{Nothing,Int},N}}`, then T is unbound
jl_value_t **sp = jl_svec_data(sparams);
while (jl_is_unionall(decl)) {
jl_tvar_t *v = (jl_tvar_t*)*sp;
if (jl_is_typevar(v)) {
// must unwrap and re-wrap Vararg object explicitly here since jl_type_unionall handles it differently
jl_value_t *T = ((jl_vararg_t*)vm)->T;
jl_value_t *N = ((jl_vararg_t*)vm)->N;
int T_has_tv = T && jl_has_typevar(T, v);
int N_has_tv = N && jl_has_typevar(N, v); // n.b. JL_VARARG_UNBOUND check means this should be false
assert(!N_has_tv || N == (jl_value_t*)v);
vm = T_has_tv ? jl_type_unionall(v, T) : T;
if (N_has_tv)
N = NULL;
vm = (jl_value_t*)jl_wrap_vararg(vm, N, 1); // this cannot throw for these inputs
}
sp++;
decl = ((jl_unionall_t*)decl)->body;
nsp--;
}
assert(nsp == 0);
JL_GC_POP();
}
return vm;
}
static jl_value_t *ml_matches(jl_methtable_t *mt,
jl_tupletype_t *type, int lim, int include_ambiguous,
int intersections, size_t world, int cache_result,
size_t *min_valid, size_t *max_valid, int *ambig);
// get the compilation signature specialization for this method
static void jl_compilation_sig(
jl_tupletype_t *const tt, // the original tupletype of the call (or DataType from precompile)
jl_svec_t *sparams,
jl_method_t *definition,
intptr_t max_varargs,
// output:
jl_svec_t **const newparams JL_REQUIRE_ROOTED_SLOT)
{
assert(jl_is_tuple_type(tt));
jl_value_t *decl = definition->sig;
size_t nargs = definition->nargs; // == jl_nparams(jl_unwrap_unionall(decl));
size_t nspec = max_varargs + nargs;
if (definition->generator) {
// staged functions aren't optimized
// so assume the caller was intelligent about calling us
return;
}
if (decl == (jl_value_t*)jl_anytuple_type && jl_atomic_load_relaxed(&definition->unspecialized)) {
*newparams = jl_anytuple_type->parameters; // handle builtin methods
return;
}
// some early sanity checks
size_t i, np = jl_nparams(tt);
switch (jl_va_tuple_kind((jl_datatype_t*)decl)) {
case JL_VARARG_NONE:
if (jl_is_va_tuple(tt))
// odd
return;
if (np != nargs)
// there are not enough input parameters to make this into a compilation sig
return;
break;
case JL_VARARG_INT:
case JL_VARARG_BOUND:
if (jl_is_va_tuple(tt))
// the length needed is not known, but required for compilation
return;
if (np < nargs - 1)
// there are not enough input parameters to make this into a compilation sig
return;
break;
case JL_VARARG_UNBOUND:
if (np < nspec && jl_is_va_tuple(tt))
// there are insufficient given parameters for jl_isa_compileable_sig now to like this type
// (there were probably fewer methods defined when we first selected this signature, or
// the max varargs limit was not reached indicating the type is already fully-specialized)
return;
break;
}
jl_value_t *type_i = NULL;
JL_GC_PUSH1(&type_i);
for (i = 0; i < np; i++) {
jl_value_t *elt = jl_tparam(tt, i);
if (jl_is_vararg(elt))
elt = jl_unwrap_vararg(elt);
jl_value_t *decl_i = jl_nth_slot_type(decl, i);
type_i = jl_rewrap_unionall(decl_i, decl);
size_t i_arg = (i < nargs - 1 ? i : nargs - 1);
if (jl_is_kind(type_i)) {
// if we can prove the match was against the kind (not a Type)
// we want to put that in the cache instead
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
elt = type_i;
jl_svecset(*newparams, i, elt);
}
else if (jl_is_type_type(elt)) {
// if the declared type was not Any or Union{Type, ...},
// then the match must been with the kind (e.g. UnionAll or DataType)
// and the result of matching the type signature
// needs to be restricted to the concrete type 'kind'
jl_value_t *kind = jl_typeof(jl_tparam0(elt));
if (jl_subtype(kind, type_i) && !jl_subtype((jl_value_t*)jl_type_type, type_i)) {
// if we can prove the match was against the kind (not a Type)
// it's simpler (and thus better) to put that cache instead
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
elt = kind;
jl_svecset(*newparams, i, elt);
}
}
else if (jl_is_kind(elt)) {
// not triggered for isdispatchtuple(tt), this attempts to handle
// some cases of adapting a random signature into a compilation signature
// if we get a kind, where we don't expect to accept one, widen it to something more expected (Type{T})
if (!(jl_subtype(elt, type_i) && !jl_subtype((jl_value_t*)jl_type_type, type_i))) {
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
elt = (jl_value_t*)jl_type_type;
jl_svecset(*newparams, i, elt);
}
}
if (jl_is_kind(elt)) {
// kind slots always need guard entries (checking for subtypes of Type)
continue;
}
if (i_arg > 0 && i_arg <= sizeof(definition->nospecialize) * 8 &&
(definition->nospecialize & (1 << (i_arg - 1)))) {
if (!jl_has_free_typevars(decl_i) && !jl_is_kind(decl_i)) {
if (decl_i != elt) {
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
// n.b. it is possible here that !(elt <: decl_i), if elt was something unusual from intersection
// so this might narrow the result slightly, though still being compatible with the declared signature
jl_svecset(*newparams, i, (jl_value_t*)decl_i);
}
continue;
}
}
if (jl_types_equal(elt, (jl_value_t*)jl_type_type)) { // elt == Type{T} where T
// not triggered for isdispatchtuple(tt), this attempts to handle
// some cases of adapting a random signature into a compilation signature
}
else if (!jl_is_datatype(elt) && jl_subtype(elt, (jl_value_t*)jl_type_type)) { // elt <: Type{T}
// not triggered for isdispatchtuple(tt), this attempts to handle
// some cases of adapting a random signature into a compilation signature
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
jl_svecset(*newparams, i, jl_type_type);
}
else if (jl_is_type_type(elt)) { // elt isa Type{T}
if (!jl_has_free_typevars(decl_i) && very_general_type(type_i)) {
/*
Here's a fairly simple heuristic: if this argument slot's
declared type is general (Type or Any),
then don't specialize for every Type that got passed.
Since every type x has its own type Type{x}, this would be
excessive specialization for an Any slot.
This may require guard entries due to other potential matches.
In particular, TypeConstructors are problematic because they can
be alternate representations of any type. Extensionally, TC == TC.body,
but typeof(TC) != typeof(TC.body). This creates an ambiguity:
Type{TC} is type-equal to Type{TC.body}, yet a slot
x::TypeConstructor matches the first but not the second, while
also matching all other TypeConstructors. This means neither
Type{TC} nor TypeConstructor is more specific.
But don't apply this heuristic if the argument is called (issue #36783).
*/
int iscalled = i_arg > 0 && i_arg <= 8 && (definition->called & (1 << (i_arg - 1)));
if (!iscalled) {
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
jl_svecset(*newparams, i, jl_type_type);
}
}
else if (jl_is_type_type(jl_tparam0(elt)) &&
// try to give up on specializing type parameters for Type{Type{Type{...}}}
(jl_is_type_type(jl_tparam0(jl_tparam0(elt))) || !jl_has_free_typevars(decl_i))) {
/*
actual argument was Type{...}, we computed its type as
Type{Type{...}}. we like to avoid unbounded nesting here, so
compile (and hopefully cache) the signature as Type{T},
unless something more specific like Type{Type{Int32}} was
actually declared. this can be determined using a type
intersection.
*/
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
if (i < nargs || !definition->isva) {
jl_value_t *di = jl_type_intersection(type_i, (jl_value_t*)jl_type_type);
assert(di != (jl_value_t*)jl_bottom_type);
// issue #11355: DataType has a UID and so would take precedence in the cache
if (jl_is_kind(di))
jl_svecset(*newparams, i, (jl_value_t*)jl_type_type);
else
jl_svecset(*newparams, i, di);
}
else {
jl_svecset(*newparams, i, (jl_value_t*)jl_type_type);
}
}
}
int notcalled_func = (i_arg > 0 && i_arg <= 8 && !(definition->called & (1 << (i_arg - 1))) &&
!jl_has_free_typevars(decl_i) &&
jl_subtype(elt, (jl_value_t*)jl_function_type));
if (notcalled_func && (type_i == (jl_value_t*)jl_any_type ||
type_i == (jl_value_t*)jl_function_type ||
(jl_is_uniontype(type_i) && // Base.Callable
((((jl_uniontype_t*)type_i)->a == (jl_value_t*)jl_function_type &&
((jl_uniontype_t*)type_i)->b == (jl_value_t*)jl_type_type) ||
(((jl_uniontype_t*)type_i)->b == (jl_value_t*)jl_function_type &&
((jl_uniontype_t*)type_i)->a == (jl_value_t*)jl_type_type))))) {
// and attempt to despecialize types marked Function, Callable, or Any
// when called with a subtype of Function but is not called
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
jl_svecset(*newparams, i, (jl_value_t*)jl_function_type);
}
}
// for varargs methods, only specialize up to max_args.
// in general, here we want to find the biggest type that's not a
// supertype of any other method signatures. so far we are conservative
// and the types we find should be bigger.
if (np >= nspec && jl_va_tuple_kind((jl_datatype_t*)decl) == JL_VARARG_UNBOUND) {
if (!*newparams) *newparams = tt->parameters;
if (max_varargs > 0) {
type_i = jl_svecref(*newparams, nspec - 2);
} else {
// If max varargs is zero, always specialize to (Any...) since
// there is no preceding parameter to use for `type_i`
type_i = jl_bottom_type;
}
// if all subsequent arguments are subtypes of type_i, specialize
// on that instead of decl. for example, if decl is
// (Any...)
// and type is
// (Symbol, Symbol, Symbol)
// then specialize as (Symbol...), but if type is
// (Symbol, Int32, Expr)
// then specialize as (Any...)
size_t j = nspec - 1;
int all_are_subtypes = 1;
for (; j < jl_svec_len(*newparams); j++) {
jl_value_t *paramj = jl_svecref(*newparams, j);
if (jl_is_vararg(paramj))
paramj = jl_unwrap_vararg(paramj);
if (!jl_subtype(paramj, type_i)) {
all_are_subtypes = 0;
break;
}
}
if (all_are_subtypes) {
// avoid Vararg{Type{Type{...}}}
if (jl_is_type_type(type_i) && jl_is_type_type(jl_tparam0(type_i)))
type_i = (jl_value_t*)jl_type_type;
type_i = (jl_value_t*)jl_wrap_vararg(type_i, (jl_value_t*)NULL, 1); // this cannot throw for these inputs
}
else {
type_i = inst_varargp_in_env(decl, sparams);
}
jl_svec_t *limited = jl_alloc_svec(nspec);
size_t i;
for (i = 0; i < nspec - 1; i++) {
jl_svecset(limited, i, jl_svecref(*newparams, i));
}
jl_svecset(limited, i, type_i);
*newparams = limited;