1 // Copyright 2017 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.
8 "cmd/compile/internal/base"
11 "internal/types/errors"
15 // Object represents an ir.Node, but without needing to import cmd/compile/internal/ir,
16 // which would cause an import cycle. The uses in other packages must type assert
17 // values of type Object to ir.Node or a more specific type.
18 type Object interface {
24 //go:generate stringer -type Kind -trimprefix T type.go
26 // Kind describes a kind of type.
65 // pseudo-types for literals
66 TIDEAL // untyped numeric constants
70 // pseudo-types used temporarily only during frame layout (CalcSize())
75 TSSA // internal types used by SSA backend (flags, memory, etc.)
76 TTUPLE // a pair of types, used by SSA backend
77 TRESULTS // multiple types; the result of calling a function or method, with a memory at the end.
82 // ChanDir is whether a channel can send, receive, or both.
85 func (c ChanDir) CanRecv() bool { return c&Crecv != 0 }
86 func (c ChanDir) CanSend() bool { return c&Csend != 0 }
90 // must match ../../../../reflect/type.go:/ChanDir
91 Crecv ChanDir = 1 << 0
92 Csend ChanDir = 1 << 1
93 Cboth ChanDir = Crecv | Csend
96 // Types stores pointers to predeclared named types.
98 // It also stores pointers to several special types:
99 // - Types[TANY] is the placeholder "any" type recognized by SubstArgTypes.
100 // - Types[TBLANK] represents the blank variable's type.
101 // - Types[TINTER] is the canonical "interface{}" type.
102 // - Types[TNIL] represents the predeclared "nil" value's type.
103 // - Types[TUNSAFEPTR] is package unsafe's Pointer type.
104 var Types [NTYPE]*Type
107 // Predeclared alias types. These are actually created as distinct
108 // defined types for better error messages, but are then specially
109 // treated as identical to their respective underlying types.
114 // Predeclared error interface type.
116 // Predeclared comparable interface type.
119 // Types to represent untyped string and boolean constants.
120 UntypedString = newType(TSTRING)
121 UntypedBool = newType(TBOOL)
123 // Types to represent untyped numeric constants.
124 UntypedInt = newType(TIDEAL)
125 UntypedRune = newType(TIDEAL)
126 UntypedFloat = newType(TIDEAL)
127 UntypedComplex = newType(TIDEAL)
130 // A Type represents a Go type.
132 // There may be multiple unnamed types with identical structure. However, there must
133 // be a unique Type object for each unique named (defined) type. After noding, a
134 // package-level type can be looked up by building its unique symbol sym (sym =
135 // package.Lookup(name)) and checking sym.Def. If sym.Def is non-nil, the type
136 // already exists at package scope and is available at sym.Def.(*ir.Name).Type().
137 // Local types (which may have the same name as a package-level type) are
138 // distinguished by the value of vargen.
140 // extra contains extra etype-specific fields.
141 // As an optimization, those etype-specific structs which contain exactly
142 // one pointer-shaped field are stored as values rather than pointers when possible.
148 // TINTER: *Interface
149 // TFUNCARGS: FuncArgs
150 // TCHANARGS: ChanArgs
158 // width is the width of this Type in bytes.
159 width int64 // valid if Align > 0
161 // list of base methods (excluding embedding)
163 // list of all methods (including embedding)
166 // canonical OTYPE node for a named type (should be an ir.Name node with same sym)
168 // the underlying type (type literal or predeclared type) for a defined type
171 // Cache of composite types, with this type being the element type.
173 ptr *Type // *T, or nil
174 slice *Type // []T, or nil
177 vargen int32 // unique name for OTYPE/ONAME
179 kind Kind // kind of type
180 align uint8 // the required alignment of this type, in bytes (0 means Width and Align have not yet been computed)
184 // For defined (named) generic types, a pointer to the list of type params
185 // (in order) of this type that need to be instantiated. For instantiated
186 // generic types, this is the targs used to instantiate them. These targs
187 // may be typeparams (for re-instantiated types such as Value[T2]) or
188 // concrete types (for fully instantiated types such as Value[int]).
189 // rparams is only set for named types that are generic or are fully
190 // instantiated from a generic type, and is otherwise set to nil.
191 // TODO(danscales): choose a better name.
195 func (*Type) CanBeAnSSAAux() {}
198 typeNotInHeap = 1 << iota // type cannot be heap allocated
199 typeNoalg // suppress hash and eq algorithm generation
200 typeDeferwidth // width computation has been deferred and type is on deferredTypeStack
202 typeIsShape // represents a set of closely related types, for generics
203 typeHasShape // there is a shape somewhere in the type
206 func (t *Type) NotInHeap() bool { return t.flags&typeNotInHeap != 0 }
207 func (t *Type) Noalg() bool { return t.flags&typeNoalg != 0 }
208 func (t *Type) Deferwidth() bool { return t.flags&typeDeferwidth != 0 }
209 func (t *Type) Recur() bool { return t.flags&typeRecur != 0 }
210 func (t *Type) IsShape() bool { return t.flags&typeIsShape != 0 }
211 func (t *Type) HasShape() bool { return t.flags&typeHasShape != 0 }
213 func (t *Type) SetNotInHeap(b bool) { t.flags.set(typeNotInHeap, b) }
214 func (t *Type) SetNoalg(b bool) { t.flags.set(typeNoalg, b) }
215 func (t *Type) SetDeferwidth(b bool) { t.flags.set(typeDeferwidth, b) }
216 func (t *Type) SetRecur(b bool) { t.flags.set(typeRecur, b) }
218 // Should always do SetHasShape(true) when doing SetIsShape(true).
219 func (t *Type) SetIsShape(b bool) { t.flags.set(typeIsShape, b) }
220 func (t *Type) SetHasShape(b bool) { t.flags.set(typeHasShape, b) }
222 // Kind returns the kind of type t.
223 func (t *Type) Kind() Kind { return t.kind }
225 // Sym returns the name of type t.
226 func (t *Type) Sym() *Sym {
233 // Underlying returns the underlying type of type t.
234 func (t *Type) Underlying() *Type { return t.underlying }
236 // Pos returns a position associated with t, if any.
237 // This should only be used for diagnostics.
238 func (t *Type) Pos() src.XPos {
245 func (t *Type) RParams() []*Type {
246 if t.rparams == nil {
252 func (t *Type) SetRParams(rparams []*Type) {
253 if len(rparams) == 0 {
254 base.Fatalf("Setting nil or zero-length rparams")
257 // HasShape should be set if any type argument is or has a shape type.
258 for _, rparam := range rparams {
259 if rparam.HasShape() {
266 // IsFullyInstantiated reports whether t is a fully instantiated generic type; i.e. an
267 // instantiated generic type where all type arguments are non-generic or fully
268 // instantiated generic types.
269 func (t *Type) IsFullyInstantiated() bool {
270 return len(t.RParams()) > 0
273 // Map contains Type fields specific to maps.
275 Key *Type // Key type
276 Elem *Type // Val (elem) type
278 Bucket *Type // internal struct type representing a hash bucket
281 // MapType returns t's extra map-specific fields.
282 func (t *Type) MapType() *Map {
284 return t.extra.(*Map)
287 // Forward contains Type fields specific to forward types.
288 type Forward struct {
289 Copyto []*Type // where to copy the eventual value to
290 Embedlineno src.XPos // first use of this type as an embedded type
293 // forwardType returns t's extra forward-type-specific fields.
294 func (t *Type) forwardType() *Forward {
296 return t.extra.(*Forward)
299 // Func contains Type fields specific to func types.
301 Receiver *Type // function receiver
302 Results *Type // function results
303 Params *Type // function params
305 // Argwid is the total width of the function receiver, params, and results.
306 // It gets calculated via a temporary TFUNCARGS type.
307 // Note that TFUNC's Width is Widthptr.
311 // funcType returns t's extra func-specific fields.
312 func (t *Type) funcType() *Func {
314 return t.extra.(*Func)
317 // StructType contains Type fields specific to struct types.
321 // Maps have three associated internal structs (see struct MapType).
322 // Map links such structs back to their map type.
325 Funarg Funarg // type of function arguments for arg struct
328 // Funarg records the kind of function argument
332 FunargNone Funarg = iota
333 FunargRcvr // receiver
334 FunargParams // input parameters
335 FunargResults // output results
336 FunargTparams // type params
339 // StructType returns t's extra struct-specific fields.
340 func (t *Type) StructType() *Struct {
342 return t.extra.(*Struct)
345 // Interface contains Type fields specific to interface types.
346 type Interface struct {
349 // Ptr contains Type fields specific to pointer types.
351 Elem *Type // element type
354 // ChanArgs contains Type fields specific to TCHANARGS types.
355 type ChanArgs struct {
356 T *Type // reference to a chan type whose elements need a width check
359 // // FuncArgs contains Type fields specific to TFUNCARGS types.
360 type FuncArgs struct {
361 T *Type // reference to a func type whose elements need a width check
364 // Chan contains Type fields specific to channel types.
366 Elem *Type // element type
367 Dir ChanDir // channel direction
370 // chanType returns t's extra channel-specific fields.
371 func (t *Type) chanType() *Chan {
373 return t.extra.(*Chan)
379 // Any tuple with a memory type must put that memory type second.
382 // Results are the output from calls that will be late-expanded.
383 type Results struct {
384 Types []*Type // Last element is memory output from call.
387 // Array contains Type fields specific to array types.
389 Elem *Type // element type
390 Bound int64 // number of elements; <0 if unknown yet
393 // Slice contains Type fields specific to slice types.
395 Elem *Type // element type
398 // A Field is a (Sym, Type) pairing along with some other information, and,
399 // depending on the context, is used to represent:
400 // - a field in a struct
401 // - a method in an interface or associated with a named type
402 // - a function parameter
406 Embedded uint8 // embedded field
410 // Name of field/method/parameter. Can be nil for interface fields embedded
411 // in interfaces and unnamed parameters.
413 Type *Type // field type
414 Note string // literal string annotation
416 // For fields that represent function parameters, Nname points to the
417 // associated ONAME Node. For fields that represent methods, Nname points to
418 // the function name node.
421 // Offset in bytes of this field or method within its enclosing struct
422 // or interface Type. Exception: if field is function receiver, arg or
423 // result, then this is BOGUS_FUNARG_OFFSET; types does not know the Abi.
428 fieldIsDDD = 1 << iota // field is ... argument
432 func (f *Field) IsDDD() bool { return f.flags&fieldIsDDD != 0 }
433 func (f *Field) Nointerface() bool { return f.flags&fieldNointerface != 0 }
435 func (f *Field) SetIsDDD(b bool) { f.flags.set(fieldIsDDD, b) }
436 func (f *Field) SetNointerface(b bool) { f.flags.set(fieldNointerface, b) }
438 // End returns the offset of the first byte immediately after this field.
439 func (f *Field) End() int64 {
440 return f.Offset + f.Type.width
443 // IsMethod reports whether f represents a method rather than a struct field.
444 func (f *Field) IsMethod() bool {
445 return f.Type.kind == TFUNC && f.Type.Recv() != nil
448 // fields is a pointer to a slice of *Field.
449 // This saves space in Types that do not have fields or methods
450 // compared to a simple slice of *Field.
455 // Slice returns the entries in f as a slice.
456 // Changes to the slice entries will be reflected in f.
457 func (f *fields) Slice() []*Field {
464 // Set sets f to a slice.
465 // This takes ownership of the slice.
466 func (f *fields) Set(s []*Field) {
470 // Copy s and take address of t rather than s to avoid
471 // allocation in the case where len(s) == 0.
477 // newType returns a new Type of the specified kind.
478 func newType(et Kind) *Type {
484 // TODO(josharian): lazily initialize some of these?
489 t.extra = new(Forward)
493 t.extra = new(Struct)
495 t.extra = new(Interface)
507 t.extra = new(Results)
512 // NewArray returns a new fixed-length array Type.
513 func NewArray(elem *Type, bound int64) *Type {
515 base.Fatalf("NewArray: invalid bound %v", bound)
518 t.extra = &Array{Elem: elem, Bound: bound}
525 // NewSlice returns the slice Type with element type elem.
526 func NewSlice(elem *Type) *Type {
527 if t := elem.cache.slice; t != nil {
528 if t.Elem() != elem {
529 base.Fatalf("elem mismatch")
531 if elem.HasShape() != t.HasShape() {
532 base.Fatalf("Incorrect HasShape flag for cached slice type")
538 t.extra = Slice{Elem: elem}
546 // NewChan returns a new chan Type with direction dir.
547 func NewChan(elem *Type, dir ChanDir) *Type {
558 func NewTuple(t1, t2 *Type) *Type {
560 t.extra.(*Tuple).first = t1
561 t.extra.(*Tuple).second = t2
562 if t1.HasShape() || t2.HasShape() {
568 func newResults(types []*Type) *Type {
569 t := newType(TRESULTS)
570 t.extra.(*Results).Types = types
574 func NewResults(types []*Type) *Type {
575 if len(types) == 1 && types[0] == TypeMem {
578 return newResults(types)
581 func newSSA(name string) *Type {
587 // NewMap returns a new map Type with key type k and element (aka value) type v.
588 func NewMap(k, v *Type) *Type {
593 if k.HasShape() || v.HasShape() {
599 // NewPtrCacheEnabled controls whether *T Types are cached in T.
600 // Caching is disabled just before starting the backend.
601 // This allows the backend to run concurrently.
602 var NewPtrCacheEnabled = true
604 // NewPtr returns the pointer type pointing to t.
605 func NewPtr(elem *Type) *Type {
607 base.Fatalf("NewPtr: pointer to elem Type is nil")
610 if t := elem.cache.ptr; t != nil {
611 if t.Elem() != elem {
612 base.Fatalf("NewPtr: elem mismatch")
614 if elem.HasShape() != t.HasShape() {
615 base.Fatalf("Incorrect HasShape flag for cached pointer type")
621 t.extra = Ptr{Elem: elem}
622 t.width = int64(PtrSize)
623 t.align = uint8(PtrSize)
624 if NewPtrCacheEnabled {
633 // NewChanArgs returns a new TCHANARGS type for channel type c.
634 func NewChanArgs(c *Type) *Type {
635 t := newType(TCHANARGS)
636 t.extra = ChanArgs{T: c}
640 // NewFuncArgs returns a new TFUNCARGS type for func type f.
641 func NewFuncArgs(f *Type) *Type {
642 t := newType(TFUNCARGS)
643 t.extra = FuncArgs{T: f}
647 func NewField(pos src.XPos, sym *Sym, typ *Type) *Field {
655 base.Fatalf("typ is nil")
660 // SubstAny walks t, replacing instances of "any" with successive
661 // elements removed from types. It returns the substituted type.
662 func SubstAny(t *Type, types *[]*Type) *Type {
669 // Leave the type unchanged.
672 if len(*types) == 0 {
673 base.Fatalf("SubstArgTypes: not enough argument types")
676 *types = (*types)[1:]
679 elem := SubstAny(t.Elem(), types)
680 if elem != t.Elem() {
682 t.extra = Ptr{Elem: elem}
686 elem := SubstAny(t.Elem(), types)
687 if elem != t.Elem() {
689 t.extra.(*Array).Elem = elem
693 elem := SubstAny(t.Elem(), types)
694 if elem != t.Elem() {
696 t.extra = Slice{Elem: elem}
700 elem := SubstAny(t.Elem(), types)
701 if elem != t.Elem() {
703 t.extra.(*Chan).Elem = elem
707 key := SubstAny(t.Key(), types)
708 elem := SubstAny(t.Elem(), types)
709 if key != t.Key() || elem != t.Elem() {
711 t.extra.(*Map).Key = key
712 t.extra.(*Map).Elem = elem
716 recvs := SubstAny(t.recvsTuple(), types)
717 params := SubstAny(t.paramsTuple(), types)
718 results := SubstAny(t.ResultsTuple(), types)
719 if recvs != t.recvsTuple() || params != t.paramsTuple() || results != t.ResultsTuple() {
721 t.funcType().Receiver = recvs
722 t.funcType().Results = results
723 t.funcType().Params = params
727 // Make a copy of all fields, including ones whose type does not change.
728 // This prevents aliasing across functions, which can lead to later
729 // fields getting their Offset incorrectly overwritten.
731 nfs := make([]*Field, len(fields))
732 for i, f := range fields {
733 nft := SubstAny(f.Type, types)
744 // copy returns a shallow copy of the Type.
745 func (t *Type) copy() *Type {
750 // copy any *T Extra fields, to avoid aliasing
756 x := *t.extra.(*Forward)
759 x := *t.extra.(*Func)
762 x := *t.extra.(*Struct)
765 x := *t.extra.(*Interface)
768 x := *t.extra.(*Chan)
771 x := *t.extra.(*Array)
773 case TTUPLE, TSSA, TRESULTS:
774 base.Fatalf("ssa types cannot be copied")
776 // TODO(mdempsky): Find out why this is necessary and explain.
777 if t.underlying == t {
783 func (f *Field) Copy() *Field {
788 func (t *Type) wantEtype(et Kind) {
790 base.Fatalf("want %v, but have %v", et, t)
794 func (t *Type) recvsTuple() *Type { return t.funcType().Receiver }
795 func (t *Type) paramsTuple() *Type { return t.funcType().Params }
797 // ResultTuple returns the result type of signature type t as a tuple.
798 // This can be used as the type of multi-valued call expressions.
799 func (t *Type) ResultsTuple() *Type { return t.funcType().Results }
801 // Recvs returns a slice of receiver parameters of signature type t.
802 // The returned slice always has length 0 or 1.
803 func (t *Type) Recvs() []*Field { return t.funcType().Receiver.Fields() }
805 // Params returns a slice of regular parameters of signature type t.
806 func (t *Type) Params() []*Field { return t.funcType().Params.Fields() }
808 // Results returns a slice of result parameters of signature type t.
809 func (t *Type) Results() []*Field { return t.funcType().Results.Fields() }
811 func (t *Type) NumRecvs() int { return t.funcType().Receiver.NumFields() }
812 func (t *Type) NumParams() int { return t.funcType().Params.NumFields() }
813 func (t *Type) NumResults() int { return t.funcType().Results.NumFields() }
815 // IsVariadic reports whether function type t is variadic.
816 func (t *Type) IsVariadic() bool {
818 return n > 0 && t.Param(n-1).IsDDD()
821 // Recv returns the receiver of function type t, if any.
822 func (t *Type) Recv() *Field {
824 if s.NumFields() == 0 {
830 // Param returns the i'th parameter of signature type t.
831 func (t *Type) Param(i int) *Field { return t.Params()[i] }
833 // Result returns the i'th result of signature type t.
834 func (t *Type) Result(i int) *Field { return t.Results()[i] }
836 // RecvsParamsResults stores the accessor functions for a function Type's
837 // receiver, parameters, and result parameters, in that order.
838 // It can be used to iterate over all of a function's parameter lists.
839 var RecvsParamsResults = [3]func(*Type) []*Field{
840 (*Type).Recvs, (*Type).Params, (*Type).Results,
843 // RecvsParams is like RecvsParamsResults, but omits result parameters.
844 var RecvsParams = [2]func(*Type) []*Field{
845 (*Type).Recvs, (*Type).Params,
848 // ParamsResults is like RecvsParamsResults, but omits receiver parameters.
849 var ParamsResults = [2]func(*Type) []*Field{
850 (*Type).Params, (*Type).Results,
853 // Key returns the key type of map type t.
854 func (t *Type) Key() *Type {
856 return t.extra.(*Map).Key
859 // Elem returns the type of elements of t.
860 // Usable with pointers, channels, arrays, slices, and maps.
861 func (t *Type) Elem() *Type {
864 return t.extra.(Ptr).Elem
866 return t.extra.(*Array).Elem
868 return t.extra.(Slice).Elem
870 return t.extra.(*Chan).Elem
872 return t.extra.(*Map).Elem
874 base.Fatalf("Type.Elem %s", t.kind)
878 // ChanArgs returns the channel type for TCHANARGS type t.
879 func (t *Type) ChanArgs() *Type {
880 t.wantEtype(TCHANARGS)
881 return t.extra.(ChanArgs).T
884 // FuncArgs returns the func type for TFUNCARGS type t.
885 func (t *Type) FuncArgs() *Type {
886 t.wantEtype(TFUNCARGS)
887 return t.extra.(FuncArgs).T
890 // IsFuncArgStruct reports whether t is a struct representing function parameters or results.
891 func (t *Type) IsFuncArgStruct() bool {
892 return t.kind == TSTRUCT && t.extra.(*Struct).Funarg != FunargNone
895 // Methods returns a pointer to the base methods (excluding embedding) for type t.
896 // These can either be concrete methods (for non-interface types) or interface
897 // methods (for interface types).
898 func (t *Type) Methods() []*Field {
899 return t.methods.Slice()
902 // AllMethods returns a pointer to all the methods (including embedding) for type t.
903 // For an interface type, this is the set of methods that are typically iterated
904 // over. For non-interface types, AllMethods() only returns a valid result after
905 // CalcMethods() has been called at least once.
906 func (t *Type) AllMethods() []*Field {
907 if t.kind == TINTER {
908 // Calculate the full method set of an interface type on the fly
909 // now, if not done yet.
912 return t.allMethods.Slice()
915 // SetMethods sets the direct method set for type t (i.e., *not*
916 // including promoted methods from embedded types).
917 func (t *Type) SetMethods(fs []*Field) {
921 // SetAllMethods sets the set of all methods for type t (i.e.,
922 // including promoted methods from embedded types).
923 func (t *Type) SetAllMethods(fs []*Field) {
927 // fields returns the fields of struct type t.
928 func (t *Type) fields() *fields {
930 return &t.extra.(*Struct).fields
933 // Field returns the i'th field of struct type t.
934 func (t *Type) Field(i int) *Field { return t.Fields()[i] }
936 // Fields returns a slice of containing all fields of
938 func (t *Type) Fields() []*Field { return t.fields().Slice() }
940 // setFields sets struct type t's fields to fields.
941 func (t *Type) setFields(fields []*Field) {
942 // If we've calculated the width of t before,
943 // then some other type such as a function signature
944 // might now have the wrong type.
945 // Rather than try to track and invalidate those,
946 // enforce that SetFields cannot be called once
947 // t's width has been calculated.
948 if t.widthCalculated() {
949 base.Fatalf("SetFields of %v: width previously calculated", t)
952 t.fields().Set(fields)
955 // SetInterface sets the base methods of an interface type t.
956 func (t *Type) SetInterface(methods []*Field) {
958 t.methods.Set(methods)
961 // ArgWidth returns the total aligned argument size for a function.
962 // It includes the receiver, parameters, and results.
963 func (t *Type) ArgWidth() int64 {
965 return t.extra.(*Func).Argwid
968 func (t *Type) Size() int64 {
979 func (t *Type) Alignment() int64 {
981 return int64(t.align)
984 func (t *Type) SimpleString() string {
985 return t.kind.String()
988 // Cmp is a comparison between values a and b.
1001 // Compare compares types for purposes of the SSA back
1002 // end, returning a Cmp (one of CMPlt, CMPeq, CMPgt).
1003 // The answers are correct for an optimizer
1004 // or code generator, but not necessarily typechecking.
1005 // The order chosen is arbitrary, only consistency and division
1006 // into equivalence classes (Types that compare CMPeq) matters.
1007 func (t *Type) Compare(x *Type) Cmp {
1014 func cmpForNe(x bool) Cmp {
1021 func (r *Sym) cmpsym(s *Sym) Cmp {
1031 // Fast sort, not pretty sort
1032 if len(r.Name) != len(s.Name) {
1033 return cmpForNe(len(r.Name) < len(s.Name))
1036 if len(r.Pkg.Prefix) != len(s.Pkg.Prefix) {
1037 return cmpForNe(len(r.Pkg.Prefix) < len(s.Pkg.Prefix))
1039 if r.Pkg.Prefix != s.Pkg.Prefix {
1040 return cmpForNe(r.Pkg.Prefix < s.Pkg.Prefix)
1043 if r.Name != s.Name {
1044 return cmpForNe(r.Name < s.Name)
1049 // cmp compares two *Types t and x, returning CMPlt,
1050 // CMPeq, CMPgt as t<x, t==x, t>x, for an arbitrary
1051 // and optimizer-centric notion of comparison.
1052 // TODO(josharian): make this safe for recursive interface types
1053 // and use in signatlist sorting. See issue 19869.
1054 func (t *Type) cmp(x *Type) Cmp {
1055 // This follows the structure of function identical in identity.go
1056 // with two exceptions.
1057 // 1. Symbols are compared more carefully because a <,=,> result is desired.
1058 // 2. Maps are treated specially to avoid endless recursion -- maps
1059 // contain an internal data type not expressible in Go source code.
1070 if t.kind != x.kind {
1071 return cmpForNe(t.kind < x.kind)
1074 if t.obj != nil || x.obj != nil {
1075 // Special case: we keep byte and uint8 separate
1076 // for error messages. Treat them as equal.
1079 if (t == Types[TUINT8] || t == ByteType) && (x == Types[TUINT8] || x == ByteType) {
1084 if (t == Types[RuneType.kind] || t == RuneType) && (x == Types[RuneType.kind] || x == RuneType) {
1089 // Make sure named any type matches any empty interface.
1090 if t == AnyType && x.IsEmptyInterface() || x == AnyType && t.IsEmptyInterface() {
1096 if c := t.Sym().cmpsym(x.Sym()); c != CMPeq {
1101 // Syms non-nil, if vargens match then equal.
1102 if t.vargen != x.vargen {
1103 return cmpForNe(t.vargen < x.vargen)
1107 // both syms nil, look at structure below.
1110 case TBOOL, TFLOAT32, TFLOAT64, TCOMPLEX64, TCOMPLEX128, TUNSAFEPTR, TUINTPTR,
1111 TINT8, TINT16, TINT32, TINT64, TINT, TUINT8, TUINT16, TUINT32, TUINT64, TUINT:
1115 tname := t.extra.(string)
1116 xname := x.extra.(string)
1117 // desire fast sorting, not pretty sorting.
1118 if len(tname) == len(xname) {
1127 if len(tname) > len(xname) {
1133 xtup := x.extra.(*Tuple)
1134 ttup := t.extra.(*Tuple)
1135 if c := ttup.first.Compare(xtup.first); c != CMPeq {
1138 return ttup.second.Compare(xtup.second)
1141 xResults := x.extra.(*Results)
1142 tResults := t.extra.(*Results)
1143 xl, tl := len(xResults.Types), len(tResults.Types)
1150 for i := 0; i < tl; i++ {
1151 if c := tResults.Types[i].Compare(xResults.Types[i]); c != CMPeq {
1158 if c := t.Key().cmp(x.Key()); c != CMPeq {
1161 return t.Elem().cmp(x.Elem())
1164 // No special cases for these, they are handled
1165 // by the general code after the switch.
1168 if t.StructType().Map == nil {
1169 if x.StructType().Map != nil {
1170 return CMPlt // nil < non-nil
1172 // to the fallthrough
1173 } else if x.StructType().Map == nil {
1174 return CMPgt // nil > non-nil
1175 } else if t.StructType().Map.MapType().Bucket == t {
1176 // Both have non-nil Map
1177 // Special case for Maps which include a recursive type where the recursion is not broken with a named type
1178 if x.StructType().Map.MapType().Bucket != x {
1179 return CMPlt // bucket maps are least
1181 return t.StructType().Map.cmp(x.StructType().Map)
1182 } else if x.StructType().Map.MapType().Bucket == x {
1183 return CMPgt // bucket maps are least
1184 } // If t != t.Map.Bucket, fall through to general case
1188 for i := 0; i < len(tfs) && i < len(xfs); i++ {
1189 t1, x1 := tfs[i], xfs[i]
1190 if t1.Embedded != x1.Embedded {
1191 return cmpForNe(t1.Embedded < x1.Embedded)
1193 if t1.Note != x1.Note {
1194 return cmpForNe(t1.Note < x1.Note)
1196 if c := t1.Sym.cmpsym(x1.Sym); c != CMPeq {
1199 if c := t1.Type.cmp(x1.Type); c != CMPeq {
1203 if len(tfs) != len(xfs) {
1204 return cmpForNe(len(tfs) < len(xfs))
1209 tfs := t.AllMethods()
1210 xfs := x.AllMethods()
1211 for i := 0; i < len(tfs) && i < len(xfs); i++ {
1212 t1, x1 := tfs[i], xfs[i]
1213 if c := t1.Sym.cmpsym(x1.Sym); c != CMPeq {
1216 if c := t1.Type.cmp(x1.Type); c != CMPeq {
1220 if len(tfs) != len(xfs) {
1221 return cmpForNe(len(tfs) < len(xfs))
1226 for _, f := range &RecvsParamsResults {
1227 // Loop over fields in structs, ignoring argument names.
1230 for i := 0; i < len(tfs) && i < len(xfs); i++ {
1233 if ta.IsDDD() != tb.IsDDD() {
1234 return cmpForNe(!ta.IsDDD())
1236 if c := ta.Type.cmp(tb.Type); c != CMPeq {
1240 if len(tfs) != len(xfs) {
1241 return cmpForNe(len(tfs) < len(xfs))
1247 if t.NumElem() != x.NumElem() {
1248 return cmpForNe(t.NumElem() < x.NumElem())
1252 if t.ChanDir() != x.ChanDir() {
1253 return cmpForNe(t.ChanDir() < x.ChanDir())
1257 e := fmt.Sprintf("Do not know how to compare %v with %v", t, x)
1261 // Common element type comparison for TARRAY, TCHAN, TPTR, and TSLICE.
1262 return t.Elem().cmp(x.Elem())
1265 // IsKind reports whether t is a Type of the specified kind.
1266 func (t *Type) IsKind(et Kind) bool {
1267 return t != nil && t.kind == et
1270 func (t *Type) IsBoolean() bool {
1271 return t.kind == TBOOL
1274 var unsignedEType = [...]Kind{
1288 // ToUnsigned returns the unsigned equivalent of integer type t.
1289 func (t *Type) ToUnsigned() *Type {
1291 base.Fatalf("unsignedType(%v)", t)
1293 return Types[unsignedEType[t.kind]]
1296 func (t *Type) IsInteger() bool {
1298 case TINT8, TUINT8, TINT16, TUINT16, TINT32, TUINT32, TINT64, TUINT64, TINT, TUINT, TUINTPTR:
1301 return t == UntypedInt || t == UntypedRune
1304 func (t *Type) IsSigned() bool {
1306 case TINT8, TINT16, TINT32, TINT64, TINT:
1312 func (t *Type) IsUnsigned() bool {
1314 case TUINT8, TUINT16, TUINT32, TUINT64, TUINT, TUINTPTR:
1320 func (t *Type) IsFloat() bool {
1321 return t.kind == TFLOAT32 || t.kind == TFLOAT64 || t == UntypedFloat
1324 func (t *Type) IsComplex() bool {
1325 return t.kind == TCOMPLEX64 || t.kind == TCOMPLEX128 || t == UntypedComplex
1328 // IsPtr reports whether t is a regular Go pointer type.
1329 // This does not include unsafe.Pointer.
1330 func (t *Type) IsPtr() bool {
1331 return t.kind == TPTR
1334 // IsPtrElem reports whether t is the element of a pointer (to t).
1335 func (t *Type) IsPtrElem() bool {
1336 return t.cache.ptr != nil
1339 // IsUnsafePtr reports whether t is an unsafe pointer.
1340 func (t *Type) IsUnsafePtr() bool {
1341 return t.kind == TUNSAFEPTR
1344 // IsUintptr reports whether t is a uintptr.
1345 func (t *Type) IsUintptr() bool {
1346 return t.kind == TUINTPTR
1349 // IsPtrShaped reports whether t is represented by a single machine pointer.
1350 // In addition to regular Go pointer types, this includes map, channel, and
1351 // function types and unsafe.Pointer. It does not include array or struct types
1352 // that consist of a single pointer shaped type.
1353 // TODO(mdempsky): Should it? See golang.org/issue/15028.
1354 func (t *Type) IsPtrShaped() bool {
1355 return t.kind == TPTR || t.kind == TUNSAFEPTR ||
1356 t.kind == TMAP || t.kind == TCHAN || t.kind == TFUNC
1359 // HasNil reports whether the set of values determined by t includes nil.
1360 func (t *Type) HasNil() bool {
1362 case TCHAN, TFUNC, TINTER, TMAP, TNIL, TPTR, TSLICE, TUNSAFEPTR:
1368 func (t *Type) IsString() bool {
1369 return t.kind == TSTRING
1372 func (t *Type) IsMap() bool {
1373 return t.kind == TMAP
1376 func (t *Type) IsChan() bool {
1377 return t.kind == TCHAN
1380 func (t *Type) IsSlice() bool {
1381 return t.kind == TSLICE
1384 func (t *Type) IsArray() bool {
1385 return t.kind == TARRAY
1388 func (t *Type) IsStruct() bool {
1389 return t.kind == TSTRUCT
1392 func (t *Type) IsInterface() bool {
1393 return t.kind == TINTER
1396 // IsEmptyInterface reports whether t is an empty interface type.
1397 func (t *Type) IsEmptyInterface() bool {
1398 return t.IsInterface() && len(t.AllMethods()) == 0
1401 // IsScalar reports whether 't' is a scalar Go type, e.g.
1402 // bool/int/float/complex. Note that struct and array types consisting
1403 // of a single scalar element are not considered scalar, likewise
1404 // pointer types are also not considered scalar.
1405 func (t *Type) IsScalar() bool {
1407 case TBOOL, TINT8, TUINT8, TINT16, TUINT16, TINT32,
1408 TUINT32, TINT64, TUINT64, TINT, TUINT,
1409 TUINTPTR, TCOMPLEX64, TCOMPLEX128, TFLOAT32, TFLOAT64:
1415 func (t *Type) PtrTo() *Type {
1419 func (t *Type) NumFields() int {
1420 if t.kind == TRESULTS {
1421 return len(t.extra.(*Results).Types)
1423 return len(t.Fields())
1425 func (t *Type) FieldType(i int) *Type {
1426 if t.kind == TTUPLE {
1429 return t.extra.(*Tuple).first
1431 return t.extra.(*Tuple).second
1433 panic("bad tuple index")
1436 if t.kind == TRESULTS {
1437 return t.extra.(*Results).Types[i]
1439 return t.Field(i).Type
1441 func (t *Type) FieldOff(i int) int64 {
1442 return t.Field(i).Offset
1444 func (t *Type) FieldName(i int) string {
1445 return t.Field(i).Sym.Name
1448 func (t *Type) NumElem() int64 {
1450 return t.extra.(*Array).Bound
1453 type componentsIncludeBlankFields bool
1456 IgnoreBlankFields componentsIncludeBlankFields = false
1457 CountBlankFields componentsIncludeBlankFields = true
1460 // NumComponents returns the number of primitive elements that compose t.
1461 // Struct and array types are flattened for the purpose of counting.
1462 // All other types (including string, slice, and interface types) count as one element.
1463 // If countBlank is IgnoreBlankFields, then blank struct fields
1464 // (and their comprised elements) are excluded from the count.
1465 // struct { x, y [3]int } has six components; [10]struct{ x, y string } has twenty.
1466 func (t *Type) NumComponents(countBlank componentsIncludeBlankFields) int64 {
1469 if t.IsFuncArgStruct() {
1470 base.Fatalf("NumComponents func arg struct")
1473 for _, f := range t.Fields() {
1474 if countBlank == IgnoreBlankFields && f.Sym.IsBlank() {
1477 n += f.Type.NumComponents(countBlank)
1481 return t.NumElem() * t.Elem().NumComponents(countBlank)
1486 // SoleComponent returns the only primitive component in t,
1487 // if there is exactly one. Otherwise, it returns nil.
1488 // Components are counted as in NumComponents, including blank fields.
1489 // Keep in sync with cmd/compile/internal/walk/convert.go:soleComponent.
1490 func (t *Type) SoleComponent() *Type {
1493 if t.IsFuncArgStruct() {
1494 base.Fatalf("SoleComponent func arg struct")
1496 if t.NumFields() != 1 {
1499 return t.Field(0).Type.SoleComponent()
1501 if t.NumElem() != 1 {
1504 return t.Elem().SoleComponent()
1509 // ChanDir returns the direction of a channel type t.
1510 // The direction will be one of Crecv, Csend, or Cboth.
1511 func (t *Type) ChanDir() ChanDir {
1513 return t.extra.(*Chan).Dir
1516 func (t *Type) IsMemory() bool {
1517 if t == TypeMem || t.kind == TTUPLE && t.extra.(*Tuple).second == TypeMem {
1520 if t.kind == TRESULTS {
1521 if types := t.extra.(*Results).Types; len(types) > 0 && types[len(types)-1] == TypeMem {
1527 func (t *Type) IsFlags() bool { return t == TypeFlags }
1528 func (t *Type) IsVoid() bool { return t == TypeVoid }
1529 func (t *Type) IsTuple() bool { return t.kind == TTUPLE }
1530 func (t *Type) IsResults() bool { return t.kind == TRESULTS }
1532 // IsUntyped reports whether t is an untyped type.
1533 func (t *Type) IsUntyped() bool {
1537 if t == UntypedString || t == UntypedBool {
1547 // HasPointers reports whether t contains a heap pointer.
1548 // Note that this function ignores pointers to not-in-heap types.
1549 func (t *Type) HasPointers() bool {
1550 return PtrDataSize(t) > 0
1555 // FakeRecvType returns the singleton type used for interface method receivers.
1556 func FakeRecvType() *Type {
1557 if recvType == nil {
1558 recvType = NewPtr(newType(TSTRUCT))
1563 func FakeRecv() *Field {
1564 return NewField(base.AutogeneratedPos, nil, FakeRecvType())
1568 // TSSA types. HasPointers assumes these are pointer-free.
1569 TypeInvalid = newSSA("invalid")
1570 TypeMem = newSSA("mem")
1571 TypeFlags = newSSA("flags")
1572 TypeVoid = newSSA("void")
1573 TypeInt128 = newSSA("int128")
1574 TypeResultMem = newResults([]*Type{TypeMem})
1578 TypeInt128.width = 16
1579 TypeInt128.align = 8
1582 // NewNamed returns a new named type for the given type name. obj should be an
1583 // ir.Name. The new type is incomplete (marked as TFORW kind), and the underlying
1584 // type should be set later via SetUnderlying(). References to the type are
1585 // maintained until the type is filled in, so those references can be updated when
1586 // the type is complete.
1587 func NewNamed(obj Object) *Type {
1590 if obj.Sym().Pkg == ShapePkg {
1597 // Obj returns the canonical type name node for a named type t, nil for an unnamed type.
1598 func (t *Type) Obj() Object {
1602 // typeGen tracks the number of function-scoped defined types that
1603 // have been declared. It's used to generate unique linker symbols for
1604 // their runtime type descriptors.
1607 // SetVargen assigns a unique generation number to type t, which must
1608 // be a defined type declared within function scope. The generation
1609 // number is used to distinguish it from other similarly spelled
1610 // defined types from the same package.
1612 // TODO(mdempsky): Come up with a better solution.
1613 func (t *Type) SetVargen() {
1614 base.Assertf(t.Sym() != nil, "SetVargen on anonymous type %v", t)
1615 base.Assertf(t.vargen == 0, "type %v already has Vargen %v", t, t.vargen)
1621 // SetUnderlying sets the underlying type of an incomplete type (i.e. type whose kind
1622 // is currently TFORW). SetUnderlying automatically updates any types that were waiting
1623 // for this type to be completed.
1624 func (t *Type) SetUnderlying(underlying *Type) {
1625 if underlying.kind == TFORW {
1626 // This type isn't computed yet; when it is, update n.
1627 underlying.forwardType().Copyto = append(underlying.forwardType().Copyto, t)
1631 ft := t.forwardType()
1633 // TODO(mdempsky): Fix Type rekinding.
1634 t.kind = underlying.kind
1635 t.extra = underlying.extra
1636 t.width = underlying.width
1637 t.align = underlying.align
1638 t.underlying = underlying.underlying
1640 if underlying.NotInHeap() {
1641 t.SetNotInHeap(true)
1643 if underlying.HasShape() {
1647 // spec: "The declared type does not inherit any methods bound
1648 // to the existing type, but the method set of an interface
1649 // type [...] remains unchanged."
1650 if t.IsInterface() {
1651 t.methods = underlying.methods
1652 t.allMethods = underlying.allMethods
1655 // Update types waiting on this type.
1656 for _, w := range ft.Copyto {
1660 // Double-check use of type as embedded type.
1661 if ft.Embedlineno.IsKnown() {
1662 if t.IsPtr() || t.IsUnsafePtr() {
1663 base.ErrorfAt(ft.Embedlineno, errors.InvalidPtrEmbed, "embedded type cannot be a pointer")
1668 func fieldsHasShape(fields []*Field) bool {
1669 for _, f := range fields {
1670 if f.Type != nil && f.Type.HasShape() {
1677 // newBasic returns a new basic type of the given kind.
1678 func newBasic(kind Kind, obj Object) *Type {
1684 // NewInterface returns a new interface for the given methods and
1685 // embedded types. Embedded types are specified as fields with no Sym.
1686 func NewInterface(methods []*Field) *Type {
1687 t := newType(TINTER)
1688 t.SetInterface(methods)
1689 for _, f := range methods {
1690 // f.Type could be nil for a broken interface declaration
1691 if f.Type != nil && f.Type.HasShape() {
1699 const BOGUS_FUNARG_OFFSET = -1000000000
1701 func unzeroFieldOffsets(f []*Field) {
1703 f[i].Offset = BOGUS_FUNARG_OFFSET // This will cause an explosion if it is not corrected
1707 // NewSignature returns a new function type for the given receiver,
1708 // parameters, and results, any of which may be nil.
1709 func NewSignature(recv *Field, params, results []*Field) *Type {
1712 recvs = []*Field{recv}
1718 funargs := func(fields []*Field, funarg Funarg) *Type {
1719 s := NewStruct(fields)
1720 s.StructType().Funarg = funarg
1725 recv.Offset = BOGUS_FUNARG_OFFSET
1727 unzeroFieldOffsets(params)
1728 unzeroFieldOffsets(results)
1729 ft.Receiver = funargs(recvs, FunargRcvr)
1730 ft.Params = funargs(params, FunargParams)
1731 ft.Results = funargs(results, FunargResults)
1732 if fieldsHasShape(recvs) || fieldsHasShape(params) || fieldsHasShape(results) {
1739 // NewStruct returns a new struct with the given fields.
1740 func NewStruct(fields []*Field) *Type {
1741 t := newType(TSTRUCT)
1743 if fieldsHasShape(fields) {
1752 IsComplex [NTYPE]bool
1753 IsSimple [NTYPE]bool
1756 var IsOrdered [NTYPE]bool
1758 // IsReflexive reports whether t has a reflexive equality operator.
1759 // That is, if x==x for all x of type t.
1760 func IsReflexive(t *Type) bool {
1788 return IsReflexive(t.Elem())
1791 for _, t1 := range t.Fields() {
1792 if !IsReflexive(t1.Type) {
1799 base.Fatalf("bad type for map key: %v", t)
1804 // Can this type be stored directly in an interface word?
1805 // Yes, if the representation is a single pointer.
1806 func IsDirectIface(t *Type) bool {
1809 // Pointers to notinheap types must be stored indirectly. See issue 42076.
1810 return !t.Elem().NotInHeap()
1818 // Array of 1 direct iface type can be direct.
1819 return t.NumElem() == 1 && IsDirectIface(t.Elem())
1822 // Struct with 1 field of direct iface type can be direct.
1823 return t.NumFields() == 1 && IsDirectIface(t.Field(0).Type)
1829 // IsInterfaceMethod reports whether (field) m is
1830 // an interface method. Such methods have the
1831 // special receiver type types.FakeRecvType().
1832 func IsInterfaceMethod(f *Type) bool {
1833 return f.Recv().Type == FakeRecvType()
1836 // IsMethodApplicable reports whether method m can be called on a
1837 // value of type t. This is necessary because we compute a single
1838 // method set for both T and *T, but some *T methods are not
1839 // applicable to T receivers.
1840 func IsMethodApplicable(t *Type, m *Field) bool {
1841 return t.IsPtr() || !m.Type.Recv().Type.IsPtr() || IsInterfaceMethod(m.Type) || m.Embedded == 2
1844 // IsRuntimePkg reports whether p is package runtime.
1845 func IsRuntimePkg(p *Pkg) bool {
1846 if base.Flag.CompilingRuntime && p == LocalPkg {
1849 return p.Path == "runtime"
1852 // IsReflectPkg reports whether p is package reflect.
1853 func IsReflectPkg(p *Pkg) bool {
1854 return p.Path == "reflect"
1857 // IsNoInstrumentPkg reports whether p is a package that
1858 // should not be instrumented.
1859 func IsNoInstrumentPkg(p *Pkg) bool {
1860 for _, np := range base.NoInstrumentPkgs {
1868 // IsNoRacePkg reports whether p is a package that
1869 // should not be race instrumented.
1870 func IsNoRacePkg(p *Pkg) bool {
1871 for _, np := range base.NoRacePkgs {
1879 // ReceiverBaseType returns the underlying type, if any,
1880 // that owns methods with receiver parameter t.
1881 // The result is either a named type or an anonymous struct.
1882 func ReceiverBaseType(t *Type) *Type {
1887 // Strip away pointer if it's there.
1898 // Must be a named type or anonymous struct.
1899 if t.Sym() == nil && !t.IsStruct() {
1904 if IsSimple[t.Kind()] {
1908 case TARRAY, TCHAN, TFUNC, TMAP, TSLICE, TSTRING, TSTRUCT:
1914 func FloatForComplex(t *Type) *Type {
1917 return Types[TFLOAT32]
1919 return Types[TFLOAT64]
1921 base.Fatalf("unexpected type: %v", t)
1925 func ComplexForFloat(t *Type) *Type {
1928 return Types[TCOMPLEX64]
1930 return Types[TCOMPLEX128]
1932 base.Fatalf("unexpected type: %v", t)
1936 func TypeSym(t *Type) *Sym {
1937 return TypeSymLookup(TypeSymName(t))
1940 func TypeSymLookup(name string) *Sym {
1942 s := typepkg.Lookup(name)
1947 func TypeSymName(t *Type) string {
1948 name := t.LinkString()
1949 // Use a separate symbol name for Noalg types for #17752.
1950 if TypeHasNoAlg(t) {
1951 name = "noalg." + name
1956 // Fake package for runtime type info (headers)
1957 // Don't access directly, use typeLookup below.
1959 typepkgmu sync.Mutex // protects typepkg lookups
1960 typepkg = NewPkg("type", "type")
1963 var SimType [NTYPE]Kind
1965 // Fake package for shape types (see typecheck.Shapify()).
1966 var ShapePkg = NewPkg("go.shape", "go.shape")