-
Notifications
You must be signed in to change notification settings - Fork 17.3k
/
stencil.go
2303 lines (2105 loc) · 77.6 KB
/
stencil.go
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
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file will evolve, since we plan to do a mix of stenciling and passing
// around dictionaries.
package noder
import (
"cmd/compile/internal/base"
"cmd/compile/internal/ir"
"cmd/compile/internal/objw"
"cmd/compile/internal/reflectdata"
"cmd/compile/internal/typecheck"
"cmd/compile/internal/types"
"cmd/internal/obj"
"cmd/internal/src"
"fmt"
"go/constant"
)
// Enable extra consistency checks.
const doubleCheck = false
func assert(p bool) {
base.Assert(p)
}
// For outputting debug information on dictionary format and instantiated dictionaries
// (type arg, derived types, sub-dictionary, and itab entries).
var infoPrintMode = false
func infoPrint(format string, a ...interface{}) {
if infoPrintMode {
fmt.Printf(format, a...)
}
}
var geninst genInst
func BuildInstantiations() {
geninst.instInfoMap = make(map[*types.Sym]*instInfo)
geninst.buildInstantiations()
geninst.instInfoMap = nil
}
// buildInstantiations scans functions for generic function calls and methods, and
// creates the required instantiations. It also creates instantiated methods for all
// fully-instantiated generic types that have been encountered already or new ones
// that are encountered during the instantiation process. It scans all declarations
// in typecheck.Target.Decls first, before scanning any new instantiations created.
func (g *genInst) buildInstantiations() {
// Instantiate the methods of instantiated generic types that we have seen so far.
g.instantiateMethods()
// Scan all currentdecls for call to generic functions/methods.
n := len(typecheck.Target.Decls)
for i := 0; i < n; i++ {
g.scanForGenCalls(typecheck.Target.Decls[i])
}
// Scan all new instantiations created due to g.instantiateMethods() and the
// scan of current decls. This loop purposely runs until no new
// instantiations are created.
for i := 0; i < len(g.newInsts); i++ {
g.scanForGenCalls(g.newInsts[i])
}
g.finalizeSyms()
// All the instantiations and dictionaries have been created. Now go through
// each new instantiation and transform the various operations that need to make
// use of their dictionary.
l := len(g.newInsts)
for _, fun := range g.newInsts {
info := g.instInfoMap[fun.Sym()]
g.dictPass(info)
if doubleCheck {
ir.Visit(info.fun, func(n ir.Node) {
if n.Op() != ir.OCONVIFACE {
return
}
c := n.(*ir.ConvExpr)
if c.X.Type().HasShape() && !c.X.Type().IsInterface() {
ir.Dump("BAD FUNCTION", info.fun)
ir.Dump("BAD CONVERSION", c)
base.Fatalf("converting shape type to interface")
}
})
}
if base.Flag.W > 1 {
ir.Dump(fmt.Sprintf("\ndictpass %v", info.fun), info.fun)
}
}
assert(l == len(g.newInsts))
g.newInsts = nil
}
// scanForGenCalls scans a single function (or global assignment), looking for
// references to generic functions/methods. At each such reference, it creates any
// required instantiation and transforms the reference.
func (g *genInst) scanForGenCalls(decl ir.Node) {
switch decl.Op() {
case ir.ODCLFUNC:
if decl.Type().HasTParam() {
// Skip any generic functions
return
}
// transformCall() below depends on CurFunc being set.
ir.CurFunc = decl.(*ir.Func)
case ir.OAS, ir.OAS2, ir.OAS2DOTTYPE, ir.OAS2FUNC, ir.OAS2MAPR, ir.OAS2RECV, ir.OASOP:
// These are all the various kinds of global assignments,
// whose right-hand-sides might contain a function
// instantiation.
default:
// The other possible ops at the top level are ODCLCONST
// and ODCLTYPE, which don't have any function
// instantiations.
return
}
// Search for any function references using generic function/methods. Then
// create the needed instantiated function if it hasn't been created yet, and
// change to calling that function directly.
modified := false
closureRequired := false
// declInfo will be non-nil exactly if we are scanning an instantiated function
declInfo := g.instInfoMap[decl.Sym()]
ir.Visit(decl, func(n ir.Node) {
if n.Op() == ir.OFUNCINST {
// generic F, not immediately called
closureRequired = true
}
if (n.Op() == ir.OMETHEXPR || n.Op() == ir.OMETHVALUE) && len(deref(n.(*ir.SelectorExpr).X.Type()).RParams()) > 0 && !types.IsInterfaceMethod(n.(*ir.SelectorExpr).Selection.Type) {
// T.M or x.M, where T or x is generic, but not immediately
// called. Not necessary if the method selected is
// actually for an embedded interface field.
closureRequired = true
}
if n.Op() == ir.OCALL && n.(*ir.CallExpr).X.Op() == ir.OFUNCINST {
// We have found a function call using a generic function
// instantiation.
call := n.(*ir.CallExpr)
inst := call.X.(*ir.InstExpr)
nameNode, isMeth := g.getInstNameNode(inst)
targs := typecheck.TypesOf(inst.Targs)
st := g.getInstantiation(nameNode, targs, isMeth).fun
dictValue, usingSubdict := g.getDictOrSubdict(declInfo, n, nameNode, targs, isMeth)
if infoPrintMode {
dictkind := "Main dictionary"
if usingSubdict {
dictkind = "Sub-dictionary"
}
if inst.X.Op() == ir.OMETHVALUE {
fmt.Printf("%s in %v at generic method call: %v - %v\n", dictkind, decl, inst.X, call)
} else {
fmt.Printf("%s in %v at generic function call: %v - %v\n", dictkind, decl, inst.X, call)
}
}
// Transform the Call now, which changes OCALL to
// OCALLFUNC and does typecheckaste/assignconvfn. Do
// it before installing the instantiation, so we are
// checking against non-shape param types in
// typecheckaste.
transformCall(call)
// Replace the OFUNCINST with a direct reference to the
// new stenciled function
call.X = st.Nname
if inst.X.Op() == ir.OMETHVALUE {
// When we create an instantiation of a method
// call, we make it a function. So, move the
// receiver to be the first arg of the function
// call.
call.Args.Prepend(inst.X.(*ir.SelectorExpr).X)
}
// Add dictionary to argument list.
call.Args.Prepend(dictValue)
modified = true
}
if n.Op() == ir.OCALLMETH && n.(*ir.CallExpr).X.Op() == ir.ODOTMETH && len(deref(n.(*ir.CallExpr).X.Type().Recv().Type).RParams()) > 0 {
// Method call on a generic type, which was instantiated by stenciling.
// Method calls on explicitly instantiated types will have an OFUNCINST
// and are handled above.
call := n.(*ir.CallExpr)
meth := call.X.(*ir.SelectorExpr)
targs := deref(meth.Type().Recv().Type).RParams()
t := meth.X.Type()
baseType := deref(t).OrigType()
var gf *ir.Name
for _, m := range baseType.Methods().Slice() {
if meth.Sel == m.Sym {
gf = m.Nname.(*ir.Name)
break
}
}
// Transform the Call now, which changes OCALL
// to OCALLFUNC and does typecheckaste/assignconvfn.
transformCall(call)
st := g.getInstantiation(gf, targs, true).fun
dictValue, usingSubdict := g.getDictOrSubdict(declInfo, n, gf, targs, true)
if hasShapeTypes(targs) {
// We have to be using a subdictionary, since this is
// a generic method call.
assert(usingSubdict)
} else {
// We should use main dictionary, because the receiver is
// an instantiation already, see issue #53406.
assert(!usingSubdict)
}
// Transform to a function call, by appending the
// dictionary and the receiver to the args.
call.SetOp(ir.OCALLFUNC)
call.X = st.Nname
call.Args.Prepend(dictValue, meth.X)
modified = true
}
})
// If we found a reference to a generic instantiation that wasn't an
// immediate call, then traverse the nodes of decl again (with
// EditChildren rather than Visit), where we actually change the
// reference to the instantiation to a closure that captures the
// dictionary, then does a direct call.
// EditChildren is more expensive than Visit, so we only do this
// in the infrequent case of an OFUNCINST without a corresponding
// call.
if closureRequired {
modified = true
var edit func(ir.Node) ir.Node
var outer *ir.Func
if f, ok := decl.(*ir.Func); ok {
outer = f
}
edit = func(x ir.Node) ir.Node {
if x.Op() == ir.OFUNCINST {
child := x.(*ir.InstExpr).X
if child.Op() == ir.OMETHEXPR || child.Op() == ir.OMETHVALUE {
// Call EditChildren on child (x.X),
// not x, so that we don't do
// buildClosure() on the
// METHEXPR/METHVALUE nodes as well.
ir.EditChildren(child, edit)
return g.buildClosure(outer, x)
}
}
ir.EditChildren(x, edit)
switch {
case x.Op() == ir.OFUNCINST:
return g.buildClosure(outer, x)
case (x.Op() == ir.OMETHEXPR || x.Op() == ir.OMETHVALUE) &&
len(deref(x.(*ir.SelectorExpr).X.Type()).RParams()) > 0 &&
!types.IsInterfaceMethod(x.(*ir.SelectorExpr).Selection.Type):
return g.buildClosure(outer, x)
}
return x
}
edit(decl)
}
if base.Flag.W > 1 && modified {
ir.Dump(fmt.Sprintf("\nmodified %v", decl), decl)
}
ir.CurFunc = nil
// We may have seen new fully-instantiated generic types while
// instantiating any needed functions/methods in the above
// function. If so, instantiate all the methods of those types
// (which will then lead to more function/methods to scan in the loop).
g.instantiateMethods()
}
// buildClosure makes a closure to implement x, a OFUNCINST or OMETHEXPR/OMETHVALUE
// of generic type. outer is the containing function (or nil if closure is
// in a global assignment instead of a function).
func (g *genInst) buildClosure(outer *ir.Func, x ir.Node) ir.Node {
pos := x.Pos()
var target *ir.Func // target instantiated function/method
var dictValue ir.Node // dictionary to use
var rcvrValue ir.Node // receiver, if a method value
typ := x.Type() // type of the closure
var outerInfo *instInfo
if outer != nil {
outerInfo = g.instInfoMap[outer.Sym()]
}
usingSubdict := false
valueMethod := false
if x.Op() == ir.OFUNCINST {
inst := x.(*ir.InstExpr)
// Type arguments we're instantiating with.
targs := typecheck.TypesOf(inst.Targs)
// Find the generic function/method.
var gf *ir.Name
if inst.X.Op() == ir.ONAME {
// Instantiating a generic function call.
gf = inst.X.(*ir.Name)
} else if inst.X.Op() == ir.OMETHVALUE {
// Instantiating a method value x.M.
se := inst.X.(*ir.SelectorExpr)
rcvrValue = se.X
gf = se.Selection.Nname.(*ir.Name)
} else {
panic("unhandled")
}
// target is the instantiated function we're trying to call.
// For functions, the target expects a dictionary as its first argument.
// For method values, the target expects a dictionary and the receiver
// as its first two arguments.
// dictValue is the value to use for the dictionary argument.
target = g.getInstantiation(gf, targs, rcvrValue != nil).fun
dictValue, usingSubdict = g.getDictOrSubdict(outerInfo, x, gf, targs, rcvrValue != nil)
if infoPrintMode {
dictkind := "Main dictionary"
if usingSubdict {
dictkind = "Sub-dictionary"
}
if rcvrValue == nil {
fmt.Printf("%s in %v for generic function value %v\n", dictkind, outer, inst.X)
} else {
fmt.Printf("%s in %v for generic method value %v\n", dictkind, outer, inst.X)
}
}
} else { // ir.OMETHEXPR or ir.METHVALUE
// Method expression T.M where T is a generic type.
se := x.(*ir.SelectorExpr)
targs := deref(se.X.Type()).RParams()
if len(targs) == 0 {
panic("bad")
}
if x.Op() == ir.OMETHVALUE {
rcvrValue = se.X
}
// se.X.Type() is the top-level type of the method expression. To
// correctly handle method expressions involving embedded fields,
// look up the generic method below using the type of the receiver
// of se.Selection, since that will be the type that actually has
// the method.
recv := deref(se.Selection.Type.Recv().Type)
if len(recv.RParams()) == 0 {
// The embedded type that actually has the method is not
// actually generic, so no need to build a closure.
return x
}
baseType := recv.OrigType()
var gf *ir.Name
for _, m := range baseType.Methods().Slice() {
if se.Sel == m.Sym {
gf = m.Nname.(*ir.Name)
break
}
}
if !gf.Type().Recv().Type.IsPtr() {
// Remember if value method, so we can detect (*T).M case.
valueMethod = true
}
target = g.getInstantiation(gf, targs, true).fun
dictValue, usingSubdict = g.getDictOrSubdict(outerInfo, x, gf, targs, true)
if infoPrintMode {
dictkind := "Main dictionary"
if usingSubdict {
dictkind = "Sub-dictionary"
}
fmt.Printf("%s in %v for method expression %v\n", dictkind, outer, x)
}
}
// Build a closure to implement a function instantiation.
//
// func f[T any] (int, int) (int, int) { ...whatever... }
//
// Then any reference to f[int] not directly called gets rewritten to
//
// .dictN := ... dictionary to use ...
// func(a0, a1 int) (r0, r1 int) {
// return .inst.f[int](.dictN, a0, a1)
// }
//
// Similarly for method expressions,
//
// type g[T any] ....
// func (rcvr g[T]) f(a0, a1 int) (r0, r1 int) { ... }
//
// Any reference to g[int].f not directly called gets rewritten to
//
// .dictN := ... dictionary to use ...
// func(rcvr g[int], a0, a1 int) (r0, r1 int) {
// return .inst.g[int].f(.dictN, rcvr, a0, a1)
// }
//
// Also method values
//
// var x g[int]
//
// Any reference to x.f not directly called gets rewritten to
//
// .dictN := ... dictionary to use ...
// x2 := x
// func(a0, a1 int) (r0, r1 int) {
// return .inst.g[int].f(.dictN, x2, a0, a1)
// }
// Make a new internal function.
fn, formalParams, formalResults := startClosure(pos, outer, typ)
fn.SetWrapper(true) // See issue 52237
// This is the dictionary we want to use.
// It may be a constant, it may be the outer functions's dictionary, or it may be
// a subdictionary acquired from the outer function's dictionary.
// For the latter, dictVar is a variable in the outer function's scope, set to the subdictionary
// read from the outer function's dictionary.
var dictVar *ir.Name
var dictAssign *ir.AssignStmt
if outer != nil {
dictVar = ir.NewNameAt(pos, closureSym(outer, typecheck.LocalDictName, g.dnum))
g.dnum++
dictVar.Class = ir.PAUTO
typed(types.Types[types.TUINTPTR], dictVar)
dictVar.Curfn = outer
dictAssign = ir.NewAssignStmt(pos, dictVar, dictValue)
dictAssign.SetTypecheck(1)
dictVar.Defn = dictAssign
outer.Dcl = append(outer.Dcl, dictVar)
}
// assign the receiver to a temporary.
var rcvrVar *ir.Name
var rcvrAssign ir.Node
if rcvrValue != nil {
rcvrVar = ir.NewNameAt(pos, closureSym(outer, ".rcvr", g.dnum))
g.dnum++
typed(rcvrValue.Type(), rcvrVar)
rcvrAssign = ir.NewAssignStmt(pos, rcvrVar, rcvrValue)
rcvrAssign.SetTypecheck(1)
rcvrVar.Defn = rcvrAssign
if outer == nil {
rcvrVar.Class = ir.PEXTERN
typecheck.Target.Decls = append(typecheck.Target.Decls, rcvrAssign)
typecheck.Target.Externs = append(typecheck.Target.Externs, rcvrVar)
} else {
rcvrVar.Class = ir.PAUTO
rcvrVar.Curfn = outer
outer.Dcl = append(outer.Dcl, rcvrVar)
}
}
// Build body of closure. This involves just calling the wrapped function directly
// with the additional dictionary argument.
// First, figure out the dictionary argument.
var dict2Var ir.Node
if usingSubdict {
// Capture sub-dictionary calculated in the outer function
dict2Var = ir.CaptureName(pos, fn, dictVar)
typed(types.Types[types.TUINTPTR], dict2Var)
} else {
// Static dictionary, so can be used directly in the closure
dict2Var = dictValue
}
// Also capture the receiver variable.
var rcvr2Var *ir.Name
if rcvrValue != nil {
rcvr2Var = ir.CaptureName(pos, fn, rcvrVar)
}
// Build arguments to call inside the closure.
var args []ir.Node
// First the dictionary argument.
args = append(args, dict2Var)
// Then the receiver.
if rcvrValue != nil {
args = append(args, rcvr2Var)
}
// Then all the other arguments (including receiver for method expressions).
for i := 0; i < typ.NumParams(); i++ {
if x.Op() == ir.OMETHEXPR && i == 0 {
// If we are doing a method expression, we need to
// explicitly traverse any embedded fields in the receiver
// argument in order to call the method instantiation.
arg0 := formalParams[0].Nname.(ir.Node)
arg0 = typecheck.AddImplicitDots(ir.NewSelectorExpr(x.Pos(), ir.OXDOT, arg0, x.(*ir.SelectorExpr).Sel)).X
if valueMethod && arg0.Type().IsPtr() {
// For handling the (*T).M case: if we have a pointer
// receiver after following all the embedded fields,
// but it's a value method, add a star operator.
arg0 = ir.NewStarExpr(arg0.Pos(), arg0)
}
args = append(args, arg0)
} else {
args = append(args, formalParams[i].Nname.(*ir.Name))
}
}
// Build call itself.
var innerCall ir.Node = ir.NewCallExpr(pos, ir.OCALL, target.Nname, args)
innerCall.(*ir.CallExpr).IsDDD = typ.IsVariadic()
if len(formalResults) > 0 {
innerCall = ir.NewReturnStmt(pos, []ir.Node{innerCall})
}
// Finish building body of closure.
ir.CurFunc = fn
// TODO: set types directly here instead of using typecheck.Stmt
typecheck.Stmt(innerCall)
ir.CurFunc = nil
fn.Body = []ir.Node{innerCall}
// We're all done with the captured dictionary (and receiver, for method values).
ir.FinishCaptureNames(pos, outer, fn)
// Make a closure referencing our new internal function.
c := ir.UseClosure(fn.OClosure, typecheck.Target)
var init []ir.Node
if outer != nil {
init = append(init, dictAssign)
}
if rcvrValue != nil {
init = append(init, rcvrAssign)
}
return ir.InitExpr(init, c)
}
// instantiateMethods instantiates all the methods (and associated dictionaries) of
// all fully-instantiated generic types that have been added to typecheck.instTypeList.
// It continues until no more types are added to typecheck.instTypeList.
func (g *genInst) instantiateMethods() {
for {
instTypeList := typecheck.GetInstTypeList()
if len(instTypeList) == 0 {
break
}
typecheck.ClearInstTypeList()
for _, typ := range instTypeList {
assert(!typ.HasShape())
// Mark runtime type as needed, since this ensures that the
// compiler puts out the needed DWARF symbols, when this
// instantiated type has a different package from the local
// package.
typecheck.NeedRuntimeType(typ)
// Lookup the method on the base generic type, since methods may
// not be set on imported instantiated types.
baseType := typ.OrigType()
for j, _ := range typ.Methods().Slice() {
if baseType.Methods().Slice()[j].Nointerface() {
typ.Methods().Slice()[j].SetNointerface(true)
}
baseNname := baseType.Methods().Slice()[j].Nname.(*ir.Name)
// Eagerly generate the instantiations and dictionaries that implement these methods.
// We don't use the instantiations here, just generate them (and any
// further instantiations those generate, etc.).
// Note that we don't set the Func for any methods on instantiated
// types. Their signatures don't match so that would be confusing.
// Direct method calls go directly to the instantiations, implemented above.
// Indirect method calls use wrappers generated in reflectcall. Those wrappers
// will use these instantiations if they are needed (for interface tables or reflection).
_ = g.getInstantiation(baseNname, typ.RParams(), true)
_ = g.getDictionarySym(baseNname, typ.RParams(), true)
}
}
}
}
// getInstNameNode returns the name node for the method or function being instantiated, and a bool which is true if a method is being instantiated.
func (g *genInst) getInstNameNode(inst *ir.InstExpr) (*ir.Name, bool) {
if meth, ok := inst.X.(*ir.SelectorExpr); ok {
return meth.Selection.Nname.(*ir.Name), true
} else {
return inst.X.(*ir.Name), false
}
}
// getDictOrSubdict returns, for a method/function call or reference (node n) in an
// instantiation (described by instInfo), a node which is accessing a sub-dictionary
// or main/static dictionary, as needed, and also returns a boolean indicating if a
// sub-dictionary was accessed. nameNode is the particular function or method being
// called/referenced, and targs are the type arguments.
func (g *genInst) getDictOrSubdict(declInfo *instInfo, n ir.Node, nameNode *ir.Name, targs []*types.Type, isMeth bool) (ir.Node, bool) {
var dict ir.Node
usingSubdict := false
if declInfo != nil {
entry := -1
for i, de := range declInfo.dictInfo.subDictCalls {
if n == de.callNode {
entry = declInfo.dictInfo.startSubDict + i
break
}
}
// If the entry is not found, it may be that this node did not have
// any type args that depend on type params, so we need a main
// dictionary, not a sub-dictionary.
if entry >= 0 {
dict = getDictionaryEntry(n.Pos(), declInfo.dictParam, entry, declInfo.dictInfo.dictLen)
usingSubdict = true
}
}
if !usingSubdict {
dict = g.getDictionaryValue(n.Pos(), nameNode, targs, isMeth)
}
return dict, usingSubdict
}
// checkFetchBody checks if a generic body can be fetched, but hasn't been loaded
// yet. If so, it imports the body.
func checkFetchBody(nameNode *ir.Name) {
if nameNode.Func.Body == nil && nameNode.Func.Inl != nil {
// If there is no body yet but Func.Inl exists, then we can
// import the whole generic body.
assert(nameNode.Func.Inl.Cost == 1 && nameNode.Sym().Pkg != types.LocalPkg)
typecheck.ImportBody(nameNode.Func)
assert(nameNode.Func.Inl.Body != nil)
nameNode.Func.Body = nameNode.Func.Inl.Body
nameNode.Func.Dcl = nameNode.Func.Inl.Dcl
}
}
// getInstantiation gets the instantiantion and dictionary of the function or method nameNode
// with the type arguments shapes. If the instantiated function is not already
// cached, then it calls genericSubst to create the new instantiation.
func (g *genInst) getInstantiation(nameNode *ir.Name, shapes []*types.Type, isMeth bool) *instInfo {
if nameNode.Func == nil {
// If nameNode.Func is nil, this must be a reference to a method of
// an imported instantiated type. We will have already called
// g.instantiateMethods() on the fully-instantiated type, so
// g.instInfoMap[sym] will be non-nil below.
rcvr := nameNode.Type().Recv()
if rcvr == nil || !deref(rcvr.Type).IsFullyInstantiated() {
base.FatalfAt(nameNode.Pos(), "Unexpected function instantiation %v with no body", nameNode)
}
} else {
checkFetchBody(nameNode)
}
var tparams []*types.Type
if isMeth {
// Get the type params from the method receiver (after skipping
// over any pointer)
recvType := nameNode.Type().Recv().Type
recvType = deref(recvType)
if recvType.IsFullyInstantiated() {
// Get the type of the base generic type, so we get
// its original typeparams.
recvType = recvType.OrigType()
}
tparams = recvType.RParams()
} else {
fields := nameNode.Type().TParams().Fields().Slice()
tparams = make([]*types.Type, len(fields))
for i, f := range fields {
tparams[i] = f.Type
}
}
// Convert any non-shape type arguments to their shape, so we can reduce the
// number of instantiations we have to generate. You can actually have a mix
// of shape and non-shape arguments, because of inferred or explicitly
// specified concrete type args.
s1 := make([]*types.Type, len(shapes))
for i, t := range shapes {
var tparam *types.Type
// Shapes are grouped differently for structural types, so we
// pass the type param to Shapify(), so we can distinguish.
tparam = tparams[i]
if !t.IsShape() {
s1[i] = typecheck.Shapify(t, i, tparam)
} else {
// Already a shape, but make sure it has the correct index.
s1[i] = typecheck.Shapify(shapes[i].Underlying(), i, tparam)
}
}
shapes = s1
sym := typecheck.MakeFuncInstSym(nameNode.Sym(), shapes, false, isMeth)
info := g.instInfoMap[sym]
if info == nil {
// If instantiation doesn't exist yet, create it and add
// to the list of decls.
info = &instInfo{
dictInfo: &dictInfo{},
}
info.dictInfo.shapeToBound = make(map[*types.Type]*types.Type)
if sym.Def != nil {
// This instantiation must have been imported from another
// package (because it was needed for inlining), so we should
// not re-generate it and have conflicting definitions for the
// symbol (issue #50121). It will have already gone through the
// dictionary transformations of dictPass, so we don't actually
// need the info.dictParam and info.shapeToBound info filled in
// below. We just set the imported instantiation as info.fun.
assert(sym.Pkg != types.LocalPkg)
info.fun = sym.Def.(*ir.Name).Func
assert(info.fun != nil)
g.instInfoMap[sym] = info
return info
}
// genericSubst fills in info.dictParam and info.shapeToBound.
st := g.genericSubst(sym, nameNode, tparams, shapes, isMeth, info)
info.fun = st
g.instInfoMap[sym] = info
// getInstInfo fills in info.dictInfo.
g.getInstInfo(st, shapes, info)
if base.Flag.W > 1 {
ir.Dump(fmt.Sprintf("\nstenciled %v", st), st)
}
// This ensures that the linker drops duplicates of this instantiation.
// All just works!
st.SetDupok(true)
typecheck.Target.Decls = append(typecheck.Target.Decls, st)
g.newInsts = append(g.newInsts, st)
}
return info
}
// Struct containing info needed for doing the substitution as we create the
// instantiation of a generic function with specified type arguments.
type subster struct {
g *genInst
isMethod bool // If a method is being instantiated
newf *ir.Func // Func node for the new stenciled function
ts typecheck.Tsubster
info *instInfo // Place to put extra info in the instantiation
skipClosure bool // Skip substituting closures
// Map from non-nil, non-ONAME node n to slice of all m, where m.Defn = n
defnMap map[ir.Node][]**ir.Name
}
// genericSubst returns a new function with name newsym. The function is an
// instantiation of a generic function or method specified by namedNode with type
// args shapes. For a method with a generic receiver, it returns an instantiated
// function type where the receiver becomes the first parameter. For either a generic
// method or function, a dictionary parameter is the added as the very first
// parameter. genericSubst fills in info.dictParam and info.shapeToBound.
func (g *genInst) genericSubst(newsym *types.Sym, nameNode *ir.Name, tparams []*types.Type, shapes []*types.Type, isMethod bool, info *instInfo) *ir.Func {
gf := nameNode.Func
// Pos of the instantiated function is same as the generic function
newf := ir.NewFunc(gf.Pos())
newf.Pragma = gf.Pragma // copy over pragmas from generic function to stenciled implementation.
newf.Endlineno = gf.Endlineno
newf.Nname = ir.NewNameAt(gf.Pos(), newsym)
newf.Nname.Func = newf
newf.Nname.Defn = newf
newsym.Def = newf.Nname
savef := ir.CurFunc
// transformCall/transformReturn (called during stenciling of the body)
// depend on ir.CurFunc being set.
ir.CurFunc = newf
assert(len(tparams) == len(shapes))
subst := &subster{
g: g,
isMethod: isMethod,
newf: newf,
info: info,
ts: typecheck.Tsubster{
Tparams: tparams,
Targs: shapes,
Vars: make(map[*ir.Name]*ir.Name),
},
defnMap: make(map[ir.Node][]**ir.Name),
}
newf.Dcl = make([]*ir.Name, 0, len(gf.Dcl)+1)
// Create the needed dictionary param
dictionarySym := newsym.Pkg.Lookup(typecheck.LocalDictName)
dictionaryType := types.Types[types.TUINTPTR]
dictionaryName := ir.NewNameAt(gf.Pos(), dictionarySym)
typed(dictionaryType, dictionaryName)
dictionaryName.Class = ir.PPARAM
dictionaryName.Curfn = newf
newf.Dcl = append(newf.Dcl, dictionaryName)
for _, n := range gf.Dcl {
if n.Sym().Name == typecheck.LocalDictName {
panic("already has dictionary")
}
newf.Dcl = append(newf.Dcl, subst.localvar(n))
}
dictionaryArg := types.NewField(gf.Pos(), dictionarySym, dictionaryType)
dictionaryArg.Nname = dictionaryName
info.dictParam = dictionaryName
// We add the dictionary as the first parameter in the function signature.
// We also transform a method type to the corresponding function type
// (make the receiver be the next parameter after the dictionary).
oldt := nameNode.Type()
var args []*types.Field
args = append(args, dictionaryArg)
args = append(args, oldt.Recvs().FieldSlice()...)
args = append(args, oldt.Params().FieldSlice()...)
// Replace the types in the function signature via subst.fields.
// Ugly: also, we have to insert the Name nodes of the parameters/results into
// the function type. The current function type has no Nname fields set,
// because it came via conversion from the types2 type.
newt := types.NewSignature(oldt.Pkg(), nil, nil,
subst.fields(ir.PPARAM, args, newf.Dcl),
subst.fields(ir.PPARAMOUT, oldt.Results().FieldSlice(), newf.Dcl))
typed(newt, newf.Nname)
ir.MarkFunc(newf.Nname)
newf.SetTypecheck(1)
// Make sure name/type of newf is set before substituting the body.
newf.Body = subst.list(gf.Body)
if len(newf.Body) == 0 {
// Ensure the body is nonempty, for issue 49524.
// TODO: have some other way to detect the difference between
// a function declared with no body, vs. one with an empty body?
newf.Body = append(newf.Body, ir.NewBlockStmt(gf.Pos(), nil))
}
if len(subst.defnMap) > 0 {
base.Fatalf("defnMap is not empty")
}
for i, tp := range tparams {
info.dictInfo.shapeToBound[shapes[i]] = subst.ts.Typ(tp.Bound())
}
ir.CurFunc = savef
return subst.newf
}
// localvar creates a new name node for the specified local variable and enters it
// in subst.vars. It substitutes type arguments for type parameters in the type of
// name as needed.
func (subst *subster) localvar(name *ir.Name) *ir.Name {
m := ir.NewNameAt(name.Pos(), name.Sym())
if name.IsClosureVar() {
m.SetIsClosureVar(true)
}
m.SetType(subst.ts.Typ(name.Type()))
m.BuiltinOp = name.BuiltinOp
m.Curfn = subst.newf
m.Class = name.Class
assert(name.Class != ir.PEXTERN && name.Class != ir.PFUNC)
m.Func = name.Func
subst.ts.Vars[name] = m
m.SetTypecheck(1)
m.DictIndex = name.DictIndex
if name.Defn != nil {
if name.Defn.Op() == ir.ONAME {
// This is a closure variable, so its Defn is the outer
// captured variable, which has already been substituted.
m.Defn = subst.node(name.Defn)
} else {
// The other values of Defn are nodes in the body of the
// function, so just remember the mapping so we can set Defn
// properly in node() when we create the new body node. We
// always call localvar() on all the local variables before
// we substitute the body.
slice := subst.defnMap[name.Defn]
subst.defnMap[name.Defn] = append(slice, &m)
}
}
if name.Outer != nil {
m.Outer = subst.node(name.Outer).(*ir.Name)
}
return m
}
// getDictionaryEntry gets the i'th entry in the dictionary dict.
func getDictionaryEntry(pos src.XPos, dict *ir.Name, i int, size int) ir.Node {
// Convert dictionary to *[N]uintptr
// All entries in the dictionary are pointers. They all point to static data, though, so we
// treat them as uintptrs so the GC doesn't need to keep track of them.
d := ir.NewConvExpr(pos, ir.OCONVNOP, types.Types[types.TUNSAFEPTR], dict)
d.SetTypecheck(1)
d = ir.NewConvExpr(pos, ir.OCONVNOP, types.NewArray(types.Types[types.TUINTPTR], int64(size)).PtrTo(), d)
d.SetTypecheck(1)
types.CheckSize(d.Type().Elem())
// Load entry i out of the dictionary.
deref := ir.NewStarExpr(pos, d)
typed(d.Type().Elem(), deref)
idx := ir.NewConstExpr(constant.MakeUint64(uint64(i)), dict) // TODO: what to set orig to?
typed(types.Types[types.TUINTPTR], idx)
r := ir.NewIndexExpr(pos, deref, idx)
typed(types.Types[types.TUINTPTR], r)
return r
}
// getDictionaryEntryAddr gets the address of the i'th entry in dictionary dict.
func getDictionaryEntryAddr(pos src.XPos, dict *ir.Name, i int, size int) ir.Node {
a := ir.NewAddrExpr(pos, getDictionaryEntry(pos, dict, i, size))
typed(types.Types[types.TUINTPTR].PtrTo(), a)
return a
}
// getDictionaryType returns a *runtime._type from the dictionary entry i (which
// refers to a type param or a derived type that uses type params). It uses the
// specified dictionary dictParam, rather than the one in info.dictParam.
func getDictionaryType(info *instInfo, dictParam *ir.Name, pos src.XPos, i int) ir.Node {
if i < 0 || i >= info.dictInfo.startSubDict {
base.Fatalf(fmt.Sprintf("bad dict index %d", i))
}
r := getDictionaryEntry(pos, dictParam, i, info.dictInfo.startSubDict)
// change type of retrieved dictionary entry to *byte, which is the
// standard typing of a *runtime._type in the compiler
typed(types.Types[types.TUINT8].PtrTo(), r)
return r
}
// node is like DeepCopy(), but substitutes ONAME nodes based on subst.ts.vars, and
// also descends into closures. It substitutes type arguments for type parameters in
// all the new nodes and does the transformations that were delayed on the generic
// function.
func (subst *subster) node(n ir.Node) ir.Node {
// Use closure to capture all state needed by the ir.EditChildren argument.
var edit func(ir.Node) ir.Node
edit = func(x ir.Node) ir.Node {
// Analogous to ir.SetPos() at beginning of typecheck.typecheck() -
// allows using base.Pos during the transform functions, just like
// the tc*() functions.
ir.SetPos(x)
switch x.Op() {
case ir.OTYPE:
return ir.TypeNode(subst.ts.Typ(x.Type()))
case ir.ONAME:
if v := subst.ts.Vars[x.(*ir.Name)]; v != nil {
return v
}
if ir.IsBlank(x) {
// Special case, because a blank local variable is
// not in the fn.Dcl list.
m := ir.NewNameAt(x.Pos(), ir.BlankNode.Sym())
return typed(subst.ts.Typ(x.Type()), m)
}
return x
case ir.ONONAME:
// This handles the identifier in a type switch guard
fallthrough
case ir.OLITERAL, ir.ONIL:
if x.Sym() != nil {
return x
}
}
m := ir.Copy(x)
slice, ok := subst.defnMap[x]
if ok {
// We just copied a non-ONAME node which was the Defn value
// of a local variable. Set the Defn value of the copied
// local variable to this new Defn node.
for _, ptr := range slice {
(*ptr).Defn = m
}
delete(subst.defnMap, x)
}
if _, isExpr := m.(ir.Expr); isExpr {
t := x.Type()
if t == nil {
// Check for known cases where t can be nil (call
// that has no return values, and key expressions)
// and otherwise cause a fatal error.
_, isCallExpr := m.(*ir.CallExpr)
_, isStructKeyExpr := m.(*ir.StructKeyExpr)
_, isKeyExpr := m.(*ir.KeyExpr)
if !isCallExpr && !isStructKeyExpr && !isKeyExpr && x.Op() != ir.OPANIC &&
x.Op() != ir.OCLOSE {
base.FatalfAt(m.Pos(), "Nil type for %v", x)
}
} else if x.Op() != ir.OCLOSURE {
m.SetType(subst.ts.Typ(x.Type()))
}
}
old := subst.skipClosure
// For unsafe.{Alignof,Offsetof,Sizeof}, subster will transform them to OLITERAL nodes,
// and discard their arguments. However, their children nodes were already process before,
// thus if they contain any closure, the closure was still be added to package declarations
// queue for processing later. Thus, genInst will fail to generate instantiation for the
// closure because of lacking dictionary information, see issue #53390.
if call, ok := m.(*ir.CallExpr); ok && call.X.Op() == ir.ONAME {
switch call.X.Name().BuiltinOp {
case ir.OALIGNOF, ir.OOFFSETOF, ir.OSIZEOF:
subst.skipClosure = true
}
}
ir.EditChildren(m, edit)