]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/reflectdata/reflect.go
[dev.typeparams] all: merge dev.regabi (7e0a81d) into dev.typeparams
[gostls13.git] / src / cmd / compile / internal / reflectdata / reflect.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package reflectdata
6
7 import (
8         "fmt"
9         "os"
10         "sort"
11         "strings"
12         "sync"
13
14         "cmd/compile/internal/base"
15         "cmd/compile/internal/bitvec"
16         "cmd/compile/internal/escape"
17         "cmd/compile/internal/inline"
18         "cmd/compile/internal/ir"
19         "cmd/compile/internal/objw"
20         "cmd/compile/internal/typebits"
21         "cmd/compile/internal/typecheck"
22         "cmd/compile/internal/types"
23         "cmd/internal/gcprog"
24         "cmd/internal/obj"
25         "cmd/internal/objabi"
26         "cmd/internal/src"
27 )
28
29 type itabEntry struct {
30         t, itype *types.Type
31         lsym     *obj.LSym // symbol of the itab itself
32
33         // symbols of each method in
34         // the itab, sorted by byte offset;
35         // filled in by CompileITabs
36         entries []*obj.LSym
37 }
38
39 type ptabEntry struct {
40         s *types.Sym
41         t *types.Type
42 }
43
44 func CountTabs() (numPTabs, numITabs int) {
45         return len(ptabs), len(itabs)
46 }
47
48 // runtime interface and reflection data structures
49 var (
50         signatmu    sync.Mutex // protects signatset and signatslice
51         signatset   = make(map[*types.Type]struct{})
52         signatslice []*types.Type
53
54         itabs []itabEntry
55         ptabs []*ir.Name
56 )
57
58 type typeSig struct {
59         name  *types.Sym
60         isym  *obj.LSym
61         tsym  *obj.LSym
62         type_ *types.Type
63         mtype *types.Type
64 }
65
66 // Builds a type representing a Bucket structure for
67 // the given map type. This type is not visible to users -
68 // we include only enough information to generate a correct GC
69 // program for it.
70 // Make sure this stays in sync with runtime/map.go.
71 const (
72         BUCKETSIZE  = 8
73         MAXKEYSIZE  = 128
74         MAXELEMSIZE = 128
75 )
76
77 func structfieldSize() int { return 3 * types.PtrSize }       // Sizeof(runtime.structfield{})
78 func imethodSize() int     { return 4 + 4 }                   // Sizeof(runtime.imethod{})
79 func commonSize() int      { return 4*types.PtrSize + 8 + 8 } // Sizeof(runtime._type{})
80
81 func uncommonSize(t *types.Type) int { // Sizeof(runtime.uncommontype{})
82         if t.Sym() == nil && len(methods(t)) == 0 {
83                 return 0
84         }
85         return 4 + 2 + 2 + 4 + 4
86 }
87
88 func makefield(name string, t *types.Type) *types.Field {
89         sym := (*types.Pkg)(nil).Lookup(name)
90         return types.NewField(src.NoXPos, sym, t)
91 }
92
93 // MapBucketType makes the map bucket type given the type of the map.
94 func MapBucketType(t *types.Type) *types.Type {
95         if t.MapType().Bucket != nil {
96                 return t.MapType().Bucket
97         }
98
99         keytype := t.Key()
100         elemtype := t.Elem()
101         types.CalcSize(keytype)
102         types.CalcSize(elemtype)
103         if keytype.Width > MAXKEYSIZE {
104                 keytype = types.NewPtr(keytype)
105         }
106         if elemtype.Width > MAXELEMSIZE {
107                 elemtype = types.NewPtr(elemtype)
108         }
109
110         field := make([]*types.Field, 0, 5)
111
112         // The first field is: uint8 topbits[BUCKETSIZE].
113         arr := types.NewArray(types.Types[types.TUINT8], BUCKETSIZE)
114         field = append(field, makefield("topbits", arr))
115
116         arr = types.NewArray(keytype, BUCKETSIZE)
117         arr.SetNoalg(true)
118         keys := makefield("keys", arr)
119         field = append(field, keys)
120
121         arr = types.NewArray(elemtype, BUCKETSIZE)
122         arr.SetNoalg(true)
123         elems := makefield("elems", arr)
124         field = append(field, elems)
125
126         // If keys and elems have no pointers, the map implementation
127         // can keep a list of overflow pointers on the side so that
128         // buckets can be marked as having no pointers.
129         // Arrange for the bucket to have no pointers by changing
130         // the type of the overflow field to uintptr in this case.
131         // See comment on hmap.overflow in runtime/map.go.
132         otyp := types.Types[types.TUNSAFEPTR]
133         if !elemtype.HasPointers() && !keytype.HasPointers() {
134                 otyp = types.Types[types.TUINTPTR]
135         }
136         overflow := makefield("overflow", otyp)
137         field = append(field, overflow)
138
139         // link up fields
140         bucket := types.NewStruct(types.NoPkg, field[:])
141         bucket.SetNoalg(true)
142         types.CalcSize(bucket)
143
144         // Check invariants that map code depends on.
145         if !types.IsComparable(t.Key()) {
146                 base.Fatalf("unsupported map key type for %v", t)
147         }
148         if BUCKETSIZE < 8 {
149                 base.Fatalf("bucket size too small for proper alignment")
150         }
151         if keytype.Align > BUCKETSIZE {
152                 base.Fatalf("key align too big for %v", t)
153         }
154         if elemtype.Align > BUCKETSIZE {
155                 base.Fatalf("elem align too big for %v", t)
156         }
157         if keytype.Width > MAXKEYSIZE {
158                 base.Fatalf("key size to large for %v", t)
159         }
160         if elemtype.Width > MAXELEMSIZE {
161                 base.Fatalf("elem size to large for %v", t)
162         }
163         if t.Key().Width > MAXKEYSIZE && !keytype.IsPtr() {
164                 base.Fatalf("key indirect incorrect for %v", t)
165         }
166         if t.Elem().Width > MAXELEMSIZE && !elemtype.IsPtr() {
167                 base.Fatalf("elem indirect incorrect for %v", t)
168         }
169         if keytype.Width%int64(keytype.Align) != 0 {
170                 base.Fatalf("key size not a multiple of key align for %v", t)
171         }
172         if elemtype.Width%int64(elemtype.Align) != 0 {
173                 base.Fatalf("elem size not a multiple of elem align for %v", t)
174         }
175         if bucket.Align%keytype.Align != 0 {
176                 base.Fatalf("bucket align not multiple of key align %v", t)
177         }
178         if bucket.Align%elemtype.Align != 0 {
179                 base.Fatalf("bucket align not multiple of elem align %v", t)
180         }
181         if keys.Offset%int64(keytype.Align) != 0 {
182                 base.Fatalf("bad alignment of keys in bmap for %v", t)
183         }
184         if elems.Offset%int64(elemtype.Align) != 0 {
185                 base.Fatalf("bad alignment of elems in bmap for %v", t)
186         }
187
188         // Double-check that overflow field is final memory in struct,
189         // with no padding at end.
190         if overflow.Offset != bucket.Width-int64(types.PtrSize) {
191                 base.Fatalf("bad offset of overflow in bmap for %v", t)
192         }
193
194         t.MapType().Bucket = bucket
195
196         bucket.StructType().Map = t
197         return bucket
198 }
199
200 // MapType builds a type representing a Hmap structure for the given map type.
201 // Make sure this stays in sync with runtime/map.go.
202 func MapType(t *types.Type) *types.Type {
203         if t.MapType().Hmap != nil {
204                 return t.MapType().Hmap
205         }
206
207         bmap := MapBucketType(t)
208
209         // build a struct:
210         // type hmap struct {
211         //    count      int
212         //    flags      uint8
213         //    B          uint8
214         //    noverflow  uint16
215         //    hash0      uint32
216         //    buckets    *bmap
217         //    oldbuckets *bmap
218         //    nevacuate  uintptr
219         //    extra      unsafe.Pointer // *mapextra
220         // }
221         // must match runtime/map.go:hmap.
222         fields := []*types.Field{
223                 makefield("count", types.Types[types.TINT]),
224                 makefield("flags", types.Types[types.TUINT8]),
225                 makefield("B", types.Types[types.TUINT8]),
226                 makefield("noverflow", types.Types[types.TUINT16]),
227                 makefield("hash0", types.Types[types.TUINT32]), // Used in walk.go for OMAKEMAP.
228                 makefield("buckets", types.NewPtr(bmap)),       // Used in walk.go for OMAKEMAP.
229                 makefield("oldbuckets", types.NewPtr(bmap)),
230                 makefield("nevacuate", types.Types[types.TUINTPTR]),
231                 makefield("extra", types.Types[types.TUNSAFEPTR]),
232         }
233
234         hmap := types.NewStruct(types.NoPkg, fields)
235         hmap.SetNoalg(true)
236         types.CalcSize(hmap)
237
238         // The size of hmap should be 48 bytes on 64 bit
239         // and 28 bytes on 32 bit platforms.
240         if size := int64(8 + 5*types.PtrSize); hmap.Width != size {
241                 base.Fatalf("hmap size not correct: got %d, want %d", hmap.Width, size)
242         }
243
244         t.MapType().Hmap = hmap
245         hmap.StructType().Map = t
246         return hmap
247 }
248
249 // MapIterType builds a type representing an Hiter structure for the given map type.
250 // Make sure this stays in sync with runtime/map.go.
251 func MapIterType(t *types.Type) *types.Type {
252         if t.MapType().Hiter != nil {
253                 return t.MapType().Hiter
254         }
255
256         hmap := MapType(t)
257         bmap := MapBucketType(t)
258
259         // build a struct:
260         // type hiter struct {
261         //    key         *Key
262         //    elem        *Elem
263         //    t           unsafe.Pointer // *MapType
264         //    h           *hmap
265         //    buckets     *bmap
266         //    bptr        *bmap
267         //    overflow    unsafe.Pointer // *[]*bmap
268         //    oldoverflow unsafe.Pointer // *[]*bmap
269         //    startBucket uintptr
270         //    offset      uint8
271         //    wrapped     bool
272         //    B           uint8
273         //    i           uint8
274         //    bucket      uintptr
275         //    checkBucket uintptr
276         // }
277         // must match runtime/map.go:hiter.
278         fields := []*types.Field{
279                 makefield("key", types.NewPtr(t.Key())),   // Used in range.go for TMAP.
280                 makefield("elem", types.NewPtr(t.Elem())), // Used in range.go for TMAP.
281                 makefield("t", types.Types[types.TUNSAFEPTR]),
282                 makefield("h", types.NewPtr(hmap)),
283                 makefield("buckets", types.NewPtr(bmap)),
284                 makefield("bptr", types.NewPtr(bmap)),
285                 makefield("overflow", types.Types[types.TUNSAFEPTR]),
286                 makefield("oldoverflow", types.Types[types.TUNSAFEPTR]),
287                 makefield("startBucket", types.Types[types.TUINTPTR]),
288                 makefield("offset", types.Types[types.TUINT8]),
289                 makefield("wrapped", types.Types[types.TBOOL]),
290                 makefield("B", types.Types[types.TUINT8]),
291                 makefield("i", types.Types[types.TUINT8]),
292                 makefield("bucket", types.Types[types.TUINTPTR]),
293                 makefield("checkBucket", types.Types[types.TUINTPTR]),
294         }
295
296         // build iterator struct holding the above fields
297         hiter := types.NewStruct(types.NoPkg, fields)
298         hiter.SetNoalg(true)
299         types.CalcSize(hiter)
300         if hiter.Width != int64(12*types.PtrSize) {
301                 base.Fatalf("hash_iter size not correct %d %d", hiter.Width, 12*types.PtrSize)
302         }
303         t.MapType().Hiter = hiter
304         hiter.StructType().Map = t
305         return hiter
306 }
307
308 // methods returns the methods of the non-interface type t, sorted by name.
309 // Generates stub functions as needed.
310 func methods(t *types.Type) []*typeSig {
311         // method type
312         mt := types.ReceiverBaseType(t)
313
314         if mt == nil {
315                 return nil
316         }
317         typecheck.CalcMethods(mt)
318
319         // type stored in interface word
320         it := t
321
322         if !types.IsDirectIface(it) {
323                 it = types.NewPtr(t)
324         }
325
326         // make list of methods for t,
327         // generating code if necessary.
328         var ms []*typeSig
329         for _, f := range mt.AllMethods().Slice() {
330                 if f.Sym == nil {
331                         base.Fatalf("method with no sym on %v", mt)
332                 }
333                 if !f.IsMethod() {
334                         base.Fatalf("non-method on %v method %v %v", mt, f.Sym, f)
335                 }
336                 if f.Type.Recv() == nil {
337                         base.Fatalf("receiver with no type on %v method %v %v", mt, f.Sym, f)
338                 }
339                 if f.Nointerface() {
340                         continue
341                 }
342
343                 // get receiver type for this particular method.
344                 // if pointer receiver but non-pointer t and
345                 // this is not an embedded pointer inside a struct,
346                 // method does not apply.
347                 if !types.IsMethodApplicable(t, f) {
348                         continue
349                 }
350
351                 sig := &typeSig{
352                         name:  f.Sym,
353                         isym:  methodWrapper(it, f),
354                         tsym:  methodWrapper(t, f),
355                         type_: typecheck.NewMethodType(f.Type, t),
356                         mtype: typecheck.NewMethodType(f.Type, nil),
357                 }
358                 ms = append(ms, sig)
359         }
360
361         return ms
362 }
363
364 // imethods returns the methods of the interface type t, sorted by name.
365 func imethods(t *types.Type) []*typeSig {
366         var methods []*typeSig
367         for _, f := range t.Fields().Slice() {
368                 if f.Type.Kind() != types.TFUNC || f.Sym == nil {
369                         continue
370                 }
371                 if f.Sym.IsBlank() {
372                         base.Fatalf("unexpected blank symbol in interface method set")
373                 }
374                 if n := len(methods); n > 0 {
375                         last := methods[n-1]
376                         if !last.name.Less(f.Sym) {
377                                 base.Fatalf("sigcmp vs sortinter %v %v", last.name, f.Sym)
378                         }
379                 }
380
381                 sig := &typeSig{
382                         name:  f.Sym,
383                         mtype: f.Type,
384                         type_: typecheck.NewMethodType(f.Type, nil),
385                 }
386                 methods = append(methods, sig)
387
388                 // NOTE(rsc): Perhaps an oversight that
389                 // IfaceType.Method is not in the reflect data.
390                 // Generate the method body, so that compiled
391                 // code can refer to it.
392                 methodWrapper(t, f)
393         }
394
395         return methods
396 }
397
398 func dimportpath(p *types.Pkg) {
399         if p.Pathsym != nil {
400                 return
401         }
402
403         // If we are compiling the runtime package, there are two runtime packages around
404         // -- localpkg and Pkgs.Runtime. We don't want to produce import path symbols for
405         // both of them, so just produce one for localpkg.
406         if base.Ctxt.Pkgpath == "runtime" && p == ir.Pkgs.Runtime {
407                 return
408         }
409
410         str := p.Path
411         if p == types.LocalPkg {
412                 // Note: myimportpath != "", or else dgopkgpath won't call dimportpath.
413                 str = base.Ctxt.Pkgpath
414         }
415
416         s := base.Ctxt.Lookup("type..importpath." + p.Prefix + ".")
417         ot := dnameData(s, 0, str, "", nil, false)
418         objw.Global(s, int32(ot), obj.DUPOK|obj.RODATA)
419         s.Set(obj.AttrContentAddressable, true)
420         p.Pathsym = s
421 }
422
423 func dgopkgpath(s *obj.LSym, ot int, pkg *types.Pkg) int {
424         if pkg == nil {
425                 return objw.Uintptr(s, ot, 0)
426         }
427
428         if pkg == types.LocalPkg && base.Ctxt.Pkgpath == "" {
429                 // If we don't know the full import path of the package being compiled
430                 // (i.e. -p was not passed on the compiler command line), emit a reference to
431                 // type..importpath.""., which the linker will rewrite using the correct import path.
432                 // Every package that imports this one directly defines the symbol.
433                 // See also https://groups.google.com/forum/#!topic/golang-dev/myb9s53HxGQ.
434                 ns := base.Ctxt.Lookup(`type..importpath."".`)
435                 return objw.SymPtr(s, ot, ns, 0)
436         }
437
438         dimportpath(pkg)
439         return objw.SymPtr(s, ot, pkg.Pathsym, 0)
440 }
441
442 // dgopkgpathOff writes an offset relocation in s at offset ot to the pkg path symbol.
443 func dgopkgpathOff(s *obj.LSym, ot int, pkg *types.Pkg) int {
444         if pkg == nil {
445                 return objw.Uint32(s, ot, 0)
446         }
447         if pkg == types.LocalPkg && base.Ctxt.Pkgpath == "" {
448                 // If we don't know the full import path of the package being compiled
449                 // (i.e. -p was not passed on the compiler command line), emit a reference to
450                 // type..importpath.""., which the linker will rewrite using the correct import path.
451                 // Every package that imports this one directly defines the symbol.
452                 // See also https://groups.google.com/forum/#!topic/golang-dev/myb9s53HxGQ.
453                 ns := base.Ctxt.Lookup(`type..importpath."".`)
454                 return objw.SymPtrOff(s, ot, ns)
455         }
456
457         dimportpath(pkg)
458         return objw.SymPtrOff(s, ot, pkg.Pathsym)
459 }
460
461 // dnameField dumps a reflect.name for a struct field.
462 func dnameField(lsym *obj.LSym, ot int, spkg *types.Pkg, ft *types.Field) int {
463         if !types.IsExported(ft.Sym.Name) && ft.Sym.Pkg != spkg {
464                 base.Fatalf("package mismatch for %v", ft.Sym)
465         }
466         nsym := dname(ft.Sym.Name, ft.Note, nil, types.IsExported(ft.Sym.Name))
467         return objw.SymPtr(lsym, ot, nsym, 0)
468 }
469
470 // dnameData writes the contents of a reflect.name into s at offset ot.
471 func dnameData(s *obj.LSym, ot int, name, tag string, pkg *types.Pkg, exported bool) int {
472         if len(name) > 1<<16-1 {
473                 base.Fatalf("name too long: %s", name)
474         }
475         if len(tag) > 1<<16-1 {
476                 base.Fatalf("tag too long: %s", tag)
477         }
478
479         // Encode name and tag. See reflect/type.go for details.
480         var bits byte
481         l := 1 + 2 + len(name)
482         if exported {
483                 bits |= 1 << 0
484         }
485         if len(tag) > 0 {
486                 l += 2 + len(tag)
487                 bits |= 1 << 1
488         }
489         if pkg != nil {
490                 bits |= 1 << 2
491         }
492         b := make([]byte, l)
493         b[0] = bits
494         b[1] = uint8(len(name) >> 8)
495         b[2] = uint8(len(name))
496         copy(b[3:], name)
497         if len(tag) > 0 {
498                 tb := b[3+len(name):]
499                 tb[0] = uint8(len(tag) >> 8)
500                 tb[1] = uint8(len(tag))
501                 copy(tb[2:], tag)
502         }
503
504         ot = int(s.WriteBytes(base.Ctxt, int64(ot), b))
505
506         if pkg != nil {
507                 ot = dgopkgpathOff(s, ot, pkg)
508         }
509
510         return ot
511 }
512
513 var dnameCount int
514
515 // dname creates a reflect.name for a struct field or method.
516 func dname(name, tag string, pkg *types.Pkg, exported bool) *obj.LSym {
517         // Write out data as "type.." to signal two things to the
518         // linker, first that when dynamically linking, the symbol
519         // should be moved to a relro section, and second that the
520         // contents should not be decoded as a type.
521         sname := "type..namedata."
522         if pkg == nil {
523                 // In the common case, share data with other packages.
524                 if name == "" {
525                         if exported {
526                                 sname += "-noname-exported." + tag
527                         } else {
528                                 sname += "-noname-unexported." + tag
529                         }
530                 } else {
531                         if exported {
532                                 sname += name + "." + tag
533                         } else {
534                                 sname += name + "-" + tag
535                         }
536                 }
537         } else {
538                 sname = fmt.Sprintf(`%s"".%d`, sname, dnameCount)
539                 dnameCount++
540         }
541         s := base.Ctxt.Lookup(sname)
542         if len(s.P) > 0 {
543                 return s
544         }
545         ot := dnameData(s, 0, name, tag, pkg, exported)
546         objw.Global(s, int32(ot), obj.DUPOK|obj.RODATA)
547         s.Set(obj.AttrContentAddressable, true)
548         return s
549 }
550
551 // dextratype dumps the fields of a runtime.uncommontype.
552 // dataAdd is the offset in bytes after the header where the
553 // backing array of the []method field is written (by dextratypeData).
554 func dextratype(lsym *obj.LSym, ot int, t *types.Type, dataAdd int) int {
555         m := methods(t)
556         if t.Sym() == nil && len(m) == 0 {
557                 return ot
558         }
559         noff := int(types.Rnd(int64(ot), int64(types.PtrSize)))
560         if noff != ot {
561                 base.Fatalf("unexpected alignment in dextratype for %v", t)
562         }
563
564         for _, a := range m {
565                 writeType(a.type_)
566         }
567
568         ot = dgopkgpathOff(lsym, ot, typePkg(t))
569
570         dataAdd += uncommonSize(t)
571         mcount := len(m)
572         if mcount != int(uint16(mcount)) {
573                 base.Fatalf("too many methods on %v: %d", t, mcount)
574         }
575         xcount := sort.Search(mcount, func(i int) bool { return !types.IsExported(m[i].name.Name) })
576         if dataAdd != int(uint32(dataAdd)) {
577                 base.Fatalf("methods are too far away on %v: %d", t, dataAdd)
578         }
579
580         ot = objw.Uint16(lsym, ot, uint16(mcount))
581         ot = objw.Uint16(lsym, ot, uint16(xcount))
582         ot = objw.Uint32(lsym, ot, uint32(dataAdd))
583         ot = objw.Uint32(lsym, ot, 0)
584         return ot
585 }
586
587 func typePkg(t *types.Type) *types.Pkg {
588         tsym := t.Sym()
589         if tsym == nil {
590                 switch t.Kind() {
591                 case types.TARRAY, types.TSLICE, types.TPTR, types.TCHAN:
592                         if t.Elem() != nil {
593                                 tsym = t.Elem().Sym()
594                         }
595                 }
596         }
597         if tsym != nil && t != types.Types[t.Kind()] && t != types.ErrorType {
598                 return tsym.Pkg
599         }
600         return nil
601 }
602
603 // dextratypeData dumps the backing array for the []method field of
604 // runtime.uncommontype.
605 func dextratypeData(lsym *obj.LSym, ot int, t *types.Type) int {
606         for _, a := range methods(t) {
607                 // ../../../../runtime/type.go:/method
608                 exported := types.IsExported(a.name.Name)
609                 var pkg *types.Pkg
610                 if !exported && a.name.Pkg != typePkg(t) {
611                         pkg = a.name.Pkg
612                 }
613                 nsym := dname(a.name.Name, "", pkg, exported)
614
615                 ot = objw.SymPtrOff(lsym, ot, nsym)
616                 ot = dmethodptrOff(lsym, ot, writeType(a.mtype))
617                 ot = dmethodptrOff(lsym, ot, a.isym)
618                 ot = dmethodptrOff(lsym, ot, a.tsym)
619         }
620         return ot
621 }
622
623 func dmethodptrOff(s *obj.LSym, ot int, x *obj.LSym) int {
624         objw.Uint32(s, ot, 0)
625         r := obj.Addrel(s)
626         r.Off = int32(ot)
627         r.Siz = 4
628         r.Sym = x
629         r.Type = objabi.R_METHODOFF
630         return ot + 4
631 }
632
633 var kinds = []int{
634         types.TINT:        objabi.KindInt,
635         types.TUINT:       objabi.KindUint,
636         types.TINT8:       objabi.KindInt8,
637         types.TUINT8:      objabi.KindUint8,
638         types.TINT16:      objabi.KindInt16,
639         types.TUINT16:     objabi.KindUint16,
640         types.TINT32:      objabi.KindInt32,
641         types.TUINT32:     objabi.KindUint32,
642         types.TINT64:      objabi.KindInt64,
643         types.TUINT64:     objabi.KindUint64,
644         types.TUINTPTR:    objabi.KindUintptr,
645         types.TFLOAT32:    objabi.KindFloat32,
646         types.TFLOAT64:    objabi.KindFloat64,
647         types.TBOOL:       objabi.KindBool,
648         types.TSTRING:     objabi.KindString,
649         types.TPTR:        objabi.KindPtr,
650         types.TSTRUCT:     objabi.KindStruct,
651         types.TINTER:      objabi.KindInterface,
652         types.TCHAN:       objabi.KindChan,
653         types.TMAP:        objabi.KindMap,
654         types.TARRAY:      objabi.KindArray,
655         types.TSLICE:      objabi.KindSlice,
656         types.TFUNC:       objabi.KindFunc,
657         types.TCOMPLEX64:  objabi.KindComplex64,
658         types.TCOMPLEX128: objabi.KindComplex128,
659         types.TUNSAFEPTR:  objabi.KindUnsafePointer,
660 }
661
662 // tflag is documented in reflect/type.go.
663 //
664 // tflag values must be kept in sync with copies in:
665 //      cmd/compile/internal/gc/reflect.go
666 //      cmd/link/internal/ld/decodesym.go
667 //      reflect/type.go
668 //      runtime/type.go
669 const (
670         tflagUncommon      = 1 << 0
671         tflagExtraStar     = 1 << 1
672         tflagNamed         = 1 << 2
673         tflagRegularMemory = 1 << 3
674 )
675
676 var (
677         memhashvarlen  *obj.LSym
678         memequalvarlen *obj.LSym
679 )
680
681 // dcommontype dumps the contents of a reflect.rtype (runtime._type).
682 func dcommontype(lsym *obj.LSym, t *types.Type) int {
683         types.CalcSize(t)
684         eqfunc := geneq(t)
685
686         sptrWeak := true
687         var sptr *obj.LSym
688         if !t.IsPtr() || t.IsPtrElem() {
689                 tptr := types.NewPtr(t)
690                 if t.Sym() != nil || methods(tptr) != nil {
691                         sptrWeak = false
692                 }
693                 sptr = writeType(tptr)
694         }
695
696         gcsym, useGCProg, ptrdata := dgcsym(t)
697
698         // ../../../../reflect/type.go:/^type.rtype
699         // actual type structure
700         //      type rtype struct {
701         //              size          uintptr
702         //              ptrdata       uintptr
703         //              hash          uint32
704         //              tflag         tflag
705         //              align         uint8
706         //              fieldAlign    uint8
707         //              kind          uint8
708         //              equal         func(unsafe.Pointer, unsafe.Pointer) bool
709         //              gcdata        *byte
710         //              str           nameOff
711         //              ptrToThis     typeOff
712         //      }
713         ot := 0
714         ot = objw.Uintptr(lsym, ot, uint64(t.Width))
715         ot = objw.Uintptr(lsym, ot, uint64(ptrdata))
716         ot = objw.Uint32(lsym, ot, types.TypeHash(t))
717
718         var tflag uint8
719         if uncommonSize(t) != 0 {
720                 tflag |= tflagUncommon
721         }
722         if t.Sym() != nil && t.Sym().Name != "" {
723                 tflag |= tflagNamed
724         }
725         if isRegularMemory(t) {
726                 tflag |= tflagRegularMemory
727         }
728
729         exported := false
730         p := t.LongString()
731         // If we're writing out type T,
732         // we are very likely to write out type *T as well.
733         // Use the string "*T"[1:] for "T", so that the two
734         // share storage. This is a cheap way to reduce the
735         // amount of space taken up by reflect strings.
736         if !strings.HasPrefix(p, "*") {
737                 p = "*" + p
738                 tflag |= tflagExtraStar
739                 if t.Sym() != nil {
740                         exported = types.IsExported(t.Sym().Name)
741                 }
742         } else {
743                 if t.Elem() != nil && t.Elem().Sym() != nil {
744                         exported = types.IsExported(t.Elem().Sym().Name)
745                 }
746         }
747
748         ot = objw.Uint8(lsym, ot, tflag)
749
750         // runtime (and common sense) expects alignment to be a power of two.
751         i := int(t.Align)
752
753         if i == 0 {
754                 i = 1
755         }
756         if i&(i-1) != 0 {
757                 base.Fatalf("invalid alignment %d for %v", t.Align, t)
758         }
759         ot = objw.Uint8(lsym, ot, t.Align) // align
760         ot = objw.Uint8(lsym, ot, t.Align) // fieldAlign
761
762         i = kinds[t.Kind()]
763         if types.IsDirectIface(t) {
764                 i |= objabi.KindDirectIface
765         }
766         if useGCProg {
767                 i |= objabi.KindGCProg
768         }
769         ot = objw.Uint8(lsym, ot, uint8(i)) // kind
770         if eqfunc != nil {
771                 ot = objw.SymPtr(lsym, ot, eqfunc, 0) // equality function
772         } else {
773                 ot = objw.Uintptr(lsym, ot, 0) // type we can't do == with
774         }
775         ot = objw.SymPtr(lsym, ot, gcsym, 0) // gcdata
776
777         nsym := dname(p, "", nil, exported)
778         ot = objw.SymPtrOff(lsym, ot, nsym) // str
779         // ptrToThis
780         if sptr == nil {
781                 ot = objw.Uint32(lsym, ot, 0)
782         } else if sptrWeak {
783                 ot = objw.SymPtrWeakOff(lsym, ot, sptr)
784         } else {
785                 ot = objw.SymPtrOff(lsym, ot, sptr)
786         }
787
788         return ot
789 }
790
791 // TrackSym returns the symbol for tracking use of field/method f, assumed
792 // to be a member of struct/interface type t.
793 func TrackSym(t *types.Type, f *types.Field) *obj.LSym {
794         return base.PkgLinksym("go.track", t.ShortString()+"."+f.Sym.Name, obj.ABI0)
795 }
796
797 func TypeSymPrefix(prefix string, t *types.Type) *types.Sym {
798         p := prefix + "." + t.ShortString()
799         s := types.TypeSymLookup(p)
800
801         // This function is for looking up type-related generated functions
802         // (e.g. eq and hash). Make sure they are indeed generated.
803         signatmu.Lock()
804         NeedRuntimeType(t)
805         signatmu.Unlock()
806
807         //print("algsym: %s -> %+S\n", p, s);
808
809         return s
810 }
811
812 func TypeSym(t *types.Type) *types.Sym {
813         if t == nil || (t.IsPtr() && t.Elem() == nil) || t.IsUntyped() {
814                 base.Fatalf("TypeSym %v", t)
815         }
816         if t.Kind() == types.TFUNC && t.Recv() != nil {
817                 base.Fatalf("misuse of method type: %v", t)
818         }
819         s := types.TypeSym(t)
820         signatmu.Lock()
821         NeedRuntimeType(t)
822         signatmu.Unlock()
823         return s
824 }
825
826 func TypeLinksymPrefix(prefix string, t *types.Type) *obj.LSym {
827         return TypeSymPrefix(prefix, t).Linksym()
828 }
829
830 func TypeLinksymLookup(name string) *obj.LSym {
831         return types.TypeSymLookup(name).Linksym()
832 }
833
834 func TypeLinksym(t *types.Type) *obj.LSym {
835         return TypeSym(t).Linksym()
836 }
837
838 func TypePtr(t *types.Type) *ir.AddrExpr {
839         n := ir.NewLinksymExpr(base.Pos, TypeLinksym(t), types.Types[types.TUINT8])
840         return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
841 }
842
843 func ITabAddr(t, itype *types.Type) *ir.AddrExpr {
844         if t == nil || (t.IsPtr() && t.Elem() == nil) || t.IsUntyped() || !itype.IsInterface() || itype.IsEmptyInterface() {
845                 base.Fatalf("ITabAddr(%v, %v)", t, itype)
846         }
847         s, existed := ir.Pkgs.Itab.LookupOK(t.ShortString() + "," + itype.ShortString())
848         if !existed {
849                 itabs = append(itabs, itabEntry{t: t, itype: itype, lsym: s.Linksym()})
850         }
851
852         lsym := s.Linksym()
853         n := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
854         return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
855 }
856
857 // needkeyupdate reports whether map updates with t as a key
858 // need the key to be updated.
859 func needkeyupdate(t *types.Type) bool {
860         switch t.Kind() {
861         case types.TBOOL, types.TINT, types.TUINT, types.TINT8, types.TUINT8, types.TINT16, types.TUINT16, types.TINT32, types.TUINT32,
862                 types.TINT64, types.TUINT64, types.TUINTPTR, types.TPTR, types.TUNSAFEPTR, types.TCHAN:
863                 return false
864
865         case types.TFLOAT32, types.TFLOAT64, types.TCOMPLEX64, types.TCOMPLEX128, // floats and complex can be +0/-0
866                 types.TINTER,
867                 types.TSTRING: // strings might have smaller backing stores
868                 return true
869
870         case types.TARRAY:
871                 return needkeyupdate(t.Elem())
872
873         case types.TSTRUCT:
874                 for _, t1 := range t.Fields().Slice() {
875                         if needkeyupdate(t1.Type) {
876                                 return true
877                         }
878                 }
879                 return false
880
881         default:
882                 base.Fatalf("bad type for map key: %v", t)
883                 return true
884         }
885 }
886
887 // hashMightPanic reports whether the hash of a map key of type t might panic.
888 func hashMightPanic(t *types.Type) bool {
889         switch t.Kind() {
890         case types.TINTER:
891                 return true
892
893         case types.TARRAY:
894                 return hashMightPanic(t.Elem())
895
896         case types.TSTRUCT:
897                 for _, t1 := range t.Fields().Slice() {
898                         if hashMightPanic(t1.Type) {
899                                 return true
900                         }
901                 }
902                 return false
903
904         default:
905                 return false
906         }
907 }
908
909 // formalType replaces byte and rune aliases with real types.
910 // They've been separate internally to make error messages
911 // better, but we have to merge them in the reflect tables.
912 func formalType(t *types.Type) *types.Type {
913         if t == types.ByteType || t == types.RuneType {
914                 return types.Types[t.Kind()]
915         }
916         return t
917 }
918
919 func writeType(t *types.Type) *obj.LSym {
920         t = formalType(t)
921         if t.IsUntyped() {
922                 base.Fatalf("writeType %v", t)
923         }
924
925         s := types.TypeSym(t)
926         lsym := s.Linksym()
927         if s.Siggen() {
928                 return lsym
929         }
930         s.SetSiggen(true)
931
932         // special case (look for runtime below):
933         // when compiling package runtime,
934         // emit the type structures for int, float, etc.
935         tbase := t
936
937         if t.IsPtr() && t.Sym() == nil && t.Elem().Sym() != nil {
938                 tbase = t.Elem()
939         }
940         dupok := 0
941         if tbase.Sym() == nil {
942                 dupok = obj.DUPOK
943         }
944
945         if base.Ctxt.Pkgpath != "runtime" || (tbase != types.Types[tbase.Kind()] && tbase != types.ByteType && tbase != types.RuneType && tbase != types.ErrorType) { // int, float, etc
946                 // named types from other files are defined only by those files
947                 if tbase.Sym() != nil && tbase.Sym().Pkg != types.LocalPkg {
948                         if i := typecheck.BaseTypeIndex(t); i >= 0 {
949                                 lsym.Pkg = tbase.Sym().Pkg.Prefix
950                                 lsym.SymIdx = int32(i)
951                                 lsym.Set(obj.AttrIndexed, true)
952                         }
953                         return lsym
954                 }
955                 // TODO(mdempsky): Investigate whether this can happen.
956                 if tbase.Kind() == types.TFORW {
957                         return lsym
958                 }
959         }
960
961         ot := 0
962         switch t.Kind() {
963         default:
964                 ot = dcommontype(lsym, t)
965                 ot = dextratype(lsym, ot, t, 0)
966
967         case types.TARRAY:
968                 // ../../../../runtime/type.go:/arrayType
969                 s1 := writeType(t.Elem())
970                 t2 := types.NewSlice(t.Elem())
971                 s2 := writeType(t2)
972                 ot = dcommontype(lsym, t)
973                 ot = objw.SymPtr(lsym, ot, s1, 0)
974                 ot = objw.SymPtr(lsym, ot, s2, 0)
975                 ot = objw.Uintptr(lsym, ot, uint64(t.NumElem()))
976                 ot = dextratype(lsym, ot, t, 0)
977
978         case types.TSLICE:
979                 // ../../../../runtime/type.go:/sliceType
980                 s1 := writeType(t.Elem())
981                 ot = dcommontype(lsym, t)
982                 ot = objw.SymPtr(lsym, ot, s1, 0)
983                 ot = dextratype(lsym, ot, t, 0)
984
985         case types.TCHAN:
986                 // ../../../../runtime/type.go:/chanType
987                 s1 := writeType(t.Elem())
988                 ot = dcommontype(lsym, t)
989                 ot = objw.SymPtr(lsym, ot, s1, 0)
990                 ot = objw.Uintptr(lsym, ot, uint64(t.ChanDir()))
991                 ot = dextratype(lsym, ot, t, 0)
992
993         case types.TFUNC:
994                 for _, t1 := range t.Recvs().Fields().Slice() {
995                         writeType(t1.Type)
996                 }
997                 isddd := false
998                 for _, t1 := range t.Params().Fields().Slice() {
999                         isddd = t1.IsDDD()
1000                         writeType(t1.Type)
1001                 }
1002                 for _, t1 := range t.Results().Fields().Slice() {
1003                         writeType(t1.Type)
1004                 }
1005
1006                 ot = dcommontype(lsym, t)
1007                 inCount := t.NumRecvs() + t.NumParams()
1008                 outCount := t.NumResults()
1009                 if isddd {
1010                         outCount |= 1 << 15
1011                 }
1012                 ot = objw.Uint16(lsym, ot, uint16(inCount))
1013                 ot = objw.Uint16(lsym, ot, uint16(outCount))
1014                 if types.PtrSize == 8 {
1015                         ot += 4 // align for *rtype
1016                 }
1017
1018                 dataAdd := (inCount + t.NumResults()) * types.PtrSize
1019                 ot = dextratype(lsym, ot, t, dataAdd)
1020
1021                 // Array of rtype pointers follows funcType.
1022                 for _, t1 := range t.Recvs().Fields().Slice() {
1023                         ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1024                 }
1025                 for _, t1 := range t.Params().Fields().Slice() {
1026                         ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1027                 }
1028                 for _, t1 := range t.Results().Fields().Slice() {
1029                         ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1030                 }
1031
1032         case types.TINTER:
1033                 m := imethods(t)
1034                 n := len(m)
1035                 for _, a := range m {
1036                         writeType(a.type_)
1037                 }
1038
1039                 // ../../../../runtime/type.go:/interfaceType
1040                 ot = dcommontype(lsym, t)
1041
1042                 var tpkg *types.Pkg
1043                 if t.Sym() != nil && t != types.Types[t.Kind()] && t != types.ErrorType {
1044                         tpkg = t.Sym().Pkg
1045                 }
1046                 ot = dgopkgpath(lsym, ot, tpkg)
1047
1048                 ot = objw.SymPtr(lsym, ot, lsym, ot+3*types.PtrSize+uncommonSize(t))
1049                 ot = objw.Uintptr(lsym, ot, uint64(n))
1050                 ot = objw.Uintptr(lsym, ot, uint64(n))
1051                 dataAdd := imethodSize() * n
1052                 ot = dextratype(lsym, ot, t, dataAdd)
1053
1054                 for _, a := range m {
1055                         // ../../../../runtime/type.go:/imethod
1056                         exported := types.IsExported(a.name.Name)
1057                         var pkg *types.Pkg
1058                         if !exported && a.name.Pkg != tpkg {
1059                                 pkg = a.name.Pkg
1060                         }
1061                         nsym := dname(a.name.Name, "", pkg, exported)
1062
1063                         ot = objw.SymPtrOff(lsym, ot, nsym)
1064                         ot = objw.SymPtrOff(lsym, ot, writeType(a.type_))
1065                 }
1066
1067         // ../../../../runtime/type.go:/mapType
1068         case types.TMAP:
1069                 s1 := writeType(t.Key())
1070                 s2 := writeType(t.Elem())
1071                 s3 := writeType(MapBucketType(t))
1072                 hasher := genhash(t.Key())
1073
1074                 ot = dcommontype(lsym, t)
1075                 ot = objw.SymPtr(lsym, ot, s1, 0)
1076                 ot = objw.SymPtr(lsym, ot, s2, 0)
1077                 ot = objw.SymPtr(lsym, ot, s3, 0)
1078                 ot = objw.SymPtr(lsym, ot, hasher, 0)
1079                 var flags uint32
1080                 // Note: flags must match maptype accessors in ../../../../runtime/type.go
1081                 // and maptype builder in ../../../../reflect/type.go:MapOf.
1082                 if t.Key().Width > MAXKEYSIZE {
1083                         ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1084                         flags |= 1 // indirect key
1085                 } else {
1086                         ot = objw.Uint8(lsym, ot, uint8(t.Key().Width))
1087                 }
1088
1089                 if t.Elem().Width > MAXELEMSIZE {
1090                         ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1091                         flags |= 2 // indirect value
1092                 } else {
1093                         ot = objw.Uint8(lsym, ot, uint8(t.Elem().Width))
1094                 }
1095                 ot = objw.Uint16(lsym, ot, uint16(MapBucketType(t).Width))
1096                 if types.IsReflexive(t.Key()) {
1097                         flags |= 4 // reflexive key
1098                 }
1099                 if needkeyupdate(t.Key()) {
1100                         flags |= 8 // need key update
1101                 }
1102                 if hashMightPanic(t.Key()) {
1103                         flags |= 16 // hash might panic
1104                 }
1105                 ot = objw.Uint32(lsym, ot, flags)
1106                 ot = dextratype(lsym, ot, t, 0)
1107
1108         case types.TPTR:
1109                 if t.Elem().Kind() == types.TANY {
1110                         // ../../../../runtime/type.go:/UnsafePointerType
1111                         ot = dcommontype(lsym, t)
1112                         ot = dextratype(lsym, ot, t, 0)
1113
1114                         break
1115                 }
1116
1117                 // ../../../../runtime/type.go:/ptrType
1118                 s1 := writeType(t.Elem())
1119
1120                 ot = dcommontype(lsym, t)
1121                 ot = objw.SymPtr(lsym, ot, s1, 0)
1122                 ot = dextratype(lsym, ot, t, 0)
1123
1124         // ../../../../runtime/type.go:/structType
1125         // for security, only the exported fields.
1126         case types.TSTRUCT:
1127                 fields := t.Fields().Slice()
1128                 for _, t1 := range fields {
1129                         writeType(t1.Type)
1130                 }
1131
1132                 // All non-exported struct field names within a struct
1133                 // type must originate from a single package. By
1134                 // identifying and recording that package within the
1135                 // struct type descriptor, we can omit that
1136                 // information from the field descriptors.
1137                 var spkg *types.Pkg
1138                 for _, f := range fields {
1139                         if !types.IsExported(f.Sym.Name) {
1140                                 spkg = f.Sym.Pkg
1141                                 break
1142                         }
1143                 }
1144
1145                 ot = dcommontype(lsym, t)
1146                 ot = dgopkgpath(lsym, ot, spkg)
1147                 ot = objw.SymPtr(lsym, ot, lsym, ot+3*types.PtrSize+uncommonSize(t))
1148                 ot = objw.Uintptr(lsym, ot, uint64(len(fields)))
1149                 ot = objw.Uintptr(lsym, ot, uint64(len(fields)))
1150
1151                 dataAdd := len(fields) * structfieldSize()
1152                 ot = dextratype(lsym, ot, t, dataAdd)
1153
1154                 for _, f := range fields {
1155                         // ../../../../runtime/type.go:/structField
1156                         ot = dnameField(lsym, ot, spkg, f)
1157                         ot = objw.SymPtr(lsym, ot, writeType(f.Type), 0)
1158                         offsetAnon := uint64(f.Offset) << 1
1159                         if offsetAnon>>1 != uint64(f.Offset) {
1160                                 base.Fatalf("%v: bad field offset for %s", t, f.Sym.Name)
1161                         }
1162                         if f.Embedded != 0 {
1163                                 offsetAnon |= 1
1164                         }
1165                         ot = objw.Uintptr(lsym, ot, offsetAnon)
1166                 }
1167         }
1168
1169         ot = dextratypeData(lsym, ot, t)
1170         objw.Global(lsym, int32(ot), int16(dupok|obj.RODATA))
1171
1172         // The linker will leave a table of all the typelinks for
1173         // types in the binary, so the runtime can find them.
1174         //
1175         // When buildmode=shared, all types are in typelinks so the
1176         // runtime can deduplicate type pointers.
1177         keep := base.Ctxt.Flag_dynlink
1178         if !keep && t.Sym() == nil {
1179                 // For an unnamed type, we only need the link if the type can
1180                 // be created at run time by reflect.PtrTo and similar
1181                 // functions. If the type exists in the program, those
1182                 // functions must return the existing type structure rather
1183                 // than creating a new one.
1184                 switch t.Kind() {
1185                 case types.TPTR, types.TARRAY, types.TCHAN, types.TFUNC, types.TMAP, types.TSLICE, types.TSTRUCT:
1186                         keep = true
1187                 }
1188         }
1189         // Do not put Noalg types in typelinks.  See issue #22605.
1190         if types.TypeHasNoAlg(t) {
1191                 keep = false
1192         }
1193         lsym.Set(obj.AttrMakeTypelink, keep)
1194
1195         return lsym
1196 }
1197
1198 // InterfaceMethodOffset returns the offset of the i-th method in the interface
1199 // type descriptor, ityp.
1200 func InterfaceMethodOffset(ityp *types.Type, i int64) int64 {
1201         // interface type descriptor layout is struct {
1202         //   _type        // commonSize
1203         //   pkgpath      // 1 word
1204         //   []imethod    // 3 words (pointing to [...]imethod below)
1205         //   uncommontype // uncommonSize
1206         //   [...]imethod
1207         // }
1208         // The size of imethod is 8.
1209         return int64(commonSize()+4*types.PtrSize+uncommonSize(ityp)) + i*8
1210 }
1211
1212 // for each itabEntry, gather the methods on
1213 // the concrete type that implement the interface
1214 func CompileITabs() {
1215         for i := range itabs {
1216                 tab := &itabs[i]
1217                 methods := genfun(tab.t, tab.itype)
1218                 if len(methods) == 0 {
1219                         continue
1220                 }
1221                 tab.entries = methods
1222         }
1223 }
1224
1225 // for the given concrete type and interface
1226 // type, return the (sorted) set of methods
1227 // on the concrete type that implement the interface
1228 func genfun(t, it *types.Type) []*obj.LSym {
1229         if t == nil || it == nil {
1230                 return nil
1231         }
1232         sigs := imethods(it)
1233         methods := methods(t)
1234         out := make([]*obj.LSym, 0, len(sigs))
1235         // TODO(mdempsky): Short circuit before calling methods(t)?
1236         // See discussion on CL 105039.
1237         if len(sigs) == 0 {
1238                 return nil
1239         }
1240
1241         // both sigs and methods are sorted by name,
1242         // so we can find the intersect in a single pass
1243         for _, m := range methods {
1244                 if m.name == sigs[0].name {
1245                         out = append(out, m.isym)
1246                         sigs = sigs[1:]
1247                         if len(sigs) == 0 {
1248                                 break
1249                         }
1250                 }
1251         }
1252
1253         if len(sigs) != 0 {
1254                 base.Fatalf("incomplete itab")
1255         }
1256
1257         return out
1258 }
1259
1260 // ITabSym uses the information gathered in
1261 // CompileITabs to de-virtualize interface methods.
1262 // Since this is called by the SSA backend, it shouldn't
1263 // generate additional Nodes, Syms, etc.
1264 func ITabSym(it *obj.LSym, offset int64) *obj.LSym {
1265         var syms []*obj.LSym
1266         if it == nil {
1267                 return nil
1268         }
1269
1270         for i := range itabs {
1271                 e := &itabs[i]
1272                 if e.lsym == it {
1273                         syms = e.entries
1274                         break
1275                 }
1276         }
1277         if syms == nil {
1278                 return nil
1279         }
1280
1281         // keep this arithmetic in sync with *itab layout
1282         methodnum := int((offset - 2*int64(types.PtrSize) - 8) / int64(types.PtrSize))
1283         if methodnum >= len(syms) {
1284                 return nil
1285         }
1286         return syms[methodnum]
1287 }
1288
1289 // NeedRuntimeType ensures that a runtime type descriptor is emitted for t.
1290 func NeedRuntimeType(t *types.Type) {
1291         if _, ok := signatset[t]; !ok {
1292                 signatset[t] = struct{}{}
1293                 signatslice = append(signatslice, t)
1294         }
1295 }
1296
1297 func WriteRuntimeTypes() {
1298         // Process signatset. Use a loop, as writeType adds
1299         // entries to signatset while it is being processed.
1300         signats := make([]typeAndStr, len(signatslice))
1301         for len(signatslice) > 0 {
1302                 signats = signats[:0]
1303                 // Transfer entries to a slice and sort, for reproducible builds.
1304                 for _, t := range signatslice {
1305                         signats = append(signats, typeAndStr{t: t, short: types.TypeSymName(t), regular: t.String()})
1306                         delete(signatset, t)
1307                 }
1308                 signatslice = signatslice[:0]
1309                 sort.Sort(typesByString(signats))
1310                 for _, ts := range signats {
1311                         t := ts.t
1312                         writeType(t)
1313                         if t.Sym() != nil {
1314                                 writeType(types.NewPtr(t))
1315                         }
1316                 }
1317         }
1318 }
1319
1320 func WriteTabs() {
1321         // process itabs
1322         for _, i := range itabs {
1323                 // dump empty itab symbol into i.sym
1324                 // type itab struct {
1325                 //   inter  *interfacetype
1326                 //   _type  *_type
1327                 //   hash   uint32
1328                 //   _      [4]byte
1329                 //   fun    [1]uintptr // variable sized
1330                 // }
1331                 o := objw.SymPtr(i.lsym, 0, writeType(i.itype), 0)
1332                 o = objw.SymPtr(i.lsym, o, writeType(i.t), 0)
1333                 o = objw.Uint32(i.lsym, o, types.TypeHash(i.t)) // copy of type hash
1334                 o += 4                                          // skip unused field
1335                 for _, fn := range genfun(i.t, i.itype) {
1336                         o = objw.SymPtr(i.lsym, o, fn, 0) // method pointer for each method
1337                 }
1338                 // Nothing writes static itabs, so they are read only.
1339                 objw.Global(i.lsym, int32(o), int16(obj.DUPOK|obj.RODATA))
1340                 i.lsym.Set(obj.AttrContentAddressable, true)
1341         }
1342
1343         // process ptabs
1344         if types.LocalPkg.Name == "main" && len(ptabs) > 0 {
1345                 ot := 0
1346                 s := base.Ctxt.Lookup("go.plugin.tabs")
1347                 for _, p := range ptabs {
1348                         // Dump ptab symbol into go.pluginsym package.
1349                         //
1350                         // type ptab struct {
1351                         //      name nameOff
1352                         //      typ  typeOff // pointer to symbol
1353                         // }
1354                         nsym := dname(p.Sym().Name, "", nil, true)
1355                         t := p.Type()
1356                         if p.Class != ir.PFUNC {
1357                                 t = types.NewPtr(t)
1358                         }
1359                         tsym := writeType(t)
1360                         ot = objw.SymPtrOff(s, ot, nsym)
1361                         ot = objw.SymPtrOff(s, ot, tsym)
1362                         // Plugin exports symbols as interfaces. Mark their types
1363                         // as UsedInIface.
1364                         tsym.Set(obj.AttrUsedInIface, true)
1365                 }
1366                 objw.Global(s, int32(ot), int16(obj.RODATA))
1367
1368                 ot = 0
1369                 s = base.Ctxt.Lookup("go.plugin.exports")
1370                 for _, p := range ptabs {
1371                         ot = objw.SymPtr(s, ot, p.Linksym(), 0)
1372                 }
1373                 objw.Global(s, int32(ot), int16(obj.RODATA))
1374         }
1375 }
1376
1377 func WriteImportStrings() {
1378         // generate import strings for imported packages
1379         for _, p := range types.ImportedPkgList() {
1380                 dimportpath(p)
1381         }
1382 }
1383
1384 func WriteBasicTypes() {
1385         // do basic types if compiling package runtime.
1386         // they have to be in at least one package,
1387         // and runtime is always loaded implicitly,
1388         // so this is as good as any.
1389         // another possible choice would be package main,
1390         // but using runtime means fewer copies in object files.
1391         if base.Ctxt.Pkgpath == "runtime" {
1392                 for i := types.Kind(1); i <= types.TBOOL; i++ {
1393                         writeType(types.NewPtr(types.Types[i]))
1394                 }
1395                 writeType(types.NewPtr(types.Types[types.TSTRING]))
1396                 writeType(types.NewPtr(types.Types[types.TUNSAFEPTR]))
1397
1398                 // emit type structs for error and func(error) string.
1399                 // The latter is the type of an auto-generated wrapper.
1400                 writeType(types.NewPtr(types.ErrorType))
1401
1402                 writeType(types.NewSignature(types.NoPkg, nil, []*types.Field{
1403                         types.NewField(base.Pos, nil, types.ErrorType),
1404                 }, []*types.Field{
1405                         types.NewField(base.Pos, nil, types.Types[types.TSTRING]),
1406                 }))
1407
1408                 // add paths for runtime and main, which 6l imports implicitly.
1409                 dimportpath(ir.Pkgs.Runtime)
1410
1411                 if base.Flag.Race {
1412                         dimportpath(types.NewPkg("runtime/race", ""))
1413                 }
1414                 if base.Flag.MSan {
1415                         dimportpath(types.NewPkg("runtime/msan", ""))
1416                 }
1417
1418                 dimportpath(types.NewPkg("main", ""))
1419         }
1420 }
1421
1422 type typeAndStr struct {
1423         t       *types.Type
1424         short   string
1425         regular string
1426 }
1427
1428 type typesByString []typeAndStr
1429
1430 func (a typesByString) Len() int { return len(a) }
1431 func (a typesByString) Less(i, j int) bool {
1432         if a[i].short != a[j].short {
1433                 return a[i].short < a[j].short
1434         }
1435         // When the only difference between the types is whether
1436         // they refer to byte or uint8, such as **byte vs **uint8,
1437         // the types' ShortStrings can be identical.
1438         // To preserve deterministic sort ordering, sort these by String().
1439         if a[i].regular != a[j].regular {
1440                 return a[i].regular < a[j].regular
1441         }
1442         // Identical anonymous interfaces defined in different locations
1443         // will be equal for the above checks, but different in DWARF output.
1444         // Sort by source position to ensure deterministic order.
1445         // See issues 27013 and 30202.
1446         if a[i].t.Kind() == types.TINTER && a[i].t.Methods().Len() > 0 {
1447                 return a[i].t.Methods().Index(0).Pos.Before(a[j].t.Methods().Index(0).Pos)
1448         }
1449         return false
1450 }
1451 func (a typesByString) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
1452
1453 // maxPtrmaskBytes is the maximum length of a GC ptrmask bitmap,
1454 // which holds 1-bit entries describing where pointers are in a given type.
1455 // Above this length, the GC information is recorded as a GC program,
1456 // which can express repetition compactly. In either form, the
1457 // information is used by the runtime to initialize the heap bitmap,
1458 // and for large types (like 128 or more words), they are roughly the
1459 // same speed. GC programs are never much larger and often more
1460 // compact. (If large arrays are involved, they can be arbitrarily
1461 // more compact.)
1462 //
1463 // The cutoff must be large enough that any allocation large enough to
1464 // use a GC program is large enough that it does not share heap bitmap
1465 // bytes with any other objects, allowing the GC program execution to
1466 // assume an aligned start and not use atomic operations. In the current
1467 // runtime, this means all malloc size classes larger than the cutoff must
1468 // be multiples of four words. On 32-bit systems that's 16 bytes, and
1469 // all size classes >= 16 bytes are 16-byte aligned, so no real constraint.
1470 // On 64-bit systems, that's 32 bytes, and 32-byte alignment is guaranteed
1471 // for size classes >= 256 bytes. On a 64-bit system, 256 bytes allocated
1472 // is 32 pointers, the bits for which fit in 4 bytes. So maxPtrmaskBytes
1473 // must be >= 4.
1474 //
1475 // We used to use 16 because the GC programs do have some constant overhead
1476 // to get started, and processing 128 pointers seems to be enough to
1477 // amortize that overhead well.
1478 //
1479 // To make sure that the runtime's chansend can call typeBitsBulkBarrier,
1480 // we raised the limit to 2048, so that even 32-bit systems are guaranteed to
1481 // use bitmaps for objects up to 64 kB in size.
1482 //
1483 // Also known to reflect/type.go.
1484 //
1485 const maxPtrmaskBytes = 2048
1486
1487 // dgcsym emits and returns a data symbol containing GC information for type t,
1488 // along with a boolean reporting whether the UseGCProg bit should be set in
1489 // the type kind, and the ptrdata field to record in the reflect type information.
1490 func dgcsym(t *types.Type) (lsym *obj.LSym, useGCProg bool, ptrdata int64) {
1491         ptrdata = types.PtrDataSize(t)
1492         if ptrdata/int64(types.PtrSize) <= maxPtrmaskBytes*8 {
1493                 lsym = dgcptrmask(t)
1494                 return
1495         }
1496
1497         useGCProg = true
1498         lsym, ptrdata = dgcprog(t)
1499         return
1500 }
1501
1502 // dgcptrmask emits and returns the symbol containing a pointer mask for type t.
1503 func dgcptrmask(t *types.Type) *obj.LSym {
1504         ptrmask := make([]byte, (types.PtrDataSize(t)/int64(types.PtrSize)+7)/8)
1505         fillptrmask(t, ptrmask)
1506         p := fmt.Sprintf("gcbits.%x", ptrmask)
1507
1508         sym := ir.Pkgs.Runtime.Lookup(p)
1509         lsym := sym.Linksym()
1510         if !sym.Uniq() {
1511                 sym.SetUniq(true)
1512                 for i, x := range ptrmask {
1513                         objw.Uint8(lsym, i, x)
1514                 }
1515                 objw.Global(lsym, int32(len(ptrmask)), obj.DUPOK|obj.RODATA|obj.LOCAL)
1516                 lsym.Set(obj.AttrContentAddressable, true)
1517         }
1518         return lsym
1519 }
1520
1521 // fillptrmask fills in ptrmask with 1s corresponding to the
1522 // word offsets in t that hold pointers.
1523 // ptrmask is assumed to fit at least typeptrdata(t)/Widthptr bits.
1524 func fillptrmask(t *types.Type, ptrmask []byte) {
1525         for i := range ptrmask {
1526                 ptrmask[i] = 0
1527         }
1528         if !t.HasPointers() {
1529                 return
1530         }
1531
1532         vec := bitvec.New(8 * int32(len(ptrmask)))
1533         typebits.Set(t, 0, vec)
1534
1535         nptr := types.PtrDataSize(t) / int64(types.PtrSize)
1536         for i := int64(0); i < nptr; i++ {
1537                 if vec.Get(int32(i)) {
1538                         ptrmask[i/8] |= 1 << (uint(i) % 8)
1539                 }
1540         }
1541 }
1542
1543 // dgcprog emits and returns the symbol containing a GC program for type t
1544 // along with the size of the data described by the program (in the range [typeptrdata(t), t.Width]).
1545 // In practice, the size is typeptrdata(t) except for non-trivial arrays.
1546 // For non-trivial arrays, the program describes the full t.Width size.
1547 func dgcprog(t *types.Type) (*obj.LSym, int64) {
1548         types.CalcSize(t)
1549         if t.Width == types.BADWIDTH {
1550                 base.Fatalf("dgcprog: %v badwidth", t)
1551         }
1552         lsym := TypeLinksymPrefix(".gcprog", t)
1553         var p gcProg
1554         p.init(lsym)
1555         p.emit(t, 0)
1556         offset := p.w.BitIndex() * int64(types.PtrSize)
1557         p.end()
1558         if ptrdata := types.PtrDataSize(t); offset < ptrdata || offset > t.Width {
1559                 base.Fatalf("dgcprog: %v: offset=%d but ptrdata=%d size=%d", t, offset, ptrdata, t.Width)
1560         }
1561         return lsym, offset
1562 }
1563
1564 type gcProg struct {
1565         lsym   *obj.LSym
1566         symoff int
1567         w      gcprog.Writer
1568 }
1569
1570 func (p *gcProg) init(lsym *obj.LSym) {
1571         p.lsym = lsym
1572         p.symoff = 4 // first 4 bytes hold program length
1573         p.w.Init(p.writeByte)
1574         if base.Debug.GCProg > 0 {
1575                 fmt.Fprintf(os.Stderr, "compile: start GCProg for %v\n", lsym)
1576                 p.w.Debug(os.Stderr)
1577         }
1578 }
1579
1580 func (p *gcProg) writeByte(x byte) {
1581         p.symoff = objw.Uint8(p.lsym, p.symoff, x)
1582 }
1583
1584 func (p *gcProg) end() {
1585         p.w.End()
1586         objw.Uint32(p.lsym, 0, uint32(p.symoff-4))
1587         objw.Global(p.lsym, int32(p.symoff), obj.DUPOK|obj.RODATA|obj.LOCAL)
1588         if base.Debug.GCProg > 0 {
1589                 fmt.Fprintf(os.Stderr, "compile: end GCProg for %v\n", p.lsym)
1590         }
1591 }
1592
1593 func (p *gcProg) emit(t *types.Type, offset int64) {
1594         types.CalcSize(t)
1595         if !t.HasPointers() {
1596                 return
1597         }
1598         if t.Width == int64(types.PtrSize) {
1599                 p.w.Ptr(offset / int64(types.PtrSize))
1600                 return
1601         }
1602         switch t.Kind() {
1603         default:
1604                 base.Fatalf("gcProg.emit: unexpected type %v", t)
1605
1606         case types.TSTRING:
1607                 p.w.Ptr(offset / int64(types.PtrSize))
1608
1609         case types.TINTER:
1610                 // Note: the first word isn't a pointer. See comment in typebits.Set
1611                 p.w.Ptr(offset/int64(types.PtrSize) + 1)
1612
1613         case types.TSLICE:
1614                 p.w.Ptr(offset / int64(types.PtrSize))
1615
1616         case types.TARRAY:
1617                 if t.NumElem() == 0 {
1618                         // should have been handled by haspointers check above
1619                         base.Fatalf("gcProg.emit: empty array")
1620                 }
1621
1622                 // Flatten array-of-array-of-array to just a big array by multiplying counts.
1623                 count := t.NumElem()
1624                 elem := t.Elem()
1625                 for elem.IsArray() {
1626                         count *= elem.NumElem()
1627                         elem = elem.Elem()
1628                 }
1629
1630                 if !p.w.ShouldRepeat(elem.Width/int64(types.PtrSize), count) {
1631                         // Cheaper to just emit the bits.
1632                         for i := int64(0); i < count; i++ {
1633                                 p.emit(elem, offset+i*elem.Width)
1634                         }
1635                         return
1636                 }
1637                 p.emit(elem, offset)
1638                 p.w.ZeroUntil((offset + elem.Width) / int64(types.PtrSize))
1639                 p.w.Repeat(elem.Width/int64(types.PtrSize), count-1)
1640
1641         case types.TSTRUCT:
1642                 for _, t1 := range t.Fields().Slice() {
1643                         p.emit(t1.Type, offset+t1.Offset)
1644                 }
1645         }
1646 }
1647
1648 // ZeroAddr returns the address of a symbol with at least
1649 // size bytes of zeros.
1650 func ZeroAddr(size int64) ir.Node {
1651         if size >= 1<<31 {
1652                 base.Fatalf("map elem too big %d", size)
1653         }
1654         if ZeroSize < size {
1655                 ZeroSize = size
1656         }
1657         lsym := base.PkgLinksym("go.map", "zero", obj.ABI0)
1658         x := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
1659         return typecheck.Expr(typecheck.NodAddr(x))
1660 }
1661
1662 func CollectPTabs() {
1663         if !base.Ctxt.Flag_dynlink || types.LocalPkg.Name != "main" {
1664                 return
1665         }
1666         for _, exportn := range typecheck.Target.Exports {
1667                 s := exportn.Sym()
1668                 nn := ir.AsNode(s.Def)
1669                 if nn == nil {
1670                         continue
1671                 }
1672                 if nn.Op() != ir.ONAME {
1673                         continue
1674                 }
1675                 n := nn.(*ir.Name)
1676                 if !types.IsExported(s.Name) {
1677                         continue
1678                 }
1679                 if s.Pkg.Name != "main" {
1680                         continue
1681                 }
1682                 ptabs = append(ptabs, n)
1683         }
1684 }
1685
1686 // Generate a wrapper function to convert from
1687 // a receiver of type T to a receiver of type U.
1688 // That is,
1689 //
1690 //      func (t T) M() {
1691 //              ...
1692 //      }
1693 //
1694 // already exists; this function generates
1695 //
1696 //      func (u U) M() {
1697 //              u.M()
1698 //      }
1699 //
1700 // where the types T and U are such that u.M() is valid
1701 // and calls the T.M method.
1702 // The resulting function is for use in method tables.
1703 //
1704 //      rcvr - U
1705 //      method - M func (t T)(), a TFIELD type struct
1706 func methodWrapper(rcvr *types.Type, method *types.Field) *obj.LSym {
1707         newnam := ir.MethodSym(rcvr, method.Sym)
1708         lsym := newnam.Linksym()
1709         if newnam.Siggen() {
1710                 return lsym
1711         }
1712         newnam.SetSiggen(true)
1713
1714         if types.Identical(rcvr, method.Type.Recv().Type) {
1715                 return lsym
1716         }
1717
1718         // Only generate (*T).M wrappers for T.M in T's own package.
1719         if rcvr.IsPtr() && rcvr.Elem() == method.Type.Recv().Type &&
1720                 rcvr.Elem().Sym() != nil && rcvr.Elem().Sym().Pkg != types.LocalPkg {
1721                 return lsym
1722         }
1723
1724         // Only generate I.M wrappers for I in I's own package
1725         // but keep doing it for error.Error (was issue #29304).
1726         if rcvr.IsInterface() && rcvr.Sym() != nil && rcvr.Sym().Pkg != types.LocalPkg && rcvr != types.ErrorType {
1727                 return lsym
1728         }
1729
1730         base.Pos = base.AutogeneratedPos
1731         typecheck.DeclContext = ir.PEXTERN
1732
1733         tfn := ir.NewFuncType(base.Pos,
1734                 ir.NewField(base.Pos, typecheck.Lookup(".this"), nil, rcvr),
1735                 typecheck.NewFuncParams(method.Type.Params(), true),
1736                 typecheck.NewFuncParams(method.Type.Results(), false))
1737
1738         fn := typecheck.DeclFunc(newnam, tfn)
1739         fn.SetDupok(true)
1740
1741         nthis := ir.AsNode(tfn.Type().Recv().Nname)
1742
1743         methodrcvr := method.Type.Recv().Type
1744
1745         // generate nil pointer check for better error
1746         if rcvr.IsPtr() && rcvr.Elem() == methodrcvr {
1747                 // generating wrapper from *T to T.
1748                 n := ir.NewIfStmt(base.Pos, nil, nil, nil)
1749                 n.Cond = ir.NewBinaryExpr(base.Pos, ir.OEQ, nthis, typecheck.NodNil())
1750                 call := ir.NewCallExpr(base.Pos, ir.OCALL, typecheck.LookupRuntime("panicwrap"), nil)
1751                 n.Body = []ir.Node{call}
1752                 fn.Body.Append(n)
1753         }
1754
1755         dot := typecheck.AddImplicitDots(ir.NewSelectorExpr(base.Pos, ir.OXDOT, nthis, method.Sym))
1756
1757         // generate call
1758         // It's not possible to use a tail call when dynamic linking on ppc64le. The
1759         // bad scenario is when a local call is made to the wrapper: the wrapper will
1760         // call the implementation, which might be in a different module and so set
1761         // the TOC to the appropriate value for that module. But if it returns
1762         // directly to the wrapper's caller, nothing will reset it to the correct
1763         // value for that function.
1764         if !base.Flag.Cfg.Instrumenting && rcvr.IsPtr() && methodrcvr.IsPtr() && method.Embedded != 0 && !types.IsInterfaceMethod(method.Type) && !(base.Ctxt.Arch.Name == "ppc64le" && base.Ctxt.Flag_dynlink) {
1765                 // generate tail call: adjust pointer receiver and jump to embedded method.
1766                 left := dot.X // skip final .M
1767                 if !left.Type().IsPtr() {
1768                         left = typecheck.NodAddr(left)
1769                 }
1770                 as := ir.NewAssignStmt(base.Pos, nthis, typecheck.ConvNop(left, rcvr))
1771                 fn.Body.Append(as)
1772                 fn.Body.Append(ir.NewTailCallStmt(base.Pos, method.Nname.(*ir.Name)))
1773         } else {
1774                 fn.SetWrapper(true) // ignore frame for panic+recover matching
1775                 call := ir.NewCallExpr(base.Pos, ir.OCALL, dot, nil)
1776                 call.Args = ir.ParamNames(tfn.Type())
1777                 call.IsDDD = tfn.Type().IsVariadic()
1778                 if method.Type.NumResults() > 0 {
1779                         ret := ir.NewReturnStmt(base.Pos, nil)
1780                         ret.Results = []ir.Node{call}
1781                         fn.Body.Append(ret)
1782                 } else {
1783                         fn.Body.Append(call)
1784                 }
1785         }
1786
1787         typecheck.FinishFuncBody()
1788         if base.Debug.DclStack != 0 {
1789                 types.CheckDclstack()
1790         }
1791
1792         typecheck.Func(fn)
1793         ir.CurFunc = fn
1794         typecheck.Stmts(fn.Body)
1795
1796         // Inline calls within (*T).M wrappers. This is safe because we only
1797         // generate those wrappers within the same compilation unit as (T).M.
1798         // TODO(mdempsky): Investigate why we can't enable this more generally.
1799         if rcvr.IsPtr() && rcvr.Elem() == method.Type.Recv().Type && rcvr.Elem().Sym() != nil {
1800                 inline.InlineCalls(fn)
1801         }
1802         escape.Batch([]*ir.Func{fn}, false)
1803
1804         ir.CurFunc = nil
1805         typecheck.Target.Decls = append(typecheck.Target.Decls, fn)
1806
1807         return lsym
1808 }
1809
1810 var ZeroSize int64
1811
1812 // MarkTypeUsedInInterface marks that type t is converted to an interface.
1813 // This information is used in the linker in dead method elimination.
1814 func MarkTypeUsedInInterface(t *types.Type, from *obj.LSym) {
1815         tsym := TypeLinksym(t)
1816         // Emit a marker relocation. The linker will know the type is converted
1817         // to an interface if "from" is reachable.
1818         r := obj.Addrel(from)
1819         r.Sym = tsym
1820         r.Type = objabi.R_USEIFACE
1821 }
1822
1823 // MarkUsedIfaceMethod marks that an interface method is used in the current
1824 // function. n is OCALLINTER node.
1825 func MarkUsedIfaceMethod(n *ir.CallExpr) {
1826         dot := n.X.(*ir.SelectorExpr)
1827         ityp := dot.X.Type()
1828         tsym := TypeLinksym(ityp)
1829         r := obj.Addrel(ir.CurFunc.LSym)
1830         r.Sym = tsym
1831         // dot.Xoffset is the method index * Widthptr (the offset of code pointer
1832         // in itab).
1833         midx := dot.Offset() / int64(types.PtrSize)
1834         r.Add = InterfaceMethodOffset(ityp, midx)
1835         r.Type = objabi.R_USEIFACEMETHOD
1836 }