-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
gf.c
2665 lines (2486 loc) · 104 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 size_t jl_world_counter = 1;
JL_DLLEXPORT size_t jl_get_world_counter(void)
{
return jl_world_counter;
}
JL_DLLEXPORT size_t jl_get_tls_world_age(void)
{
return jl_get_ptls_states()->world_age;
}
JL_DLLEXPORT jl_value_t *jl_invoke(jl_method_instance_t *meth, jl_value_t **args, uint32_t nargs)
{
jl_callptr_t fptr = meth->invoke;
if (fptr != jl_fptr_trampoline) {
return fptr(meth, args, nargs);
}
else {
// if this hasn't been inferred (compiled) yet,
// inferring it might not be able to handle the world range
// so we just do a generic apply here
// because that might actually be faster
// since it can go through the unrolled caches for this world
// and if inference is successful, this meth would get updated anyways,
// and we'll get the fast path here next time
// TODO: if `meth` came from an `invoke` call, we should make sure
// meth->def is called instead of doing normal dispatch.
return jl_apply(args, nargs);
}
}
/// ----- Handling for Julia callbacks ----- ///
JL_DLLEXPORT int8_t jl_is_in_pure_context(void)
{
jl_ptls_t ptls = jl_get_ptls_states();
return ptls->in_pure_callback;
}
JL_DLLEXPORT void jl_trace_method(jl_method_t *m)
{
assert(jl_is_method(m));
m->traced = 1;
}
JL_DLLEXPORT void jl_untrace_method(jl_method_t *m)
{
assert(jl_is_method(m));
m->traced = 0;
}
JL_DLLEXPORT void jl_trace_linfo(jl_method_instance_t *linfo)
{
assert(jl_is_method_instance(linfo));
linfo->compile_traced = 1;
}
JL_DLLEXPORT void jl_untrace_linfo(jl_method_instance_t *linfo)
{
assert(jl_is_method_instance(linfo));
linfo->compile_traced = 0;
}
static tracer_cb jl_method_tracer = NULL;
JL_DLLEXPORT void jl_register_method_tracer(void (*callback)(jl_method_instance_t *tracee))
{
jl_method_tracer = (tracer_cb)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;
}
tracer_cb jl_linfo_tracer = NULL;
JL_DLLEXPORT void jl_register_linfo_tracer(void (*callback)(jl_method_instance_t *tracee))
{
jl_linfo_tracer = (tracer_cb)callback;
}
void jl_call_tracer(tracer_cb callback, jl_value_t *tracee)
{
jl_ptls_t ptls = jl_get_ptls_states();
int last_in = ptls->in_pure_callback;
JL_TRY {
ptls->in_pure_callback = 1;
callback(tracee);
ptls->in_pure_callback = last_in;
}
JL_CATCH {
ptls->in_pure_callback = last_in;
jl_printf(JL_STDERR, "WARNING: tracer callback function threw an error:\n");
jl_static_show(JL_STDERR, jl_current_exception());
jl_printf(JL_STDERR, "\n");
jlbacktrace();
}
}
/// ----- Definitions for various internal TypeMaps ----- ///
const struct jl_typemap_info method_defs = {
0, &jl_method_type
};
const struct jl_typemap_info lambda_cache = {
0, &jl_method_instance_type
};
const struct jl_typemap_info tfunc_cache = {
1, &jl_any_type
};
static int8_t jl_cachearg_offset(jl_methtable_t *mt)
{
// TODO: consider reverting this when we can split on Type{...} better
return 1; //(mt == jl_type_type_mt) ? 0 : 1;
}
/// ----- Insertion logic for special entries ----- ///
// get or create the MethodInstance for a specialization
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, size_t world)
{
assert(world >= m->min_world && world <= m->max_world && "typemap lookup is corrupted");
JL_LOCK(&m->writelock);
jl_typemap_entry_t *sf =
jl_typemap_assoc_by_type(m->specializations, type, NULL, /*subtype*/0, /*offs*/0, world, /*max_world_mask*/0);
if (sf && jl_is_method_instance(sf->func.value)) {
jl_method_instance_t *linfo = (jl_method_instance_t*)sf->func.value;
assert(linfo->min_world <= sf->min_world && linfo->max_world >= sf->max_world);
JL_UNLOCK(&m->writelock);
return linfo;
}
jl_method_instance_t *li = jl_get_specialized(m, type, sparams);
JL_GC_PUSH1(&li);
// TODO: fuse lookup and insert steps
// pick an initial world that is likely to be valid both before and after inference
if (world > jl_world_counter) {
li->min_world = jl_world_counter;
}
else {
li->min_world = world;
}
if (world == jl_world_counter) {
li->max_world = m->max_world;
}
else {
li->max_world = world;
}
jl_typemap_insert(&m->specializations, (jl_value_t*)m, (jl_tupletype_t*)type,
NULL, jl_emptysvec, (jl_value_t*)li, 0, &tfunc_cache,
li->min_world, li->max_world, NULL);
JL_UNLOCK(&m->writelock);
JL_GC_POP();
return li;
}
JL_DLLEXPORT jl_value_t *jl_specializations_lookup(jl_method_t *m, jl_value_t *type, size_t world)
{
jl_typemap_entry_t *sf = jl_typemap_assoc_by_type(
m->specializations, type, NULL, /*subtype*/0, /*offs*/0, world, /*max_world_mask*/0);
if (!sf)
return jl_nothing;
return sf->func.value;
}
JL_DLLEXPORT jl_value_t *jl_methtable_lookup(jl_methtable_t *mt, jl_value_t *type, size_t world)
{
jl_typemap_entry_t *sf = jl_typemap_assoc_by_type(
mt->defs, type, NULL, /*subtype*/0, /*offs*/0, world, /*max_world_mask*/0);
if (!sf)
return jl_nothing;
return sf->func.value;
}
// ----- MethodInstance specialization instantiation ----- //
JL_DLLEXPORT jl_method_t *jl_new_method_uninit(jl_module_t*);
void 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, 0);
jl_set_const(jl_core_module, sname, f);
dt = (jl_datatype_t*)jl_typeof(f);
}
jl_method_instance_t *li = jl_new_method_instance_uninit();
li->invoke = jl_fptr_args;
li->specptr.fptr1 = fptr;
li->specTypes = (jl_value_t*)jl_anytuple_type;
li->min_world = 1;
li->max_world = ~(size_t)0;
JL_GC_PUSH1(&li);
jl_method_t *m = jl_new_method_uninit(jl_core_module);
li->def.method = m;
jl_gc_wb(li, m);
m->name = sname;
m->module = jl_core_module;
m->isva = 1;
m->nargs = 2;
m->sig = (jl_value_t*)jl_anytuple_type;
m->sparam_syms = jl_emptysvec;
jl_methtable_t *mt = dt->name->mt;
jl_typemap_insert(&mt->cache, (jl_value_t*)mt, jl_anytuple_type,
NULL, jl_emptysvec, (jl_value_t*)li, 0, &lambda_cache, 1, ~(size_t)0, NULL);
JL_GC_POP();
}
// run type inference on lambda "li" for given argument types.
// returns the inferred source, and may cache the result in li
// if successful, also updates the li 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 **pli JL_ROOTS_TEMPORARILY, size_t world, int force)
{
JL_TIMING(INFERENCE);
if (jl_typeinf_func == NULL)
return NULL;
static int in_inference;
if (in_inference > 2)
return NULL;
jl_code_info_t *src = NULL;
#ifdef ENABLE_INFERENCE
jl_method_instance_t *li = *pli;
if (li->inInference && !force)
return NULL;
jl_value_t **fargs;
JL_GC_PUSHARGS(fargs, 3);
fargs[0] = (jl_value_t*)jl_typeinf_func;
fargs[1] = (jl_value_t*)li;
fargs[2] = jl_box_ulong(world);
#ifdef TRACE_INFERENCE
if (li->specTypes != (jl_value_t*)jl_emptytuple_type) {
jl_printf(JL_STDERR,"inference on ");
jl_static_show_func_sig(JL_STDERR, (jl_value_t*)li->specTypes);
jl_printf(JL_STDERR, "\n");
}
#endif
jl_ptls_t ptls = jl_get_ptls_states();
size_t last_age = ptls->world_age;
ptls->world_age = jl_typeinf_world;
li->inInference = 1;
in_inference++;
jl_svec_t *linfo_src;
JL_TRY {
linfo_src = (jl_svec_t*)jl_apply(fargs, 3);
}
JL_CATCH {
jl_printf(JL_STDERR, "Internal error: encountered unexpected error in runtime:\n");
jl_static_show(JL_STDERR, jl_current_exception());
jl_printf(JL_STDERR, "\n");
jlbacktrace(); // written to STDERR_FILENO
linfo_src = NULL;
}
ptls->world_age = last_age;
in_inference--;
li->inInference = 0;
if (linfo_src && jl_is_svec(linfo_src) && jl_svec_len(linfo_src) == 2) {
jl_value_t *mi = jl_svecref(linfo_src, 0);
jl_value_t *ci = jl_svecref(linfo_src, 1);
if (jl_is_method_instance(mi) && jl_is_code_info(ci)) {
*pli = (jl_method_instance_t*)mi;
src = (jl_code_info_t*)ci;
}
}
JL_GC_POP();
#endif
return src;
}
JL_DLLEXPORT jl_value_t *jl_call_in_typeinf_world(jl_value_t **args, int nargs)
{
jl_ptls_t ptls = jl_get_ptls_states();
size_t last_age = ptls->world_age;
ptls->world_age = jl_typeinf_world;
jl_value_t *ret = jl_apply(args, nargs);
ptls->world_age = last_age;
return ret;
}
int jl_is_rettype_inferred(jl_method_instance_t *li) JL_NOTSAFEPOINT
{
if (!li->inferred)
return 0;
if (jl_is_code_info(li->inferred) && !((jl_code_info_t*)li->inferred)->inferred)
return 0;
return 1;
}
struct set_world {
jl_method_instance_t *replaced;
size_t world;
};
static int set_max_world2(jl_typemap_entry_t *entry, void *closure0)
{
struct set_world *closure = (struct set_world*)closure0;
// entry->max_world should be <= closure->replaced->max_world
if (entry->func.linfo == closure->replaced && entry->max_world > closure->world) {
entry->max_world = closure->world;
}
return 1;
}
static int set_min_world2(jl_typemap_entry_t *entry, void *closure0)
{
struct set_world *closure = (struct set_world*)closure0;
// entry->min_world should be >= closure->replaced->min_world and >= closure->world
if (entry->func.linfo == closure->replaced) {
entry->min_world = closure->world;
}
return 1;
}
static void update_world_bound(jl_method_instance_t *replaced, jl_typemap_visitor_fptr fptr, size_t world)
{
struct set_world update;
update.replaced = replaced;
update.world = world;
jl_method_t *m = replaced->def.method;
// update the world-valid in the specializations caches
jl_typemap_visitor(m->specializations, fptr, (void*)&update);
// update the world-valid in the invoke cache
if (m->invokes != NULL)
jl_typemap_visitor(m->invokes, fptr, (void*)&update);
// update the world-valid in the gf cache
jl_datatype_t *gf = jl_first_argument_datatype((jl_value_t*)m->sig);
assert(jl_is_datatype(gf) && gf->name->mt && "method signature invalid?");
jl_typemap_visitor(gf->name->mt->cache, fptr, (void*)&update);
}
JL_DLLEXPORT jl_method_instance_t* jl_set_method_inferred(
jl_method_instance_t *li, 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)
{
JL_GC_PUSH1(&li);
assert(min_world <= max_world && "attempting to set invalid world constraints");
assert(li->inInference && "shouldn't be caching an inference result for a MethodInstance that wasn't being inferred");
if (min_world != li->min_world || max_world != li->max_world) {
if (!jl_is_method(li->def.method)) {
// thunks don't have multiple references, so just update in-place
li->min_world = min_world;
li->max_world = max_world;
}
else {
JL_LOCK(&li->def.method->writelock);
assert(min_world >= li->def.method->min_world);
assert(max_world <= li->def.method->max_world);
int isinferred = jl_is_rettype_inferred(li);
if (!isinferred && li->min_world >= min_world && li->max_world <= max_world) {
// expand the current (uninferred) entry to cover the full inferred range
// only update the specializations though, since the method table may have other
// reasons for needing a narrower applicability range
struct set_world update;
update.replaced = li;
if (li->min_world != min_world) {
li->min_world = min_world;
update.world = min_world;
jl_typemap_visitor(li->def.method->specializations, set_min_world2, (void*)&update);
}
if (li->max_world != max_world) {
li->max_world = max_world;
update.world = max_world;
jl_typemap_visitor(li->def.method->specializations, set_max_world2, (void*)&update);
}
}
else {
// clip applicability of old method instance (uninferred or inferred)
// to make it easier to find the inferred method
// (even though the real applicability was unchanged)
// there are 6(!) regions here to consider + boundary conditions for each
if (li->max_world >= min_world && li->min_world <= max_world) {
// there is a non-zero overlap between [li->min, li->max] and [min, max]
// there are now 4 regions left to consider
// TODO: also take into account li->def.method->world range when computing preferred division
if (li->max_world > max_world) {
// prefer making it applicable to future ages,
// as those are more likely to be useful
update_world_bound(li, set_min_world2, max_world + 1);
}
else if (li->min_world < min_world) {
assert(min_world > 1 && "logic violation: min(li->min_world) == 1 (by construction), so min(min_world) == 2");
update_world_bound(li, set_max_world2, min_world - 1);
}
else {
// old inferred li is fully covered by new inference result, so just delete it
assert(isinferred);
update_world_bound(li, set_max_world2, li->min_world - 1);
}
}
// build a new entry to describe the new (inferred) applicability
li = jl_get_specialized(li->def.method, li->specTypes, li->sparam_vals);
li->min_world = min_world;
li->max_world = max_world;
jl_typemap_insert(&li->def.method->specializations, li->def.value,
(jl_tupletype_t*)li->specTypes, NULL, jl_emptysvec,
(jl_value_t*)li, 0, &tfunc_cache,
li->min_world, li->max_world, NULL);
}
JL_UNLOCK(&li->def.method->writelock);
}
}
// changing rettype changes the llvm signature,
// so clear all of the llvm state at the same time
li->invoke = jl_fptr_trampoline;
li->functionObjectsDecls.functionObject = NULL;
li->functionObjectsDecls.specFunctionObject = NULL;
li->rettype = rettype;
jl_gc_wb(li, rettype);
li->inferred = inferred;
jl_gc_wb(li, inferred);
if (const_flags & 2) {
li->inferred_const = inferred_const;
jl_gc_wb(li, inferred_const);
}
if (const_flags & 1) {
assert(const_flags & 2);
li->invoke = jl_fptr_const_return;
}
li->specptr.fptr = NULL;
JL_GC_POP();
return li;
}
static int get_spec_unspec_list(jl_typemap_entry_t *l, void *closure)
{
if (jl_is_method_instance(l->func.value) && !jl_is_rettype_inferred(l->func.linfo))
jl_array_ptr_1d_push((jl_array_t*)closure, l->func.value);
return 1;
}
static int get_method_unspec_list(jl_typemap_entry_t *def, void *closure)
{
jl_typemap_visitor(def->func.method->specializations, get_spec_unspec_list, closure);
return 1;
}
static void foreach_mtable_in_module(
jl_module_t *m,
void (*visit)(jl_methtable_t *mt, void *env),
void *env,
jl_array_t *visited)
{
size_t i;
void **table = m->bindings.table;
jl_eqtable_put(visited, (jl_value_t*)m, jl_true, NULL);
for (i = 1; i < m->bindings.size; i += 2) {
if (table[i] != HT_NOTFOUND) {
jl_binding_t *b = (jl_binding_t*)table[i];
if (b->owner == m && b->value && b->constp) {
jl_value_t *v = jl_unwrap_unionall(b->value);
if (jl_is_datatype(v)) {
jl_typename_t *tn = ((jl_datatype_t*)v)->name;
if (tn->module == m && tn->name == b->name) {
jl_methtable_t *mt = tn->mt;
if (mt != NULL && (jl_value_t*)mt != jl_nothing && mt != jl_type_type_mt) {
visit(mt, env);
}
}
}
else if (jl_is_module(v)) {
jl_module_t *child = (jl_module_t*)v;
if (child != m && child->parent == m && child->name == b->name &&
!jl_eqtable_get(visited, v, NULL)) {
// this is the original/primary binding for the submodule
foreach_mtable_in_module(child, visit, env, visited);
}
}
}
}
}
}
void jl_foreach_reachable_mtable(void (*visit)(jl_methtable_t *mt, void *env), void *env)
{
jl_array_t *visited = jl_alloc_vec_any(16);
jl_array_t *mod_array = NULL;
JL_GC_PUSH2(&visited, &mod_array);
mod_array = jl_get_loaded_modules();
visit(jl_type_type_mt, env);
if (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 (!jl_eqtable_get(visited, (jl_value_t*)m, NULL))
foreach_mtable_in_module(m, visit, env, visited);
}
}
else {
foreach_mtable_in_module(jl_main_module, visit, env, visited);
}
JL_GC_POP();
}
static void reset_mt_caches(jl_methtable_t *mt, void *env)
{
// removes all method caches
if (mt->defs != jl_nothing) // make sure not to reset builtin functions
mt->cache = jl_nothing;
jl_typemap_visitor(mt->defs, get_method_unspec_list, env);
}
jl_function_t *jl_typeinf_func = NULL;
size_t jl_typeinf_world = 0;
JL_DLLEXPORT void jl_set_typeinf_func(jl_value_t *f)
{
jl_typeinf_func = (jl_function_t*)f;
jl_typeinf_world = jl_get_tls_world_age();
++jl_world_counter; // make type-inference the only thing in this world
// 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 *li = (jl_method_instance_t*)jl_array_ptr_ref(unspec, i);
if (!jl_is_rettype_inferred(li))
jl_type_infer(&li, jl_world_counter, 1);
}
JL_GC_POP();
}
static int very_general_type(jl_value_t *t)
{
return (t == (jl_value_t*)jl_any_type || t == (jl_value_t*)jl_type_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)
{
sig = jl_unwrap_unionall(sig);
size_t len = jl_field_count(sig);
if (len == 0)
return NULL;
if (i < len-1)
return jl_tparam(sig, i);
if (jl_is_vararg_type(jl_tparam(sig,len-1)))
return jl_unwrap_vararg(jl_tparam(sig,len-1));
if (i == len-1)
return jl_tparam(sig, i);
return NULL;
}
// 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 *ml_matches(jl_typemap_t *ml, int offs,
jl_tupletype_t *type, int lim, int include_ambiguous,
size_t world, size_t *min_valid, size_t *max_valid);
// get the compilation signature specialization for this method
static void jl_compilation_sig(
jl_tupletype_t *const tt, // the original tupletype of the call : this is expected to be a relative simple type (no Varags, Union, UnionAll, etc.)
jl_svec_t *sparams,
jl_method_t *definition,
intptr_t nspec,
// output:
jl_svec_t **const newparams JL_REQUIRE_ROOTED_SLOT)
{
if (definition->generator) {
// staged functions aren't optimized
// so assume the caller was intelligent about calling us
return;
}
jl_value_t *decl = definition->sig;
assert(jl_is_tuple_type(tt));
size_t i, np = jl_nparams(tt);
size_t nargs = definition->nargs; // == jl_field_count(jl_unwrap_unionall(decl));
for (i = 0; i < np; i++) {
jl_value_t *elt = jl_tparam(tt, i);
jl_value_t *decl_i = jl_nth_slot_type(decl, i);
size_t i_arg = (i < nargs - 1 ? i : nargs - 1);
if (jl_is_kind(decl_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 = decl_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, decl_i) && !jl_subtype((jl_value_t*)jl_type_type, decl_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, decl_i) && !jl_subtype((jl_value_t*)jl_type_type, decl_i))) {
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
elt = (jl_value_t*)jl_typetype_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);
jl_svecset(*newparams, i, (jl_value_t*)decl_i);
}
continue;
}
}
if (jl_types_equal(elt, (jl_value_t*)jl_typetype_type)) {
// 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_has_empty_intersection((jl_value_t*)jl_type_type, elt)) {
// 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_typetype_type);
}
else if (jl_is_type_type(elt)) {
if (very_general_type(decl_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.
*/
if (!*newparams) *newparams = jl_svec_copy(tt->parameters);
jl_svecset(*newparams, i, jl_typetype_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))) {
// TODO: this is probably solidly unsound and would corrupt the cache in many cases
/*
actual argument was Type{...}, we computed its type as
Type{Type{...}}. we must avoid unbounded nesting here, so
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(decl_i, (jl_value_t*)jl_typetype_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_typetype_type);
else
jl_svecset(*newparams, i, di);
// TODO: recompute static parameter values, so in extreme cases we
// can give `T=Type` instead of `T=Type{Type{Type{...`. /* make editors happy:}}} */
}
else {
jl_svecset(*newparams, i, (jl_value_t*)jl_typetype_type);
}
}
}
int notcalled_func = (i_arg > 0 && i_arg <= 8 && !(definition->called & (1 << (i_arg - 1))) &&
jl_subtype(elt, (jl_value_t*)jl_function_type));
if (notcalled_func && (decl_i == (jl_value_t*)jl_any_type ||
decl_i == (jl_value_t*)jl_function_type ||
(jl_is_uniontype(decl_i) && // Base.Callable
((((jl_uniontype_t*)decl_i)->a == (jl_value_t*)jl_function_type &&
((jl_uniontype_t*)decl_i)->b == (jl_value_t*)jl_type_type) ||
(((jl_uniontype_t*)decl_i)->b == (jl_value_t*)jl_function_type &&
((jl_uniontype_t*)decl_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 (jl_nparams(tt) >= nspec && jl_va_tuple_kind((jl_datatype_t*)decl) == JL_VARARG_UNBOUND) {
jl_svec_t *limited = jl_alloc_svec(nspec);
JL_GC_PUSH1(&limited);
if (!*newparams) *newparams = tt->parameters;
size_t i;
for (i = 0; i < nspec - 1; i++) {
jl_svecset(limited, i, jl_svecref(*newparams, i));
}
jl_value_t *lasttype = jl_svecref(*newparams, i - 1);
// if all subsequent arguments are subtypes of lasttype, 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 = i;
int all_are_subtypes = 1;
for (; j < jl_svec_len(*newparams); j++) {
if (!jl_subtype(jl_svecref(*newparams, j), lasttype)) {
all_are_subtypes = 0;
break;
}
}
if (all_are_subtypes) {
// avoid Vararg{Type{Type{...}}}
if (jl_is_type_type(lasttype) && jl_is_type_type(jl_tparam0(lasttype)))
lasttype = (jl_value_t*)jl_type_type;
jl_svecset(limited, i, jl_wrap_vararg(lasttype, (jl_value_t*)NULL));
}
else {
jl_value_t *unw = jl_unwrap_unionall(decl);
jl_value_t *lastdeclt = jl_tparam(unw, nargs - 1);
assert(jl_is_vararg_type(lastdeclt) && jl_nparams(unw) == nargs);
int nsp = jl_svec_len(sparams);
if (nsp > 0 && jl_has_free_typevars(lastdeclt)) {
assert(jl_subtype_env_size(decl) == nsp);
lastdeclt = jl_instantiate_type_in_env(lastdeclt, (jl_unionall_t*)decl, jl_svec_data(sparams));
// TODO: rewrap_unionall(lastdeclt, sparams) if any sparams isa TypeVar???
// TODO: if we made any replacements above, sparams may now be incorrect
}
jl_svecset(limited, i, lastdeclt);
}
*newparams = limited;
// now there is a problem: the widened signature is more
// general than just the given arguments, so it might conflict
// with another definition that doesn't have cache instances yet.
// to fix this, we insert guard cache entries for all intersections
// of this signature and definitions. those guard entries will
// supersede this one in conflicted cases, alerting us that there
// should actually be a cache miss.
// TODO: the above analysis assumes that there will never
// be a call attempted that should throw a no-method error
JL_GC_POP();
}
}
// compute whether this type signature is a possible return value from jl_compilation_sig given a concrete-type for `tt`
JL_DLLEXPORT int jl_isa_compileable_sig(
jl_tupletype_t *type,
jl_method_t *definition)
{
jl_value_t *decl = definition->sig;
if (!jl_is_datatype(type) || jl_has_free_typevars((jl_value_t*)type))
return 0;
size_t i, np = jl_nparams(type);
size_t nargs = definition->nargs; // == jl_field_count(jl_unwrap_unionall(decl));
if (np == 0)
return nargs == 0;
if (definition->generator) {
// staged functions aren't optimized
// so assume the caller was intelligent about calling us
return (definition->isva ? np >= nargs - 1 : np == nargs) && type->isdispatchtuple;
}
// for varargs methods, only specialize up to max_args (>= nargs + 1).
// 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 (definition->isva) {
unsigned nspec_min = nargs + 1; // min number of non-vararg values before vararg
unsigned nspec_max = INT32_MAX; // max number of non-vararg values before vararg
jl_datatype_t *gf = jl_first_argument_datatype(decl);
if (gf != NULL && jl_is_datatype(gf) && gf->name->mt != NULL) {
// try to refine estimate of min and max
if (gf->name->mt != jl_type_type_mt)
nspec_min = gf->name->mt->max_args + 2;
else
nspec_max = nspec_min;
}
int isbound = (jl_va_tuple_kind((jl_datatype_t*)decl) == JL_VARARG_UNBOUND);
if (jl_is_vararg_type(jl_tparam(type, np - 1))) {
if (!isbound || np < nspec_min || np > nspec_max)
return 0;
}
else {
if (np < nargs - 1 || (isbound && np >= nspec_max))
return 0;
}
}
else if (np != nargs || jl_is_vararg_type(jl_tparam(type, np - 1))) {
return 0;
}
for (i = 0; i < np; i++) {
jl_value_t *elt = jl_tparam(type, i);
jl_value_t *decl_i = jl_nth_slot_type((jl_value_t*)decl, i);
size_t i_arg = (i < nargs - 1 ? i : nargs - 1);
if (jl_is_vararg_type(elt)) {
elt = jl_unwrap_vararg(elt);
if (jl_has_free_typevars(decl_i)) {
// TODO: in this case, answer semi-conservatively that these varargs are always compilable
// we don't have the ability to get sparams, so deciding if elt
// is a potential result of jl_instantiate_type_in_env for decl_i
// for any sparams that is consistent with the rest of the arguments
// seems like it would be extremely difficult
// and hopefully the upstream code probably gave us something reasonable
continue;
}
else if (jl_egal(elt, decl_i)) {
continue;
}
else if (jl_is_type_type(elt) && jl_is_type_type(jl_tparam0(elt))) {
return 0;
}
// else, it needs to meet the usual rules
}
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 (jl_egal(elt, decl_i))
continue;
return 0;
}
}
if (jl_is_kind(elt)) {
// kind slots always get guard entries (checking for subtypes of Type)
if (jl_subtype(elt, decl_i) && !jl_subtype((jl_value_t*)jl_type_type, decl_i))
continue;
// TODO: other code paths that could reach here
return 0;
}
else if (jl_is_kind(decl_i)) {
return 0;
}
if (jl_is_type_type(jl_unwrap_unionall(elt))) {
if (jl_types_equal(elt, (jl_value_t*)jl_type_type)) {
if (very_general_type(decl_i))
continue;
if (i >= nargs && definition->isva)
continue;
return 0;
}
if (very_general_type(decl_i))
return 0;
if (!jl_is_datatype(elt))
return 0;
// if the declared type was not Any or Union{Type, ...},
// then the match must been with kind, such as UnionAll or DataType,
// and the result of matching the type signature
// needs to be corrected to the concrete type 'kind' (and not to Type)
jl_value_t *kind = jl_typeof(jl_tparam0(elt));
if (kind == jl_bottom_type)
return 0; // Type{Union{}} gets normalized to typeof(Union{})
if (jl_subtype(kind, decl_i) && !jl_subtype((jl_value_t*)jl_type_type, decl_i))
return 0; // gets turned into a kind
else if (jl_is_type_type(jl_tparam0(elt)) &&
// give up on specializing static 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 must avoid unbounded nesting here, so
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 (i < nargs || !definition->isva) {
jl_value_t *di = jl_type_intersection(decl_i, (jl_value_t*)jl_typetype_type);
JL_GC_PUSH1(&di);
assert(di != (jl_value_t*)jl_bottom_type);
if (jl_is_kind(di)) {
JL_GC_POP();
return 0;
}
else if (!jl_types_equal(di, elt)) {
JL_GC_POP();
return 0;
}
JL_GC_POP();
}
else {
return 0;
}
}
continue;
}
int notcalled_func = (i_arg > 0 && i_arg <= 8 && !(definition->called & (1 << (i_arg - 1))) &&
jl_subtype(elt, (jl_value_t*)jl_function_type));
if (notcalled_func && (decl_i == (jl_value_t*)jl_any_type ||
decl_i == (jl_value_t*)jl_function_type ||
(jl_is_uniontype(decl_i) && // Base.Callable
((((jl_uniontype_t*)decl_i)->a == (jl_value_t*)jl_function_type &&
((jl_uniontype_t*)decl_i)->b == (jl_value_t*)jl_type_type) ||
(((jl_uniontype_t*)decl_i)->b == (jl_value_t*)jl_function_type &&
((jl_uniontype_t*)decl_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 (elt == (jl_value_t*)jl_function_type)
continue;
return 0;
}
if (!jl_is_concrete_type(elt))
return 0;
}
return 1;
}
static jl_method_instance_t *cache_method(
jl_methtable_t *mt, jl_typemap_t **cache, jl_value_t *parent JL_PROPAGATES_ROOT,
jl_tupletype_t *tt, // the original tupletype of the signature
jl_method_t *definition,
size_t world,
jl_svec_t *sparams,
int allow_exec)
{
// caller must hold the mt->writelock
// short-circuit (now that we hold the lock) if this entry is already present
jl_typemap_entry_t *entry = jl_typemap_assoc_by_type(*cache, (jl_value_t*)tt, NULL, /*subtype*/1, jl_cachearg_offset(mt), world, /*max_world_mask*/0);
if (entry && entry->func.value)
return (jl_method_instance_t*)entry->func.value;