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.
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"
29 type itabEntry struct {
31 lsym *obj.LSym // symbol of the itab itself
33 // symbols of each method in
34 // the itab, sorted by byte offset;
35 // filled in by CompileITabs
39 type ptabEntry struct {
44 func CountTabs() (numPTabs, numITabs int) {
45 return len(ptabs), len(itabs)
48 // runtime interface and reflection data structures
50 signatmu sync.Mutex // protects signatset and signatslice
51 signatset = make(map[*types.Type]struct{})
52 signatslice []*types.Type
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
70 // Make sure this stays in sync with runtime/map.go.
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{})
81 func uncommonSize(t *types.Type) int { // Sizeof(runtime.uncommontype{})
82 if t.Sym() == nil && len(methods(t)) == 0 {
85 return 4 + 2 + 2 + 4 + 4
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)
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
101 types.CalcSize(keytype)
102 types.CalcSize(elemtype)
103 if keytype.Width > MAXKEYSIZE {
104 keytype = types.NewPtr(keytype)
106 if elemtype.Width > MAXELEMSIZE {
107 elemtype = types.NewPtr(elemtype)
110 field := make([]*types.Field, 0, 5)
112 // The first field is: uint8 topbits[BUCKETSIZE].
113 arr := types.NewArray(types.Types[types.TUINT8], BUCKETSIZE)
114 field = append(field, makefield("topbits", arr))
116 arr = types.NewArray(keytype, BUCKETSIZE)
118 keys := makefield("keys", arr)
119 field = append(field, keys)
121 arr = types.NewArray(elemtype, BUCKETSIZE)
123 elems := makefield("elems", arr)
124 field = append(field, elems)
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]
136 overflow := makefield("overflow", otyp)
137 field = append(field, overflow)
140 bucket := types.NewStruct(types.NoPkg, field[:])
141 bucket.SetNoalg(true)
142 types.CalcSize(bucket)
144 // Check invariants that map code depends on.
145 if !types.IsComparable(t.Key()) {
146 base.Fatalf("unsupported map key type for %v", t)
149 base.Fatalf("bucket size too small for proper alignment")
151 if keytype.Align > BUCKETSIZE {
152 base.Fatalf("key align too big for %v", t)
154 if elemtype.Align > BUCKETSIZE {
155 base.Fatalf("elem align too big for %v", t)
157 if keytype.Width > MAXKEYSIZE {
158 base.Fatalf("key size to large for %v", t)
160 if elemtype.Width > MAXELEMSIZE {
161 base.Fatalf("elem size to large for %v", t)
163 if t.Key().Width > MAXKEYSIZE && !keytype.IsPtr() {
164 base.Fatalf("key indirect incorrect for %v", t)
166 if t.Elem().Width > MAXELEMSIZE && !elemtype.IsPtr() {
167 base.Fatalf("elem indirect incorrect for %v", t)
169 if keytype.Width%int64(keytype.Align) != 0 {
170 base.Fatalf("key size not a multiple of key align for %v", t)
172 if elemtype.Width%int64(elemtype.Align) != 0 {
173 base.Fatalf("elem size not a multiple of elem align for %v", t)
175 if bucket.Align%keytype.Align != 0 {
176 base.Fatalf("bucket align not multiple of key align %v", t)
178 if bucket.Align%elemtype.Align != 0 {
179 base.Fatalf("bucket align not multiple of elem align %v", t)
181 if keys.Offset%int64(keytype.Align) != 0 {
182 base.Fatalf("bad alignment of keys in bmap for %v", t)
184 if elems.Offset%int64(elemtype.Align) != 0 {
185 base.Fatalf("bad alignment of elems in bmap for %v", t)
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)
194 t.MapType().Bucket = bucket
196 bucket.StructType().Map = t
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
207 bmap := MapBucketType(t)
210 // type hmap struct {
219 // extra unsafe.Pointer // *mapextra
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]),
234 hmap := types.NewStruct(types.NoPkg, fields)
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)
244 t.MapType().Hmap = hmap
245 hmap.StructType().Map = t
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
257 bmap := MapBucketType(t)
260 // type hiter struct {
263 // t unsafe.Pointer // *MapType
267 // overflow unsafe.Pointer // *[]*bmap
268 // oldoverflow unsafe.Pointer // *[]*bmap
269 // startBucket uintptr
275 // checkBucket uintptr
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]),
296 // build iterator struct holding the above fields
297 hiter := types.NewStruct(types.NoPkg, fields)
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)
303 t.MapType().Hiter = hiter
304 hiter.StructType().Map = t
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 {
312 mt := types.ReceiverBaseType(t)
317 typecheck.CalcMethods(mt)
319 // type stored in interface word
322 if !types.IsDirectIface(it) {
326 // make list of methods for t,
327 // generating code if necessary.
329 for _, f := range mt.AllMethods().Slice() {
331 base.Fatalf("method with no sym on %v", mt)
334 base.Fatalf("non-method on %v method %v %v", mt, f.Sym, f)
336 if f.Type.Recv() == nil {
337 base.Fatalf("receiver with no type on %v method %v %v", mt, f.Sym, f)
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) {
353 isym: methodWrapper(it, f),
354 tsym: methodWrapper(t, f),
355 type_: typecheck.NewMethodType(f.Type, t),
356 mtype: typecheck.NewMethodType(f.Type, nil),
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 {
372 base.Fatalf("unexpected blank symbol in interface method set")
374 if n := len(methods); n > 0 {
376 if !last.name.Less(f.Sym) {
377 base.Fatalf("sigcmp vs sortinter %v %v", last.name, f.Sym)
384 type_: typecheck.NewMethodType(f.Type, nil),
386 methods = append(methods, sig)
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.
398 func dimportpath(p *types.Pkg) {
399 if p.Pathsym != nil {
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 {
411 if p == types.LocalPkg {
412 // Note: myimportpath != "", or else dgopkgpath won't call dimportpath.
413 str = base.Ctxt.Pkgpath
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)
423 func dgopkgpath(s *obj.LSym, ot int, pkg *types.Pkg) int {
425 return objw.Uintptr(s, ot, 0)
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)
439 return objw.SymPtr(s, ot, pkg.Pathsym, 0)
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 {
445 return objw.Uint32(s, ot, 0)
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)
458 return objw.SymPtrOff(s, ot, pkg.Pathsym)
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)
466 nsym := dname(ft.Sym.Name, ft.Note, nil, types.IsExported(ft.Sym.Name))
467 return objw.SymPtr(lsym, ot, nsym, 0)
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)
475 if len(tag) > 1<<16-1 {
476 base.Fatalf("tag too long: %s", tag)
479 // Encode name and tag. See reflect/type.go for details.
481 l := 1 + 2 + len(name)
494 b[1] = uint8(len(name) >> 8)
495 b[2] = uint8(len(name))
498 tb := b[3+len(name):]
499 tb[0] = uint8(len(tag) >> 8)
500 tb[1] = uint8(len(tag))
504 ot = int(s.WriteBytes(base.Ctxt, int64(ot), b))
507 ot = dgopkgpathOff(s, ot, pkg)
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."
523 // In the common case, share data with other packages.
526 sname += "-noname-exported." + tag
528 sname += "-noname-unexported." + tag
532 sname += name + "." + tag
534 sname += name + "-" + tag
538 sname = fmt.Sprintf(`%s"".%d`, sname, dnameCount)
541 s := base.Ctxt.Lookup(sname)
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)
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 {
556 if t.Sym() == nil && len(m) == 0 {
559 noff := int(types.Rnd(int64(ot), int64(types.PtrSize)))
561 base.Fatalf("unexpected alignment in dextratype for %v", t)
564 for _, a := range m {
568 ot = dgopkgpathOff(lsym, ot, typePkg(t))
570 dataAdd += uncommonSize(t)
572 if mcount != int(uint16(mcount)) {
573 base.Fatalf("too many methods on %v: %d", t, mcount)
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)
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)
587 func typePkg(t *types.Type) *types.Pkg {
591 case types.TARRAY, types.TSLICE, types.TPTR, types.TCHAN:
593 tsym = t.Elem().Sym()
597 if tsym != nil && t != types.Types[t.Kind()] && t != types.ErrorType {
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)
610 if !exported && a.name.Pkg != typePkg(t) {
613 nsym := dname(a.name.Name, "", pkg, exported)
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)
623 func dmethodptrOff(s *obj.LSym, ot int, x *obj.LSym) int {
624 objw.Uint32(s, ot, 0)
629 r.Type = objabi.R_METHODOFF
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,
662 // tflag is documented in reflect/type.go.
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
670 tflagUncommon = 1 << 0
671 tflagExtraStar = 1 << 1
673 tflagRegularMemory = 1 << 3
677 memhashvarlen *obj.LSym
678 memequalvarlen *obj.LSym
681 // dcommontype dumps the contents of a reflect.rtype (runtime._type).
682 func dcommontype(lsym *obj.LSym, t *types.Type) int {
688 if !t.IsPtr() || t.IsPtrElem() {
689 tptr := types.NewPtr(t)
690 if t.Sym() != nil || methods(tptr) != nil {
693 sptr = writeType(tptr)
696 gcsym, useGCProg, ptrdata := dgcsym(t)
698 // ../../../../reflect/type.go:/^type.rtype
699 // actual type structure
700 // type rtype struct {
708 // equal func(unsafe.Pointer, unsafe.Pointer) bool
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))
719 if uncommonSize(t) != 0 {
720 tflag |= tflagUncommon
722 if t.Sym() != nil && t.Sym().Name != "" {
725 if isRegularMemory(t) {
726 tflag |= tflagRegularMemory
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, "*") {
738 tflag |= tflagExtraStar
740 exported = types.IsExported(t.Sym().Name)
743 if t.Elem() != nil && t.Elem().Sym() != nil {
744 exported = types.IsExported(t.Elem().Sym().Name)
748 ot = objw.Uint8(lsym, ot, tflag)
750 // runtime (and common sense) expects alignment to be a power of two.
757 base.Fatalf("invalid alignment %d for %v", t.Align, t)
759 ot = objw.Uint8(lsym, ot, t.Align) // align
760 ot = objw.Uint8(lsym, ot, t.Align) // fieldAlign
763 if types.IsDirectIface(t) {
764 i |= objabi.KindDirectIface
767 i |= objabi.KindGCProg
769 ot = objw.Uint8(lsym, ot, uint8(i)) // kind
771 ot = objw.SymPtr(lsym, ot, eqfunc, 0) // equality function
773 ot = objw.Uintptr(lsym, ot, 0) // type we can't do == with
775 ot = objw.SymPtr(lsym, ot, gcsym, 0) // gcdata
777 nsym := dname(p, "", nil, exported)
778 ot = objw.SymPtrOff(lsym, ot, nsym) // str
781 ot = objw.Uint32(lsym, ot, 0)
783 ot = objw.SymPtrWeakOff(lsym, ot, sptr)
785 ot = objw.SymPtrOff(lsym, ot, sptr)
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)
797 func TypeSymPrefix(prefix string, t *types.Type) *types.Sym {
798 p := prefix + "." + t.ShortString()
799 s := types.TypeSymLookup(p)
801 // This function is for looking up type-related generated functions
802 // (e.g. eq and hash). Make sure they are indeed generated.
807 //print("algsym: %s -> %+S\n", p, s);
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)
816 if t.Kind() == types.TFUNC && t.Recv() != nil {
817 base.Fatalf("misuse of method type: %v", t)
819 s := types.TypeSym(t)
826 func TypeLinksymPrefix(prefix string, t *types.Type) *obj.LSym {
827 return TypeSymPrefix(prefix, t).Linksym()
830 func TypeLinksymLookup(name string) *obj.LSym {
831 return types.TypeSymLookup(name).Linksym()
834 func TypeLinksym(t *types.Type) *obj.LSym {
835 return TypeSym(t).Linksym()
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)
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)
847 s, existed := ir.Pkgs.Itab.LookupOK(t.ShortString() + "," + itype.ShortString())
849 itabs = append(itabs, itabEntry{t: t, itype: itype, lsym: s.Linksym()})
853 n := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
854 return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
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 {
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:
865 case types.TFLOAT32, types.TFLOAT64, types.TCOMPLEX64, types.TCOMPLEX128, // floats and complex can be +0/-0
867 types.TSTRING: // strings might have smaller backing stores
871 return needkeyupdate(t.Elem())
874 for _, t1 := range t.Fields().Slice() {
875 if needkeyupdate(t1.Type) {
882 base.Fatalf("bad type for map key: %v", t)
887 // hashMightPanic reports whether the hash of a map key of type t might panic.
888 func hashMightPanic(t *types.Type) bool {
894 return hashMightPanic(t.Elem())
897 for _, t1 := range t.Fields().Slice() {
898 if hashMightPanic(t1.Type) {
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()]
919 func writeType(t *types.Type) *obj.LSym {
922 base.Fatalf("writeType %v", t)
925 s := types.TypeSym(t)
932 // special case (look for runtime below):
933 // when compiling package runtime,
934 // emit the type structures for int, float, etc.
937 if t.IsPtr() && t.Sym() == nil && t.Elem().Sym() != nil {
941 if tbase.Sym() == nil {
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)
955 // TODO(mdempsky): Investigate whether this can happen.
956 if tbase.Kind() == types.TFORW {
964 ot = dcommontype(lsym, t)
965 ot = dextratype(lsym, ot, t, 0)
968 // ../../../../runtime/type.go:/arrayType
969 s1 := writeType(t.Elem())
970 t2 := types.NewSlice(t.Elem())
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)
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)
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)
994 for _, t1 := range t.Recvs().Fields().Slice() {
998 for _, t1 := range t.Params().Fields().Slice() {
1002 for _, t1 := range t.Results().Fields().Slice() {
1006 ot = dcommontype(lsym, t)
1007 inCount := t.NumRecvs() + t.NumParams()
1008 outCount := t.NumResults()
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
1018 dataAdd := (inCount + t.NumResults()) * types.PtrSize
1019 ot = dextratype(lsym, ot, t, dataAdd)
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)
1025 for _, t1 := range t.Params().Fields().Slice() {
1026 ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1028 for _, t1 := range t.Results().Fields().Slice() {
1029 ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1035 for _, a := range m {
1039 // ../../../../runtime/type.go:/interfaceType
1040 ot = dcommontype(lsym, t)
1043 if t.Sym() != nil && t != types.Types[t.Kind()] && t != types.ErrorType {
1046 ot = dgopkgpath(lsym, ot, tpkg)
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)
1054 for _, a := range m {
1055 // ../../../../runtime/type.go:/imethod
1056 exported := types.IsExported(a.name.Name)
1058 if !exported && a.name.Pkg != tpkg {
1061 nsym := dname(a.name.Name, "", pkg, exported)
1063 ot = objw.SymPtrOff(lsym, ot, nsym)
1064 ot = objw.SymPtrOff(lsym, ot, writeType(a.type_))
1067 // ../../../../runtime/type.go:/mapType
1069 s1 := writeType(t.Key())
1070 s2 := writeType(t.Elem())
1071 s3 := writeType(MapBucketType(t))
1072 hasher := genhash(t.Key())
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)
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
1086 ot = objw.Uint8(lsym, ot, uint8(t.Key().Width))
1089 if t.Elem().Width > MAXELEMSIZE {
1090 ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1091 flags |= 2 // indirect value
1093 ot = objw.Uint8(lsym, ot, uint8(t.Elem().Width))
1095 ot = objw.Uint16(lsym, ot, uint16(MapBucketType(t).Width))
1096 if types.IsReflexive(t.Key()) {
1097 flags |= 4 // reflexive key
1099 if needkeyupdate(t.Key()) {
1100 flags |= 8 // need key update
1102 if hashMightPanic(t.Key()) {
1103 flags |= 16 // hash might panic
1105 ot = objw.Uint32(lsym, ot, flags)
1106 ot = dextratype(lsym, ot, t, 0)
1109 if t.Elem().Kind() == types.TANY {
1110 // ../../../../runtime/type.go:/UnsafePointerType
1111 ot = dcommontype(lsym, t)
1112 ot = dextratype(lsym, ot, t, 0)
1117 // ../../../../runtime/type.go:/ptrType
1118 s1 := writeType(t.Elem())
1120 ot = dcommontype(lsym, t)
1121 ot = objw.SymPtr(lsym, ot, s1, 0)
1122 ot = dextratype(lsym, ot, t, 0)
1124 // ../../../../runtime/type.go:/structType
1125 // for security, only the exported fields.
1127 fields := t.Fields().Slice()
1128 for _, t1 := range fields {
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.
1138 for _, f := range fields {
1139 if !types.IsExported(f.Sym.Name) {
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)))
1151 dataAdd := len(fields) * structfieldSize()
1152 ot = dextratype(lsym, ot, t, dataAdd)
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)
1162 if f.Embedded != 0 {
1165 ot = objw.Uintptr(lsym, ot, offsetAnon)
1169 ot = dextratypeData(lsym, ot, t)
1170 objw.Global(lsym, int32(ot), int16(dupok|obj.RODATA))
1172 // The linker will leave a table of all the typelinks for
1173 // types in the binary, so the runtime can find them.
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.
1185 case types.TPTR, types.TARRAY, types.TCHAN, types.TFUNC, types.TMAP, types.TSLICE, types.TSTRUCT:
1189 // Do not put Noalg types in typelinks. See issue #22605.
1190 if types.TypeHasNoAlg(t) {
1193 lsym.Set(obj.AttrMakeTypelink, keep)
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
1208 // The size of imethod is 8.
1209 return int64(commonSize()+4*types.PtrSize+uncommonSize(ityp)) + i*8
1212 // for each itabEntry, gather the methods on
1213 // the concrete type that implement the interface
1214 func CompileITabs() {
1215 for i := range itabs {
1217 methods := genfun(tab.t, tab.itype)
1218 if len(methods) == 0 {
1221 tab.entries = methods
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 {
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.
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)
1254 base.Fatalf("incomplete itab")
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
1270 for i := range itabs {
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) {
1286 return syms[methodnum]
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)
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)
1308 signatslice = signatslice[:0]
1309 sort.Sort(typesByString(signats))
1310 for _, ts := range signats {
1314 writeType(types.NewPtr(t))
1322 for _, i := range itabs {
1323 // dump empty itab symbol into i.sym
1324 // type itab struct {
1325 // inter *interfacetype
1329 // fun [1]uintptr // variable sized
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
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)
1344 if types.LocalPkg.Name == "main" && len(ptabs) > 0 {
1346 s := base.Ctxt.Lookup("go.plugin.tabs")
1347 for _, p := range ptabs {
1348 // Dump ptab symbol into go.pluginsym package.
1350 // type ptab struct {
1352 // typ typeOff // pointer to symbol
1354 nsym := dname(p.Sym().Name, "", nil, true)
1356 if p.Class != ir.PFUNC {
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
1364 tsym.Set(obj.AttrUsedInIface, true)
1366 objw.Global(s, int32(ot), int16(obj.RODATA))
1369 s = base.Ctxt.Lookup("go.plugin.exports")
1370 for _, p := range ptabs {
1371 ot = objw.SymPtr(s, ot, p.Linksym(), 0)
1373 objw.Global(s, int32(ot), int16(obj.RODATA))
1377 func WriteImportStrings() {
1378 // generate import strings for imported packages
1379 for _, p := range types.ImportedPkgList() {
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]))
1395 writeType(types.NewPtr(types.Types[types.TSTRING]))
1396 writeType(types.NewPtr(types.Types[types.TUNSAFEPTR]))
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))
1402 writeType(types.NewSignature(types.NoPkg, nil, []*types.Field{
1403 types.NewField(base.Pos, nil, types.ErrorType),
1405 types.NewField(base.Pos, nil, types.Types[types.TSTRING]),
1408 // add paths for runtime and main, which 6l imports implicitly.
1409 dimportpath(ir.Pkgs.Runtime)
1412 dimportpath(types.NewPkg("runtime/race", ""))
1415 dimportpath(types.NewPkg("runtime/msan", ""))
1418 dimportpath(types.NewPkg("main", ""))
1422 type typeAndStr struct {
1428 type typesByString []typeAndStr
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
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
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)
1451 func (a typesByString) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
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
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
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.
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.
1483 // Also known to reflect/type.go.
1485 const maxPtrmaskBytes = 2048
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)
1498 lsym, ptrdata = dgcprog(t)
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)
1508 sym := ir.Pkgs.Runtime.Lookup(p)
1509 lsym := sym.Linksym()
1512 for i, x := range ptrmask {
1513 objw.Uint8(lsym, i, x)
1515 objw.Global(lsym, int32(len(ptrmask)), obj.DUPOK|obj.RODATA|obj.LOCAL)
1516 lsym.Set(obj.AttrContentAddressable, true)
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 {
1528 if !t.HasPointers() {
1532 vec := bitvec.New(8 * int32(len(ptrmask)))
1533 typebits.Set(t, 0, vec)
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)
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) {
1549 if t.Width == types.BADWIDTH {
1550 base.Fatalf("dgcprog: %v badwidth", t)
1552 lsym := TypeLinksymPrefix(".gcprog", t)
1556 offset := p.w.BitIndex() * int64(types.PtrSize)
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)
1564 type gcProg struct {
1570 func (p *gcProg) init(lsym *obj.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)
1580 func (p *gcProg) writeByte(x byte) {
1581 p.symoff = objw.Uint8(p.lsym, p.symoff, x)
1584 func (p *gcProg) 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)
1593 func (p *gcProg) emit(t *types.Type, offset int64) {
1595 if !t.HasPointers() {
1598 if t.Width == int64(types.PtrSize) {
1599 p.w.Ptr(offset / int64(types.PtrSize))
1604 base.Fatalf("gcProg.emit: unexpected type %v", t)
1607 p.w.Ptr(offset / int64(types.PtrSize))
1610 // Note: the first word isn't a pointer. See comment in typebits.Set
1611 p.w.Ptr(offset/int64(types.PtrSize) + 1)
1614 p.w.Ptr(offset / int64(types.PtrSize))
1617 if t.NumElem() == 0 {
1618 // should have been handled by haspointers check above
1619 base.Fatalf("gcProg.emit: empty array")
1622 // Flatten array-of-array-of-array to just a big array by multiplying counts.
1623 count := t.NumElem()
1625 for elem.IsArray() {
1626 count *= elem.NumElem()
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)
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)
1642 for _, t1 := range t.Fields().Slice() {
1643 p.emit(t1.Type, offset+t1.Offset)
1648 // ZeroAddr returns the address of a symbol with at least
1649 // size bytes of zeros.
1650 func ZeroAddr(size int64) ir.Node {
1652 base.Fatalf("map elem too big %d", size)
1654 if ZeroSize < size {
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))
1662 func CollectPTabs() {
1663 if !base.Ctxt.Flag_dynlink || types.LocalPkg.Name != "main" {
1666 for _, exportn := range typecheck.Target.Exports {
1668 nn := ir.AsNode(s.Def)
1672 if nn.Op() != ir.ONAME {
1676 if !types.IsExported(s.Name) {
1679 if s.Pkg.Name != "main" {
1682 ptabs = append(ptabs, n)
1686 // Generate a wrapper function to convert from
1687 // a receiver of type T to a receiver of type U.
1694 // already exists; this function generates
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.
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() {
1712 newnam.SetSiggen(true)
1714 if types.Identical(rcvr, method.Type.Recv().Type) {
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 {
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 {
1730 base.Pos = base.AutogeneratedPos
1731 typecheck.DeclContext = ir.PEXTERN
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))
1738 fn := typecheck.DeclFunc(newnam, tfn)
1741 nthis := ir.AsNode(tfn.Type().Recv().Nname)
1743 methodrcvr := method.Type.Recv().Type
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}
1755 dot := typecheck.AddImplicitDots(ir.NewSelectorExpr(base.Pos, ir.OXDOT, nthis, method.Sym))
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)
1770 as := ir.NewAssignStmt(base.Pos, nthis, typecheck.ConvNop(left, rcvr))
1772 fn.Body.Append(ir.NewTailCallStmt(base.Pos, method.Nname.(*ir.Name)))
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}
1783 fn.Body.Append(call)
1787 typecheck.FinishFuncBody()
1788 if base.Debug.DclStack != 0 {
1789 types.CheckDclstack()
1794 typecheck.Stmts(fn.Body)
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)
1802 escape.Batch([]*ir.Func{fn}, false)
1805 typecheck.Target.Decls = append(typecheck.Target.Decls, fn)
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)
1820 r.Type = objabi.R_USEIFACE
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)
1831 // dot.Xoffset is the method index * Widthptr (the offset of code pointer
1833 midx := dot.Offset() / int64(types.PtrSize)
1834 r.Add = InterfaceMethodOffset(ityp, midx)
1835 r.Type = objabi.R_USEIFACEMETHOD