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

View as plain text