Source file src/cmd/compile/internal/noder/reader.go

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package noder
     6  
     7  import (
     8  	"encoding/hex"
     9  	"fmt"
    10  	"go/constant"
    11  	"internal/buildcfg"
    12  	"internal/pkgbits"
    13  	"path/filepath"
    14  	"slices"
    15  	"strings"
    16  
    17  	"cmd/compile/internal/base"
    18  	"cmd/compile/internal/dwarfgen"
    19  	"cmd/compile/internal/inline"
    20  	"cmd/compile/internal/inline/interleaved"
    21  	"cmd/compile/internal/ir"
    22  	"cmd/compile/internal/midway"
    23  	"cmd/compile/internal/objw"
    24  	"cmd/compile/internal/pgoir"
    25  	"cmd/compile/internal/reflectdata"
    26  	"cmd/compile/internal/staticinit"
    27  	"cmd/compile/internal/typecheck"
    28  	"cmd/compile/internal/types"
    29  	"cmd/internal/hash"
    30  	"cmd/internal/obj"
    31  	"cmd/internal/objabi"
    32  	"cmd/internal/src"
    33  )
    34  
    35  // This file implements cmd/compile backend's reader for the Unified
    36  // IR export data.
    37  
    38  // A pkgReader reads Unified IR export data.
    39  type pkgReader struct {
    40  	pkgbits.PkgDecoder
    41  
    42  	// Indices for encoded things; lazily populated as needed.
    43  	//
    44  	// Note: Objects (i.e., ir.Names) are lazily instantiated by
    45  	// populating their types.Sym.Def; see objReader below.
    46  
    47  	posBases []*src.PosBase
    48  	pkgs     []*types.Pkg
    49  	typs     []*types.Type
    50  
    51  	// offset for rewriting the given (absolute!) index into the output,
    52  	// but bitwise inverted so we can detect if we're missing the entry
    53  	// or not.
    54  	newindex []index
    55  }
    56  
    57  func newPkgReader(pr pkgbits.PkgDecoder) *pkgReader {
    58  	return &pkgReader{
    59  		PkgDecoder: pr,
    60  
    61  		posBases: make([]*src.PosBase, pr.NumElems(pkgbits.SectionPosBase)),
    62  		pkgs:     make([]*types.Pkg, pr.NumElems(pkgbits.SectionPkg)),
    63  		typs:     make([]*types.Type, pr.NumElems(pkgbits.SectionType)),
    64  
    65  		newindex: make([]index, pr.TotalElems()),
    66  	}
    67  }
    68  
    69  // A pkgReaderIndex compactly identifies an index (and its
    70  // corresponding dictionary) within a package's export data.
    71  type pkgReaderIndex struct {
    72  	pr        *pkgReader
    73  	idx       index
    74  	dict      *readerDict
    75  	methodSym *types.Sym
    76  
    77  	synthetic func(pos src.XPos, r *reader)
    78  }
    79  
    80  func (pri pkgReaderIndex) asReader(k pkgbits.SectionKind, marker pkgbits.SyncMarker) *reader {
    81  	if pri.synthetic != nil {
    82  		return &reader{synthetic: pri.synthetic}
    83  	}
    84  
    85  	r := pri.pr.newReader(k, pri.idx, marker)
    86  	r.dict = pri.dict
    87  	r.methodSym = pri.methodSym
    88  	return r
    89  }
    90  
    91  func (pr *pkgReader) newReader(k pkgbits.SectionKind, idx index, marker pkgbits.SyncMarker) *reader {
    92  	return &reader{
    93  		Decoder: pr.NewDecoder(k, idx, marker),
    94  		p:       pr,
    95  	}
    96  }
    97  
    98  // A reader provides APIs for reading an individual element.
    99  type reader struct {
   100  	pkgbits.Decoder
   101  
   102  	p *pkgReader
   103  
   104  	dict *readerDict
   105  
   106  	// funcLitGen is a counter for closure names.
   107  	funcLitGen int
   108  	// rangeLitGen is a counter for range func closure names.
   109  	rangeLitGen int
   110  
   111  	// TODO(mdempsky): The state below is all specific to reading
   112  	// function bodies. It probably makes sense to split it out
   113  	// separately so that it doesn't take up space in every reader
   114  	// instance.
   115  
   116  	curfn       *ir.Func
   117  	locals      []*ir.Name
   118  	closureVars []*ir.Name
   119  
   120  	// funarghack is used during inlining to suppress setting
   121  	// Field.Nname to the inlined copies of the parameters. This is
   122  	// necessary because we reuse the same types.Type as the original
   123  	// function, and most of the compiler still relies on field.Nname to
   124  	// find parameters/results.
   125  	funarghack bool
   126  
   127  	// methodSym is the name of method's name, if reading a method.
   128  	// It's nil if reading a normal function or closure body.
   129  	methodSym *types.Sym
   130  
   131  	// dictParam is the .dict param, if any.
   132  	dictParam *ir.Name
   133  
   134  	// synthetic is a callback function to construct a synthetic
   135  	// function body. It's used for creating the bodies of function
   136  	// literals used to curry arguments to shaped functions.
   137  	synthetic func(pos src.XPos, r *reader)
   138  
   139  	// scopeVars is a stack tracking the number of variables declared in
   140  	// the current function at the moment each open scope was opened.
   141  	scopeVars         []int
   142  	marker            dwarfgen.ScopeMarker
   143  	lastCloseScopePos src.XPos
   144  
   145  	// === details for handling inline body expansion ===
   146  
   147  	// If we're reading in a function body because of inlining, this is
   148  	// the call that we're inlining for.
   149  	inlCaller    *ir.Func
   150  	inlCall      *ir.CallExpr
   151  	inlFunc      *ir.Func
   152  	inlTreeIndex int
   153  	inlPosBases  map[*src.PosBase]*src.PosBase
   154  
   155  	// suppressInlPos tracks whether position base rewriting for
   156  	// inlining should be suppressed. See funcLit.
   157  	suppressInlPos int
   158  
   159  	delayResults bool
   160  
   161  	// Label to return to.
   162  	retlabel *types.Sym
   163  }
   164  
   165  // A readerDict represents an instantiated "compile-time dictionary,"
   166  // used for resolving any derived types needed for instantiating a
   167  // generic object.
   168  //
   169  // A compile-time dictionary can either be "shaped" or "non-shaped."
   170  // Shaped compile-time dictionaries are only used for instantiating
   171  // shaped type definitions and function bodies, while non-shaped
   172  // compile-time dictionaries are used for instantiating runtime
   173  // dictionaries.
   174  type readerDict struct {
   175  	shaped bool // whether this is a shaped dictionary
   176  
   177  	// baseSym is the symbol for the object this dictionary belongs to.
   178  	// If the object is an instantiated function or defined type, then
   179  	// baseSym is the mangled symbol, including any type arguments.
   180  	baseSym *types.Sym
   181  
   182  	// For non-shaped dictionaries, shapedObj is a reference to the
   183  	// corresponding shaped object (always a function or defined type).
   184  	shapedObj *ir.Name
   185  
   186  	// targs holds the implicit and explicit type arguments in use for
   187  	// reading the current object. For example:
   188  	//
   189  	//	func F[T any]() {
   190  	//		type X[U any] struct { t T; u U }
   191  	//		var _ X[string]
   192  	//	}
   193  	//
   194  	//	var _ = F[int]
   195  	//
   196  	// While instantiating F[int], we need to in turn instantiate
   197  	// X[string]. [int] and [string] are explicit type arguments for F
   198  	// and X, respectively; but [int] is also the implicit type
   199  	// arguments for X.
   200  	//
   201  	// (As an analogy to function literals, explicits are the function
   202  	// literal's formal parameters, while implicits are variables
   203  	// captured by the function literal.)
   204  	targs []*types.Type
   205  
   206  	// implicits counts how many of types within targs are implicit type
   207  	// arguments; the rest are explicit.
   208  	implicits int
   209  	// receivers counts how many of types within targs are receiver type
   210  	// arguments; they are explicit.
   211  	receivers int
   212  
   213  	derived      []derivedInfo // reloc index of the derived type's descriptor
   214  	derivedTypes []*types.Type // slice of previously computed derived types
   215  
   216  	// These slices correspond to entries in the runtime dictionary.
   217  	typeParamMethodExprs []readerMethodExprInfo
   218  	subdicts             []objInfo
   219  	rtypes               []typeInfo
   220  	itabs                []itabInfo
   221  }
   222  
   223  type readerMethodExprInfo struct {
   224  	typeParamIdx int
   225  	method       *types.Sym
   226  }
   227  
   228  func setType(n ir.Node, typ *types.Type) {
   229  	n.SetType(typ)
   230  	n.SetTypecheck(1)
   231  }
   232  
   233  func setValue(name *ir.Name, val constant.Value) {
   234  	name.SetVal(val)
   235  	name.Defn = nil
   236  }
   237  
   238  // @@@ Positions
   239  
   240  // pos reads a position from the bitstream.
   241  func (r *reader) pos() src.XPos {
   242  	return base.Ctxt.PosTable.XPos(r.pos0())
   243  }
   244  
   245  // origPos reads a position from the bitstream, and returns both the
   246  // original raw position and an inlining-adjusted position.
   247  func (r *reader) origPos() (origPos, inlPos src.XPos) {
   248  	r.suppressInlPos++
   249  	origPos = r.pos()
   250  	r.suppressInlPos--
   251  	inlPos = r.inlPos(origPos)
   252  	return
   253  }
   254  
   255  func (r *reader) pos0() src.Pos {
   256  	r.Sync(pkgbits.SyncPos)
   257  	if !r.Bool() {
   258  		return src.NoPos
   259  	}
   260  
   261  	posBase := r.posBase()
   262  	line := r.Uint()
   263  	col := r.Uint()
   264  	return src.MakePos(posBase, line, col)
   265  }
   266  
   267  // posBase reads a position base from the bitstream.
   268  func (r *reader) posBase() *src.PosBase {
   269  	return r.inlPosBase(r.p.posBaseIdx(r.Reloc(pkgbits.SectionPosBase)))
   270  }
   271  
   272  // posBaseIdx returns the specified position base, reading it first if
   273  // needed.
   274  func (pr *pkgReader) posBaseIdx(idx index) *src.PosBase {
   275  	if b := pr.posBases[idx]; b != nil {
   276  		return b
   277  	}
   278  
   279  	r := pr.newReader(pkgbits.SectionPosBase, idx, pkgbits.SyncPosBase)
   280  	var b *src.PosBase
   281  
   282  	absFilename := r.String()
   283  	filename := absFilename
   284  
   285  	// For build artifact stability, the export data format only
   286  	// contains the "absolute" filename as returned by objabi.AbsFile.
   287  	// However, some tests (e.g., test/run.go's asmcheck tests) expect
   288  	// to see the full, original filename printed out. Re-expanding
   289  	// "$GOROOT" to buildcfg.GOROOT is a close-enough approximation to
   290  	// satisfy this.
   291  	//
   292  	// The export data format only ever uses slash paths
   293  	// (for cross-operating-system reproducible builds),
   294  	// but error messages need to use native paths (backslash on Windows)
   295  	// as if they had been specified on the command line.
   296  	// (The go command always passes native paths to the compiler.)
   297  	const dollarGOROOT = "$GOROOT"
   298  	if buildcfg.GOROOT != "" && strings.HasPrefix(filename, dollarGOROOT) {
   299  		filename = filepath.FromSlash(buildcfg.GOROOT + filename[len(dollarGOROOT):])
   300  	}
   301  
   302  	if r.Bool() {
   303  		b = src.NewFileBase(filename, absFilename)
   304  	} else {
   305  		pos := r.pos0()
   306  		line := r.Uint()
   307  		col := r.Uint()
   308  		b = src.NewLinePragmaBase(pos, filename, absFilename, line, col)
   309  	}
   310  
   311  	pr.posBases[idx] = b
   312  	return b
   313  }
   314  
   315  // inlPosBase returns the inlining-adjusted src.PosBase corresponding
   316  // to oldBase, which must be a non-inlined position. When not
   317  // inlining, this is just oldBase.
   318  func (r *reader) inlPosBase(oldBase *src.PosBase) *src.PosBase {
   319  	if index := oldBase.InliningIndex(); index >= 0 {
   320  		base.Fatalf("oldBase %v already has inlining index %v", oldBase, index)
   321  	}
   322  
   323  	if r.inlCall == nil || r.suppressInlPos != 0 {
   324  		return oldBase
   325  	}
   326  
   327  	if newBase, ok := r.inlPosBases[oldBase]; ok {
   328  		return newBase
   329  	}
   330  
   331  	newBase := src.NewInliningBase(oldBase, r.inlTreeIndex)
   332  	r.inlPosBases[oldBase] = newBase
   333  	return newBase
   334  }
   335  
   336  // inlPos returns the inlining-adjusted src.XPos corresponding to
   337  // xpos, which must be a non-inlined position. When not inlining, this
   338  // is just xpos.
   339  func (r *reader) inlPos(xpos src.XPos) src.XPos {
   340  	pos := base.Ctxt.PosTable.Pos(xpos)
   341  	pos.SetBase(r.inlPosBase(pos.Base()))
   342  	return base.Ctxt.PosTable.XPos(pos)
   343  }
   344  
   345  // @@@ Packages
   346  
   347  // pkg reads a package reference from the bitstream.
   348  func (r *reader) pkg() *types.Pkg {
   349  	r.Sync(pkgbits.SyncPkg)
   350  	return r.p.pkgIdx(r.Reloc(pkgbits.SectionPkg))
   351  }
   352  
   353  // pkgIdx returns the specified package from the export data, reading
   354  // it first if needed.
   355  func (pr *pkgReader) pkgIdx(idx index) *types.Pkg {
   356  	if pkg := pr.pkgs[idx]; pkg != nil {
   357  		return pkg
   358  	}
   359  
   360  	pkg := pr.newReader(pkgbits.SectionPkg, idx, pkgbits.SyncPkgDef).doPkg()
   361  	pr.pkgs[idx] = pkg
   362  	return pkg
   363  }
   364  
   365  // doPkg reads a package definition from the bitstream.
   366  func (r *reader) doPkg() *types.Pkg {
   367  	path := r.String()
   368  	switch path {
   369  	case "":
   370  		path = r.p.PkgPath()
   371  	case "builtin":
   372  		return types.BuiltinPkg
   373  	case "unsafe":
   374  		return types.UnsafePkg
   375  	}
   376  
   377  	name := r.String()
   378  
   379  	pkg := types.NewPkg(path, "")
   380  
   381  	if pkg.Name == "" {
   382  		pkg.Name = name
   383  	} else {
   384  		base.Assertf(pkg.Name == name, "package %q has name %q, but want %q", pkg.Path, pkg.Name, name)
   385  	}
   386  
   387  	return pkg
   388  }
   389  
   390  // @@@ Types
   391  
   392  func (r *reader) typ() *types.Type {
   393  	return r.typWrapped(true)
   394  }
   395  
   396  // typWrapped is like typ, but allows suppressing generation of
   397  // unnecessary wrappers as a compile-time optimization.
   398  func (r *reader) typWrapped(wrapped bool) *types.Type {
   399  	return r.p.typIdx(r.typInfo(), r.dict, wrapped)
   400  }
   401  
   402  func (r *reader) typInfo() typeInfo {
   403  	r.Sync(pkgbits.SyncType)
   404  	if r.Bool() {
   405  		return typeInfo{idx: index(r.Len()), derived: true}
   406  	}
   407  	return typeInfo{idx: r.Reloc(pkgbits.SectionType), derived: false}
   408  }
   409  
   410  // typListIdx returns a list of the specified types, resolving derived
   411  // types within the given dictionary.
   412  func (pr *pkgReader) typListIdx(infos []typeInfo, dict *readerDict) []*types.Type {
   413  	typs := make([]*types.Type, len(infos))
   414  	for i, info := range infos {
   415  		typs[i] = pr.typIdx(info, dict, true)
   416  	}
   417  	return typs
   418  }
   419  
   420  // typIdx returns the specified type. If info specifies a derived
   421  // type, it's resolved within the given dictionary. If wrapped is
   422  // true, then method wrappers will be generated, if appropriate.
   423  func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict, wrapped bool) *types.Type {
   424  	idx := info.idx
   425  	var where **types.Type
   426  	if info.derived {
   427  		where = &dict.derivedTypes[idx]
   428  		idx = dict.derived[idx].idx
   429  	} else {
   430  		where = &pr.typs[idx]
   431  	}
   432  
   433  	if typ := *where; typ != nil {
   434  		return typ
   435  	}
   436  
   437  	r := pr.newReader(pkgbits.SectionType, idx, pkgbits.SyncTypeIdx)
   438  	r.dict = dict
   439  
   440  	typ := r.doTyp()
   441  	if typ == nil {
   442  		base.Fatalf("doTyp returned nil for info=%v", info)
   443  	}
   444  
   445  	// For recursive type declarations involving interfaces and aliases,
   446  	// above r.doTyp() call may have already set pr.typs[idx], so just
   447  	// double check and return the type.
   448  	//
   449  	// Example:
   450  	//
   451  	//     type F = func(I)
   452  	//
   453  	//     type I interface {
   454  	//         m(F)
   455  	//     }
   456  	//
   457  	// The writer writes data types in following index order:
   458  	//
   459  	//     0: func(I)
   460  	//     1: I
   461  	//     2: interface{m(func(I))}
   462  	//
   463  	// The reader resolves it in following index order:
   464  	//
   465  	//     0 -> 1 -> 2 -> 0 -> 1
   466  	//
   467  	// and can divide in logically 2 steps:
   468  	//
   469  	//  - 0 -> 1     : first time the reader reach type I,
   470  	//                 it creates new named type with symbol I.
   471  	//
   472  	//  - 2 -> 0 -> 1: the reader ends up reaching symbol I again,
   473  	//                 now the symbol I was setup in above step, so
   474  	//                 the reader just return the named type.
   475  	//
   476  	// Now, the functions called return, the pr.typs looks like below:
   477  	//
   478  	//  - 0 -> 1 -> 2 -> 0 : [<T> I <T>]
   479  	//  - 0 -> 1 -> 2      : [func(I) I <T>]
   480  	//  - 0 -> 1           : [func(I) I interface { "".m(func("".I)) }]
   481  	//
   482  	// The idx 1, corresponding with type I was resolved successfully
   483  	// after r.doTyp() call.
   484  
   485  	if prev := *where; prev != nil {
   486  		return prev
   487  	}
   488  
   489  	if wrapped {
   490  		// Only cache if we're adding wrappers, so that other callers that
   491  		// find a cached type know it was wrapped.
   492  		*where = typ
   493  
   494  		r.needWrapper(typ)
   495  	}
   496  
   497  	if !typ.IsUntyped() {
   498  		types.CheckSize(typ)
   499  	}
   500  
   501  	return typ
   502  }
   503  
   504  func (r *reader) doTyp() *types.Type {
   505  	switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag {
   506  	default:
   507  		panic(fmt.Sprintf("unexpected type: %v", tag))
   508  
   509  	case pkgbits.TypeBasic:
   510  		return *basics[r.Len()]
   511  
   512  	case pkgbits.TypeNamed:
   513  		obj := r.obj()
   514  		assert(obj.Op() == ir.OTYPE)
   515  		return obj.Type()
   516  
   517  	case pkgbits.TypeTypeParam:
   518  		return r.dict.targs[r.Len()]
   519  
   520  	case pkgbits.TypeArray:
   521  		len := int64(r.Uint64())
   522  		return types.NewArray(r.typ(), len)
   523  	case pkgbits.TypeChan:
   524  		dir := dirs[r.Len()]
   525  		return types.NewChan(r.typ(), dir)
   526  	case pkgbits.TypeMap:
   527  		return types.NewMap(r.typ(), r.typ())
   528  	case pkgbits.TypePointer:
   529  		return types.NewPtr(r.typ())
   530  	case pkgbits.TypeSignature:
   531  		return r.signature(nil)
   532  	case pkgbits.TypeSlice:
   533  		return types.NewSlice(r.typ())
   534  	case pkgbits.TypeStruct:
   535  		return r.structType()
   536  	case pkgbits.TypeInterface:
   537  		return r.interfaceType()
   538  	case pkgbits.TypeUnion:
   539  		return r.unionType()
   540  	}
   541  }
   542  
   543  func (r *reader) unionType() *types.Type {
   544  	// In the types1 universe, we only need to handle value types.
   545  	// Impure interfaces (i.e., interfaces with non-trivial type sets
   546  	// like "int | string") can only appear as type parameter bounds,
   547  	// and this is enforced by the types2 type checker.
   548  	//
   549  	// However, type unions can still appear in pure interfaces if the
   550  	// type union is equivalent to "any". E.g., typeparam/issue52124.go
   551  	// declares variables with the type "interface { any | int }".
   552  	//
   553  	// To avoid needing to represent type unions in types1 (since we
   554  	// don't have any uses for that today anyway), we simply fold them
   555  	// to "any".
   556  
   557  	// TODO(mdempsky): Restore consistency check to make sure folding to
   558  	// "any" is safe. This is unfortunately tricky, because a pure
   559  	// interface can reference impure interfaces too, including
   560  	// cyclically (#60117).
   561  	if false {
   562  		pure := false
   563  		for i, n := 0, r.Len(); i < n; i++ {
   564  			_ = r.Bool() // tilde
   565  			term := r.typ()
   566  			if term.IsEmptyInterface() {
   567  				pure = true
   568  			}
   569  		}
   570  		if !pure {
   571  			base.Fatalf("impure type set used in value type")
   572  		}
   573  	}
   574  
   575  	return types.Types[types.TINTER]
   576  }
   577  
   578  func (r *reader) interfaceType() *types.Type {
   579  	nmethods, nembeddeds := r.Len(), r.Len()
   580  	implicit := nmethods == 0 && nembeddeds == 1 && r.Bool()
   581  	assert(!implicit) // implicit interfaces only appear in constraints
   582  
   583  	fields := make([]*types.Field, nmethods+nembeddeds)
   584  	methods, embeddeds := fields[:nmethods], fields[nmethods:]
   585  
   586  	for i := range methods {
   587  		methods[i] = types.NewField(r.pos(), r.selector(), r.signature(types.FakeRecv()))
   588  	}
   589  	for i := range embeddeds {
   590  		embeddeds[i] = types.NewField(src.NoXPos, nil, r.typ())
   591  	}
   592  
   593  	if len(fields) == 0 {
   594  		return types.Types[types.TINTER] // empty interface
   595  	}
   596  	return types.NewInterface(fields)
   597  }
   598  
   599  func (r *reader) structType() *types.Type {
   600  	fields := make([]*types.Field, r.Len())
   601  	for i := range fields {
   602  		field := types.NewField(r.pos(), r.selector(), r.typ())
   603  		field.Note = r.String()
   604  		if r.Bool() {
   605  			field.Embedded = 1
   606  		}
   607  		fields[i] = field
   608  	}
   609  	return types.NewStruct(fields)
   610  }
   611  
   612  func (r *reader) signature(recv *types.Field) *types.Type {
   613  	r.Sync(pkgbits.SyncSignature)
   614  
   615  	params := r.params()
   616  	results := r.params()
   617  	if r.Bool() { // variadic
   618  		params[len(params)-1].SetIsDDD(true)
   619  	}
   620  
   621  	return types.NewSignature(recv, params, results)
   622  }
   623  
   624  func (r *reader) params() []*types.Field {
   625  	r.Sync(pkgbits.SyncParams)
   626  	params := make([]*types.Field, r.Len())
   627  	for i := range params {
   628  		params[i] = r.param()
   629  	}
   630  	return params
   631  }
   632  
   633  func (r *reader) param() *types.Field {
   634  	r.Sync(pkgbits.SyncParam)
   635  	return types.NewField(r.pos(), r.localIdent(), r.typ())
   636  }
   637  
   638  // @@@ Objects
   639  
   640  // objReader maps qualified identifiers (represented as *types.Sym) to
   641  // a pkgReader and corresponding index that can be used for reading
   642  // that object's definition.
   643  var objReader = map[*types.Sym]pkgReaderIndex{}
   644  
   645  // obj reads an instantiated object reference from the bitstream.
   646  func (r *reader) obj() ir.Node {
   647  	return r.p.objInstIdx(r.objInfo(), r.dict, false)
   648  }
   649  
   650  // objInfo reads an instantiated object reference from the bitstream
   651  // and returns the encoded reference to it, without instantiating it.
   652  func (r *reader) objInfo() objInfo {
   653  	r.Sync(pkgbits.SyncObject)
   654  	if r.Version().Has(pkgbits.DerivedFuncInstance) {
   655  		assert(!r.Bool())
   656  	}
   657  	idx := r.Reloc(pkgbits.SectionObj)
   658  
   659  	explicits := make([]typeInfo, r.Len())
   660  	for i := range explicits {
   661  		explicits[i] = r.typInfo()
   662  	}
   663  
   664  	return objInfo{idx, explicits}
   665  }
   666  
   667  // objInstIdx returns the encoded, instantiated object. If shaped is
   668  // true, then the shaped variant of the object is returned instead.
   669  func (pr *pkgReader) objInstIdx(info objInfo, dict *readerDict, shaped bool) ir.Node {
   670  	explicits := pr.typListIdx(info.explicits, dict)
   671  
   672  	var implicits []*types.Type
   673  	if dict != nil {
   674  		implicits = dict.targs
   675  	}
   676  
   677  	return pr.objIdx(info.idx, implicits, explicits, shaped)
   678  }
   679  
   680  // objIdx returns the specified object, instantiated with the given
   681  // type arguments, if any.
   682  // If shaped is true, then the shaped variant of the object is returned
   683  // instead.
   684  func (pr *pkgReader) objIdx(idx index, implicits, explicits []*types.Type, shaped bool) ir.Node {
   685  	n, err := pr.objIdxMayFail(idx, implicits, explicits, shaped)
   686  	if err != nil {
   687  		base.Fatalf("%v", err)
   688  	}
   689  	return n
   690  }
   691  
   692  // objIdxMayFail is equivalent to objIdx, but returns an error rather than
   693  // failing the build if this object requires type arguments and the incorrect
   694  // number of type arguments were passed.
   695  //
   696  // Other sources of internal failure (such as duplicate definitions) still fail
   697  // the build.
   698  func (pr *pkgReader) objIdxMayFail(idx index, implicits, explicits []*types.Type, shaped bool) (ir.Node, error) {
   699  	rname := pr.newReader(pkgbits.SectionName, idx, pkgbits.SyncObject1)
   700  	_, sym := rname.qualifiedIdent()
   701  	tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
   702  
   703  	if tag == pkgbits.ObjStub {
   704  		assert(!sym.IsBlank())
   705  		switch sym.Pkg {
   706  		case types.BuiltinPkg, types.UnsafePkg:
   707  			return sym.Def.(ir.Node), nil
   708  		}
   709  		if pri, ok := objReader[sym]; ok {
   710  			return pri.pr.objIdxMayFail(pri.idx, nil, explicits, shaped)
   711  		}
   712  		if sym.Pkg.Path == "runtime" {
   713  			return typecheck.LookupRuntime(sym.Name), nil
   714  		}
   715  		base.Fatalf("unresolved stub: %v", sym)
   716  	}
   717  
   718  	dict, err := pr.objDictIdx(sym, idx, implicits, explicits, shaped)
   719  	if err != nil {
   720  		return nil, err
   721  	}
   722  
   723  	sym = dict.baseSym
   724  	if !sym.IsBlank() && sym.Def != nil {
   725  		return sym.Def.(*ir.Name), nil
   726  	}
   727  
   728  	r := pr.newReader(pkgbits.SectionObj, idx, pkgbits.SyncObject1)
   729  	rext := pr.newReader(pkgbits.SectionObjExt, idx, pkgbits.SyncObject1)
   730  
   731  	r.dict = dict
   732  	rext.dict = dict
   733  
   734  	do := func(op ir.Op, hasTParams bool) *ir.Name {
   735  		pos := r.pos()
   736  		setBasePos(pos)
   737  		if hasTParams {
   738  			r.typeParamNames()
   739  		}
   740  
   741  		name := ir.NewDeclNameAt(pos, op, sym)
   742  		name.Class = ir.PEXTERN // may be overridden later
   743  		if !sym.IsBlank() {
   744  			if sym.Def != nil {
   745  				base.FatalfAt(name.Pos(), "already have a definition for %v", name)
   746  			}
   747  			assert(sym.Def == nil)
   748  			sym.Def = name
   749  		}
   750  		return name
   751  	}
   752  
   753  	switch tag {
   754  	default:
   755  		panic("unexpected object")
   756  
   757  	case pkgbits.ObjAlias:
   758  		name := do(ir.OTYPE, false)
   759  
   760  		if r.Version().Has(pkgbits.AliasTypeParamNames) {
   761  			r.typeParamNames()
   762  		}
   763  
   764  		// Clumsy dance: the r.typ() call here might recursively find this
   765  		// type alias name, before we've set its type (#66873). So we
   766  		// temporarily clear sym.Def and then restore it later, if still
   767  		// unset.
   768  		hack := sym.Def == name
   769  		if hack {
   770  			sym.Def = nil
   771  		}
   772  		typ := r.typ()
   773  		if hack {
   774  			if sym.Def != nil {
   775  				name = sym.Def.(*ir.Name)
   776  				assert(types.IdenticalStrict(name.Type(), typ))
   777  				return name, nil
   778  			}
   779  			sym.Def = name
   780  		}
   781  
   782  		setType(name, typ)
   783  		name.SetAlias(true)
   784  		return name, nil
   785  
   786  	case pkgbits.ObjConst:
   787  		name := do(ir.OLITERAL, false)
   788  		typ := r.typ()
   789  		val := FixValue(typ, r.Value())
   790  		setType(name, typ)
   791  		setValue(name, val)
   792  		return name, nil
   793  
   794  	case pkgbits.ObjFunc:
   795  		npos := r.pos()
   796  		setBasePos(npos)
   797  
   798  		var sel *types.Sym
   799  		var recv *types.Field
   800  		if r.Version().Has(pkgbits.GenericMethods) && r.Bool() {
   801  			sel = r.selector()
   802  			r.recvTypeParamNames()
   803  			recv = r.param()
   804  			if r.Version().Has(pkgbits.PreserveMethodOrder) {
   805  				_ = r.Len() // method index not needed in compiler
   806  			}
   807  		} else {
   808  			if sym.Name == "init" {
   809  				sym = Renameinit()
   810  			}
   811  		}
   812  		r.typeParamNames()
   813  		typ := r.signature(recv)
   814  		fpos := r.pos()
   815  
   816  		fn := ir.NewFunc(fpos, npos, sym, typ)
   817  		if r.hasTypeParams() && r.dict.shaped {
   818  			typ.SetHasShape(true)
   819  		}
   820  
   821  		name := fn.Nname
   822  		if !sym.IsBlank() {
   823  			if sym.Def != nil {
   824  				base.FatalfAt(name.Pos(), "already have a definition for %v", name)
   825  			}
   826  			assert(sym.Def == nil)
   827  			sym.Def = name
   828  		}
   829  
   830  		if r.hasTypeParams() {
   831  			name.Func.SetDupok(true)
   832  			if r.dict.shaped {
   833  				setType(name, shapeSig(name.Func, r.dict))
   834  			} else {
   835  				todoDicts = append(todoDicts, func() {
   836  					r.dict.shapedObj = pr.objIdx(idx, implicits, explicits, true).(*ir.Name)
   837  				})
   838  			}
   839  		}
   840  
   841  		rext.funcExt(name, sel)
   842  		return name, nil
   843  
   844  	case pkgbits.ObjType:
   845  		name := do(ir.OTYPE, true)
   846  		typ := types.NewNamed(name)
   847  		setType(name, typ)
   848  		if r.hasTypeParams() && r.dict.shaped {
   849  			typ.SetHasShape(true)
   850  		}
   851  
   852  		// Important: We need to do this before SetUnderlying.
   853  		rext.typeExt(name)
   854  
   855  		// We need to defer CheckSize until we've called SetUnderlying to
   856  		// handle recursive types.
   857  		types.DeferCheckSize()
   858  		typ.SetUnderlying(r.typWrapped(false))
   859  		types.ResumeCheckSize()
   860  
   861  		if r.hasTypeParams() && !r.dict.shaped {
   862  			todoDicts = append(todoDicts, func() {
   863  				r.dict.shapedObj = pr.objIdx(idx, implicits, explicits, true).(*ir.Name)
   864  			})
   865  		}
   866  
   867  		methods := make([]*types.Field, r.Len())
   868  		for i := range methods {
   869  			methods[i] = r.method(rext)
   870  		}
   871  		if len(methods) != 0 {
   872  			typ.SetMethods(methods)
   873  		}
   874  
   875  		if !r.dict.shaped {
   876  			r.needWrapper(typ)
   877  		}
   878  
   879  		return name, nil
   880  
   881  	case pkgbits.ObjVar:
   882  		name := do(ir.ONAME, false)
   883  		setType(name, r.typ())
   884  		rext.varExt(name)
   885  		return name, nil
   886  	}
   887  }
   888  
   889  // mangle shapes the non-shaped symbol sym under the current dictionary.
   890  func (dict *readerDict) mangle(sym *types.Sym) *types.Sym {
   891  	if !dict.hasTypeParams() {
   892  		return sym
   893  	}
   894  
   895  	var buf strings.Builder
   896  	// If sym is a locally defined generic type, we need the suffix to
   897  	// stay at the end after mangling so that types/fmt.go can strip it
   898  	// out again when writing the type's runtime descriptor (#54456).
   899  	n0, vsuff := types.SplitVargenSuffix(sym.Name)
   900  	n1, msuff := types.SplitMethSuffix(sym.Name)
   901  
   902  	// Methods are never locally defined.
   903  	var n string
   904  	assert(vsuff == "" || msuff == "")
   905  	if vsuff != "" {
   906  		n = n0
   907  	} else {
   908  		n = n1
   909  	}
   910  
   911  	var j int
   912  	assert(dict.implicits == 0 || dict.receivers == 0)
   913  	if msuff != "" {
   914  		j = dict.receivers // consume receiver type arguments
   915  	} else {
   916  		j = len(dict.targs) // consume all type arguments
   917  	}
   918  
   919  	// put type arguments inside parenthesis; (*T)[int] -> (*T[int])
   920  	n, ok := strings.CutSuffix(n, ")")
   921  
   922  	// type arguments, if any
   923  	buf.WriteString(n)
   924  	if j > 0 {
   925  		buf.WriteByte('[')
   926  		for i := 0; i < j; i++ {
   927  			if i > 0 {
   928  				if i == dict.implicits {
   929  					buf.WriteByte(';')
   930  				} else {
   931  					buf.WriteByte(',')
   932  				}
   933  			}
   934  			buf.WriteString(dict.targs[i].LinkString())
   935  		}
   936  		buf.WriteByte(']')
   937  	}
   938  
   939  	if ok {
   940  		buf.WriteString(")")
   941  	}
   942  
   943  	buf.WriteString(vsuff)
   944  	buf.WriteString(msuff)
   945  
   946  	// method arguments, if any
   947  	if msuff != "" {
   948  		buf.WriteByte('[')
   949  		for i := j; i < len(dict.targs); i++ {
   950  			if i > j {
   951  				buf.WriteByte(',')
   952  			}
   953  			buf.WriteString(dict.targs[i].LinkString())
   954  		}
   955  		buf.WriteByte(']')
   956  	}
   957  
   958  	return sym.Pkg.Lookup(buf.String())
   959  }
   960  
   961  // Shapify returns the shape type for targ.
   962  //
   963  // If basic is true, then the type argument is used to instantiate a
   964  // type parameter whose constraint is a basic interface.
   965  func Shapify(targ *types.Type, basic bool) *types.Type {
   966  	if targ.Kind() == types.TFORW {
   967  		if targ.IsFullyInstantiated() {
   968  			// For recursive instantiated type argument, it may  still be a TFORW
   969  			// when shapifying happens. If we don't have targ's underlying type,
   970  			// shapify won't work. The worst case is we end up not reusing code
   971  			// optimally in some tricky cases.
   972  			if base.Debug.Shapify != 0 {
   973  				base.Warn("skipping shaping of recursive type %v", targ)
   974  			}
   975  			if targ.HasShape() {
   976  				return targ
   977  			}
   978  		} else {
   979  			base.Fatalf("%v is missing its underlying type", targ)
   980  		}
   981  	}
   982  	// For fully instantiated shape interface type, use it as-is. Otherwise, the instantiation
   983  	// involved recursive generic interface may cause mismatching in function signature, see issue #65362.
   984  	if targ.Kind() == types.TINTER && targ.IsFullyInstantiated() && targ.HasShape() {
   985  		return targ
   986  	}
   987  
   988  	// When a pointer type is used to instantiate a type parameter
   989  	// constrained by a basic interface, we know the pointer's element
   990  	// type can't matter to the generated code. In this case, we can use
   991  	// an arbitrary pointer type as the shape type. (To match the
   992  	// non-unified frontend, we use `*byte`.)
   993  	//
   994  	// Otherwise, we simply use the type's underlying type as its shape.
   995  	//
   996  	// TODO(mdempsky): It should be possible to do much more aggressive
   997  	// shaping still; e.g., collapsing all pointer-shaped types into a
   998  	// common type, collapsing scalars of the same size/alignment into a
   999  	// common type, recursively shaping the element types of composite
  1000  	// types, and discarding struct field names and tags. However, we'll
  1001  	// need to start tracking how type parameters are actually used to
  1002  	// implement some of these optimizations.
  1003  	under := targ.Underlying()
  1004  	if basic && targ.IsPtr() && !targ.Elem().NotInHeap() {
  1005  		under = types.NewPtr(types.Types[types.TUINT8])
  1006  	}
  1007  
  1008  	// Hash long type names to bound symbol name length seen by users,
  1009  	// particularly for large protobuf structs (#65030).
  1010  	uls := under.LinkString()
  1011  	if base.Debug.MaxShapeLen != 0 &&
  1012  		len(uls) > base.Debug.MaxShapeLen {
  1013  		h := hash.Sum32([]byte(uls))
  1014  		uls = hex.EncodeToString(h[:])
  1015  	}
  1016  
  1017  	sym := types.ShapePkg.Lookup(uls)
  1018  	if sym.Def == nil {
  1019  		name := ir.NewDeclNameAt(under.Pos(), ir.OTYPE, sym)
  1020  		typ := types.NewNamed(name)
  1021  		typ.SetUnderlying(under)
  1022  		sym.Def = typed(typ, name)
  1023  	}
  1024  	res := sym.Def.Type()
  1025  	assert(res.IsShape())
  1026  	assert(res.HasShape())
  1027  	return res
  1028  }
  1029  
  1030  // objDictIdx reads and returns the specified object dictionary.
  1031  func (pr *pkgReader) objDictIdx(sym *types.Sym, idx index, implicits, explicits []*types.Type, shaped bool) (*readerDict, error) {
  1032  	r := pr.newReader(pkgbits.SectionObjDict, idx, pkgbits.SyncObject1)
  1033  
  1034  	dict := readerDict{
  1035  		shaped: shaped,
  1036  	}
  1037  
  1038  	nimplicits := r.Len()
  1039  	nreceivers := 0
  1040  	if r.Version().Has(pkgbits.GenericMethods) {
  1041  		nreceivers = r.Len()
  1042  	}
  1043  	nexplicits := r.Len() + nreceivers
  1044  
  1045  	if nimplicits > len(implicits) || nexplicits != len(explicits) {
  1046  		return nil, fmt.Errorf("%v has %v+%v params, but instantiated with %v+%v args", sym, nimplicits, nexplicits, len(implicits), len(explicits))
  1047  	}
  1048  
  1049  	dict.targs = append(implicits[:nimplicits:nimplicits], explicits...)
  1050  	dict.implicits = nimplicits
  1051  	dict.receivers = nreceivers
  1052  
  1053  	// Within the compiler, we can just skip over the type parameters.
  1054  	for range dict.targs[dict.implicits:] {
  1055  		// Skip past bounds without actually evaluating them.
  1056  		r.typInfo()
  1057  	}
  1058  
  1059  	dict.derived = make([]derivedInfo, r.Len())
  1060  	dict.derivedTypes = make([]*types.Type, len(dict.derived))
  1061  	for i := range dict.derived {
  1062  		dict.derived[i] = derivedInfo{idx: r.Reloc(pkgbits.SectionType)}
  1063  		if r.Version().Has(pkgbits.DerivedInfoNeeded) {
  1064  			assert(!r.Bool())
  1065  		}
  1066  	}
  1067  
  1068  	// Runtime dictionary information; private to the compiler.
  1069  
  1070  	// If any type argument is already shaped, then we're constructing a
  1071  	// shaped object, even if not explicitly requested (i.e., calling
  1072  	// objIdx with shaped==true). This can happen with instantiating
  1073  	// types that are referenced within a function body.
  1074  	for _, targ := range dict.targs {
  1075  		if targ.HasShape() {
  1076  			dict.shaped = true
  1077  			break
  1078  		}
  1079  	}
  1080  
  1081  	// And if we're constructing a shaped object, then shapify all type
  1082  	// arguments.
  1083  	for i, targ := range dict.targs {
  1084  		basic := r.Bool()
  1085  		if dict.shaped {
  1086  			dict.targs[i] = Shapify(targ, basic)
  1087  		}
  1088  	}
  1089  
  1090  	dict.baseSym = dict.mangle(sym)
  1091  
  1092  	dict.typeParamMethodExprs = make([]readerMethodExprInfo, r.Len())
  1093  	for i := range dict.typeParamMethodExprs {
  1094  		typeParamIdx := r.Len()
  1095  		method := r.selector()
  1096  
  1097  		dict.typeParamMethodExprs[i] = readerMethodExprInfo{typeParamIdx, method}
  1098  	}
  1099  
  1100  	dict.subdicts = make([]objInfo, r.Len())
  1101  	for i := range dict.subdicts {
  1102  		dict.subdicts[i] = r.objInfo()
  1103  	}
  1104  
  1105  	dict.rtypes = make([]typeInfo, r.Len())
  1106  	for i := range dict.rtypes {
  1107  		dict.rtypes[i] = r.typInfo()
  1108  	}
  1109  
  1110  	dict.itabs = make([]itabInfo, r.Len())
  1111  	for i := range dict.itabs {
  1112  		dict.itabs[i] = itabInfo{typ: r.typInfo(), iface: r.typInfo()}
  1113  	}
  1114  
  1115  	return &dict, nil
  1116  }
  1117  
  1118  func (r *reader) recvTypeParamNames() {
  1119  	r.Sync(pkgbits.SyncTypeParamNames)
  1120  
  1121  	for range r.dict.targs[r.dict.implicits : r.dict.implicits+r.dict.receivers] {
  1122  		r.pos()
  1123  		r.localIdent()
  1124  	}
  1125  }
  1126  
  1127  func (r *reader) typeParamNames() {
  1128  	r.Sync(pkgbits.SyncTypeParamNames)
  1129  
  1130  	for range r.dict.targs[r.dict.implicits+r.dict.receivers:] {
  1131  		r.pos()
  1132  		r.localIdent()
  1133  	}
  1134  }
  1135  
  1136  func (r *reader) method(rext *reader) *types.Field {
  1137  	r.Sync(pkgbits.SyncMethod)
  1138  	if r.Version().Has(pkgbits.PreserveMethodOrder) {
  1139  		_ = r.Len() // method index not needed in compiler
  1140  	}
  1141  	npos := r.pos()
  1142  	sym := r.selector()
  1143  	r.typeParamNames()
  1144  	recv := r.param()
  1145  	typ := r.signature(recv)
  1146  
  1147  	fpos := r.pos()
  1148  	fn := ir.NewFunc(fpos, npos, ir.ReceiverMethodSym(recv.Type, sym), typ)
  1149  	name := fn.Nname
  1150  
  1151  	if r.hasTypeParams() {
  1152  		name.Func.SetDupok(true)
  1153  		if r.dict.shaped {
  1154  			typ = shapeSig(name.Func, r.dict)
  1155  			setType(name, typ)
  1156  		}
  1157  	}
  1158  
  1159  	rext.funcExt(name, sym)
  1160  
  1161  	meth := types.NewField(name.Func.Pos(), sym, typ)
  1162  	meth.Nname = name
  1163  	meth.SetNointerface(name.Func.Pragma&ir.Nointerface != 0)
  1164  
  1165  	return meth
  1166  }
  1167  
  1168  func (r *reader) qualifiedIdent() (pkg *types.Pkg, sym *types.Sym) {
  1169  	r.Sync(pkgbits.SyncSym)
  1170  	pkg = r.pkg()
  1171  	if name := r.String(); name != "" {
  1172  		sym = pkg.Lookup(name)
  1173  	}
  1174  	return
  1175  }
  1176  
  1177  func (r *reader) localIdent() *types.Sym {
  1178  	r.Sync(pkgbits.SyncLocalIdent)
  1179  	pkg := r.pkg()
  1180  	if name := r.String(); name != "" {
  1181  		return pkg.Lookup(name)
  1182  	}
  1183  	return nil
  1184  }
  1185  
  1186  func (r *reader) selector() *types.Sym {
  1187  	r.Sync(pkgbits.SyncSelector)
  1188  	pkg := r.pkg()
  1189  	name := r.String()
  1190  	if types.IsExported(name) {
  1191  		pkg = types.LocalPkg
  1192  	}
  1193  	return pkg.Lookup(name)
  1194  }
  1195  
  1196  func (r *reader) hasTypeParams() bool {
  1197  	return r.dict.hasTypeParams()
  1198  }
  1199  
  1200  func (dict *readerDict) hasTypeParams() bool {
  1201  	return dict != nil && len(dict.targs) != 0
  1202  }
  1203  
  1204  // @@@ Compiler extensions
  1205  
  1206  func (r *reader) funcExt(name *ir.Name, method *types.Sym) {
  1207  	r.Sync(pkgbits.SyncFuncExt)
  1208  
  1209  	fn := name.Func
  1210  
  1211  	// XXX: Workaround because linker doesn't know how to copy Pos.
  1212  	if !fn.Pos().IsKnown() {
  1213  		fn.SetPos(name.Pos())
  1214  	}
  1215  
  1216  	// Normally, we only compile local functions, which saves redundant compilation work.
  1217  	// n.Defn is not nil for local functions, and is nil for imported function. But for
  1218  	// generic functions, we might have an instantiation that no other package has seen before.
  1219  	// So we need to be conservative and compile it again.
  1220  	//
  1221  	// That's why name.Defn is set here, so ir.VisitFuncsBottomUp can analyze function.
  1222  	// TODO(mdempsky,cuonglm): find a cleaner way to handle this.
  1223  	if name.Sym().Pkg == types.LocalPkg || r.hasTypeParams() {
  1224  		name.Defn = fn
  1225  	}
  1226  
  1227  	fn.Pragma = r.pragmaFlag()
  1228  	r.linkname(name)
  1229  
  1230  	if buildcfg.GOARCH == "wasm" || buildcfg.GOARCH == "wasm32" {
  1231  		importmod := r.String()
  1232  		importname := r.String()
  1233  		exportname := r.String()
  1234  
  1235  		if importmod != "" && importname != "" {
  1236  			fn.WasmImport = &ir.WasmImport{
  1237  				Module: importmod,
  1238  				Name:   importname,
  1239  			}
  1240  		}
  1241  		if exportname != "" {
  1242  			if method != nil {
  1243  				base.ErrorfAt(fn.Pos(), 0, "cannot use //go:wasmexport on a method")
  1244  			}
  1245  			fn.WasmExport = &ir.WasmExport{Name: exportname}
  1246  		}
  1247  	}
  1248  
  1249  	if r.Bool() {
  1250  		assert(name.Defn == nil)
  1251  
  1252  		fn.ABI = obj.ABI(r.Uint64())
  1253  
  1254  		// Escape analysis.
  1255  		for _, f := range name.Type().RecvParams() {
  1256  			f.Note = r.String()
  1257  		}
  1258  
  1259  		if r.Bool() {
  1260  			fn.Inl = &ir.Inline{
  1261  				Cost:            int32(r.Len()),
  1262  				CanDelayResults: r.Bool(),
  1263  			}
  1264  			if buildcfg.Experiment.NewInliner {
  1265  				fn.Inl.Properties = r.String()
  1266  			}
  1267  		}
  1268  	} else {
  1269  		r.addBody(name.Func, method)
  1270  	}
  1271  	r.Sync(pkgbits.SyncEOF)
  1272  }
  1273  
  1274  func (r *reader) typeExt(name *ir.Name) {
  1275  	r.Sync(pkgbits.SyncTypeExt)
  1276  
  1277  	typ := name.Type()
  1278  
  1279  	if r.hasTypeParams() {
  1280  		// Mark type as fully instantiated to ensure the type descriptor is written
  1281  		// out as DUPOK and method wrappers are generated even for imported types.
  1282  		typ.SetIsFullyInstantiated(true)
  1283  		// HasShape should be set if any type argument is or has a shape type.
  1284  		for _, targ := range r.dict.targs {
  1285  			if targ.HasShape() {
  1286  				typ.SetHasShape(true)
  1287  				break
  1288  			}
  1289  		}
  1290  	}
  1291  
  1292  	name.SetPragma(r.pragmaFlag())
  1293  
  1294  	typecheck.SetBaseTypeIndex(typ, r.Int64(), r.Int64())
  1295  }
  1296  
  1297  func (r *reader) varExt(name *ir.Name) {
  1298  	r.Sync(pkgbits.SyncVarExt)
  1299  	r.linkname(name)
  1300  }
  1301  
  1302  func (r *reader) linkname(name *ir.Name) {
  1303  	assert(name.Op() == ir.ONAME)
  1304  	r.Sync(pkgbits.SyncLinkname)
  1305  
  1306  	if idx := r.Int64(); idx >= 0 {
  1307  		lsym := name.Linksym()
  1308  		lsym.SymIdx = int32(idx)
  1309  		lsym.Set(obj.AttrIndexed, true)
  1310  	} else {
  1311  		linkname := r.String()
  1312  		std := r.Bool()
  1313  		sym := name.Sym()
  1314  		sym.Linkname = linkname
  1315  		if sym.Pkg == types.LocalPkg && linkname != "" {
  1316  			// Mark linkname in the current package. We don't mark the
  1317  			// ones that are imported and propagated (e.g. through
  1318  			// inlining or instantiation, which are marked in their
  1319  			// corresponding packages). So we can tell in which package
  1320  			// the linkname is used (pulled), and the linker can
  1321  			// make a decision for allowing or disallowing it.
  1322  			if std {
  1323  				sym.Linksym().Set(obj.AttrLinknameStd, true)
  1324  			} else {
  1325  				sym.Linksym().Set(obj.AttrLinkname, true)
  1326  			}
  1327  		}
  1328  	}
  1329  }
  1330  
  1331  func (r *reader) pragmaFlag() ir.PragmaFlag {
  1332  	r.Sync(pkgbits.SyncPragma)
  1333  	return ir.PragmaFlag(r.Int())
  1334  }
  1335  
  1336  // @@@ Function bodies
  1337  
  1338  // bodyReader tracks where the serialized IR for a local or imported,
  1339  // generic function's body can be found.
  1340  var bodyReader = map[*ir.Func]pkgReaderIndex{}
  1341  
  1342  // importBodyReader tracks where the serialized IR for an imported,
  1343  // static (i.e., non-generic) function body can be read.
  1344  var importBodyReader = map[*types.Sym]pkgReaderIndex{}
  1345  
  1346  // bodyReaderFor returns the pkgReaderIndex for reading fn's
  1347  // serialized IR, and whether one was found.
  1348  func bodyReaderFor(fn *ir.Func) (pri pkgReaderIndex, ok bool) {
  1349  	if fn.Nname.Defn != nil {
  1350  		pri, ok = bodyReader[fn]
  1351  		base.AssertfAt(ok, base.Pos, "must have bodyReader for %v", fn) // must always be available
  1352  	} else {
  1353  		pri, ok = importBodyReader[fn.Sym()]
  1354  	}
  1355  	return
  1356  }
  1357  
  1358  // todoDicts holds the list of dictionaries that still need their
  1359  // runtime dictionary objects constructed.
  1360  var todoDicts []func()
  1361  
  1362  // todoBodies holds the list of function bodies that still need to be
  1363  // constructed.
  1364  var todoBodies []*ir.Func
  1365  
  1366  // addBody reads a function body reference from the element bitstream,
  1367  // and associates it with fn.
  1368  func (r *reader) addBody(fn *ir.Func, method *types.Sym) {
  1369  	// addBody should only be called for local functions or imported
  1370  	// generic functions; see comment in funcExt.
  1371  	assert(fn.Nname.Defn != nil)
  1372  
  1373  	idx := r.Reloc(pkgbits.SectionBody)
  1374  
  1375  	pri := pkgReaderIndex{r.p, idx, r.dict, method, nil}
  1376  	bodyReader[fn] = pri
  1377  
  1378  	if r.curfn == nil {
  1379  		todoBodies = append(todoBodies, fn)
  1380  		return
  1381  	}
  1382  
  1383  	pri.funcBody(fn)
  1384  }
  1385  
  1386  func (pri pkgReaderIndex) funcBody(fn *ir.Func) {
  1387  	r := pri.asReader(pkgbits.SectionBody, pkgbits.SyncFuncBody)
  1388  	panicking := true
  1389  	defer func() {
  1390  		if panicking {
  1391  			// TODO not sure what the best way to print in this context is.
  1392  			// If code panics in unified IR reading, you want *something* like this.
  1393  			// Whoever ends up debugging the next unified IR failure, please
  1394  			// improve this (base.Warnf?) if you can figure out how.
  1395  			fmt.Printf("****** panic traversed funcBody of %v\n", fn)
  1396  		}
  1397  	}()
  1398  	r.funcBody(fn)
  1399  	panicking = false
  1400  
  1401  }
  1402  
  1403  // funcBody reads a function body definition from the element
  1404  // bitstream, and populates fn with it.
  1405  func (r *reader) funcBody(fn *ir.Func) {
  1406  	r.curfn = fn
  1407  	r.closureVars = fn.ClosureVars
  1408  	if len(r.closureVars) != 0 && r.hasTypeParams() {
  1409  		r.dictParam = r.closureVars[len(r.closureVars)-1] // dictParam is last; see reader.funcLit
  1410  	}
  1411  
  1412  	ir.WithPos(fn, func() {
  1413  		r.declareParams()
  1414  
  1415  		if r.syntheticBody(fn.Pos()) {
  1416  			return
  1417  		}
  1418  
  1419  		if !r.Bool() {
  1420  			return
  1421  		}
  1422  
  1423  		body := r.stmts()
  1424  		if body == nil {
  1425  			body = []ir.Node{typecheck.Stmt(r.curfn, ir.NewBlockStmt(src.NoXPos, nil))}
  1426  		}
  1427  		fn.Body = body
  1428  		fn.Endlineno = r.pos()
  1429  	})
  1430  
  1431  	r.marker.WriteTo(fn)
  1432  }
  1433  
  1434  // syntheticBody adds a synthetic body to r.curfn if appropriate, and
  1435  // reports whether it did.
  1436  func (r *reader) syntheticBody(pos src.XPos) bool {
  1437  	if r.synthetic != nil {
  1438  		r.synthetic(pos, r)
  1439  		return true
  1440  	}
  1441  
  1442  	// If this function has type parameters and isn't shaped, then we
  1443  	// just tail call its corresponding shaped variant.
  1444  	if r.hasTypeParams() && !r.dict.shaped {
  1445  		r.callShaped(pos)
  1446  		return true
  1447  	}
  1448  
  1449  	return false
  1450  }
  1451  
  1452  // callShaped emits a tail call to r.shapedFn, passing along the
  1453  // arguments to the current function.
  1454  func (r *reader) callShaped(pos src.XPos) {
  1455  	shapedObj := r.dict.shapedObj
  1456  	assert(shapedObj != nil)
  1457  
  1458  	var shapedFn ir.Node
  1459  	if r.methodSym == nil {
  1460  		// Instantiating a generic function; shapedObj is the shaped function itself.
  1461  		assert(shapedObj.Op() == ir.ONAME && shapedObj.Class == ir.PFUNC)
  1462  		shapedFn = shapedObj
  1463  	} else {
  1464  		// Instantiating a generic type's method; shapedObj is the shaped method itself
  1465  		// if the method is generic — else, it is the shaped type declaring the method.
  1466  		shapedFn = shapedMethodExpr(pos, shapedObj, r.methodSym)
  1467  	}
  1468  
  1469  	params := r.syntheticArgs()
  1470  
  1471  	// Construct the arguments list: receiver (if any), then runtime
  1472  	// dictionary, and finally normal parameters.
  1473  	//
  1474  	// Note: For simplicity, shaped methods are added as normal methods
  1475  	// on their shaped types. So existing code (e.g., packages ir and
  1476  	// typecheck) expects the shaped type to appear as the receiver
  1477  	// parameter (or first parameter, as a method expression). Hence
  1478  	// putting the dictionary parameter after that is the least invasive
  1479  	// solution at the moment.
  1480  	var args ir.Nodes
  1481  	if r.methodSym != nil {
  1482  		args.Append(params[0])
  1483  		params = params[1:]
  1484  	}
  1485  	args.Append(typecheck.Expr(r.curfn, ir.NewAddrExpr(pos, r.p.dictNameOf(r.dict))))
  1486  	args.Append(params...)
  1487  
  1488  	r.syntheticTailCall(pos, shapedFn, args)
  1489  }
  1490  
  1491  // syntheticArgs returns the recvs and params arguments passed to the
  1492  // current function.
  1493  func (r *reader) syntheticArgs() ir.Nodes {
  1494  	sig := r.curfn.Nname.Type()
  1495  	return ir.ToNodes(r.curfn.Dcl[:sig.NumRecvs()+sig.NumParams()])
  1496  }
  1497  
  1498  // syntheticTailCall emits a tail call to fn, passing the given
  1499  // arguments list.
  1500  func (r *reader) syntheticTailCall(pos src.XPos, fn ir.Node, args ir.Nodes) {
  1501  	// Mark the function as a wrapper so it doesn't show up in stack
  1502  	// traces.
  1503  	r.curfn.SetWrapper(true)
  1504  
  1505  	call := typecheck.Call(r.curfn, pos, fn, args, fn.Type().IsVariadic()).(*ir.CallExpr)
  1506  
  1507  	var stmt ir.Node
  1508  	if fn.Type().NumResults() != 0 {
  1509  		stmt = typecheck.Stmt(r.curfn, ir.NewReturnStmt(pos, []ir.Node{call}))
  1510  	} else {
  1511  		stmt = call
  1512  	}
  1513  	r.curfn.Body.Append(stmt)
  1514  }
  1515  
  1516  // dictNameOf returns the runtime dictionary corresponding to dict.
  1517  func (pr *pkgReader) dictNameOf(dict *readerDict) *ir.Name {
  1518  	pos := base.AutogeneratedPos
  1519  
  1520  	// Check that we only instantiate runtime dictionaries with real types.
  1521  	base.AssertfAt(!dict.shaped, pos, "runtime dictionary of shaped object %v", dict.baseSym)
  1522  
  1523  	sym := dict.baseSym.Pkg.Lookup(objabi.GlobalDictPrefix + "." + dict.baseSym.Name)
  1524  	if sym.Def != nil {
  1525  		return sym.Def.(*ir.Name)
  1526  	}
  1527  
  1528  	name := ir.NewNameAt(pos, sym, dict.varType())
  1529  	name.Class = ir.PEXTERN
  1530  	sym.Def = name // break cycles with mutual subdictionaries
  1531  
  1532  	lsym := name.Linksym()
  1533  	ot := 0
  1534  
  1535  	assertOffset := func(section string, offset int) {
  1536  		base.AssertfAt(ot == offset*types.PtrSize, pos, "writing section %v at offset %v, but it should be at %v*%v", section, ot, offset, types.PtrSize)
  1537  	}
  1538  
  1539  	assertOffset("type param method exprs", dict.typeParamMethodExprsOffset())
  1540  	for _, info := range dict.typeParamMethodExprs {
  1541  		typeParam := dict.targs[info.typeParamIdx]
  1542  		method := typecheck.NewMethodExpr(pos, typeParam, info.method)
  1543  
  1544  		rsym := method.FuncName().Linksym()
  1545  		assert(rsym.ABI() == obj.ABIInternal) // must be ABIInternal; see ir.OCFUNC in ssagen/ssa.go
  1546  
  1547  		ot = objw.SymFuncPtr(lsym, ot, rsym)
  1548  	}
  1549  
  1550  	assertOffset("subdictionaries", dict.subdictsOffset())
  1551  	for _, info := range dict.subdicts {
  1552  		explicits := pr.typListIdx(info.explicits, dict)
  1553  
  1554  		// Careful: Due to subdictionary cycles, name may not be fully
  1555  		// initialized yet.
  1556  		name := pr.objDictName(info.idx, dict.targs, explicits)
  1557  
  1558  		ot = objw.SymPtr(lsym, ot, name.Linksym(), 0)
  1559  	}
  1560  
  1561  	assertOffset("rtypes", dict.rtypesOffset())
  1562  	for _, info := range dict.rtypes {
  1563  		typ := pr.typIdx(info, dict, true)
  1564  		ot = objw.SymPtr(lsym, ot, reflectdata.TypeLinksym(typ), 0)
  1565  
  1566  		// TODO(mdempsky): Double check this.
  1567  		reflectdata.MarkTypeUsedInInterface(typ, lsym)
  1568  	}
  1569  
  1570  	// For each (typ, iface) pair, we write the *runtime.itab pointer
  1571  	// for the pair. For pairs that don't actually require an itab
  1572  	// (i.e., typ is an interface, or iface is an empty interface), we
  1573  	// write a nil pointer instead. This is wasteful, but rare in
  1574  	// practice (e.g., instantiating a type parameter with an interface
  1575  	// type).
  1576  	assertOffset("itabs", dict.itabsOffset())
  1577  	for _, info := range dict.itabs {
  1578  		typ := pr.typIdx(info.typ, dict, true)
  1579  		iface := pr.typIdx(info.iface, dict, true)
  1580  
  1581  		if !typ.IsInterface() && iface.IsInterface() && !iface.IsEmptyInterface() {
  1582  			ot = objw.SymPtr(lsym, ot, reflectdata.ITabLsym(typ, iface), 0)
  1583  		} else {
  1584  			ot += types.PtrSize
  1585  		}
  1586  
  1587  		// TODO(mdempsky): Double check this.
  1588  		reflectdata.MarkTypeUsedInInterface(typ, lsym)
  1589  		reflectdata.MarkTypeUsedInInterface(iface, lsym)
  1590  	}
  1591  
  1592  	objw.Global(lsym, int32(ot), obj.DUPOK|obj.RODATA)
  1593  
  1594  	return name
  1595  }
  1596  
  1597  // typeParamMethodExprsOffset returns the offset of the runtime
  1598  // dictionary's type parameter method expressions section, in words.
  1599  func (dict *readerDict) typeParamMethodExprsOffset() int {
  1600  	return 0
  1601  }
  1602  
  1603  // subdictsOffset returns the offset of the runtime dictionary's
  1604  // subdictionary section, in words.
  1605  func (dict *readerDict) subdictsOffset() int {
  1606  	return dict.typeParamMethodExprsOffset() + len(dict.typeParamMethodExprs)
  1607  }
  1608  
  1609  // rtypesOffset returns the offset of the runtime dictionary's rtypes
  1610  // section, in words.
  1611  func (dict *readerDict) rtypesOffset() int {
  1612  	return dict.subdictsOffset() + len(dict.subdicts)
  1613  }
  1614  
  1615  // itabsOffset returns the offset of the runtime dictionary's itabs
  1616  // section, in words.
  1617  func (dict *readerDict) itabsOffset() int {
  1618  	return dict.rtypesOffset() + len(dict.rtypes)
  1619  }
  1620  
  1621  // numWords returns the total number of words that comprise dict's
  1622  // runtime dictionary variable.
  1623  func (dict *readerDict) numWords() int64 {
  1624  	return int64(dict.itabsOffset() + len(dict.itabs))
  1625  }
  1626  
  1627  // varType returns the type of dict's runtime dictionary variable.
  1628  func (dict *readerDict) varType() *types.Type {
  1629  	return types.NewArray(types.Types[types.TUINTPTR], dict.numWords())
  1630  }
  1631  
  1632  func (r *reader) declareParams() {
  1633  	r.curfn.DeclareParams(!r.funarghack)
  1634  
  1635  	for _, name := range r.curfn.Dcl {
  1636  		if name.Sym().Name == dictParamName {
  1637  			r.dictParam = name
  1638  			continue
  1639  		}
  1640  
  1641  		r.addLocal(name)
  1642  	}
  1643  }
  1644  
  1645  func (r *reader) addLocal(name *ir.Name) {
  1646  	if r.synthetic == nil {
  1647  		r.Sync(pkgbits.SyncAddLocal)
  1648  		if r.p.SyncMarkers() {
  1649  			want := r.Int()
  1650  			if have := len(r.locals); have != want {
  1651  				base.FatalfAt(name.Pos(), "locals table has desynced")
  1652  			}
  1653  		}
  1654  		r.varDictIndex(name)
  1655  	}
  1656  
  1657  	r.locals = append(r.locals, name)
  1658  }
  1659  
  1660  func (r *reader) useLocal() *ir.Name {
  1661  	r.Sync(pkgbits.SyncUseObjLocal)
  1662  	if r.Bool() {
  1663  		return r.locals[r.Len()]
  1664  	}
  1665  	return r.closureVars[r.Len()]
  1666  }
  1667  
  1668  func (r *reader) openScope() {
  1669  	r.Sync(pkgbits.SyncOpenScope)
  1670  	pos := r.pos()
  1671  
  1672  	if base.Flag.Dwarf {
  1673  		r.scopeVars = append(r.scopeVars, len(r.curfn.Dcl))
  1674  		r.marker.Push(pos)
  1675  	}
  1676  }
  1677  
  1678  func (r *reader) closeScope() {
  1679  	r.Sync(pkgbits.SyncCloseScope)
  1680  	r.lastCloseScopePos = r.pos()
  1681  
  1682  	r.closeAnotherScope()
  1683  }
  1684  
  1685  // closeAnotherScope is like closeScope, but it reuses the same mark
  1686  // position as the last closeScope call. This is useful for "for" and
  1687  // "if" statements, as their implicit blocks always end at the same
  1688  // position as an explicit block.
  1689  func (r *reader) closeAnotherScope() {
  1690  	r.Sync(pkgbits.SyncCloseAnotherScope)
  1691  
  1692  	if base.Flag.Dwarf {
  1693  		scopeVars := r.scopeVars[len(r.scopeVars)-1]
  1694  		r.scopeVars = r.scopeVars[:len(r.scopeVars)-1]
  1695  
  1696  		// Quirkish: noder decides which scopes to keep before
  1697  		// typechecking, whereas incremental typechecking during IR
  1698  		// construction can result in new autotemps being allocated. To
  1699  		// produce identical output, we ignore autotemps here for the
  1700  		// purpose of deciding whether to retract the scope.
  1701  		//
  1702  		// This is important for net/http/fcgi, because it contains:
  1703  		//
  1704  		//	var body io.ReadCloser
  1705  		//	if len(content) > 0 {
  1706  		//		body, req.pw = io.Pipe()
  1707  		//	} else { … }
  1708  		//
  1709  		// Notably, io.Pipe is inlinable, and inlining it introduces a ~R0
  1710  		// variable at the call site.
  1711  		//
  1712  		// Noder does not preserve the scope where the io.Pipe() call
  1713  		// resides, because it doesn't contain any declared variables in
  1714  		// source. So the ~R0 variable ends up being assigned to the
  1715  		// enclosing scope instead.
  1716  		//
  1717  		// However, typechecking this assignment also introduces
  1718  		// autotemps, because io.Pipe's results need conversion before
  1719  		// they can be assigned to their respective destination variables.
  1720  		//
  1721  		// TODO(mdempsky): We should probably just keep all scopes, and
  1722  		// let dwarfgen take care of pruning them instead.
  1723  		retract := true
  1724  		for _, n := range r.curfn.Dcl[scopeVars:] {
  1725  			if !n.AutoTemp() {
  1726  				retract = false
  1727  				break
  1728  			}
  1729  		}
  1730  
  1731  		if retract {
  1732  			// no variables were declared in this scope, so we can retract it.
  1733  			r.marker.Unpush()
  1734  		} else {
  1735  			r.marker.Pop(r.lastCloseScopePos)
  1736  		}
  1737  	}
  1738  }
  1739  
  1740  // @@@ Statements
  1741  
  1742  func (r *reader) stmt() ir.Node {
  1743  	return block(r.stmts())
  1744  }
  1745  
  1746  func block(stmts []ir.Node) ir.Node {
  1747  	switch len(stmts) {
  1748  	case 0:
  1749  		return nil
  1750  	case 1:
  1751  		return stmts[0]
  1752  	default:
  1753  		return ir.NewBlockStmt(stmts[0].Pos(), stmts)
  1754  	}
  1755  }
  1756  
  1757  func (r *reader) stmts() ir.Nodes {
  1758  	assert(r.curfn == r.curfn)
  1759  	var res ir.Nodes
  1760  
  1761  	r.Sync(pkgbits.SyncStmts)
  1762  	for {
  1763  		tag := codeStmt(r.Code(pkgbits.SyncStmt1))
  1764  		if tag == stmtEnd {
  1765  			r.Sync(pkgbits.SyncStmtsEnd)
  1766  			return res
  1767  		}
  1768  
  1769  		if n := r.stmt1(tag, &res); n != nil {
  1770  			res.Append(typecheck.Stmt(r.curfn, n))
  1771  		}
  1772  	}
  1773  }
  1774  
  1775  func (r *reader) stmt1(tag codeStmt, out *ir.Nodes) ir.Node {
  1776  	var label *types.Sym
  1777  	if n := len(*out); n > 0 {
  1778  		if ls, ok := (*out)[n-1].(*ir.LabelStmt); ok {
  1779  			label = ls.Label
  1780  		}
  1781  	}
  1782  
  1783  	switch tag {
  1784  	default:
  1785  		panic("unexpected statement")
  1786  
  1787  	case stmtAssign:
  1788  		pos := r.pos()
  1789  		lno := base.Pos
  1790  		defer func() { base.Pos = lno }()
  1791  		base.Pos = pos
  1792  		names, lhs := r.assignList()
  1793  		rhs := r.multiExpr()
  1794  
  1795  		if len(rhs) == 0 {
  1796  			for _, name := range names {
  1797  				as := ir.NewAssignStmt(pos, name, nil)
  1798  				as.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, name))
  1799  				out.Append(typecheck.Stmt(r.curfn, as))
  1800  			}
  1801  			return nil
  1802  		}
  1803  
  1804  		if len(lhs) == 1 && len(rhs) == 1 {
  1805  			n := ir.NewAssignStmt(pos, lhs[0], rhs[0])
  1806  			n.Def = r.initDefn(n, names)
  1807  			return n
  1808  		}
  1809  
  1810  		n := ir.NewAssignListStmt(pos, ir.OAS2, lhs, rhs)
  1811  		n.Def = r.initDefn(n, names)
  1812  		return n
  1813  
  1814  	case stmtAssignOp:
  1815  		op := r.op()
  1816  		lhs := r.expr()
  1817  		pos := r.pos()
  1818  		rhs := r.expr()
  1819  		return ir.NewAssignOpStmt(pos, op, lhs, rhs)
  1820  
  1821  	case stmtIncDec:
  1822  		op := r.op()
  1823  		lhs := r.expr()
  1824  		pos := r.pos()
  1825  		n := ir.NewAssignOpStmt(pos, op, lhs, ir.NewOne(pos, lhs.Type()))
  1826  		n.IncDec = true
  1827  		return n
  1828  
  1829  	case stmtBlock:
  1830  		out.Append(r.blockStmt()...)
  1831  		return nil
  1832  
  1833  	case stmtBranch:
  1834  		pos := r.pos()
  1835  		op := r.op()
  1836  		sym := r.optLabel()
  1837  		return ir.NewBranchStmt(pos, op, sym)
  1838  
  1839  	case stmtCall:
  1840  		pos := r.pos()
  1841  		op := r.op()
  1842  		call := r.expr()
  1843  		stmt := ir.NewGoDeferStmt(pos, op, call)
  1844  		if op == ir.ODEFER {
  1845  			x := r.optExpr()
  1846  			if x != nil {
  1847  				stmt.DeferAt = x.(ir.Expr)
  1848  			}
  1849  		}
  1850  		return stmt
  1851  
  1852  	case stmtExpr:
  1853  		return r.expr()
  1854  
  1855  	case stmtFor:
  1856  		return r.forStmt(label)
  1857  
  1858  	case stmtIf:
  1859  		return r.ifStmt()
  1860  
  1861  	case stmtLabel:
  1862  		pos := r.pos()
  1863  		sym := r.label()
  1864  		return ir.NewLabelStmt(pos, sym)
  1865  
  1866  	case stmtReturn:
  1867  		pos := r.pos()
  1868  		results := r.multiExpr()
  1869  		return ir.NewReturnStmt(pos, results)
  1870  
  1871  	case stmtSelect:
  1872  		return r.selectStmt(label)
  1873  
  1874  	case stmtSend:
  1875  		pos := r.pos()
  1876  		ch := r.expr()
  1877  		value := r.expr()
  1878  		return ir.NewSendStmt(pos, ch, value)
  1879  
  1880  	case stmtSwitch:
  1881  		return r.switchStmt(label)
  1882  	}
  1883  }
  1884  
  1885  func (r *reader) assignList() ([]*ir.Name, []ir.Node) {
  1886  	lhs := make([]ir.Node, r.Len())
  1887  	var names []*ir.Name
  1888  
  1889  	for i := range lhs {
  1890  		expr, def := r.assign()
  1891  		lhs[i] = expr
  1892  		if def {
  1893  			names = append(names, expr.(*ir.Name))
  1894  		}
  1895  	}
  1896  
  1897  	return names, lhs
  1898  }
  1899  
  1900  // assign returns an assignee expression. It also reports whether the
  1901  // returned expression is a newly declared variable.
  1902  func (r *reader) assign() (ir.Node, bool) {
  1903  	switch tag := codeAssign(r.Code(pkgbits.SyncAssign)); tag {
  1904  	default:
  1905  		panic("unhandled assignee expression")
  1906  
  1907  	case assignBlank:
  1908  		return typecheck.AssignExpr(r.curfn, ir.BlankNode), false
  1909  
  1910  	case assignDef:
  1911  		pos := r.pos()
  1912  		lno := base.Pos
  1913  		defer func() { base.Pos = lno }()
  1914  		setBasePos(pos) // test/fixedbugs/issue49767.go depends on base.Pos being set for the r.typ() call here, ugh
  1915  		name := r.curfn.NewLocal(pos, r.localIdent(), r.typ())
  1916  		r.addLocal(name)
  1917  		return name, true
  1918  
  1919  	case assignExpr:
  1920  		return r.expr(), false
  1921  	}
  1922  }
  1923  
  1924  func (r *reader) blockStmt() []ir.Node {
  1925  	r.Sync(pkgbits.SyncBlockStmt)
  1926  	r.openScope()
  1927  	stmts := r.stmts()
  1928  	r.closeScope()
  1929  	return stmts
  1930  }
  1931  
  1932  func (r *reader) forStmt(label *types.Sym) ir.Node {
  1933  	r.Sync(pkgbits.SyncForStmt)
  1934  
  1935  	r.openScope()
  1936  
  1937  	isRange := r.Bool()
  1938  	pos := r.pos()
  1939  	lno := base.Pos
  1940  	defer func() { base.Pos = lno }()
  1941  	base.Pos = pos
  1942  
  1943  	if isRange {
  1944  		rang := ir.NewRangeStmt(pos, nil, nil, nil, nil, false)
  1945  		rang.Label = label
  1946  
  1947  		names, lhs := r.assignList()
  1948  		if len(lhs) >= 1 {
  1949  			rang.Key = lhs[0]
  1950  			if len(lhs) >= 2 {
  1951  				rang.Value = lhs[1]
  1952  			}
  1953  		}
  1954  		rang.Def = r.initDefn(rang, names)
  1955  
  1956  		rang.X = r.expr()
  1957  		if rang.X.Type().IsMap() {
  1958  			rang.RType = r.rtype(pos)
  1959  		}
  1960  		if rang.Key != nil && !ir.IsBlank(rang.Key) {
  1961  			rang.KeyTypeWord, rang.KeySrcRType = r.convRTTI(pos)
  1962  		}
  1963  		if rang.Value != nil && !ir.IsBlank(rang.Value) {
  1964  			rang.ValueTypeWord, rang.ValueSrcRType = r.convRTTI(pos)
  1965  		}
  1966  
  1967  		rang.Body = r.blockStmt()
  1968  		rang.DistinctVars = r.Bool()
  1969  		r.closeAnotherScope()
  1970  
  1971  		return rang
  1972  	}
  1973  
  1974  	init := r.stmt()
  1975  	if init != nil && init.Pos().IsKnown() {
  1976  		lno := base.Pos
  1977  		defer func() { base.Pos = lno }()
  1978  		base.Pos = init.Pos()
  1979  	}
  1980  	cond := r.optExpr()
  1981  	post := r.stmt()
  1982  	body := r.blockStmt()
  1983  	perLoopVars := r.Bool()
  1984  	r.closeAnotherScope()
  1985  
  1986  	if ir.IsConst(cond, constant.Bool) && !ir.BoolVal(cond) {
  1987  		return init // simplify "for init; false; post { ... }" into "init"
  1988  	}
  1989  
  1990  	stmt := ir.NewForStmt(pos, init, cond, post, body, perLoopVars)
  1991  	stmt.Label = label
  1992  	return stmt
  1993  }
  1994  
  1995  func (r *reader) ifStmt() ir.Node {
  1996  	r.Sync(pkgbits.SyncIfStmt)
  1997  	r.openScope()
  1998  	pos := r.pos()
  1999  	lno := base.Pos
  2000  	defer func() { base.Pos = lno }()
  2001  	base.Pos = pos
  2002  	init := r.stmts()
  2003  	if len(init) > 0 && init[len(init)-1].Pos().IsKnown() {
  2004  		lno := base.Pos
  2005  		defer func() { base.Pos = lno }()
  2006  		base.Pos = init[len(init)-1].Pos()
  2007  	}
  2008  	cond := r.expr()
  2009  	staticCond := r.Int()
  2010  	var then, els []ir.Node
  2011  	if staticCond >= 0 {
  2012  		then = r.blockStmt()
  2013  	} else {
  2014  		r.lastCloseScopePos = r.pos()
  2015  	}
  2016  	if staticCond <= 0 {
  2017  		els = r.stmts()
  2018  	}
  2019  	r.closeAnotherScope()
  2020  
  2021  	if staticCond != 0 {
  2022  		// We may have removed a dead return statement, which can trip up
  2023  		// later passes (#62211). To avoid confusion, we instead flatten
  2024  		// the if statement into a block.
  2025  
  2026  		if cond.Op() != ir.OLITERAL {
  2027  			init.Append(typecheck.Stmt(r.curfn, ir.NewAssignStmt(pos, ir.BlankNode, cond))) // for side effects
  2028  		}
  2029  		init.Append(then...)
  2030  		init.Append(els...)
  2031  		return block(init)
  2032  	}
  2033  
  2034  	n := ir.NewIfStmt(pos, cond, then, els)
  2035  	n.SetInit(init)
  2036  	return n
  2037  }
  2038  
  2039  func (r *reader) selectStmt(label *types.Sym) ir.Node {
  2040  	r.Sync(pkgbits.SyncSelectStmt)
  2041  
  2042  	pos := r.pos()
  2043  	clauses := make([]*ir.CommClause, r.Len())
  2044  	for i := range clauses {
  2045  		if i > 0 {
  2046  			r.closeScope()
  2047  		}
  2048  		r.openScope()
  2049  
  2050  		pos := r.pos()
  2051  		comm := r.stmt()
  2052  		body := r.stmts()
  2053  
  2054  		// "case i = <-c: ..." may require an implicit conversion (e.g.,
  2055  		// see fixedbugs/bug312.go). Currently, typecheck throws away the
  2056  		// implicit conversion and relies on it being reinserted later,
  2057  		// but that would lose any explicit RTTI operands too. To preserve
  2058  		// RTTI, we rewrite this as "case tmp := <-c: i = tmp; ...".
  2059  		if as, ok := comm.(*ir.AssignStmt); ok && as.Op() == ir.OAS && !as.Def {
  2060  			if conv, ok := as.Y.(*ir.ConvExpr); ok && conv.Op() == ir.OCONVIFACE {
  2061  				base.AssertfAt(conv.Implicit(), conv.Pos(), "expected implicit conversion: %v", conv)
  2062  
  2063  				recv := conv.X
  2064  				base.AssertfAt(recv.Op() == ir.ORECV, recv.Pos(), "expected receive expression: %v", recv)
  2065  
  2066  				tmp := r.temp(pos, recv.Type())
  2067  
  2068  				// Replace comm with `tmp := <-c`.
  2069  				tmpAs := ir.NewAssignStmt(pos, tmp, recv)
  2070  				tmpAs.Def = true
  2071  				tmpAs.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, tmp))
  2072  				comm = tmpAs
  2073  
  2074  				// Change original assignment to `i = tmp`, and prepend to body.
  2075  				conv.X = tmp
  2076  				body = append([]ir.Node{as}, body...)
  2077  			}
  2078  		}
  2079  
  2080  		// multiExpr will have desugared a comma-ok receive expression
  2081  		// into a separate statement. However, the rest of the compiler
  2082  		// expects comm to be the OAS2RECV statement itself, so we need to
  2083  		// shuffle things around to fit that pattern.
  2084  		if as2, ok := comm.(*ir.AssignListStmt); ok && as2.Op() == ir.OAS2 {
  2085  			init := ir.TakeInit(as2.Rhs[0])
  2086  			base.AssertfAt(len(init) == 1 && init[0].Op() == ir.OAS2RECV, as2.Pos(), "unexpected assignment: %+v", as2)
  2087  
  2088  			comm = init[0]
  2089  			body = append([]ir.Node{as2}, body...)
  2090  		}
  2091  
  2092  		clauses[i] = ir.NewCommStmt(pos, comm, body)
  2093  	}
  2094  	if len(clauses) > 0 {
  2095  		r.closeScope()
  2096  	}
  2097  	n := ir.NewSelectStmt(pos, clauses)
  2098  	n.Label = label
  2099  	return n
  2100  }
  2101  
  2102  func (r *reader) switchStmt(label *types.Sym) ir.Node {
  2103  	r.Sync(pkgbits.SyncSwitchStmt)
  2104  
  2105  	r.openScope()
  2106  	pos := r.pos()
  2107  	lno := base.Pos
  2108  	defer func() { base.Pos = lno }()
  2109  	base.Pos = pos
  2110  	init := r.stmt()
  2111  	if init != nil && init.Pos().IsKnown() {
  2112  		lno := base.Pos
  2113  		defer func() { base.Pos = lno }()
  2114  		base.Pos = init.Pos()
  2115  	}
  2116  
  2117  	var tag ir.Node
  2118  	var ident *ir.Ident
  2119  	var iface *types.Type
  2120  	if r.Bool() {
  2121  		pos := r.pos()
  2122  		lno := base.Pos
  2123  		defer func() { base.Pos = lno }()
  2124  		base.Pos = pos
  2125  		if r.Bool() {
  2126  			ident = ir.NewIdent(r.pos(), r.localIdent())
  2127  		}
  2128  		x := r.expr()
  2129  		iface = x.Type()
  2130  		tag = ir.NewTypeSwitchGuard(pos, ident, x)
  2131  	} else {
  2132  		tag = r.optExpr()
  2133  	}
  2134  
  2135  	clauses := make([]*ir.CaseClause, r.Len())
  2136  	for i := range clauses {
  2137  		if i > 0 {
  2138  			r.closeScope()
  2139  		}
  2140  		r.openScope()
  2141  
  2142  		pos := r.pos()
  2143  		lno := base.Pos
  2144  		base.Pos = pos
  2145  		var cases, rtypes []ir.Node
  2146  		if iface != nil {
  2147  			cases = make([]ir.Node, r.Len())
  2148  			if len(cases) == 0 {
  2149  				cases = nil // TODO(mdempsky): Unclear if this matters.
  2150  			}
  2151  			for i := range cases {
  2152  				if r.Bool() { // case nil
  2153  					cases[i] = typecheck.Expr(r.curfn, types.BuiltinPkg.Lookup("nil").Def.(*ir.NilExpr))
  2154  				} else {
  2155  					cases[i] = r.exprType()
  2156  				}
  2157  			}
  2158  		} else {
  2159  			cases = r.exprList()
  2160  
  2161  			// For `switch { case any(true): }` (e.g., issue 3980 in
  2162  			// test/switch.go), the backend still creates a mixed bool/any
  2163  			// comparison, and we need to explicitly supply the RTTI for the
  2164  			// comparison.
  2165  			//
  2166  			// TODO(mdempsky): Change writer.go to desugar "switch {" into
  2167  			// "switch true {", which we already handle correctly.
  2168  			if tag == nil {
  2169  				for i, cas := range cases {
  2170  					if cas.Type().IsEmptyInterface() {
  2171  						for len(rtypes) < i {
  2172  							rtypes = append(rtypes, nil)
  2173  						}
  2174  						rtypes = append(rtypes, reflectdata.TypePtrAt(r.curfn, cas.Pos(), types.Types[types.TBOOL]))
  2175  					}
  2176  				}
  2177  			}
  2178  		}
  2179  
  2180  		clause := ir.NewCaseStmt(pos, cases, nil)
  2181  		clause.RTypes = rtypes
  2182  
  2183  		if ident != nil {
  2184  			name := r.curfn.NewLocal(r.pos(), ident.Sym(), r.typ())
  2185  			r.addLocal(name)
  2186  			clause.Var = name
  2187  			name.Defn = tag
  2188  		}
  2189  
  2190  		clause.Body = r.stmts()
  2191  		clauses[i] = clause
  2192  		base.Pos = lno
  2193  	}
  2194  	if len(clauses) > 0 {
  2195  		r.closeScope()
  2196  	}
  2197  	r.closeScope()
  2198  
  2199  	n := ir.NewSwitchStmt(pos, tag, clauses)
  2200  	n.Label = label
  2201  	if init != nil {
  2202  		n.SetInit([]ir.Node{init})
  2203  	}
  2204  	return n
  2205  }
  2206  
  2207  func (r *reader) label() *types.Sym {
  2208  	r.Sync(pkgbits.SyncLabel)
  2209  	name := r.String()
  2210  	if r.inlCall != nil && name != "_" {
  2211  		name = fmt.Sprintf("~%s·%d", name, inlgen)
  2212  	}
  2213  	return typecheck.Lookup(name)
  2214  }
  2215  
  2216  func (r *reader) optLabel() *types.Sym {
  2217  	r.Sync(pkgbits.SyncOptLabel)
  2218  	if r.Bool() {
  2219  		return r.label()
  2220  	}
  2221  	return nil
  2222  }
  2223  
  2224  // initDefn marks the given names as declared by defn and populates
  2225  // its Init field with ODCL nodes. It then reports whether any names
  2226  // were so declared, which can be used to initialize defn.Def.
  2227  func (r *reader) initDefn(defn ir.InitNode, names []*ir.Name) bool {
  2228  	if len(names) == 0 {
  2229  		return false
  2230  	}
  2231  
  2232  	init := make([]ir.Node, len(names))
  2233  	for i, name := range names {
  2234  		name.Defn = defn
  2235  		init[i] = ir.NewDecl(name.Pos(), ir.ODCL, name)
  2236  	}
  2237  	defn.SetInit(init)
  2238  	return true
  2239  }
  2240  
  2241  // @@@ Expressions
  2242  
  2243  // expr reads and returns a typechecked expression.
  2244  func (r *reader) expr() (res ir.Node) {
  2245  	defer func() {
  2246  		if res != nil && res.Typecheck() == 0 {
  2247  			base.FatalfAt(res.Pos(), "%v missed typecheck", res)
  2248  		}
  2249  	}()
  2250  
  2251  	switch tag := codeExpr(r.Code(pkgbits.SyncExpr)); tag {
  2252  	default:
  2253  		panic("unhandled expression")
  2254  
  2255  	case exprLocal:
  2256  		return typecheck.Expr(r.curfn, r.useLocal())
  2257  
  2258  	case exprGlobal:
  2259  		// Callee instead of Expr allows builtins
  2260  		// TODO(mdempsky): Handle builtins directly in exprCall, like method calls?
  2261  		return typecheck.Callee(r.curfn, r.obj())
  2262  
  2263  	case exprFuncInst:
  2264  		origPos, pos := r.origPos()
  2265  		wrapperFn, baseFn, dictPtr := r.funcInst(pos)
  2266  		if wrapperFn != nil {
  2267  			return wrapperFn
  2268  		}
  2269  		return r.curry(origPos, false, baseFn, dictPtr, nil)
  2270  
  2271  	case exprConst:
  2272  		pos := r.pos()
  2273  		typ := r.typ()
  2274  		val := FixValue(typ, r.Value())
  2275  		return ir.NewBasicLit(pos, typ, val)
  2276  
  2277  	case exprZero:
  2278  		pos := r.pos()
  2279  		typ := r.typ()
  2280  		return ir.NewZero(pos, typ)
  2281  
  2282  	case exprCompLit:
  2283  		return r.compLit()
  2284  
  2285  	case exprFuncLit:
  2286  		return r.funcLit()
  2287  
  2288  	case exprFieldVal:
  2289  		x := r.expr()
  2290  		pos := r.pos()
  2291  		sym := r.selector()
  2292  
  2293  		return typecheck.XDotField(r.curfn, pos, x, sym)
  2294  
  2295  	case exprMethodVal:
  2296  		recv := r.expr()
  2297  		origPos, pos := r.origPos()
  2298  		wrapperFn, baseFn, dictPtr := r.methodExpr()
  2299  
  2300  		// For simple wrapperFn values, the existing machinery for creating
  2301  		// and deduplicating wrapperFn value wrappers still works fine.
  2302  		if wrapperFn, ok := wrapperFn.(*ir.SelectorExpr); ok && wrapperFn.Op() == ir.OMETHEXPR {
  2303  			// The receiver expression we constructed may have a shape type.
  2304  			// For example, in fixedbugs/issue54343.go, `New[int]()` is
  2305  			// constructed as `New[go.shape.int](&.dict.New[int])`, which
  2306  			// has type `*T[go.shape.int]`, not `*T[int]`.
  2307  			//
  2308  			// However, the method we want to select here is `(*T[int]).M`,
  2309  			// not `(*T[go.shape.int]).M`, so we need to manually convert
  2310  			// the type back so that the OXDOT resolves correctly.
  2311  			//
  2312  			// TODO(mdempsky): Logically it might make more sense for
  2313  			// exprCall to take responsibility for setting a non-shaped
  2314  			// result type, but this is the only place where we care
  2315  			// currently. And only because existing ir.OMETHVALUE backend
  2316  			// code relies on n.X.Type() instead of n.Selection.Recv().Type
  2317  			// (because the latter is types.FakeRecvType() in the case of
  2318  			// interface method values).
  2319  			//
  2320  			if recv.Type().HasShape() {
  2321  				typ := wrapperFn.Type().Param(0).Type
  2322  				if !types.Identical(typ, recv.Type()) {
  2323  					base.FatalfAt(wrapperFn.Pos(), "receiver %L does not match %L", recv, wrapperFn)
  2324  				}
  2325  				recv = typecheck.Expr(r.curfn, ir.NewConvExpr(recv.Pos(), ir.OCONVNOP, typ, recv))
  2326  			}
  2327  
  2328  			n := typecheck.XDotMethod(r.curfn, pos, recv, wrapperFn.Sel, false)
  2329  
  2330  			// As a consistency check here, we make sure "n" selected the
  2331  			// same method (represented by a types.Field) that wrapperFn
  2332  			// selected. However, for anonymous receiver types, there can be
  2333  			// multiple such types.Field instances (#58563). So we may need
  2334  			// to fallback to making sure Sym and Type (including the
  2335  			// receiver parameter's type) match.
  2336  			if n.Selection != wrapperFn.Selection {
  2337  				assert(n.Selection.Sym == wrapperFn.Selection.Sym)
  2338  				assert(types.Identical(n.Selection.Type, wrapperFn.Selection.Type))
  2339  				assert(types.Identical(n.Selection.Type.Recv().Type, wrapperFn.Selection.Type.Recv().Type))
  2340  			}
  2341  
  2342  			wrapper := methodValueWrapper{
  2343  				rcvr:   n.X.Type(),
  2344  				method: n.Selection,
  2345  			}
  2346  
  2347  			if r.importedDef() {
  2348  				haveMethodValueWrappers = append(haveMethodValueWrappers, wrapper)
  2349  			} else {
  2350  				needMethodValueWrappers = append(needMethodValueWrappers, wrapper)
  2351  			}
  2352  			return n
  2353  		}
  2354  
  2355  		// For more complicated method expressions, we construct a
  2356  		// function literal wrapper.
  2357  		return r.curry(origPos, true, baseFn, recv, dictPtr)
  2358  
  2359  	case exprMethodExpr:
  2360  		recv := r.typ()
  2361  
  2362  		implicits := make([]int, r.Len())
  2363  		for i := range implicits {
  2364  			implicits[i] = r.Len()
  2365  		}
  2366  		var deref, addr bool
  2367  		if r.Bool() {
  2368  			deref = true
  2369  		} else if r.Bool() {
  2370  			addr = true
  2371  		}
  2372  
  2373  		origPos, pos := r.origPos()
  2374  		wrapperFn, baseFn, dictPtr := r.methodExpr()
  2375  
  2376  		// If we already have a wrapper and don't need to do anything with
  2377  		// it, we can just return the wrapper directly.
  2378  		//
  2379  		// N.B., we use implicits/deref/addr here as the source of truth
  2380  		// rather than types.Identical, because the latter can be confused
  2381  		// by tricky promoted methods (e.g., typeparam/mdempsky/21.go).
  2382  		if wrapperFn != nil && len(implicits) == 0 && !deref && !addr {
  2383  			if !types.Identical(recv, wrapperFn.Type().Param(0).Type) {
  2384  				base.FatalfAt(pos, "want receiver type %v, but have method %L", recv, wrapperFn)
  2385  			}
  2386  			return wrapperFn
  2387  		}
  2388  
  2389  		// Otherwise, if the wrapper function is a static method
  2390  		// expression (OMETHEXPR) and the receiver type is unshaped, then
  2391  		// we can rely on a statically generated wrapper being available.
  2392  		if method, ok := wrapperFn.(*ir.SelectorExpr); ok && method.Op() == ir.OMETHEXPR && !recv.HasShape() {
  2393  			return typecheck.NewMethodExpr(pos, recv, method.Sel)
  2394  		}
  2395  
  2396  		return r.methodExprWrap(origPos, recv, implicits, deref, addr, baseFn, dictPtr)
  2397  
  2398  	case exprIndex:
  2399  		x := r.expr()
  2400  		pos := r.pos()
  2401  		index := r.expr()
  2402  		n := typecheck.Expr(r.curfn, ir.NewIndexExpr(pos, x, index))
  2403  		switch n.Op() {
  2404  		case ir.OINDEXMAP:
  2405  			n := n.(*ir.IndexExpr)
  2406  			n.RType = r.rtype(pos)
  2407  		}
  2408  		return n
  2409  
  2410  	case exprSlice:
  2411  		x := r.expr()
  2412  		pos := r.pos()
  2413  		var index [3]ir.Node
  2414  		for i := range index {
  2415  			index[i] = r.optExpr()
  2416  		}
  2417  		op := ir.OSLICE
  2418  		if index[2] != nil {
  2419  			op = ir.OSLICE3
  2420  		}
  2421  		return typecheck.Expr(r.curfn, ir.NewSliceExpr(pos, op, x, index[0], index[1], index[2]))
  2422  
  2423  	case exprAssert:
  2424  		x := r.expr()
  2425  		pos := r.pos()
  2426  		typ := r.exprType()
  2427  		srcRType := r.rtype(pos)
  2428  
  2429  		// TODO(mdempsky): Always emit ODYNAMICDOTTYPE for uniformity?
  2430  		if typ, ok := typ.(*ir.DynamicType); ok && typ.Op() == ir.ODYNAMICTYPE {
  2431  			assert := ir.NewDynamicTypeAssertExpr(pos, ir.ODYNAMICDOTTYPE, x, typ.RType)
  2432  			assert.SrcRType = srcRType
  2433  			assert.ITab = typ.ITab
  2434  			return typed(typ.Type(), assert)
  2435  		}
  2436  		return typecheck.Expr(r.curfn, ir.NewTypeAssertExpr(pos, x, typ.Type()))
  2437  
  2438  	case exprUnaryOp:
  2439  		op := r.op()
  2440  		pos := r.pos()
  2441  		x := r.expr()
  2442  
  2443  		switch op {
  2444  		case ir.OADDR:
  2445  			return typecheck.Expr(r.curfn, typecheck.NodAddrAt(r.curfn, pos, x))
  2446  		case ir.ODEREF:
  2447  			return typecheck.Expr(r.curfn, ir.NewStarExpr(pos, x))
  2448  		}
  2449  		return typecheck.Expr(r.curfn, ir.NewUnaryExpr(pos, op, x))
  2450  
  2451  	case exprBinaryOp:
  2452  		op := r.op()
  2453  		x := r.expr()
  2454  		pos := r.pos()
  2455  		y := r.expr()
  2456  
  2457  		switch op {
  2458  		case ir.OANDAND, ir.OOROR:
  2459  			return typecheck.Expr(r.curfn, ir.NewLogicalExpr(pos, op, x, y))
  2460  		case ir.OLSH, ir.ORSH:
  2461  			// Untyped rhs of non-constant shift, e.g. x << 1.0.
  2462  			// If we have a constant value, it must be an int >= 0.
  2463  			if ir.IsConstNode(y) {
  2464  				val := constant.ToInt(y.Val())
  2465  				assert(val.Kind() == constant.Int && constant.Sign(val) >= 0)
  2466  			}
  2467  		}
  2468  		return typecheck.Expr(r.curfn, ir.NewBinaryExpr(pos, op, x, y))
  2469  
  2470  	case exprRecv:
  2471  		x := r.expr()
  2472  		pos := r.pos()
  2473  		for i, n := 0, r.Len(); i < n; i++ {
  2474  			x = Implicit(typecheck.DotField(pos, x, r.Len()))
  2475  		}
  2476  		if r.Bool() { // needs deref
  2477  			x = Implicit(Deref(pos, x.Type().Elem(), x))
  2478  		} else if r.Bool() { // needs addr
  2479  			x = Implicit(Addr(r.curfn, pos, x))
  2480  		}
  2481  		return x
  2482  
  2483  	case exprCall:
  2484  		var fun ir.Node
  2485  		var args ir.Nodes
  2486  		if r.Bool() { // method call
  2487  			recv := r.expr()
  2488  			_, method, dictPtr := r.methodExpr()
  2489  
  2490  			if recv.Type().IsInterface() && method.Op() == ir.OMETHEXPR {
  2491  				method := method.(*ir.SelectorExpr)
  2492  
  2493  				// The compiler backend (e.g., devirtualization) handle
  2494  				// OCALLINTER/ODOTINTER better than OCALLFUNC/OMETHEXPR for
  2495  				// interface calls, so we prefer to continue constructing
  2496  				// calls that way where possible.
  2497  				//
  2498  				// There are also corner cases where semantically it's perhaps
  2499  				// significant; e.g., fixedbugs/issue15975.go, #38634, #52025.
  2500  
  2501  				fun = typecheck.XDotMethod(r.curfn, method.Pos(), recv, method.Sel, true)
  2502  			} else {
  2503  				if recv.Type().IsInterface() {
  2504  					// N.B., this happens currently for typeparam/issue51521.go
  2505  					// and typeparam/typeswitch3.go.
  2506  					if base.Flag.LowerM != 0 {
  2507  						base.WarnfAt(method.Pos(), "imprecise interface call")
  2508  					}
  2509  				}
  2510  
  2511  				fun = method
  2512  				args.Append(recv)
  2513  			}
  2514  			if dictPtr != nil {
  2515  				args.Append(dictPtr)
  2516  			}
  2517  		} else if r.Bool() { // call to instanced function
  2518  			pos := r.pos()
  2519  			_, shapedFn, dictPtr := r.funcInst(pos)
  2520  			fun = shapedFn
  2521  			args.Append(dictPtr)
  2522  		} else {
  2523  			fun = r.expr()
  2524  		}
  2525  		pos := r.pos()
  2526  		args.Append(r.multiExpr()...)
  2527  		dots := r.Bool()
  2528  		n := typecheck.Call(r.curfn, pos, fun, args, dots)
  2529  		switch n.Op() {
  2530  		case ir.OAPPEND:
  2531  			n := n.(*ir.CallExpr)
  2532  			n.RType = r.rtype(pos)
  2533  			// For append(a, b...), we don't need the implicit conversion. The typechecker already
  2534  			// ensured that a and b are both slices with the same base type, or []byte and string.
  2535  			if n.IsDDD {
  2536  				if conv, ok := n.Args[1].(*ir.ConvExpr); ok && conv.Op() == ir.OCONVNOP && conv.Implicit() {
  2537  					n.Args[1] = conv.X
  2538  				}
  2539  			}
  2540  		case ir.OCOPY:
  2541  			n := n.(*ir.BinaryExpr)
  2542  			n.RType = r.rtype(pos)
  2543  		case ir.ODELETE:
  2544  			n := n.(*ir.CallExpr)
  2545  			n.RType = r.rtype(pos)
  2546  		case ir.OUNSAFESLICE:
  2547  			n := n.(*ir.BinaryExpr)
  2548  			n.RType = r.rtype(pos)
  2549  		}
  2550  		return n
  2551  
  2552  	case exprMake:
  2553  		pos := r.pos()
  2554  		typ := r.exprType()
  2555  		extra := r.exprs()
  2556  		n := typecheck.Expr(r.curfn, ir.NewCallExpr(pos, ir.OMAKE, nil, append([]ir.Node{typ}, extra...))).(*ir.MakeExpr)
  2557  		n.RType = r.rtype(pos)
  2558  		return n
  2559  
  2560  	case exprNew:
  2561  		pos := r.pos()
  2562  		if r.Bool() {
  2563  			// new(expr) -> tmp := expr; &tmp
  2564  			x := r.expr()
  2565  			x = typecheck.DefaultLit(x, nil) // See TODO in exprConvert case.
  2566  			var init ir.Nodes
  2567  			addr := ir.NewAddrExpr(pos, r.tempCopy(pos, x, &init))
  2568  			addr.SetInit(init)
  2569  			return typecheck.Expr(r.curfn, addr)
  2570  		}
  2571  		// new(T)
  2572  		return typecheck.Expr(r.curfn, ir.NewUnaryExpr(pos, ir.ONEW, r.exprType()))
  2573  
  2574  	case exprSizeof:
  2575  		return ir.NewUintptr(r.pos(), r.typ().Size())
  2576  
  2577  	case exprAlignof:
  2578  		return ir.NewUintptr(r.pos(), r.typ().Alignment())
  2579  
  2580  	case exprOffsetof:
  2581  		pos := r.pos()
  2582  		typ := r.typ()
  2583  		types.CalcSize(typ)
  2584  
  2585  		var offset int64
  2586  		for i := r.Len(); i >= 0; i-- {
  2587  			field := typ.Field(r.Len())
  2588  			offset += field.Offset
  2589  			typ = field.Type
  2590  		}
  2591  
  2592  		return ir.NewUintptr(pos, offset)
  2593  
  2594  	case exprReshape:
  2595  		typ := r.typ()
  2596  		x := r.expr()
  2597  
  2598  		if types.IdenticalStrict(x.Type(), typ) {
  2599  			return x
  2600  		}
  2601  
  2602  		// Comparison expressions are constructed as "untyped bool" still.
  2603  		//
  2604  		// TODO(mdempsky): It should be safe to reshape them here too, but
  2605  		// maybe it's better to construct them with the proper type
  2606  		// instead.
  2607  		if x.Type() == types.UntypedBool && typ.IsBoolean() {
  2608  			return x
  2609  		}
  2610  
  2611  		base.AssertfAt(x.Type().HasShape() || typ.HasShape(), x.Pos(), "%L and %v are not shape types", x, typ)
  2612  		base.AssertfAt(types.Identical(x.Type(), typ), x.Pos(), "%L is not shape-identical to %v", x, typ)
  2613  
  2614  		// We use ir.HasUniquePos here as a check that x only appears once
  2615  		// in the AST, so it's okay for us to call SetType without
  2616  		// breaking any other uses of it.
  2617  		//
  2618  		// Notably, any ONAMEs should already have the exactly right shape
  2619  		// type and been caught by types.IdenticalStrict above.
  2620  		base.AssertfAt(ir.HasUniquePos(x), x.Pos(), "cannot call SetType(%v) on %L", typ, x)
  2621  
  2622  		if base.Debug.Reshape != 0 {
  2623  			base.WarnfAt(x.Pos(), "reshaping %L to %v", x, typ)
  2624  		}
  2625  
  2626  		x.SetType(typ)
  2627  
  2628  		if call, ok := x.(*ir.CallExpr); ok {
  2629  			call.Reshape = true
  2630  		}
  2631  
  2632  		return x
  2633  
  2634  	case exprConvert:
  2635  		implicit := r.Bool()
  2636  		typ := r.typ()
  2637  		pos := r.pos()
  2638  		typeWord, srcRType := r.convRTTI(pos)
  2639  		dstTypeParam := r.Bool()
  2640  		identical := r.Bool()
  2641  		x := r.expr()
  2642  
  2643  		// spec: "If the type is a type parameter, the constant is converted
  2644  		// into a non-constant value of the type parameter."
  2645  		if dstTypeParam && ir.IsConstNode(x) {
  2646  			// ConvertVal only handles conversions to constant types.
  2647  			if v := typecheck.ConvertVal(x.Val(), typ, false); v.Kind() != constant.Unknown {
  2648  				x = ir.NewBasicLit(x.Pos(), typ, v)
  2649  				// Wrap in an OCONVNOP node to ensure result is non-constant.
  2650  				n := Implicit(ir.NewConvExpr(pos, ir.OCONVNOP, typ, x))
  2651  				n.SetTypecheck(1)
  2652  				return n
  2653  			}
  2654  			// A Go language constant could be converted to a non-constant value,
  2655  			// like converting string to []byte/[]rune. In this case, just construct
  2656  			// the conversion expression as usual, see #79960.
  2657  		}
  2658  
  2659  		// TODO(mdempsky): Stop constructing expressions of untyped type.
  2660  		x = typecheck.DefaultLit(x, typ)
  2661  
  2662  		ce := ir.NewConvExpr(pos, ir.OCONV, typ, x)
  2663  		ce.TypeWord, ce.SrcRType = typeWord, srcRType
  2664  		if implicit {
  2665  			ce.SetImplicit(true)
  2666  		}
  2667  		n := typecheck.Expr(r.curfn, ce)
  2668  
  2669  		// Conversions between non-identical, non-empty interfaces always
  2670  		// requires a runtime call, even if they have identical underlying
  2671  		// interfaces. This is because we create separate itab instances
  2672  		// for each unique interface type, not merely each unique
  2673  		// interface shape.
  2674  		//
  2675  		// However, due to shape types, typecheck.Expr might mistakenly
  2676  		// think a conversion between two non-empty interfaces are
  2677  		// identical and set ir.OCONVNOP, instead of ir.OCONVIFACE. To
  2678  		// ensure we update the itab field appropriately, we force it to
  2679  		// ir.OCONVIFACE instead when shape types are involved.
  2680  		//
  2681  		// TODO(mdempsky): Are there other places we might get this wrong?
  2682  		// Should this be moved down into typecheck.{Assign,Convert}op?
  2683  		// This would be a non-issue if itabs were unique for each
  2684  		// *underlying* interface type instead.
  2685  		if !identical {
  2686  			if n, ok := n.(*ir.ConvExpr); ok && n.Op() == ir.OCONVNOP && n.Type().IsInterface() && !n.Type().IsEmptyInterface() && (n.Type().HasShape() || n.X.Type().HasShape()) {
  2687  				n.SetOp(ir.OCONVIFACE)
  2688  			}
  2689  		}
  2690  
  2691  		return n
  2692  
  2693  	case exprRuntimeBuiltin:
  2694  		builtin := typecheck.LookupRuntime(r.String())
  2695  		return builtin
  2696  	}
  2697  }
  2698  
  2699  // funcInst reads an instantiated function reference, and returns
  2700  // three (possibly nil) expressions related to it:
  2701  //
  2702  // baseFn is always non-nil: it's either a function of the appropriate
  2703  // type already, or it has an extra dictionary parameter as the first
  2704  // parameter.
  2705  //
  2706  // If dictPtr is non-nil, then it's a dictionary argument that must be
  2707  // passed as the first argument to baseFn.
  2708  //
  2709  // If wrapperFn is non-nil, then it's either the same as baseFn (if
  2710  // dictPtr is nil), or it's semantically equivalent to currying baseFn
  2711  // to pass dictPtr. (wrapperFn is nil when dictPtr is an expression
  2712  // that needs to be computed dynamically.)
  2713  //
  2714  // For callers that are creating a call to the returned function, it's
  2715  // best to emit a call to baseFn, and include dictPtr in the arguments
  2716  // list as appropriate.
  2717  //
  2718  // For callers that want to return the function without invoking it,
  2719  // they may return wrapperFn if it's non-nil; but otherwise, they need
  2720  // to create their own wrapper.
  2721  func (r *reader) funcInst(pos src.XPos) (wrapperFn, baseFn, dictPtr ir.Node) {
  2722  	// Like in methodExpr, I'm pretty sure this isn't needed.
  2723  	var implicits []*types.Type
  2724  	if r.dict != nil {
  2725  		implicits = r.dict.targs
  2726  	}
  2727  
  2728  	if r.Bool() { // dynamic subdictionary
  2729  		idx := r.Len()
  2730  		info := r.dict.subdicts[idx]
  2731  		explicits := r.p.typListIdx(info.explicits, r.dict)
  2732  
  2733  		baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
  2734  
  2735  		// TODO(mdempsky): Is there a more robust way to get the
  2736  		// dictionary pointer type here?
  2737  		dictPtrType := baseFn.Type().Param(0).Type
  2738  		dictPtr = typecheck.Expr(r.curfn, ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx)))
  2739  
  2740  		return
  2741  	}
  2742  
  2743  	info := r.objInfo()
  2744  	explicits := r.p.typListIdx(info.explicits, r.dict)
  2745  
  2746  	wrapperFn = r.p.objIdx(info.idx, implicits, explicits, false).(*ir.Name)
  2747  	baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
  2748  
  2749  	dictName := r.p.objDictName(info.idx, implicits, explicits)
  2750  	dictPtr = typecheck.Expr(r.curfn, ir.NewAddrExpr(pos, dictName))
  2751  
  2752  	return
  2753  }
  2754  
  2755  func (pr *pkgReader) objDictName(idx index, implicits, explicits []*types.Type) *ir.Name {
  2756  	rname := pr.newReader(pkgbits.SectionName, idx, pkgbits.SyncObject1)
  2757  	_, sym := rname.qualifiedIdent()
  2758  	tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
  2759  
  2760  	if tag == pkgbits.ObjStub {
  2761  		assert(!sym.IsBlank())
  2762  		if pri, ok := objReader[sym]; ok {
  2763  			return pri.pr.objDictName(pri.idx, nil, explicits)
  2764  		}
  2765  		base.Fatalf("unresolved stub: %v", sym)
  2766  	}
  2767  
  2768  	dict, err := pr.objDictIdx(sym, idx, implicits, explicits, false)
  2769  	if err != nil {
  2770  		base.Fatalf("%v", err)
  2771  	}
  2772  
  2773  	return pr.dictNameOf(dict)
  2774  }
  2775  
  2776  // curry returns a function literal that calls fun with arg0 and
  2777  // (optionally) arg1, accepting additional arguments to the function
  2778  // literal as necessary to satisfy fun's signature.
  2779  //
  2780  // If nilCheck is true and arg0 is an interface value, then it's
  2781  // checked to be non-nil as an initial step at the point of evaluating
  2782  // the function literal itself.
  2783  func (r *reader) curry(origPos src.XPos, ifaceHack bool, fun ir.Node, arg0, arg1 ir.Node) ir.Node {
  2784  	var captured ir.Nodes
  2785  	captured.Append(fun, arg0)
  2786  	if arg1 != nil {
  2787  		captured.Append(arg1)
  2788  	}
  2789  
  2790  	params, results := syntheticSig(fun.Type())
  2791  	params = params[len(captured)-1:] // skip curried parameters
  2792  	typ := types.NewSignature(nil, params, results)
  2793  
  2794  	addBody := func(pos src.XPos, r *reader, captured []ir.Node) {
  2795  		fun := captured[0]
  2796  
  2797  		var args ir.Nodes
  2798  		args.Append(captured[1:]...)
  2799  		args.Append(r.syntheticArgs()...)
  2800  
  2801  		r.syntheticTailCall(pos, fun, args)
  2802  	}
  2803  
  2804  	return r.syntheticClosure(origPos, typ, ifaceHack, captured, addBody)
  2805  }
  2806  
  2807  // methodExprWrap returns a function literal that changes method's
  2808  // first parameter's type to recv, and uses implicits/deref/addr to
  2809  // select the appropriate receiver parameter to pass to method.
  2810  func (r *reader) methodExprWrap(origPos src.XPos, recv *types.Type, implicits []int, deref, addr bool, method, dictPtr ir.Node) ir.Node {
  2811  	var captured ir.Nodes
  2812  	captured.Append(method)
  2813  
  2814  	params, results := syntheticSig(method.Type())
  2815  
  2816  	// Change first parameter to recv.
  2817  	params[0].Type = recv
  2818  
  2819  	// If we have a dictionary pointer argument to pass, then omit the
  2820  	// underlying method expression's dictionary parameter from the
  2821  	// returned signature too.
  2822  	if dictPtr != nil {
  2823  		captured.Append(dictPtr)
  2824  		params = append(params[:1], params[2:]...)
  2825  	}
  2826  
  2827  	typ := types.NewSignature(nil, params, results)
  2828  
  2829  	addBody := func(pos src.XPos, r *reader, captured []ir.Node) {
  2830  		fn := captured[0]
  2831  		args := r.syntheticArgs()
  2832  
  2833  		// Rewrite first argument based on implicits/deref/addr.
  2834  		{
  2835  			arg := args[0]
  2836  			for _, ix := range implicits {
  2837  				arg = Implicit(typecheck.DotField(pos, arg, ix))
  2838  			}
  2839  			if deref {
  2840  				arg = Implicit(Deref(pos, arg.Type().Elem(), arg))
  2841  			} else if addr {
  2842  				arg = Implicit(Addr(r.curfn, pos, arg))
  2843  			}
  2844  			args[0] = arg
  2845  		}
  2846  
  2847  		// Insert dictionary argument, if provided.
  2848  		if dictPtr != nil {
  2849  			newArgs := make([]ir.Node, len(args)+1)
  2850  			newArgs[0] = args[0]
  2851  			newArgs[1] = captured[1]
  2852  			copy(newArgs[2:], args[1:])
  2853  			args = newArgs
  2854  		}
  2855  
  2856  		r.syntheticTailCall(pos, fn, args)
  2857  	}
  2858  
  2859  	return r.syntheticClosure(origPos, typ, false, captured, addBody)
  2860  }
  2861  
  2862  // syntheticClosure constructs a synthetic function literal for
  2863  // currying dictionary arguments. origPos is the position used for the
  2864  // closure, which must be a non-inlined position. typ is the function
  2865  // literal's signature type.
  2866  //
  2867  // captures is a list of expressions that need to be evaluated at the
  2868  // point of function literal evaluation and captured by the function
  2869  // literal. If ifaceHack is true and captures[1] is an interface type,
  2870  // it's checked to be non-nil after evaluation.
  2871  //
  2872  // addBody is a callback function to populate the function body. The
  2873  // list of captured values passed back has the captured variables for
  2874  // use within the function literal, corresponding to the expressions
  2875  // in captures.
  2876  func (r *reader) syntheticClosure(origPos src.XPos, typ *types.Type, ifaceHack bool, captures ir.Nodes, addBody func(pos src.XPos, r *reader, captured []ir.Node)) ir.Node {
  2877  	// isSafe reports whether n is an expression that we can safely
  2878  	// defer to evaluating inside the closure instead, to avoid storing
  2879  	// them into the closure.
  2880  	//
  2881  	// In practice this is always (and only) the wrappee function.
  2882  	isSafe := func(n ir.Node) bool {
  2883  		if n.Op() == ir.ONAME && n.(*ir.Name).Class == ir.PFUNC {
  2884  			return true
  2885  		}
  2886  		if n.Op() == ir.OMETHEXPR {
  2887  			return true
  2888  		}
  2889  
  2890  		return false
  2891  	}
  2892  
  2893  	fn := r.inlClosureFunc(origPos, typ, ir.OCLOSURE)
  2894  	fn.SetWrapper(true)
  2895  
  2896  	clo := fn.OClosure
  2897  	inlPos := clo.Pos()
  2898  
  2899  	var init ir.Nodes
  2900  	for i, n := range captures {
  2901  		if isSafe(n) {
  2902  			continue // skip capture; can reference directly
  2903  		}
  2904  
  2905  		tmp := r.tempCopy(inlPos, n, &init)
  2906  		ir.NewClosureVar(origPos, fn, tmp)
  2907  
  2908  		// We need to nil check interface receivers at the point of method
  2909  		// value evaluation, ugh.
  2910  		if ifaceHack && i == 1 && n.Type().IsInterface() {
  2911  			check := ir.NewUnaryExpr(inlPos, ir.OCHECKNIL, ir.NewUnaryExpr(inlPos, ir.OITAB, tmp))
  2912  			init.Append(typecheck.Stmt(r.curfn, check))
  2913  		}
  2914  	}
  2915  
  2916  	pri := pkgReaderIndex{synthetic: func(pos src.XPos, r *reader) {
  2917  		captured := make([]ir.Node, len(captures))
  2918  		next := 0
  2919  		for i, n := range captures {
  2920  			if isSafe(n) {
  2921  				captured[i] = n
  2922  			} else {
  2923  				captured[i] = r.closureVars[next]
  2924  				next++
  2925  			}
  2926  		}
  2927  		assert(next == len(r.closureVars))
  2928  
  2929  		addBody(origPos, r, captured)
  2930  	}}
  2931  	bodyReader[fn] = pri
  2932  	pri.funcBody(fn)
  2933  
  2934  	return ir.InitExpr(init, clo)
  2935  }
  2936  
  2937  // syntheticSig duplicates and returns the params and results lists
  2938  // for sig, but renaming anonymous parameters so they can be assigned
  2939  // ir.Names.
  2940  func syntheticSig(sig *types.Type) (params, results []*types.Field) {
  2941  	clone := func(params []*types.Field) []*types.Field {
  2942  		res := make([]*types.Field, len(params))
  2943  		for i, param := range params {
  2944  			// TODO(mdempsky): It would be nice to preserve the original
  2945  			// parameter positions here instead, but at least
  2946  			// typecheck.NewMethodType replaces them with base.Pos, making
  2947  			// them useless. Worse, the positions copied from base.Pos may
  2948  			// have inlining contexts, which we definitely don't want here
  2949  			// (e.g., #54625).
  2950  			res[i] = types.NewField(base.AutogeneratedPos, param.Sym, param.Type)
  2951  			res[i].SetIsDDD(param.IsDDD())
  2952  		}
  2953  		return res
  2954  	}
  2955  
  2956  	return clone(sig.Params()), clone(sig.Results())
  2957  }
  2958  
  2959  func (r *reader) optExpr() ir.Node {
  2960  	if r.Bool() {
  2961  		return r.expr()
  2962  	}
  2963  	return nil
  2964  }
  2965  
  2966  // methodExpr reads a method expression reference, and returns three
  2967  // (possibly nil) expressions related to it:
  2968  //
  2969  // baseFn is always non-nil: it's either a function of the appropriate
  2970  // type already, or it has an extra dictionary parameter as the second
  2971  // parameter (i.e., immediately after the promoted receiver
  2972  // parameter).
  2973  //
  2974  // If dictPtr is non-nil, then it's a dictionary argument that must be
  2975  // passed as the second argument to baseFn.
  2976  //
  2977  // If wrapperFn is non-nil, then it's either the same as baseFn (if
  2978  // dictPtr is nil), or it's semantically equivalent to currying baseFn
  2979  // to pass dictPtr. (wrapperFn is nil when dictPtr is an expression
  2980  // that needs to be computed dynamically.)
  2981  //
  2982  // For callers that are creating a call to the returned method, it's
  2983  // best to emit a call to baseFn, and include dictPtr in the arguments
  2984  // list as appropriate.
  2985  //
  2986  // For callers that want to return a method expression without
  2987  // invoking it, they may return wrapperFn if it's non-nil; but
  2988  // otherwise, they need to create their own wrapper.
  2989  func (r *reader) methodExpr() (wrapperFn, baseFn, dictPtr ir.Node) {
  2990  	recv := r.typ()
  2991  
  2992  	var sig *types.Type
  2993  	generic := r.Version().Has(pkgbits.GenericMethods) && r.Bool()
  2994  	if !generic {
  2995  		// Signature type to return (i.e., recv prepended to the method's
  2996  		// normal parameters list).
  2997  		sig = typecheck.NewMethodType(r.typ(), recv)
  2998  	}
  2999  
  3000  	pos := r.pos()
  3001  	sym := r.selector()
  3002  
  3003  	if r.Bool() { // type parameter method expression
  3004  		idx := r.Len()
  3005  		word := r.dictWord(pos, r.dict.typeParamMethodExprsOffset()+idx)
  3006  
  3007  		// TODO(mdempsky): If the type parameter was instantiated with an
  3008  		// interface type (i.e., embed.IsInterface()), then we could
  3009  		// return the OMETHEXPR instead and save an indirection.
  3010  
  3011  		// We wrote the method expression's entry point PC into the
  3012  		// dictionary, but for Go `func` values we need to return a
  3013  		// closure (i.e., pointer to a structure with the PC as the first
  3014  		// field). Because method expressions don't have any closure
  3015  		// variables, we pun the dictionary entry as the closure struct.
  3016  		fn := typecheck.Expr(r.curfn, ir.NewConvExpr(pos, ir.OCONVNOP, sig, ir.NewAddrExpr(pos, word)))
  3017  		return fn, fn, nil
  3018  	}
  3019  
  3020  	if r.Bool() { // dynamic subdictionary
  3021  		idx := r.Len()
  3022  		info := r.dict.subdicts[idx]
  3023  		explicits := r.p.typListIdx(info.explicits, r.dict)
  3024  
  3025  		shapedObj := r.p.objIdx(info.idx, nil, explicits, true).(*ir.Name)
  3026  		shapedFn := shapedMethodExpr(pos, shapedObj, sym)
  3027  
  3028  		// TODO(mdempsky): Is there a more robust way to get the
  3029  		// dictionary pointer type here?
  3030  		dictPtrType := shapedFn.Type().Param(1).Type
  3031  		dictPtr := typecheck.Expr(r.curfn, ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx)))
  3032  
  3033  		return nil, shapedFn, dictPtr
  3034  	}
  3035  
  3036  	if r.Bool() { // static dictionary
  3037  		info := r.objInfo()
  3038  		explicits := r.p.typListIdx(info.explicits, r.dict)
  3039  
  3040  		shapedObj := r.p.objIdx(info.idx, nil, explicits, true).(*ir.Name)
  3041  		shapedFn := shapedMethodExpr(pos, shapedObj, sym)
  3042  
  3043  		dict := r.p.objDictName(info.idx, nil, explicits)
  3044  		dictPtr := typecheck.Expr(r.curfn, ir.NewAddrExpr(pos, dict))
  3045  
  3046  		// Check that dictPtr matches shapedFn's dictionary parameter.
  3047  		if !types.Identical(dictPtr.Type(), shapedFn.Type().Param(1).Type) {
  3048  			base.FatalfAt(pos, "dict %L, but shaped method %L", dict, shapedFn)
  3049  		}
  3050  
  3051  		if !generic {
  3052  			// For statically known instantiations, we can take advantage of
  3053  			// the stenciled wrapper.
  3054  			base.AssertfAt(!recv.HasShape(), pos, "shaped receiver %v", recv)
  3055  			wrapperFn := typecheck.NewMethodExpr(pos, recv, sym)
  3056  			base.AssertfAt(types.Identical(sig, wrapperFn.Type()), pos, "wrapper %L does not have type %v", wrapperFn, sig)
  3057  			return wrapperFn, shapedFn, dictPtr
  3058  		} else {
  3059  			// Also statically known, but there is a good amount of existing
  3060  			// machinery downstream which makes assumptions about method
  3061  			// wrapper functions. It's safest not to emit them for now.
  3062  			// TODO(mark): Emit wrapper functions for generic methods.
  3063  			return nil, shapedFn, dictPtr
  3064  		}
  3065  	}
  3066  
  3067  	// Simple method expression; no dictionary needed.
  3068  	base.AssertfAt(!recv.HasShape() || recv.IsInterface(), pos, "shaped receiver %v", recv)
  3069  	fn := typecheck.NewMethodExpr(pos, recv, sym)
  3070  	return fn, fn, nil
  3071  }
  3072  
  3073  // shapedMethodExpr creates an OMETHEXPR for obj using sym.
  3074  //
  3075  // If obj is an OTYPE, it must refer to a generic type. If obj is an ONAME,
  3076  // it must refer to a generic method. In either case, sym.Name must be the
  3077  // unqualified name of the method.
  3078  //
  3079  // For example, given:
  3080  //
  3081  //	package p
  3082  //
  3083  //	type T[P any] struct {}
  3084  //
  3085  //	func (T[P]) m() {}
  3086  //	func (T[P]) n[Q any]() {}
  3087  //
  3088  // then, using S as go.shape.int:
  3089  //   - in T[int].m,      obj is T[S]      and sym.Name is "m".
  3090  //   - in T[int].n[int], obj is T[S].n[S] and sym.Name is "n".
  3091  //
  3092  // Note that we could have pushed dictionaries down to methods in every case,
  3093  // but since non-generic methods will always share the same "type environment"
  3094  // as their defining type, we can optimize by reusing the type's dictionary.
  3095  func shapedMethodExpr(pos src.XPos, obj *ir.Name, sym *types.Sym) ir.Node {
  3096  	if obj.Op() == ir.OTYPE {
  3097  		// non-generic method on generic type
  3098  		typ := obj.Type()
  3099  		assert(typ.HasShape())
  3100  
  3101  		method := func() *types.Field {
  3102  			for _, m := range typ.Methods() {
  3103  				if m.Sym == sym {
  3104  					return m
  3105  				}
  3106  			}
  3107  
  3108  			base.FatalfAt(pos, "failed to find method %v in shaped type %v", sym, typ)
  3109  			panic("unreachable")
  3110  		}()
  3111  
  3112  		return typecheck.NewMethodExpr(pos, method.Type.Recv().Type, sym)
  3113  	} else {
  3114  		// generic method on possibly generic type
  3115  		assert(obj.Op() == ir.ONAME && obj.Class == ir.PFUNC)
  3116  		typ := obj.Type()
  3117  		assert(typ.HasShape())
  3118  
  3119  		// OMETHEXPR assumes that the linker symbol to call looks like "<type sym>.<method sym>".
  3120  		// This works because non-generic method symbols are relative to their type. But generic
  3121  		// methods use fully-qualified names, so this won't work.
  3122  		//
  3123  		// To use OMETHEXPR for generic methods, we craft a dummy field on the type by removing
  3124  		// the qualifier; OMETHEXPR will put it back later.
  3125  		lsym := obj.Linksym().Name
  3126  		// Since the method is generic, we know the method name must be followed by a bracket.
  3127  		// TODO(mark): It's not ideal to rely on string naming here. Find a more robust solution.
  3128  		idx := func() int { // Find the index of the bracket following the method name.
  3129  			depth, i := 0, len(lsym)-1
  3130  			for {
  3131  				switch lsym[i] {
  3132  				case ']':
  3133  					depth++
  3134  				case '[':
  3135  					depth--
  3136  				}
  3137  				if depth == 0 {
  3138  					return i
  3139  				}
  3140  				i--
  3141  			}
  3142  		}()
  3143  		msym := sym.Pkg.Lookup(lsym[idx-len(sym.Name):])
  3144  
  3145  		// Note that the field name here includes the type arguments; while also not ideal, the
  3146  		// types package does not seem to complain.
  3147  		m := types.NewField(obj.Pos(), msym, typ)
  3148  		m.Nname = obj
  3149  
  3150  		n := ir.NewSelectorExpr(pos, ir.OMETHEXPR, ir.TypeNode(typ.Recv().Type), msym)
  3151  		n.Selection = m
  3152  		n.SetType(typecheck.NewMethodType(typ, typ.Recv().Type))
  3153  		n.SetTypecheck(1)
  3154  
  3155  		return n
  3156  	}
  3157  }
  3158  
  3159  func (r *reader) multiExpr() []ir.Node {
  3160  	r.Sync(pkgbits.SyncMultiExpr)
  3161  
  3162  	if r.Bool() { // N:1
  3163  		pos := r.pos()
  3164  		expr := r.expr()
  3165  
  3166  		results := make([]ir.Node, r.Len())
  3167  		as := ir.NewAssignListStmt(pos, ir.OAS2, nil, []ir.Node{expr})
  3168  		as.Def = true
  3169  		for i := range results {
  3170  			typ := r.typ()
  3171  
  3172  			// The writer skips reshaping *types2.Tuple, thus if expr is a
  3173  			// call to a shaped function, its results have shape types, so
  3174  			// we have to declare the tmps with those types and reshape them
  3175  			// back to the caller's types below. Otherwise the assignment is
  3176  			// a no-op, and the shape type reaches the backend. See #71252.
  3177  			tmpTyp := typ
  3178  			if exprTyp := expr.Type(); exprTyp.IsFuncArgStruct() && exprTyp.HasShape() {
  3179  				tmpTyp = exprTyp.Field(i).Type
  3180  			}
  3181  
  3182  			tmp := r.temp(pos, tmpTyp)
  3183  			tmp.Defn = as
  3184  			as.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, tmp))
  3185  			as.Lhs.Append(tmp)
  3186  
  3187  			res := ir.Node(tmp)
  3188  			if tmpTyp != typ {
  3189  				base.AssertfAt(types.Identical(tmpTyp, typ), pos, "%v is not shape-identical to %v", tmpTyp, typ)
  3190  				conv := ir.NewConvExpr(pos, ir.OCONVNOP, typ, res)
  3191  				conv.SetTypecheck(1)
  3192  				res = conv
  3193  			}
  3194  			if r.Bool() {
  3195  				n := ir.NewConvExpr(pos, ir.OCONV, r.typ(), res)
  3196  				n.TypeWord, n.SrcRType = r.convRTTI(pos)
  3197  				n.SetImplicit(true)
  3198  				res = typecheck.Expr(r.curfn, n)
  3199  			}
  3200  			results[i] = res
  3201  		}
  3202  
  3203  		// TODO(mdempsky): Could use ir.InlinedCallExpr instead?
  3204  		results[0] = ir.InitExpr([]ir.Node{typecheck.Stmt(r.curfn, as)}, results[0])
  3205  		return results
  3206  	}
  3207  
  3208  	// N:N
  3209  	exprs := make([]ir.Node, r.Len())
  3210  	if len(exprs) == 0 {
  3211  		return nil
  3212  	}
  3213  	for i := range exprs {
  3214  		exprs[i] = r.expr()
  3215  	}
  3216  	return exprs
  3217  }
  3218  
  3219  // temp returns a new autotemp of the specified type.
  3220  func (r *reader) temp(pos src.XPos, typ *types.Type) *ir.Name {
  3221  	return typecheck.TempAt(pos, r.curfn, typ)
  3222  }
  3223  
  3224  // tempCopy declares and returns a new autotemp initialized to the
  3225  // value of expr.
  3226  func (r *reader) tempCopy(pos src.XPos, expr ir.Node, init *ir.Nodes) *ir.Name {
  3227  	tmp := r.temp(pos, expr.Type())
  3228  
  3229  	init.Append(typecheck.Stmt(r.curfn, ir.NewDecl(pos, ir.ODCL, tmp)))
  3230  
  3231  	assign := ir.NewAssignStmt(pos, tmp, expr)
  3232  	assign.Def = true
  3233  	init.Append(typecheck.Stmt(r.curfn, assign))
  3234  
  3235  	tmp.Defn = assign
  3236  
  3237  	return tmp
  3238  }
  3239  
  3240  func (r *reader) compLit() ir.Node {
  3241  	r.Sync(pkgbits.SyncCompLit)
  3242  	pos := r.pos()
  3243  	typ0 := r.typ()
  3244  
  3245  	typ := typ0
  3246  	if typ.IsPtr() {
  3247  		typ = typ.Elem()
  3248  	}
  3249  	if typ.Kind() == types.TFORW {
  3250  		base.FatalfAt(pos, "unresolved composite literal type: %v", typ)
  3251  	}
  3252  	var rtype ir.Node
  3253  	if typ.IsMap() {
  3254  		rtype = r.rtype(pos)
  3255  	}
  3256  
  3257  	var elems []ir.Node
  3258  	if r.Version().Has(pkgbits.CompactCompLiterals) {
  3259  		n := r.Int()
  3260  		elems = make([]ir.Node, max(n, -n) /* abs(n) */)
  3261  		switch typ.Kind() {
  3262  		default:
  3263  			base.FatalfAt(pos, "unexpected composite literal type: %v", typ)
  3264  		case types.TARRAY:
  3265  			r.arrayElems(n >= 0, elems)
  3266  		case types.TMAP:
  3267  			r.mapElems(elems)
  3268  		case types.TSLICE:
  3269  			r.arrayElems(n >= 0, elems)
  3270  		case types.TSTRUCT:
  3271  			r.structElems(typ, n >= 0, elems)
  3272  		}
  3273  	} else {
  3274  		elems = make([]ir.Node, r.Len())
  3275  		isStruct := typ.Kind() == types.TSTRUCT
  3276  		for i := range elems {
  3277  			elemp := &elems[i]
  3278  			if isStruct {
  3279  				sk := ir.NewStructKeyExpr(r.pos(), typ.Field(r.Len()), nil)
  3280  				*elemp, elemp = sk, &sk.Value
  3281  			} else if r.Bool() {
  3282  				kv := ir.NewKeyExpr(r.pos(), r.expr(), nil)
  3283  				*elemp, elemp = kv, &kv.Value
  3284  			}
  3285  			*elemp = r.expr()
  3286  		}
  3287  	}
  3288  
  3289  	lit := typecheck.Expr(r.curfn, ir.NewCompLitExpr(pos, ir.OCOMPLIT, typ, elems))
  3290  	if rtype != nil {
  3291  		lit := lit.(*ir.CompLitExpr)
  3292  		lit.RType = rtype
  3293  	}
  3294  	if typ0.IsPtr() {
  3295  		lit = typecheck.Expr(r.curfn, typecheck.NodAddrAt(r.curfn, pos, lit))
  3296  		lit.SetType(typ0)
  3297  	}
  3298  	return lit
  3299  }
  3300  
  3301  func (r *reader) arrayElems(valuesOnly bool, elems []ir.Node) {
  3302  	if valuesOnly {
  3303  		for i := range elems {
  3304  			elems[i] = r.expr()
  3305  		}
  3306  		return
  3307  	}
  3308  	// some elements may have a key
  3309  	for i := range elems {
  3310  		if r.Bool() {
  3311  			kv := ir.NewKeyExpr(r.pos(), r.expr(), nil)
  3312  			kv.Value = r.expr()
  3313  			elems[i] = kv
  3314  		} else {
  3315  			elems[i] = r.expr()
  3316  		}
  3317  	}
  3318  }
  3319  
  3320  func (r *reader) mapElems(elems []ir.Node) {
  3321  	// all elements have a key
  3322  	for i := range elems {
  3323  		kv := ir.NewKeyExpr(r.pos(), r.expr(), nil)
  3324  		kv.Value = r.expr()
  3325  		elems[i] = kv
  3326  	}
  3327  }
  3328  
  3329  func (r *reader) structElems(typ *types.Type, valuesOnly bool, elems []ir.Node) {
  3330  	if valuesOnly {
  3331  		for i := range elems {
  3332  			sk := ir.NewStructKeyExpr(r.pos(), typ.Field(i), nil)
  3333  			sk.Value = r.expr()
  3334  			elems[i] = sk
  3335  		}
  3336  		return
  3337  	}
  3338  
  3339  	// all elements have a key
  3340  	for i := range elems {
  3341  		pos := r.pos()
  3342  		var fld *types.Field
  3343  		if n := r.Int(); n < 0 {
  3344  			// embedded field
  3345  			typ := typ // don't modify the original typ
  3346  			for range -n {
  3347  				fld = typ.Field(r.Int())
  3348  				typ = fld.Type
  3349  			}
  3350  		} else { // n >= 0
  3351  			fld = typ.Field(n)
  3352  		}
  3353  		sk := ir.NewStructKeyExpr(pos, fld, nil)
  3354  		sk.Value = r.expr()
  3355  		elems[i] = sk
  3356  	}
  3357  }
  3358  
  3359  func (r *reader) funcLit() ir.Node {
  3360  	r.Sync(pkgbits.SyncFuncLit)
  3361  
  3362  	// The underlying function declaration (including its parameters'
  3363  	// positions, if any) need to remain the original, uninlined
  3364  	// positions. This is because we track inlining-context on nodes so
  3365  	// we can synthesize the extra implied stack frames dynamically when
  3366  	// generating tracebacks, whereas those stack frames don't make
  3367  	// sense *within* the function literal. (Any necessary inlining
  3368  	// adjustments will have been applied to the call expression
  3369  	// instead.)
  3370  	//
  3371  	// This is subtle, and getting it wrong leads to cycles in the
  3372  	// inlining tree, which lead to infinite loops during stack
  3373  	// unwinding (#46234, #54625).
  3374  	//
  3375  	// Note that we *do* want the inline-adjusted position for the
  3376  	// OCLOSURE node, because that position represents where any heap
  3377  	// allocation of the closure is credited (#49171).
  3378  	r.suppressInlPos++
  3379  	origPos := r.pos()
  3380  	sig := r.signature(nil)
  3381  	r.suppressInlPos--
  3382  	why := ir.OCLOSURE
  3383  	if r.Bool() {
  3384  		why = ir.ORANGE
  3385  	}
  3386  
  3387  	fn := r.inlClosureFunc(origPos, sig, why)
  3388  
  3389  	fn.ClosureVars = make([]*ir.Name, 0, r.Len())
  3390  	for len(fn.ClosureVars) < cap(fn.ClosureVars) {
  3391  		// TODO(mdempsky): I think these should be original positions too
  3392  		// (i.e., not inline-adjusted).
  3393  		ir.NewClosureVar(r.pos(), fn, r.useLocal())
  3394  	}
  3395  	if param := r.dictParam; param != nil {
  3396  		// If we have a dictionary parameter, capture it too. For
  3397  		// simplicity, we capture it last and unconditionally.
  3398  		ir.NewClosureVar(param.Pos(), fn, param)
  3399  	}
  3400  
  3401  	r.addBody(fn, nil)
  3402  
  3403  	return fn.OClosure
  3404  }
  3405  
  3406  // inlClosureFunc constructs a new closure function, but correctly
  3407  // handles inlining.
  3408  func (r *reader) inlClosureFunc(origPos src.XPos, sig *types.Type, why ir.Op) *ir.Func {
  3409  	curfn := r.inlCaller
  3410  	if curfn == nil {
  3411  		curfn = r.curfn
  3412  	}
  3413  
  3414  	var gen int
  3415  	if why == ir.ORANGE {
  3416  		r.rangeLitGen++
  3417  		gen = r.rangeLitGen
  3418  	} else {
  3419  		r.funcLitGen++
  3420  		gen = r.funcLitGen
  3421  	}
  3422  
  3423  	// TODO(mdempsky): Remove hard-coding of typecheck.Target.
  3424  	return ir.NewClosureFunc(origPos, r.inlPos(origPos), why, sig, curfn, typecheck.Target, gen)
  3425  }
  3426  
  3427  func (r *reader) exprList() []ir.Node {
  3428  	r.Sync(pkgbits.SyncExprList)
  3429  	return r.exprs()
  3430  }
  3431  
  3432  func (r *reader) exprs() []ir.Node {
  3433  	r.Sync(pkgbits.SyncExprs)
  3434  	nodes := make([]ir.Node, r.Len())
  3435  	if len(nodes) == 0 {
  3436  		return nil // TODO(mdempsky): Unclear if this matters.
  3437  	}
  3438  	for i := range nodes {
  3439  		nodes[i] = r.expr()
  3440  	}
  3441  	return nodes
  3442  }
  3443  
  3444  // dictWord returns an expression to return the specified
  3445  // uintptr-typed word from the dictionary parameter.
  3446  func (r *reader) dictWord(pos src.XPos, idx int) ir.Node {
  3447  	base.AssertfAt(r.dictParam != nil, pos, "expected dictParam in %v", r.curfn)
  3448  	return typecheck.Expr(r.curfn, ir.NewIndexExpr(pos, r.dictParam, ir.NewInt(pos, int64(idx))))
  3449  }
  3450  
  3451  // rttiWord is like dictWord, but converts it to *byte (the type used
  3452  // internally to represent *runtime._type and *runtime.itab).
  3453  func (r *reader) rttiWord(pos src.XPos, idx int) ir.Node {
  3454  	return typecheck.Expr(r.curfn, ir.NewConvExpr(pos, ir.OCONVNOP, types.NewPtr(types.Types[types.TUINT8]), r.dictWord(pos, idx)))
  3455  }
  3456  
  3457  // rtype reads a type reference from the element bitstream, and
  3458  // returns an expression of type *runtime._type representing that
  3459  // type.
  3460  func (r *reader) rtype(pos src.XPos) ir.Node {
  3461  	_, rtype := r.rtype0(pos)
  3462  	return rtype
  3463  }
  3464  
  3465  func (r *reader) rtype0(pos src.XPos) (typ *types.Type, rtype ir.Node) {
  3466  	r.Sync(pkgbits.SyncRType)
  3467  	if r.Bool() { // derived type
  3468  		idx := r.Len()
  3469  		info := r.dict.rtypes[idx]
  3470  		typ = r.p.typIdx(info, r.dict, true)
  3471  		rtype = r.rttiWord(pos, r.dict.rtypesOffset()+idx)
  3472  		return
  3473  	}
  3474  
  3475  	typ = r.typ()
  3476  	rtype = reflectdata.TypePtrAt(r.curfn, pos, typ)
  3477  	return
  3478  }
  3479  
  3480  // varDictIndex populates name.DictIndex if name is a derived type.
  3481  func (r *reader) varDictIndex(name *ir.Name) {
  3482  	if r.Bool() {
  3483  		idx := 1 + r.dict.rtypesOffset() + r.Len()
  3484  		if int(uint16(idx)) != idx {
  3485  			base.FatalfAt(name.Pos(), "DictIndex overflow for %v: %v", name, idx)
  3486  		}
  3487  		name.DictIndex = uint16(idx)
  3488  	}
  3489  }
  3490  
  3491  // itab returns a (typ, iface) pair of types.
  3492  //
  3493  // typRType and ifaceRType are expressions that evaluate to the
  3494  // *runtime._type for typ and iface, respectively.
  3495  //
  3496  // If typ is a concrete type and iface is a non-empty interface type,
  3497  // then itab is an expression that evaluates to the *runtime.itab for
  3498  // the pair. Otherwise, itab is nil.
  3499  func (r *reader) itab(pos src.XPos) (typ *types.Type, typRType ir.Node, iface *types.Type, ifaceRType ir.Node, itab ir.Node) {
  3500  	typ, typRType = r.rtype0(pos)
  3501  	iface, ifaceRType = r.rtype0(pos)
  3502  
  3503  	idx := -1
  3504  	if r.Bool() {
  3505  		idx = r.Len()
  3506  	}
  3507  
  3508  	if !typ.IsInterface() && iface.IsInterface() && !iface.IsEmptyInterface() {
  3509  		if idx >= 0 {
  3510  			itab = r.rttiWord(pos, r.dict.itabsOffset()+idx)
  3511  		} else {
  3512  			base.AssertfAt(!typ.HasShape(), pos, "%v is a shape type", typ)
  3513  			base.AssertfAt(!iface.HasShape(), pos, "%v is a shape type", iface)
  3514  
  3515  			lsym := reflectdata.ITabLsym(typ, iface)
  3516  			itab = typecheck.LinksymAddr(r.curfn, pos, lsym, types.Types[types.TUINT8])
  3517  		}
  3518  	}
  3519  
  3520  	return
  3521  }
  3522  
  3523  // convRTTI returns expressions appropriate for populating an
  3524  // ir.ConvExpr's TypeWord and SrcRType fields, respectively.
  3525  func (r *reader) convRTTI(pos src.XPos) (typeWord, srcRType ir.Node) {
  3526  	r.Sync(pkgbits.SyncConvRTTI)
  3527  	src, srcRType0, dst, dstRType, itab := r.itab(pos)
  3528  	if !dst.IsInterface() {
  3529  		return
  3530  	}
  3531  
  3532  	// See reflectdata.ConvIfaceTypeWord.
  3533  	switch {
  3534  	case dst.IsEmptyInterface():
  3535  		if !src.IsInterface() {
  3536  			typeWord = srcRType0 // direct eface construction
  3537  		}
  3538  	case !src.IsInterface():
  3539  		typeWord = itab // direct iface construction
  3540  	default:
  3541  		typeWord = dstRType // convI2I
  3542  	}
  3543  
  3544  	// See reflectdata.ConvIfaceSrcRType.
  3545  	if !src.IsInterface() {
  3546  		srcRType = srcRType0
  3547  	}
  3548  
  3549  	return
  3550  }
  3551  
  3552  func (r *reader) exprType() ir.Node {
  3553  	r.Sync(pkgbits.SyncExprType)
  3554  	pos := r.pos()
  3555  
  3556  	var typ *types.Type
  3557  	var rtype, itab ir.Node
  3558  
  3559  	if r.Bool() {
  3560  		// non-empty interface
  3561  		typ, rtype, _, _, itab = r.itab(pos)
  3562  		if !typ.IsInterface() {
  3563  			rtype = nil // TODO(mdempsky): Leave set?
  3564  		}
  3565  	} else {
  3566  		typ, rtype = r.rtype0(pos)
  3567  
  3568  		if !r.Bool() { // not derived
  3569  			return ir.TypeNode(typ)
  3570  		}
  3571  	}
  3572  
  3573  	dt := ir.NewDynamicType(pos, rtype)
  3574  	dt.ITab = itab
  3575  	dt = typed(typ, dt).(*ir.DynamicType)
  3576  	if st := dt.ToStatic(); st != nil {
  3577  		return st
  3578  	}
  3579  	return dt
  3580  }
  3581  
  3582  func (r *reader) op() ir.Op {
  3583  	r.Sync(pkgbits.SyncOp)
  3584  	return ir.Op(r.Len())
  3585  }
  3586  
  3587  // @@@ Package initialization
  3588  
  3589  func (r *reader) pkgInit(self *types.Pkg, target *ir.Package) {
  3590  	cgoPragmas := make([][]string, r.Len())
  3591  	for i := range cgoPragmas {
  3592  		cgoPragmas[i] = r.Strings()
  3593  	}
  3594  	target.CgoPragmas = cgoPragmas
  3595  
  3596  	r.pkgInitOrder(target)
  3597  
  3598  	r.pkgDecls(target)
  3599  
  3600  	r.Sync(pkgbits.SyncEOF)
  3601  }
  3602  
  3603  // pkgInitOrder creates a synthetic init function to handle any
  3604  // package-scope initialization statements.
  3605  func (r *reader) pkgInitOrder(target *ir.Package) {
  3606  	initOrder := make([]ir.Node, r.Len())
  3607  	if len(initOrder) == 0 {
  3608  		return
  3609  	}
  3610  
  3611  	// Make a function that contains all the initialization statements.
  3612  	pos := base.AutogeneratedPos
  3613  	lno := base.Pos
  3614  	defer func() { base.Pos = lno }()
  3615  	base.Pos = pos
  3616  
  3617  	fn := ir.NewFunc(pos, pos, typecheck.Lookup("init"), types.NewSignature(nil, nil, nil))
  3618  	fn.SetIsPackageInit(true)
  3619  	fn.SetInlinabilityChecked(true) // suppress useless "can inline" diagnostics
  3620  
  3621  	typecheck.DeclFunc(fn)
  3622  	r.curfn = fn
  3623  
  3624  	var varInitFns []*ir.Func
  3625  	if len(initOrder) <= maxInitStatements {
  3626  		fn.Body = r.doPkgInitOrder(initOrder)
  3627  	} else {
  3628  		varInitFns = r.splitLargeInitOrder(initOrder)
  3629  		calls := make([]ir.Node, len(varInitFns))
  3630  		for i, varInitFn := range varInitFns {
  3631  			ir.WithPos(fn, func() {
  3632  				calls[i] = typecheck.Call(r.curfn, varInitFn.Pos(), varInitFn.Nname, nil, false)
  3633  			})
  3634  		}
  3635  		fn.Body = calls
  3636  	}
  3637  
  3638  	r.curfn = nil
  3639  	r.locals = nil
  3640  
  3641  	// Outline (if legal/profitable) global map inits.
  3642  	staticinit.OutlineMapInits(fn)
  3643  	for _, varInitFn := range varInitFns {
  3644  		staticinit.OutlineMapInits(varInitFn)
  3645  	}
  3646  
  3647  	target.Inits = append(target.Inits, fn)
  3648  }
  3649  
  3650  const maxInitStatements = 1000
  3651  
  3652  func (r *reader) generateVarInitFunc(body []ir.Node) *ir.Func {
  3653  	fn := staticinit.GenerateVarInitFunc()
  3654  	typecheck.DeclFunc(fn)
  3655  
  3656  	old := r.curfn
  3657  	r.curfn = fn
  3658  	fn.Body = r.doPkgInitOrder(body)
  3659  	r.curfn = old
  3660  
  3661  	return fn
  3662  }
  3663  
  3664  func (r *reader) doPkgInitOrder(initOrder []ir.Node) []ir.Node {
  3665  	for i := range initOrder {
  3666  		lhs := make([]ir.Node, r.Len())
  3667  		for j := range lhs {
  3668  			lhs[j] = r.obj()
  3669  		}
  3670  		rhs := r.expr()
  3671  		pos := lhs[0].Pos()
  3672  
  3673  		simdCond := r.simdInitGuard(pos, lhs)
  3674  
  3675  		var as ir.Node
  3676  		if len(lhs) == 1 {
  3677  			as = typecheck.Stmt(r.curfn, ir.NewAssignStmt(pos, lhs[0], rhs))
  3678  		} else {
  3679  			as = typecheck.Stmt(r.curfn, ir.NewAssignListStmt(pos, ir.OAS2, lhs, []ir.Node{rhs}))
  3680  		}
  3681  
  3682  		if simdCond != nil {
  3683  			// Leave Defn nil for conditionally initialized vars so staticinit
  3684  			// will not treat a guarded assignment as an unconditional static value.
  3685  			as = typecheck.Stmt(r.curfn, ir.NewIfStmt(pos, simdCond, []ir.Node{as}, nil))
  3686  		} else {
  3687  			for _, v := range lhs {
  3688  				v.(*ir.Name).Defn = as
  3689  			}
  3690  		}
  3691  
  3692  		initOrder[i] = as
  3693  	}
  3694  	return initOrder
  3695  }
  3696  
  3697  // simdInitGuard inspects the LHS of a package-level variable initializer for
  3698  // either:
  3699  //   - synthetic SIMD init proxies ("@simdinit<size>@<target>"), which
  3700  //     represent conditional initializers for non-SIMD-typed variables (or blank
  3701  //     "_") and are rewritten in place on lhs to target the original variable
  3702  //     (or a blank name), or
  3703  //   - SIMD-specialized variables ("<name>@simd<size>"), whose type
  3704  //     depends on SIMD.
  3705  //
  3706  // Package-level variable initializers cannot use a switch in func init()
  3707  // (which would break Go-spec package variable initialization order) or an
  3708  // immediately-invoked func() T { ... }() dispatcher emitted in midway (which
  3709  // cannot spell inferred unexported types from other packages in Go syntax,
  3710  // such as "var V = isimd.F()" in simd/testdata/timport/relay). Instead,
  3711  // midway emits per-size VarDecls/proxies in place and the unified IR reader
  3712  // wraps each specialized initializer in a runtime guard here.
  3713  //
  3714  // If lhs contains neither (or GOEXPERIMENT=simdstable is disabled), it returns nil.
  3715  // Otherwise it returns a runtime boolean expression testing whether the active
  3716  // SIMD configuration matches the initializer's vector bit size (or emulation
  3717  // when size == 0). The guard predicate must stay in sync with the runtime
  3718  // dispatch logic in midway.(*Rewriter).createDispatcherBody.
  3719  func (r *reader) simdInitGuard(pos src.XPos, lhs []ir.Node) ir.Node {
  3720  	if !buildcfg.Experiment.SIMDStable {
  3721  		return nil
  3722  	}
  3723  
  3724  	oldPos := base.Pos
  3725  	base.Pos = pos
  3726  	defer func() { base.Pos = oldPos }()
  3727  
  3728  	vecSize := -1
  3729  	for i, n := range lhs {
  3730  		name := n.(*ir.Name)
  3731  		if name.Sym() == nil {
  3732  			continue
  3733  		}
  3734  		if baseName, size, ok := midway.ParseSimdInitProxy(name.Sym().Name); ok {
  3735  			if vecSize != -1 && vecSize != size {
  3736  				base.FatalfAt(pos, "saw more than one size for SIMD init proxy or suffix, first = %d, second = %d", vecSize, size)
  3737  			}
  3738  			vecSize = size
  3739  			if baseName == "_" {
  3740  				blank := ir.NewDeclNameAt(name.Pos(), ir.ONAME, types.LocalPkg.Lookup("_"))
  3741  				blank.Class = ir.PEXTERN
  3742  				setType(blank, name.Type())
  3743  				lhs[i] = blank
  3744  			} else {
  3745  				origName := lookupPkgVar(baseName)
  3746  				if origName == nil {
  3747  					base.FatalfAt(pos, "failed to lookup local var %q for SIMD init proxy %q", baseName, name.Sym().Name)
  3748  				}
  3749  				lhs[i] = origName
  3750  			}
  3751  			continue
  3752  		}
  3753  		if _, size, ok := midway.ParseSimdSuffix(name.Sym().Name); ok {
  3754  			if vecSize != -1 && vecSize != size {
  3755  				base.FatalfAt(pos, "saw more than one size for SIMD init proxy or suffix, first = %d, second = %d", vecSize, size)
  3756  			}
  3757  			vecSize = size
  3758  		}
  3759  	}
  3760  	if vecSize < 0 {
  3761  		return nil
  3762  	}
  3763  
  3764  	simdPkg := types.NewPkg("simd", "")
  3765  	callSimd := func(fnName string) ir.Node {
  3766  		fn, err := lookupFunction(simdPkg, fnName)
  3767  		if err != nil {
  3768  			base.FatalfAt(pos, "failed to lookup simd.%s: %v", fnName, err)
  3769  		}
  3770  		return typecheck.Call(r.curfn, pos, fn.Nname, nil, false)
  3771  	}
  3772  
  3773  	if vecSize == 0 {
  3774  		return callSimd("Emulated")
  3775  	}
  3776  
  3777  	notEmulated := typecheck.Expr(r.curfn, ir.NewUnaryExpr(pos, ir.ONOT, callSimd("Emulated")))
  3778  	sizeEq := typecheck.Expr(r.curfn, ir.NewBinaryExpr(pos, ir.OEQ, callSimd("VectorBits"), ir.NewInt(pos, int64(vecSize))))
  3779  	return typecheck.Expr(r.curfn, ir.NewLogicalExpr(pos, ir.OANDAND, notEmulated, sizeEq))
  3780  }
  3781  
  3782  // lookupPkgVar looks up a package-level variable (ir.PEXTERN) named baseName
  3783  // in types.LocalPkg, instantiating it from Unified IR via objReader if its
  3784  // symbol definition has not yet been materialized. It returns nil if no such
  3785  // package-level variable exists.
  3786  func lookupPkgVar(baseName string) *ir.Name {
  3787  	sym := types.LocalPkg.Lookup(baseName)
  3788  	if sym.Def != nil {
  3789  		if n, ok := sym.Def.(*ir.Name); ok && n.Op() == ir.ONAME && n.Class == ir.PEXTERN {
  3790  			return n
  3791  		}
  3792  		return nil
  3793  	}
  3794  	pri, ok := objReader[sym]
  3795  	if !ok {
  3796  		return nil
  3797  	}
  3798  	node, err := pri.pr.objIdxMayFail(pri.idx, nil, nil, false)
  3799  	if err != nil {
  3800  		return nil
  3801  	}
  3802  	if n, ok := node.(*ir.Name); ok && n.Op() == ir.ONAME && n.Class == ir.PEXTERN {
  3803  		return n
  3804  	}
  3805  	return nil
  3806  }
  3807  
  3808  func (r *reader) splitLargeInitOrder(initOrder []ir.Node) []*ir.Func {
  3809  	var initFuncs []*ir.Func
  3810  	for chunk := range slices.Chunk(initOrder, maxInitStatements) {
  3811  		initFuncs = append(initFuncs, r.generateVarInitFunc(chunk))
  3812  	}
  3813  	return initFuncs
  3814  }
  3815  
  3816  // midwayOriginals is the set of package-level declarations in the
  3817  // local package that the midway rewrite kept only for type checking
  3818  // and export data (see [midway.RewriteWrapper]). The methods of a type
  3819  // in this set are also originals.
  3820  //
  3821  // The reader still reads the originals, because writing the export
  3822  // data requires their IR. But nothing that gets compiled refers to
  3823  // them, so the reader doesn't add them to the target package. That
  3824  // keeps the backend from generating code, type descriptors, or
  3825  // storage for them.
  3826  var midwayOriginals map[*types.Sym]bool
  3827  
  3828  func (r *reader) pkgDecls(target *ir.Package) {
  3829  	r.Sync(pkgbits.SyncDecls)
  3830  	for _, name := range r.Strings() {
  3831  		if midwayOriginals == nil {
  3832  			midwayOriginals = make(map[*types.Sym]bool)
  3833  		}
  3834  		midwayOriginals[types.LocalPkg.Lookup(name)] = true
  3835  	}
  3836  	for {
  3837  		switch code := codeDecl(r.Code(pkgbits.SyncDecl)); code {
  3838  		default:
  3839  			panic(fmt.Sprintf("unhandled decl: %v", code))
  3840  
  3841  		case declEnd:
  3842  			return
  3843  
  3844  		case declFunc:
  3845  			names := r.pkgObjs(target)
  3846  			assert(len(names) == 1)
  3847  			if midwayOriginals[names[0].Sym()] {
  3848  				break
  3849  			}
  3850  			target.Funcs = append(target.Funcs, names[0].Func)
  3851  
  3852  		case declMethod:
  3853  			typ := r.typ()
  3854  			sym := r.selector()
  3855  
  3856  			method := typecheck.Lookdot1(nil, sym, typ, typ.Methods(), 0)
  3857  			if midwayOriginals[typ.Sym()] {
  3858  				break
  3859  			}
  3860  			target.Funcs = append(target.Funcs, method.Nname.(*ir.Name).Func)
  3861  
  3862  		case declVar:
  3863  			names := r.pkgObjs(target)
  3864  
  3865  			if n := r.Len(); n > 0 {
  3866  				assert(len(names) == 1)
  3867  				embeds := make([]ir.Embed, n)
  3868  				for i := range embeds {
  3869  					embeds[i] = ir.Embed{Pos: r.pos(), Patterns: r.Strings()}
  3870  				}
  3871  				names[0].Embed = &embeds
  3872  				target.Embeds = append(target.Embeds, names[0])
  3873  			}
  3874  
  3875  		case declOther:
  3876  			r.pkgObjs(target)
  3877  		}
  3878  	}
  3879  }
  3880  
  3881  func (r *reader) pkgObjs(target *ir.Package) []*ir.Name {
  3882  	r.Sync(pkgbits.SyncDeclNames)
  3883  	nodes := make([]*ir.Name, r.Len())
  3884  	for i := range nodes {
  3885  		r.Sync(pkgbits.SyncDeclName)
  3886  
  3887  		name := r.obj().(*ir.Name)
  3888  		nodes[i] = name
  3889  
  3890  		sym := name.Sym()
  3891  		if sym.IsBlank() || midwayOriginals[sym] {
  3892  			continue
  3893  		}
  3894  
  3895  		switch name.Class {
  3896  		default:
  3897  			base.FatalfAt(name.Pos(), "unexpected class: %v", name.Class)
  3898  
  3899  		case ir.PEXTERN:
  3900  			target.Externs = append(target.Externs, name)
  3901  
  3902  		case ir.PFUNC:
  3903  			assert(name.Type().Recv() == nil)
  3904  
  3905  			// TODO(mdempsky): Cleaner way to recognize init?
  3906  			if strings.HasPrefix(sym.Name, "init.") {
  3907  				target.Inits = append(target.Inits, name.Func)
  3908  			}
  3909  		}
  3910  
  3911  		// The size-specialized copies that midway makes of a declaration
  3912  		// are an implementation detail, like the instantiations of a
  3913  		// generic function, so a plugin doesn't export them.
  3914  		if base.Ctxt.Flag_dynlink && types.LocalPkg.Name == "main" && types.IsExported(sym.Name) && name.Op() == ir.ONAME && !midway.IsSpecializedName(sym.Name) {
  3915  			assert(!sym.OnExportList())
  3916  			target.PluginExports = append(target.PluginExports, name)
  3917  			sym.SetOnExportList(true)
  3918  		}
  3919  
  3920  		if base.Flag.AsmHdr != "" && (name.Op() == ir.OLITERAL || name.Op() == ir.OTYPE) {
  3921  			assert(!sym.Asm())
  3922  			target.AsmHdrDecls = append(target.AsmHdrDecls, name)
  3923  			sym.SetAsm(true)
  3924  		}
  3925  	}
  3926  
  3927  	return nodes
  3928  }
  3929  
  3930  // @@@ Inlining
  3931  
  3932  // unifiedHaveInlineBody reports whether we have the function body for
  3933  // fn, so we can inline it.
  3934  func unifiedHaveInlineBody(fn *ir.Func) bool {
  3935  	if fn.Inl == nil {
  3936  		return false
  3937  	}
  3938  
  3939  	_, ok := bodyReaderFor(fn)
  3940  	return ok
  3941  }
  3942  
  3943  var inlgen = 0
  3944  
  3945  // unifiedInlineCall implements inline.NewInline by re-reading the function
  3946  // body from its Unified IR export data.
  3947  func unifiedInlineCall(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int, profile *pgoir.Profile) *ir.InlinedCallExpr {
  3948  	pri, ok := bodyReaderFor(fn)
  3949  	if !ok {
  3950  		base.FatalfAt(call.Pos(), "cannot inline call to %v: missing inline body", fn)
  3951  	}
  3952  
  3953  	// Run expandInline even for CompiledByImport so export data does not change.
  3954  	if !fn.Inl.HaveDcl {
  3955  		expandInline(fn, pri)
  3956  	}
  3957  
  3958  	r := pri.asReader(pkgbits.SectionBody, pkgbits.SyncFuncBody)
  3959  
  3960  	tmpfn := ir.NewFunc(fn.Pos(), fn.Nname.Pos(), callerfn.Sym(), fn.Type())
  3961  
  3962  	r.curfn = tmpfn
  3963  
  3964  	r.inlCaller = callerfn
  3965  	r.inlCall = call
  3966  	r.inlFunc = fn
  3967  	r.inlTreeIndex = inlIndex
  3968  	r.inlPosBases = make(map[*src.PosBase]*src.PosBase)
  3969  	r.funarghack = true
  3970  
  3971  	r.closureVars = make([]*ir.Name, len(r.inlFunc.ClosureVars))
  3972  	for i, cv := range r.inlFunc.ClosureVars {
  3973  		// TODO(mdempsky): It should be possible to support this case, but
  3974  		// for now we rely on the inliner avoiding it.
  3975  		if cv.Outer.Curfn != callerfn {
  3976  			base.FatalfAt(call.Pos(), "inlining closure call across frames")
  3977  		}
  3978  		r.closureVars[i] = cv.Outer
  3979  	}
  3980  	if len(r.closureVars) != 0 && r.hasTypeParams() {
  3981  		r.dictParam = r.closureVars[len(r.closureVars)-1] // dictParam is last; see reader.funcLit
  3982  	}
  3983  
  3984  	r.declareParams()
  3985  
  3986  	var inlvars, retvars []*ir.Name
  3987  	{
  3988  		sig := r.curfn.Type()
  3989  		endParams := sig.NumRecvs() + sig.NumParams()
  3990  		endResults := endParams + sig.NumResults()
  3991  
  3992  		inlvars = r.curfn.Dcl[:endParams]
  3993  		retvars = r.curfn.Dcl[endParams:endResults]
  3994  	}
  3995  
  3996  	r.delayResults = fn.Inl.CanDelayResults
  3997  
  3998  	r.retlabel = typecheck.AutoLabel(callerfn, ".i")
  3999  	inlgen++
  4000  
  4001  	init := ir.TakeInit(call)
  4002  
  4003  	// For normal function calls, the function callee expression
  4004  	// may contain side effects. Make sure to preserve these,
  4005  	// if necessary (#42703).
  4006  	if call.Op() == ir.OCALLFUNC {
  4007  		inline.CalleeEffects(&init, call.Fun)
  4008  	}
  4009  
  4010  	var args ir.Nodes
  4011  	if call.Op() == ir.OCALLMETH {
  4012  		base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
  4013  	}
  4014  	args.Append(call.Args...)
  4015  
  4016  	// Create assignment to declare and initialize inlvars.
  4017  	as2 := ir.NewAssignListStmt(call.Pos(), ir.OAS2, ir.ToNodes(inlvars), args)
  4018  	as2.Def = true
  4019  	var as2init ir.Nodes
  4020  	for _, name := range inlvars {
  4021  		if ir.IsBlank(name) {
  4022  			continue
  4023  		}
  4024  		// TODO(mdempsky): Use inlined position of name.Pos() instead?
  4025  		as2init.Append(ir.NewDecl(call.Pos(), ir.ODCL, name))
  4026  		name.Defn = as2
  4027  	}
  4028  	as2.SetInit(as2init)
  4029  	init.Append(typecheck.Stmt(callerfn, as2))
  4030  
  4031  	if !r.delayResults {
  4032  		// If not delaying retvars, declare and zero initialize the
  4033  		// result variables now.
  4034  		for _, name := range retvars {
  4035  			// TODO(mdempsky): Use inlined position of name.Pos() instead?
  4036  			init.Append(ir.NewDecl(call.Pos(), ir.ODCL, name))
  4037  			ras := ir.NewAssignStmt(call.Pos(), name, nil)
  4038  			init.Append(typecheck.Stmt(callerfn, ras))
  4039  		}
  4040  	}
  4041  
  4042  	// Add an inline mark just before the inlined body.
  4043  	// This mark is inline in the code so that it's a reasonable spot
  4044  	// to put a breakpoint. Not sure if that's really necessary or not
  4045  	// (in which case it could go at the end of the function instead).
  4046  	// Note issue 28603.
  4047  	init.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(r.inlTreeIndex)))
  4048  
  4049  	ir.WithPos(r.curfn, func() {
  4050  		if !r.syntheticBody(call.Pos()) {
  4051  			assert(r.Bool()) // have body
  4052  
  4053  			r.curfn.Body = r.stmts()
  4054  			r.curfn.Endlineno = r.pos()
  4055  		}
  4056  
  4057  		// TODO(mdempsky): This shouldn't be necessary. Inlining might
  4058  		// read in new function/method declarations, which could
  4059  		// potentially be recursively inlined themselves; but we shouldn't
  4060  		// need to read in the non-inlined bodies for the declarations
  4061  		// themselves. But currently it's an easy fix to #50552.
  4062  		readBodies(typecheck.Target, true, profile)
  4063  
  4064  		// Replace any "return" statements within the function body.
  4065  		var edit func(ir.Node) ir.Node
  4066  		edit = func(n ir.Node) ir.Node {
  4067  			if ret, ok := n.(*ir.ReturnStmt); ok {
  4068  				n = typecheck.Stmt(callerfn, r.inlReturn(ret, retvars))
  4069  			}
  4070  			ir.EditChildren(n, edit)
  4071  			return n
  4072  		}
  4073  		edit(r.curfn)
  4074  	})
  4075  
  4076  	body := r.curfn.Body
  4077  
  4078  	// Reparent any declarations into the caller function.
  4079  	for _, name := range r.curfn.Dcl {
  4080  		name.Curfn = callerfn
  4081  
  4082  		if name.Class != ir.PAUTO {
  4083  			name.SetPos(r.inlPos(name.Pos()))
  4084  			name.SetInlFormal(true)
  4085  			name.Class = ir.PAUTO
  4086  		} else {
  4087  			name.SetInlLocal(true)
  4088  		}
  4089  	}
  4090  	callerfn.Dcl = append(callerfn.Dcl, r.curfn.Dcl...)
  4091  
  4092  	body.Append(ir.NewLabelStmt(call.Pos(), r.retlabel))
  4093  
  4094  	res := ir.NewInlinedCallExpr(call.Pos(), body, ir.ToNodes(retvars))
  4095  	res.SetInit(init)
  4096  	res.SetType(call.Type())
  4097  	res.SetTypecheck(1)
  4098  	res.Reshape = call.Reshape
  4099  
  4100  	// Inlining shouldn't add any functions to todoBodies.
  4101  	assert(len(todoBodies) == 0)
  4102  
  4103  	return res
  4104  }
  4105  
  4106  // inlReturn returns a statement that can substitute for the given
  4107  // return statement when inlining.
  4108  func (r *reader) inlReturn(ret *ir.ReturnStmt, retvars []*ir.Name) *ir.BlockStmt {
  4109  	pos := r.inlCall.Pos()
  4110  
  4111  	block := ir.TakeInit(ret)
  4112  
  4113  	if results := ret.Results; len(results) != 0 {
  4114  		assert(len(retvars) == len(results))
  4115  
  4116  		as2 := ir.NewAssignListStmt(pos, ir.OAS2, ir.ToNodes(retvars), ret.Results)
  4117  
  4118  		if r.delayResults {
  4119  			for _, name := range retvars {
  4120  				// TODO(mdempsky): Use inlined position of name.Pos() instead?
  4121  				block.Append(ir.NewDecl(pos, ir.ODCL, name))
  4122  				name.Defn = as2
  4123  			}
  4124  		}
  4125  
  4126  		block.Append(as2)
  4127  	}
  4128  
  4129  	block.Append(ir.NewBranchStmt(pos, ir.OGOTO, r.retlabel))
  4130  	return ir.NewBlockStmt(pos, block)
  4131  }
  4132  
  4133  // expandInline reads in an extra copy of IR to populate
  4134  // fn.Inl.Dcl.
  4135  func expandInline(fn *ir.Func, pri pkgReaderIndex) {
  4136  	// TODO(mdempsky): Remove this function. It's currently needed by
  4137  	// dwarfgen/dwarf.go:preInliningDcls, which requires fn.Inl.Dcl to
  4138  	// create abstract function DIEs. But we should be able to provide it
  4139  	// with the same information some other way.
  4140  
  4141  	fndcls := len(fn.Dcl)
  4142  	topdcls := len(typecheck.Target.Funcs)
  4143  
  4144  	tmpfn := ir.NewFunc(fn.Pos(), fn.Nname.Pos(), fn.Sym(), fn.Type())
  4145  	tmpfn.ClosureVars = fn.ClosureVars
  4146  
  4147  	{
  4148  		r := pri.asReader(pkgbits.SectionBody, pkgbits.SyncFuncBody)
  4149  
  4150  		// Don't change parameter's Sym/Nname fields.
  4151  		r.funarghack = true
  4152  
  4153  		r.funcBody(tmpfn)
  4154  	}
  4155  
  4156  	// Move tmpfn's params to fn.Inl.Dcl, and reparent under fn.
  4157  	for _, name := range tmpfn.Dcl {
  4158  		name.Curfn = fn
  4159  	}
  4160  	fn.Inl.Dcl = tmpfn.Dcl
  4161  	fn.Inl.HaveDcl = true
  4162  
  4163  	// Double check that we didn't change fn.Dcl by accident.
  4164  	assert(fndcls == len(fn.Dcl))
  4165  
  4166  	// typecheck.Stmts may have added function literals to
  4167  	// typecheck.Target.Decls. Remove them again so we don't risk trying
  4168  	// to compile them multiple times.
  4169  	typecheck.Target.Funcs = typecheck.Target.Funcs[:topdcls]
  4170  }
  4171  
  4172  // @@@ Method wrappers
  4173  //
  4174  // Here we handle constructing "method wrappers," alternative entry
  4175  // points that adapt methods to different calling conventions. Given a
  4176  // user-declared method "func (T) M(i int) bool { ... }", there are a
  4177  // few wrappers we may need to construct:
  4178  //
  4179  //	- Implicit dereferencing. Methods declared with a value receiver T
  4180  //	  are also included in the method set of the pointer type *T, so
  4181  //	  we need to construct a wrapper like "func (recv *T) M(i int)
  4182  //	  bool { return (*recv).M(i) }".
  4183  //
  4184  //	- Promoted methods. If struct type U contains an embedded field of
  4185  //	  type T or *T, we need to construct a wrapper like "func (recv U)
  4186  //	  M(i int) bool { return recv.T.M(i) }".
  4187  //
  4188  //	- Method values. If x is an expression of type T, then "x.M" is
  4189  //	  roughly "tmp := x; func(i int) bool { return tmp.M(i) }".
  4190  //
  4191  // At call sites, we always prefer to call the user-declared method
  4192  // directly, if known, so wrappers are only needed for indirect calls
  4193  // (for example, interface method calls that can't be devirtualized).
  4194  // Consequently, we can save some compile time by skipping
  4195  // construction of wrappers that are never needed.
  4196  //
  4197  // Alternatively, because the linker doesn't care which compilation
  4198  // unit constructed a particular wrapper, we can instead construct
  4199  // them as needed. However, if a wrapper is needed in multiple
  4200  // downstream packages, we may end up needing to compile it multiple
  4201  // times, costing us more compile time and object file size. (We mark
  4202  // the wrappers as DUPOK, so the linker doesn't complain about the
  4203  // duplicate symbols.)
  4204  //
  4205  // The current heuristics we use to balance these trade offs are:
  4206  //
  4207  //	- For a (non-parameterized) defined type T, we construct wrappers
  4208  //	  for *T and any promoted methods on T (and *T) in the same
  4209  //	  compilation unit as the type declaration.
  4210  //
  4211  //	- For a parameterized defined type, we construct wrappers in the
  4212  //	  compilation units in which the type is instantiated. We
  4213  //	  similarly handle wrappers for anonymous types with methods and
  4214  //	  compilation units where their type literals appear in source.
  4215  //
  4216  //	- Method value expressions are relatively uncommon, so we
  4217  //	  construct their wrappers in the compilation units that they
  4218  //	  appear in.
  4219  //
  4220  // Finally, as an opportunistic compile-time optimization, if we know
  4221  // a wrapper was constructed in any imported package's compilation
  4222  // unit, then we skip constructing a duplicate one. However, currently
  4223  // this is only done on a best-effort basis.
  4224  
  4225  // needWrapperTypes lists types for which we may need to generate
  4226  // method wrappers.
  4227  var needWrapperTypes []*types.Type
  4228  
  4229  // haveWrapperTypes lists types for which we know we already have
  4230  // method wrappers, because we found the type in an imported package.
  4231  var haveWrapperTypes []*types.Type
  4232  
  4233  // needMethodValueWrappers lists methods for which we may need to
  4234  // generate method value wrappers.
  4235  var needMethodValueWrappers []methodValueWrapper
  4236  
  4237  // haveMethodValueWrappers lists methods for which we know we already
  4238  // have method value wrappers, because we found it in an imported
  4239  // package.
  4240  var haveMethodValueWrappers []methodValueWrapper
  4241  
  4242  type methodValueWrapper struct {
  4243  	rcvr   *types.Type
  4244  	method *types.Field
  4245  }
  4246  
  4247  // needWrapper records that wrapper methods may be needed at link
  4248  // time.
  4249  func (r *reader) needWrapper(typ *types.Type) {
  4250  	// Non-interface shape types have no run-time method sets (see
  4251  	// reflectdata.methods), so their wrappers would be unreachable.
  4252  	// Shaped interface method expressions still call static wrappers.
  4253  	if typ.IsPtr() || typ.IsKind(types.TFORW) || typ.HasShape() && !typ.IsInterface() {
  4254  		return
  4255  	}
  4256  
  4257  	// Special case: runtime must define error even if imported packages mention it (#29304).
  4258  	forceNeed := typ == types.ErrorType && base.Ctxt.Pkgpath == "runtime"
  4259  
  4260  	// If a type was found in an imported package, then we can assume
  4261  	// that package (or one of its transitive dependencies) already
  4262  	// generated method wrappers for it.
  4263  	if r.importedDef() && !forceNeed {
  4264  		haveWrapperTypes = append(haveWrapperTypes, typ)
  4265  	} else {
  4266  		needWrapperTypes = append(needWrapperTypes, typ)
  4267  	}
  4268  }
  4269  
  4270  // importedDef reports whether r is reading from an imported and
  4271  // non-generic element.
  4272  //
  4273  // If a type was found in an imported package, then we can assume that
  4274  // package (or one of its transitive dependencies) already generated
  4275  // method wrappers for it.
  4276  //
  4277  // Exception: If we're instantiating an imported generic type or
  4278  // function, we might be instantiating it with type arguments not
  4279  // previously seen before.
  4280  //
  4281  // TODO(mdempsky): Distinguish when a generic function or type was
  4282  // instantiated in an imported package so that we can add types to
  4283  // haveWrapperTypes instead.
  4284  func (r *reader) importedDef() bool {
  4285  	return r.p != localPkgReader && !r.hasTypeParams()
  4286  }
  4287  
  4288  // MakeWrappers constructs all wrapper methods needed for the target
  4289  // compilation unit.
  4290  func MakeWrappers(target *ir.Package) {
  4291  	// always generate a wrapper for error.Error (#29304)
  4292  	needWrapperTypes = append(needWrapperTypes, types.ErrorType)
  4293  
  4294  	seen := make(map[string]*types.Type)
  4295  
  4296  	for _, typ := range haveWrapperTypes {
  4297  		wrapType(typ, target, seen, false)
  4298  	}
  4299  	haveWrapperTypes = nil
  4300  
  4301  	for _, typ := range needWrapperTypes {
  4302  		if midwayOriginals[typ.Sym()] {
  4303  			// Nothing refers to this type's method wrappers.
  4304  			continue
  4305  		}
  4306  		wrapType(typ, target, seen, true)
  4307  	}
  4308  	needWrapperTypes = nil
  4309  
  4310  	for _, wrapper := range haveMethodValueWrappers {
  4311  		wrapMethodValue(wrapper.rcvr, wrapper.method, target, false)
  4312  	}
  4313  	haveMethodValueWrappers = nil
  4314  
  4315  	for _, wrapper := range needMethodValueWrappers {
  4316  		wrapMethodValue(wrapper.rcvr, wrapper.method, target, true)
  4317  	}
  4318  	needMethodValueWrappers = nil
  4319  }
  4320  
  4321  func wrapType(typ *types.Type, target *ir.Package, seen map[string]*types.Type, needed bool) {
  4322  	key := typ.LinkString()
  4323  	if prev := seen[key]; prev != nil {
  4324  		if !types.Identical(typ, prev) {
  4325  			base.Fatalf("collision: types %v and %v have link string %q", typ, prev, key)
  4326  		}
  4327  		// Wrapper generation is shared by structurally identical types.
  4328  		// Share the cached TFlag too, without computing duplicate method sets.
  4329  		typ.CopyTFlagFrom(prev)
  4330  		return
  4331  	}
  4332  	seen[key] = typ
  4333  
  4334  	if !needed {
  4335  		// Only called to add to 'seen'.
  4336  		return
  4337  	}
  4338  
  4339  	if !typ.IsInterface() {
  4340  		typecheck.CalcMethods(typ)
  4341  	}
  4342  	if !typ.IsUntyped() {
  4343  		typ.TFlag()
  4344  	}
  4345  	for _, meth := range typ.AllMethods() {
  4346  		if meth.Sym.IsBlank() || !meth.IsMethod() {
  4347  			base.FatalfAt(meth.Pos, "invalid method: %v", meth)
  4348  		}
  4349  
  4350  		methodWrapper(0, typ, meth, target)
  4351  
  4352  		// For non-interface types, we also want *T wrappers.
  4353  		if !typ.IsInterface() {
  4354  			methodWrapper(1, typ, meth, target)
  4355  
  4356  			// For not-in-heap types, *T is a scalar, not pointer shaped,
  4357  			// so the interface wrappers use **T.
  4358  			if typ.NotInHeap() {
  4359  				methodWrapper(2, typ, meth, target)
  4360  			}
  4361  		}
  4362  	}
  4363  }
  4364  
  4365  func methodWrapper(derefs int, tbase *types.Type, method *types.Field, target *ir.Package) {
  4366  	wrapper := tbase
  4367  	for i := 0; i < derefs; i++ {
  4368  		wrapper = types.NewPtr(wrapper)
  4369  	}
  4370  
  4371  	wrappee := method.Type.Recv().Type
  4372  	if types.Identical(wrapper, wrappee) ||
  4373  		!types.IsMethodApplicable(wrapper, method) ||
  4374  		!reflectdata.NeedEmit(tbase) {
  4375  		return
  4376  	}
  4377  	sym, sharedPromoted := ir.MethodSym(wrapper, method)
  4378  	if sym.Siggen() {
  4379  		if sharedPromoted {
  4380  			return
  4381  		}
  4382  		base.Fatalf("already generated wrapper %v", sym)
  4383  	}
  4384  	sym.SetSiggen(true)
  4385  
  4386  	// TODO(mdempsky): Use method.Pos instead?
  4387  	pos := base.AutogeneratedPos
  4388  
  4389  	fn := newWrapperFunc(pos, sym, wrapper, method)
  4390  
  4391  	var recv ir.Node = fn.Nname.Type().Recv().Nname.(*ir.Name)
  4392  
  4393  	// For simple *T wrappers around T methods, panicwrap produces a
  4394  	// nicer panic message.
  4395  	if wrapper.IsPtr() && types.Identical(wrapper.Elem(), wrappee) {
  4396  		cond := ir.NewBinaryExpr(pos, ir.OEQ, recv, types.BuiltinPkg.Lookup("nil").Def.(ir.Node))
  4397  		then := []ir.Node{ir.NewCallExpr(pos, ir.OCALL, typecheck.LookupRuntime("panicwrap"), nil)}
  4398  		fn.Body.Append(ir.NewIfStmt(pos, cond, then, nil))
  4399  	}
  4400  
  4401  	// typecheck will add one implicit deref, if necessary,
  4402  	// but not-in-heap types require more for their **T wrappers.
  4403  	for i := 1; i < derefs; i++ {
  4404  		recv = Implicit(ir.NewStarExpr(pos, recv))
  4405  	}
  4406  
  4407  	addTailCall(pos, fn, recv, method)
  4408  
  4409  	finishWrapperFunc(fn, target)
  4410  }
  4411  
  4412  func wrapMethodValue(recvType *types.Type, method *types.Field, target *ir.Package, needed bool) {
  4413  	sym := ir.ReceiverMethodSymSuffix(recvType, method.Sym, "-fm")
  4414  	if sym.Uniq() {
  4415  		return
  4416  	}
  4417  	sym.SetUniq(true)
  4418  
  4419  	// TODO(mdempsky): Use method.Pos instead?
  4420  	pos := base.AutogeneratedPos
  4421  
  4422  	fn := newWrapperFunc(pos, sym, nil, method)
  4423  	sym.Def = fn.Nname
  4424  
  4425  	// Declare and initialize variable holding receiver.
  4426  	recv := ir.NewHiddenParam(pos, fn, typecheck.Lookup(".this"), recvType)
  4427  
  4428  	if !needed {
  4429  		return
  4430  	}
  4431  
  4432  	addTailCall(pos, fn, recv, method)
  4433  
  4434  	finishWrapperFunc(fn, target)
  4435  }
  4436  
  4437  func newWrapperFunc(pos src.XPos, sym *types.Sym, wrapper *types.Type, method *types.Field) *ir.Func {
  4438  	sig := newWrapperType(wrapper, method)
  4439  	fn := ir.NewFunc(pos, pos, sym, sig)
  4440  	fn.DeclareParams(true)
  4441  	fn.SetDupok(true) // TODO(mdempsky): Leave unset for local, non-generic wrappers?
  4442  
  4443  	return fn
  4444  }
  4445  
  4446  func finishWrapperFunc(fn *ir.Func, target *ir.Package) {
  4447  	ir.WithPos(fn, func() {
  4448  		typecheck.Stmts(fn, fn.Body)
  4449  	})
  4450  
  4451  	// We generate wrappers after the global inlining pass,
  4452  	// so we're responsible for applying inlining ourselves here.
  4453  	// TODO(prattmic): plumb PGO.
  4454  	interleaved.DevirtualizeAndInlineFunc(fn, nil)
  4455  
  4456  	// The body of wrapper function after inlining may reveal new ir.OMETHVALUE node,
  4457  	// we don't know whether wrapper function has been generated for it or not, so
  4458  	// generate one immediately here.
  4459  	//
  4460  	// Further, after CL 492017, function that construct closures is allowed to be inlined,
  4461  	// even though the closure itself can't be inline. So we also need to visit body of any
  4462  	// closure that we see when visiting body of the wrapper function.
  4463  	ir.VisitFuncAndClosures(fn, func(n ir.Node) {
  4464  		if n, ok := n.(*ir.SelectorExpr); ok && n.Op() == ir.OMETHVALUE {
  4465  			wrapMethodValue(n.X.Type(), n.Selection, target, true)
  4466  		}
  4467  	})
  4468  
  4469  	fn.Nname.Defn = fn
  4470  	target.Funcs = append(target.Funcs, fn)
  4471  }
  4472  
  4473  // newWrapperType returns a copy of the given signature type, but with
  4474  // the receiver parameter type substituted with recvType.
  4475  // If recvType is nil, newWrapperType returns a signature
  4476  // without a receiver parameter.
  4477  func newWrapperType(recvType *types.Type, method *types.Field) *types.Type {
  4478  	clone := func(params []*types.Field) []*types.Field {
  4479  		res := make([]*types.Field, len(params))
  4480  		for i, param := range params {
  4481  			res[i] = types.NewField(param.Pos, param.Sym, param.Type)
  4482  			res[i].SetIsDDD(param.IsDDD())
  4483  		}
  4484  		return res
  4485  	}
  4486  
  4487  	sig := method.Type
  4488  
  4489  	var recv *types.Field
  4490  	if recvType != nil {
  4491  		recv = types.NewField(sig.Recv().Pos, sig.Recv().Sym, recvType)
  4492  	}
  4493  	params := clone(sig.Params())
  4494  	results := clone(sig.Results())
  4495  
  4496  	return types.NewSignature(recv, params, results)
  4497  }
  4498  
  4499  func addTailCall(pos src.XPos, fn *ir.Func, recv ir.Node, method *types.Field) {
  4500  	sig := fn.Nname.Type()
  4501  	args := make([]ir.Node, sig.NumParams())
  4502  	for i, param := range sig.Params() {
  4503  		args[i] = param.Nname.(*ir.Name)
  4504  	}
  4505  
  4506  	dot := typecheck.XDotMethod(fn, pos, recv, method.Sym, true)
  4507  	call := typecheck.Call(fn, pos, dot, args, method.Type.IsVariadic()).(*ir.CallExpr)
  4508  
  4509  	if recv.Type() != nil && recv.Type().IsPtr() && method.Type.Recv().Type.IsPtr() &&
  4510  		method.Embedded != 0 &&
  4511  		(types.IsInterfaceMethod(method.Type) && base.Ctxt.Arch.Name != "wasm" && base.Ctxt.Arch.Name != "wasm32" ||
  4512  			!types.IsInterfaceMethod(method.Type) && !unifiedHaveInlineBody(ir.MethodExprName(dot).Func)) &&
  4513  		// TODO: implement wasm indirect tail calls
  4514  		// TODO: do we need the ppc64le/dynlink restriction for interface tail calls?
  4515  		!((base.Ctxt.Arch.Name == "ppc64le" || base.Ctxt.Arch.Name == "ppc64") && base.Ctxt.Flag_dynlink) {
  4516  		if base.Debug.TailCall != 0 {
  4517  			base.WarnfAt(fn.Nname.Type().Recv().Type.Elem().Pos(), "tail call emitted for the method %v wrapper", method.Nname)
  4518  		}
  4519  		// Prefer OTAILCALL to reduce code size (except the case when the called method can be inlined).
  4520  		fn.Body.Append(ir.NewTailCallStmt(pos, call))
  4521  		return
  4522  	}
  4523  
  4524  	fn.SetWrapper(true)
  4525  
  4526  	if method.Type.NumResults() == 0 {
  4527  		fn.Body.Append(call)
  4528  		return
  4529  	}
  4530  
  4531  	ret := ir.NewReturnStmt(pos, nil)
  4532  	ret.Results = []ir.Node{call}
  4533  	fn.Body.Append(ret)
  4534  }
  4535  
  4536  func setBasePos(pos src.XPos) {
  4537  	// Set the position for any error messages we might print (e.g. too large types).
  4538  	base.Pos = pos
  4539  }
  4540  
  4541  // dictParamName is the name of the synthetic dictionary parameter
  4542  // added to shaped functions.
  4543  //
  4544  // N.B., this variable name is known to Delve:
  4545  // https://github.com/go-delve/delve/blob/cb91509630529e6055be845688fd21eb89ae8714/pkg/proc/eval.go#L28
  4546  const dictParamName = typecheck.LocalDictName
  4547  
  4548  // shapeSig returns a copy of fn's signature, except adding a
  4549  // dictionary parameter and promoting the receiver parameter (if any)
  4550  // to a normal parameter.
  4551  //
  4552  // The parameter types.Fields are all copied too, so their Nname
  4553  // fields can be initialized for use by the shape function.
  4554  //
  4555  // All signatures returned by shapeSig are marked as shaped.
  4556  func shapeSig(fn *ir.Func, dict *readerDict) *types.Type {
  4557  	sig := fn.Nname.Type()
  4558  	oldRecv := sig.Recv()
  4559  
  4560  	var recv *types.Field
  4561  	if oldRecv != nil {
  4562  		recv = types.NewField(oldRecv.Pos, oldRecv.Sym, oldRecv.Type)
  4563  	}
  4564  
  4565  	params := make([]*types.Field, 1+sig.NumParams())
  4566  	params[0] = types.NewField(fn.Pos(), fn.Sym().Pkg.Lookup(dictParamName), types.NewPtr(dict.varType()))
  4567  	for i, param := range sig.Params() {
  4568  		d := types.NewField(param.Pos, param.Sym, param.Type)
  4569  		d.SetIsDDD(param.IsDDD())
  4570  		params[1+i] = d
  4571  	}
  4572  
  4573  	results := make([]*types.Field, sig.NumResults())
  4574  	for i, result := range sig.Results() {
  4575  		results[i] = types.NewField(result.Pos, result.Sym, result.Type)
  4576  	}
  4577  
  4578  	typ := types.NewSignature(recv, params, results)
  4579  	typ.SetHasShape(true)
  4580  	return typ
  4581  }
  4582  

View as plain text