Source file src/cmd/compile/internal/types2/sizes.go

     1  // Copyright 2013 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  // This file implements Sizes.
     6  
     7  package types2
     8  
     9  // Sizes defines the sizing functions for package unsafe.
    10  type Sizes interface {
    11  	// Alignof returns the alignment of a variable of type T.
    12  	// Alignof must implement the alignment guarantees required by the spec.
    13  	// The result must be >= 1.
    14  	Alignof(T Type) int64
    15  
    16  	// Offsetsof returns the offsets of the given struct fields, in bytes.
    17  	// Offsetsof must implement the offset guarantees required by the spec.
    18  	// A negative entry in the result indicates that the struct is too large.
    19  	Offsetsof(fields []*Var) []int64
    20  
    21  	// Sizeof returns the size of a variable of type T.
    22  	// Sizeof must implement the size guarantees required by the spec.
    23  	// A negative result indicates that T is too large.
    24  	Sizeof(T Type) int64
    25  }
    26  
    27  // StdSizes is a convenience type for creating commonly used Sizes.
    28  // It makes the following simplifying assumptions:
    29  //
    30  //   - The size of explicitly sized basic types (int16, etc.) is the
    31  //     specified size.
    32  //   - The size of strings and interfaces is 2*WordSize.
    33  //   - The size of slices is 3*WordSize.
    34  //   - The size of an array of n elements corresponds to the size of
    35  //     a struct of n consecutive fields of the array's element type.
    36  //   - The size of a struct is the offset of the last field plus that
    37  //     field's size. As with all element types, if the struct is used
    38  //     in an array its size must first be aligned to a multiple of the
    39  //     struct's alignment.
    40  //   - All other types have size WordSize.
    41  //   - Arrays and structs are aligned per spec definition; all other
    42  //     types are naturally aligned with a maximum alignment MaxAlign.
    43  //
    44  // *StdSizes implements Sizes.
    45  type StdSizes struct {
    46  	WordSize int64 // word size in bytes - must be >= 4 (32bits)
    47  	MaxAlign int64 // maximum alignment in bytes - must be >= 1
    48  }
    49  
    50  func (s *StdSizes) Alignof(T Type) (result int64) {
    51  	defer func() {
    52  		assert(result >= 1)
    53  	}()
    54  
    55  	// For arrays and structs, alignment is defined in terms
    56  	// of alignment of the elements and fields, respectively.
    57  	switch t := under(T).(type) {
    58  	case *Array:
    59  		// spec: "For a variable x of array type: unsafe.Alignof(x)
    60  		// is the same as unsafe.Alignof(x[0]), but at least 1."
    61  		return s.Alignof(t.elem)
    62  	case *Struct:
    63  		if len(t.fields) == 0 && IsSyncAtomicAlign64(T) {
    64  			// Special case: sync/atomic.align64 is an
    65  			// empty struct we recognize as a signal that
    66  			// the struct it contains must be
    67  			// 64-bit-aligned.
    68  			//
    69  			// This logic is equivalent to the logic in
    70  			// cmd/compile/internal/types/size.go:calcStructOffset
    71  			return 8
    72  		}
    73  
    74  		// spec: "For a variable x of struct type: unsafe.Alignof(x)
    75  		// is the largest of the values unsafe.Alignof(x.f) for each
    76  		// field f of x, but at least 1."
    77  		max := int64(1)
    78  		for _, f := range t.fields {
    79  			if a := s.Alignof(f.typ); a > max {
    80  				max = a
    81  			}
    82  		}
    83  		return max
    84  	case *Slice, *Interface:
    85  		// Multiword data structures are effectively structs
    86  		// in which each element has size WordSize.
    87  		// Type parameters lead to variable sizes/alignments;
    88  		// StdSizes.Alignof won't be called for them.
    89  		assert(!isTypeParam(T))
    90  		return s.WordSize
    91  	case *Basic:
    92  		// Strings are like slices and interfaces.
    93  		if t.Info()&IsString != 0 {
    94  			return s.WordSize
    95  		}
    96  	case *TypeParam, *Union:
    97  		unreachable()
    98  	}
    99  	a := s.Sizeof(T) // may be 0 or negative
   100  	// spec: "For a variable x of any type: unsafe.Alignof(x) is at least 1."
   101  	if a < 1 {
   102  		return 1
   103  	}
   104  	// complex{64,128} are aligned like [2]float{32,64}.
   105  	if isComplex(T) {
   106  		a /= 2
   107  	}
   108  	if a > s.MaxAlign {
   109  		return s.MaxAlign
   110  	}
   111  	return a
   112  }
   113  
   114  func IsSyncAtomicAlign64(T Type) bool {
   115  	named := asNamed(T)
   116  	if named == nil {
   117  		return false
   118  	}
   119  	obj := named.Obj()
   120  	return obj.Name() == "align64" &&
   121  		obj.Pkg() != nil &&
   122  		(obj.Pkg().Path() == "sync/atomic" ||
   123  			obj.Pkg().Path() == "runtime/internal/atomic")
   124  }
   125  
   126  func (s *StdSizes) Offsetsof(fields []*Var) []int64 {
   127  	offsets := make([]int64, len(fields))
   128  	var offs int64
   129  	for i, f := range fields {
   130  		if offs < 0 {
   131  			// all remaining offsets are too large
   132  			offsets[i] = -1
   133  			continue
   134  		}
   135  		// offs >= 0
   136  		a := s.Alignof(f.typ)
   137  		offs = align(offs, a) // possibly < 0 if align overflows
   138  		offsets[i] = offs
   139  		if d := s.Sizeof(f.typ); d >= 0 && offs >= 0 {
   140  			offs += d // ok to overflow to < 0
   141  		} else {
   142  			offs = -1 // f.typ or offs is too large
   143  		}
   144  	}
   145  	return offsets
   146  }
   147  
   148  var basicSizes = [...]byte{
   149  	Bool:       1,
   150  	Int8:       1,
   151  	Int16:      2,
   152  	Int32:      4,
   153  	Int64:      8,
   154  	Uint8:      1,
   155  	Uint16:     2,
   156  	Uint32:     4,
   157  	Uint64:     8,
   158  	Float32:    4,
   159  	Float64:    8,
   160  	Complex64:  8,
   161  	Complex128: 16,
   162  }
   163  
   164  func (s *StdSizes) Sizeof(T Type) int64 {
   165  	switch t := under(T).(type) {
   166  	case *Basic:
   167  		assert(isTyped(T))
   168  		k := t.kind
   169  		if int(k) < len(basicSizes) {
   170  			if s := basicSizes[k]; s > 0 {
   171  				return int64(s)
   172  			}
   173  		}
   174  		if k == String {
   175  			return s.WordSize * 2
   176  		}
   177  	case *Array:
   178  		n := t.len
   179  		if n <= 0 {
   180  			return 0
   181  		}
   182  		// n > 0
   183  		esize := s.Sizeof(t.elem)
   184  		if esize < 0 {
   185  			return -1 // element too large
   186  		}
   187  		if esize == 0 {
   188  			return 0 // 0-size element
   189  		}
   190  		// esize > 0
   191  		a := s.Alignof(t.elem)
   192  		ea := align(esize, a) // possibly < 0 if align overflows
   193  		if ea < 0 {
   194  			return -1
   195  		}
   196  		// ea >= 1
   197  		n1 := n - 1 // n1 >= 0
   198  		// Final size is ea*n1 + esize; and size must be <= maxInt64.
   199  		const maxInt64 = 1<<63 - 1
   200  		if n1 > 0 && ea > maxInt64/n1 {
   201  			return -1 // ea*n1 overflows
   202  		}
   203  		return ea*n1 + esize // may still overflow to < 0 which is ok
   204  	case *Slice:
   205  		return s.WordSize * 3
   206  	case *Struct:
   207  		n := t.NumFields()
   208  		if n == 0 {
   209  			return 0
   210  		}
   211  		offsets := s.Offsetsof(t.fields)
   212  		offs := offsets[n-1]
   213  		size := s.Sizeof(t.fields[n-1].typ)
   214  		if offs < 0 || size < 0 {
   215  			return -1 // type too large
   216  		}
   217  		return offs + size // may overflow to < 0 which is ok
   218  	case *Interface:
   219  		// Type parameters lead to variable sizes/alignments;
   220  		// StdSizes.Sizeof won't be called for them.
   221  		assert(!isTypeParam(T))
   222  		return s.WordSize * 2
   223  	case *TypeParam, *Union:
   224  		unreachable()
   225  	}
   226  	return s.WordSize // catch-all
   227  }
   228  
   229  // common architecture word sizes and alignments
   230  var gcArchSizes = map[string]*gcSizes{
   231  	"386":      {4, 4},
   232  	"amd64":    {8, 8},
   233  	"amd64p32": {4, 8},
   234  	"arm":      {4, 4},
   235  	"arm64":    {8, 8},
   236  	"loong64":  {8, 8},
   237  	"mips":     {4, 4},
   238  	"mipsle":   {4, 4},
   239  	"mips64":   {8, 8},
   240  	"mips64le": {8, 8},
   241  	"ppc64":    {8, 8},
   242  	"ppc64le":  {8, 8},
   243  	"riscv64":  {8, 8},
   244  	"s390x":    {8, 8},
   245  	"sparc64":  {8, 8},
   246  	"wasm":     {8, 8},
   247  	// When adding more architectures here,
   248  	// update the doc string of SizesFor below.
   249  }
   250  
   251  // SizesFor returns the Sizes used by a compiler for an architecture.
   252  // The result is nil if a compiler/architecture pair is not known.
   253  //
   254  // Supported architectures for compiler "gc":
   255  // "386", "amd64", "amd64p32", "arm", "arm64", "loong64", "mips", "mipsle",
   256  // "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm".
   257  func SizesFor(compiler, arch string) Sizes {
   258  	switch compiler {
   259  	case "gc":
   260  		if s := gcSizesFor(compiler, arch); s != nil {
   261  			return Sizes(s)
   262  		}
   263  	case "gccgo":
   264  		if s, ok := gccgoArchSizes[arch]; ok {
   265  			return Sizes(s)
   266  		}
   267  	}
   268  	return nil
   269  }
   270  
   271  // stdSizes is used if Config.Sizes == nil.
   272  var stdSizes = SizesFor("gc", "amd64")
   273  
   274  func (conf *Config) alignof(T Type) int64 {
   275  	f := stdSizes.Alignof
   276  	if conf.Sizes != nil {
   277  		f = conf.Sizes.Alignof
   278  	}
   279  	if a := f(T); a >= 1 {
   280  		return a
   281  	}
   282  	panic("implementation of alignof returned an alignment < 1")
   283  }
   284  
   285  func (conf *Config) offsetsof(T *Struct) []int64 {
   286  	var offsets []int64
   287  	if T.NumFields() > 0 {
   288  		// compute offsets on demand
   289  		f := stdSizes.Offsetsof
   290  		if conf.Sizes != nil {
   291  			f = conf.Sizes.Offsetsof
   292  		}
   293  		offsets = f(T.fields)
   294  		// sanity checks
   295  		if len(offsets) != T.NumFields() {
   296  			panic("implementation of offsetsof returned the wrong number of offsets")
   297  		}
   298  	}
   299  	return offsets
   300  }
   301  
   302  // offsetof returns the offset of the field specified via
   303  // the index sequence relative to T. All embedded fields
   304  // must be structs (rather than pointers to structs).
   305  // If the offset is too large (because T is too large),
   306  // the result is negative.
   307  func (conf *Config) offsetof(T Type, index []int) int64 {
   308  	var offs int64
   309  	for _, i := range index {
   310  		s := under(T).(*Struct)
   311  		d := conf.offsetsof(s)[i]
   312  		if d < 0 {
   313  			return -1
   314  		}
   315  		offs += d
   316  		if offs < 0 {
   317  			return -1
   318  		}
   319  		T = s.fields[i].typ
   320  	}
   321  	return offs
   322  }
   323  
   324  // sizeof returns the size of T.
   325  // If T is too large, the result is negative.
   326  func (conf *Config) sizeof(T Type) int64 {
   327  	f := stdSizes.Sizeof
   328  	if conf.Sizes != nil {
   329  		f = conf.Sizes.Sizeof
   330  	}
   331  	return f(T)
   332  }
   333  
   334  // align returns the smallest y >= x such that y % a == 0.
   335  // a must be within 1 and 8 and it must be a power of 2.
   336  // The result may be negative due to overflow.
   337  func align(x, a int64) int64 {
   338  	assert(x >= 0 && 1 <= a && a <= 8 && a&(a-1) == 0)
   339  	return (x + a - 1) &^ (a - 1)
   340  }
   341  

View as plain text