]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/writer.go
cmd/compile: implement range over integer
[gostls13.git] / src / cmd / compile / internal / noder / writer.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         "fmt"
9         "go/constant"
10         "go/token"
11         "internal/buildcfg"
12         "internal/pkgbits"
13
14         "cmd/compile/internal/base"
15         "cmd/compile/internal/ir"
16         "cmd/compile/internal/syntax"
17         "cmd/compile/internal/types"
18         "cmd/compile/internal/types2"
19 )
20
21 // This file implements the Unified IR package writer and defines the
22 // Unified IR export data format.
23 //
24 // Low-level coding details (e.g., byte-encoding of individual
25 // primitive values, or handling element bitstreams and
26 // cross-references) are handled by internal/pkgbits, so here we only
27 // concern ourselves with higher-level worries like mapping Go
28 // language constructs into elements.
29
30 // There are two central types in the writing process: the "writer"
31 // type handles writing out individual elements, while the "pkgWriter"
32 // type keeps track of which elements have already been created.
33 //
34 // For each sort of "thing" (e.g., position, package, object, type)
35 // that can be written into the export data, there are generally
36 // several methods that work together:
37 //
38 // - writer.thing handles writing out a *use* of a thing, which often
39 //   means writing a relocation to that thing's encoded index.
40 //
41 // - pkgWriter.thingIdx handles reserving an index for a thing, and
42 //   writing out any elements needed for the thing.
43 //
44 // - writer.doThing handles writing out the *definition* of a thing,
45 //   which in general is a mix of low-level coding primitives (e.g.,
46 //   ints and strings) or uses of other things.
47 //
48 // A design goal of Unified IR is to have a single, canonical writer
49 // implementation, but multiple reader implementations each tailored
50 // to their respective needs. For example, within cmd/compile's own
51 // backend, inlining is implemented largely by just re-running the
52 // function body reading code.
53
54 // TODO(mdempsky): Add an importer for Unified IR to the x/tools repo,
55 // and better document the file format boundary between public and
56 // private data.
57
58 // A pkgWriter constructs Unified IR export data from the results of
59 // running the types2 type checker on a Go compilation unit.
60 type pkgWriter struct {
61         pkgbits.PkgEncoder
62
63         m      posMap
64         curpkg *types2.Package
65         info   *types2.Info
66
67         // Indices for previously written syntax and types2 things.
68
69         posBasesIdx map[*syntax.PosBase]pkgbits.Index
70         pkgsIdx     map[*types2.Package]pkgbits.Index
71         typsIdx     map[types2.Type]pkgbits.Index
72         objsIdx     map[types2.Object]pkgbits.Index
73
74         // Maps from types2.Objects back to their syntax.Decl.
75
76         funDecls map[*types2.Func]*syntax.FuncDecl
77         typDecls map[*types2.TypeName]typeDeclGen
78
79         // linknames maps package-scope objects to their linker symbol name,
80         // if specified by a //go:linkname directive.
81         linknames map[types2.Object]string
82
83         // cgoPragmas accumulates any //go:cgo_* pragmas that need to be
84         // passed through to cmd/link.
85         cgoPragmas [][]string
86 }
87
88 // newPkgWriter returns an initialized pkgWriter for the specified
89 // package.
90 func newPkgWriter(m posMap, pkg *types2.Package, info *types2.Info) *pkgWriter {
91         return &pkgWriter{
92                 PkgEncoder: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
93
94                 m:      m,
95                 curpkg: pkg,
96                 info:   info,
97
98                 pkgsIdx: make(map[*types2.Package]pkgbits.Index),
99                 objsIdx: make(map[types2.Object]pkgbits.Index),
100                 typsIdx: make(map[types2.Type]pkgbits.Index),
101
102                 posBasesIdx: make(map[*syntax.PosBase]pkgbits.Index),
103
104                 funDecls: make(map[*types2.Func]*syntax.FuncDecl),
105                 typDecls: make(map[*types2.TypeName]typeDeclGen),
106
107                 linknames: make(map[types2.Object]string),
108         }
109 }
110
111 // errorf reports a user error about thing p.
112 func (pw *pkgWriter) errorf(p poser, msg string, args ...interface{}) {
113         base.ErrorfAt(pw.m.pos(p), 0, msg, args...)
114 }
115
116 // fatalf reports an internal compiler error about thing p.
117 func (pw *pkgWriter) fatalf(p poser, msg string, args ...interface{}) {
118         base.FatalfAt(pw.m.pos(p), msg, args...)
119 }
120
121 // unexpected reports a fatal error about a thing of unexpected
122 // dynamic type.
123 func (pw *pkgWriter) unexpected(what string, p poser) {
124         pw.fatalf(p, "unexpected %s: %v (%T)", what, p, p)
125 }
126
127 func (pw *pkgWriter) typeAndValue(x syntax.Expr) syntax.TypeAndValue {
128         tv, ok := pw.maybeTypeAndValue(x)
129         if !ok {
130                 pw.fatalf(x, "missing Types entry: %v", syntax.String(x))
131         }
132         return tv
133 }
134
135 func (pw *pkgWriter) maybeTypeAndValue(x syntax.Expr) (syntax.TypeAndValue, bool) {
136         tv := x.GetTypeInfo()
137
138         // If x is a generic function whose type arguments are inferred
139         // from assignment context, then we need to find its inferred type
140         // in Info.Instances instead.
141         if name, ok := x.(*syntax.Name); ok {
142                 if inst, ok := pw.info.Instances[name]; ok {
143                         tv.Type = inst.Type
144                 }
145         }
146
147         return tv, tv.Type != nil
148 }
149
150 // typeOf returns the Type of the given value expression.
151 func (pw *pkgWriter) typeOf(expr syntax.Expr) types2.Type {
152         tv := pw.typeAndValue(expr)
153         if !tv.IsValue() {
154                 pw.fatalf(expr, "expected value: %v", syntax.String(expr))
155         }
156         return tv.Type
157 }
158
159 // A writer provides APIs for writing out an individual element.
160 type writer struct {
161         p *pkgWriter
162
163         pkgbits.Encoder
164
165         // sig holds the signature for the current function body, if any.
166         sig *types2.Signature
167
168         // TODO(mdempsky): We should be able to prune localsIdx whenever a
169         // scope closes, and then maybe we can just use the same map for
170         // storing the TypeParams too (as their TypeName instead).
171
172         // localsIdx tracks any local variables declared within this
173         // function body. It's unused for writing out non-body things.
174         localsIdx map[*types2.Var]int
175
176         // closureVars tracks any free variables that are referenced by this
177         // function body. It's unused for writing out non-body things.
178         closureVars    []posVar
179         closureVarsIdx map[*types2.Var]int // index of previously seen free variables
180
181         dict *writerDict
182
183         // derived tracks whether the type being written out references any
184         // type parameters. It's unused for writing non-type things.
185         derived bool
186 }
187
188 // A writerDict tracks types and objects that are used by a declaration.
189 type writerDict struct {
190         implicits []*types2.TypeName
191
192         // derived is a slice of type indices for computing derived types
193         // (i.e., types that depend on the declaration's type parameters).
194         derived []derivedInfo
195
196         // derivedIdx maps a Type to its corresponding index within the
197         // derived slice, if present.
198         derivedIdx map[types2.Type]pkgbits.Index
199
200         // These slices correspond to entries in the runtime dictionary.
201         typeParamMethodExprs []writerMethodExprInfo
202         subdicts             []objInfo
203         rtypes               []typeInfo
204         itabs                []itabInfo
205 }
206
207 type itabInfo struct {
208         typ   typeInfo
209         iface typeInfo
210 }
211
212 // typeParamIndex returns the index of the given type parameter within
213 // the dictionary. This may differ from typ.Index() when there are
214 // implicit type parameters due to defined types declared within a
215 // generic function or method.
216 func (dict *writerDict) typeParamIndex(typ *types2.TypeParam) int {
217         for idx, implicit := range dict.implicits {
218                 if implicit.Type().(*types2.TypeParam) == typ {
219                         return idx
220                 }
221         }
222
223         return len(dict.implicits) + typ.Index()
224 }
225
226 // A derivedInfo represents a reference to an encoded generic Go type.
227 type derivedInfo struct {
228         idx    pkgbits.Index
229         needed bool // TODO(mdempsky): Remove.
230 }
231
232 // A typeInfo represents a reference to an encoded Go type.
233 //
234 // If derived is true, then the typeInfo represents a generic Go type
235 // that contains type parameters. In this case, idx is an index into
236 // the readerDict.derived{,Types} arrays.
237 //
238 // Otherwise, the typeInfo represents a non-generic Go type, and idx
239 // is an index into the reader.typs array instead.
240 type typeInfo struct {
241         idx     pkgbits.Index
242         derived bool
243 }
244
245 // An objInfo represents a reference to an encoded, instantiated (if
246 // applicable) Go object.
247 type objInfo struct {
248         idx       pkgbits.Index // index for the generic function declaration
249         explicits []typeInfo    // info for the type arguments
250 }
251
252 // A selectorInfo represents a reference to an encoded field or method
253 // name (i.e., objects that can only be accessed using selector
254 // expressions).
255 type selectorInfo struct {
256         pkgIdx  pkgbits.Index
257         nameIdx pkgbits.Index
258 }
259
260 // anyDerived reports whether any of info's explicit type arguments
261 // are derived types.
262 func (info objInfo) anyDerived() bool {
263         for _, explicit := range info.explicits {
264                 if explicit.derived {
265                         return true
266                 }
267         }
268         return false
269 }
270
271 // equals reports whether info and other represent the same Go object
272 // (i.e., same base object and identical type arguments, if any).
273 func (info objInfo) equals(other objInfo) bool {
274         if info.idx != other.idx {
275                 return false
276         }
277         assert(len(info.explicits) == len(other.explicits))
278         for i, targ := range info.explicits {
279                 if targ != other.explicits[i] {
280                         return false
281                 }
282         }
283         return true
284 }
285
286 type writerMethodExprInfo struct {
287         typeParamIdx int
288         methodInfo   selectorInfo
289 }
290
291 // typeParamMethodExprIdx returns the index where the given encoded
292 // method expression function pointer appears within this dictionary's
293 // type parameters method expressions section, adding it if necessary.
294 func (dict *writerDict) typeParamMethodExprIdx(typeParamIdx int, methodInfo selectorInfo) int {
295         newInfo := writerMethodExprInfo{typeParamIdx, methodInfo}
296
297         for idx, oldInfo := range dict.typeParamMethodExprs {
298                 if oldInfo == newInfo {
299                         return idx
300                 }
301         }
302
303         idx := len(dict.typeParamMethodExprs)
304         dict.typeParamMethodExprs = append(dict.typeParamMethodExprs, newInfo)
305         return idx
306 }
307
308 // subdictIdx returns the index where the given encoded object's
309 // runtime dictionary appears within this dictionary's subdictionary
310 // section, adding it if necessary.
311 func (dict *writerDict) subdictIdx(newInfo objInfo) int {
312         for idx, oldInfo := range dict.subdicts {
313                 if oldInfo.equals(newInfo) {
314                         return idx
315                 }
316         }
317
318         idx := len(dict.subdicts)
319         dict.subdicts = append(dict.subdicts, newInfo)
320         return idx
321 }
322
323 // rtypeIdx returns the index where the given encoded type's
324 // *runtime._type value appears within this dictionary's rtypes
325 // section, adding it if necessary.
326 func (dict *writerDict) rtypeIdx(newInfo typeInfo) int {
327         for idx, oldInfo := range dict.rtypes {
328                 if oldInfo == newInfo {
329                         return idx
330                 }
331         }
332
333         idx := len(dict.rtypes)
334         dict.rtypes = append(dict.rtypes, newInfo)
335         return idx
336 }
337
338 // itabIdx returns the index where the given encoded type pair's
339 // *runtime.itab value appears within this dictionary's itabs section,
340 // adding it if necessary.
341 func (dict *writerDict) itabIdx(typInfo, ifaceInfo typeInfo) int {
342         newInfo := itabInfo{typInfo, ifaceInfo}
343
344         for idx, oldInfo := range dict.itabs {
345                 if oldInfo == newInfo {
346                         return idx
347                 }
348         }
349
350         idx := len(dict.itabs)
351         dict.itabs = append(dict.itabs, newInfo)
352         return idx
353 }
354
355 func (pw *pkgWriter) newWriter(k pkgbits.RelocKind, marker pkgbits.SyncMarker) *writer {
356         return &writer{
357                 Encoder: pw.NewEncoder(k, marker),
358                 p:       pw,
359         }
360 }
361
362 // @@@ Positions
363
364 // pos writes the position of p into the element bitstream.
365 func (w *writer) pos(p poser) {
366         w.Sync(pkgbits.SyncPos)
367         pos := p.Pos()
368
369         // TODO(mdempsky): Track down the remaining cases here and fix them.
370         if !w.Bool(pos.IsKnown()) {
371                 return
372         }
373
374         // TODO(mdempsky): Delta encoding.
375         w.posBase(pos.Base())
376         w.Uint(pos.Line())
377         w.Uint(pos.Col())
378 }
379
380 // posBase writes a reference to the given PosBase into the element
381 // bitstream.
382 func (w *writer) posBase(b *syntax.PosBase) {
383         w.Reloc(pkgbits.RelocPosBase, w.p.posBaseIdx(b))
384 }
385
386 // posBaseIdx returns the index for the given PosBase.
387 func (pw *pkgWriter) posBaseIdx(b *syntax.PosBase) pkgbits.Index {
388         if idx, ok := pw.posBasesIdx[b]; ok {
389                 return idx
390         }
391
392         w := pw.newWriter(pkgbits.RelocPosBase, pkgbits.SyncPosBase)
393         w.p.posBasesIdx[b] = w.Idx
394
395         w.String(trimFilename(b))
396
397         if !w.Bool(b.IsFileBase()) {
398                 w.pos(b)
399                 w.Uint(b.Line())
400                 w.Uint(b.Col())
401         }
402
403         return w.Flush()
404 }
405
406 // @@@ Packages
407
408 // pkg writes a use of the given Package into the element bitstream.
409 func (w *writer) pkg(pkg *types2.Package) {
410         w.pkgRef(w.p.pkgIdx(pkg))
411 }
412
413 func (w *writer) pkgRef(idx pkgbits.Index) {
414         w.Sync(pkgbits.SyncPkg)
415         w.Reloc(pkgbits.RelocPkg, idx)
416 }
417
418 // pkgIdx returns the index for the given package, adding it to the
419 // package export data if needed.
420 func (pw *pkgWriter) pkgIdx(pkg *types2.Package) pkgbits.Index {
421         if idx, ok := pw.pkgsIdx[pkg]; ok {
422                 return idx
423         }
424
425         w := pw.newWriter(pkgbits.RelocPkg, pkgbits.SyncPkgDef)
426         pw.pkgsIdx[pkg] = w.Idx
427
428         // The universe and package unsafe need to be handled specially by
429         // importers anyway, so we serialize them using just their package
430         // path. This ensures that readers don't confuse them for
431         // user-defined packages.
432         switch pkg {
433         case nil: // universe
434                 w.String("builtin") // same package path used by godoc
435         case types2.Unsafe:
436                 w.String("unsafe")
437         default:
438                 // TODO(mdempsky): Write out pkg.Path() for curpkg too.
439                 var path string
440                 if pkg != w.p.curpkg {
441                         path = pkg.Path()
442                 }
443                 base.Assertf(path != "builtin" && path != "unsafe", "unexpected path for user-defined package: %q", path)
444                 w.String(path)
445                 w.String(pkg.Name())
446
447                 w.Len(len(pkg.Imports()))
448                 for _, imp := range pkg.Imports() {
449                         w.pkg(imp)
450                 }
451         }
452
453         return w.Flush()
454 }
455
456 // @@@ Types
457
458 var (
459         anyTypeName        = types2.Universe.Lookup("any").(*types2.TypeName)
460         comparableTypeName = types2.Universe.Lookup("comparable").(*types2.TypeName)
461         runeTypeName       = types2.Universe.Lookup("rune").(*types2.TypeName)
462 )
463
464 // typ writes a use of the given type into the bitstream.
465 func (w *writer) typ(typ types2.Type) {
466         w.typInfo(w.p.typIdx(typ, w.dict))
467 }
468
469 // typInfo writes a use of the given type (specified as a typeInfo
470 // instead) into the bitstream.
471 func (w *writer) typInfo(info typeInfo) {
472         w.Sync(pkgbits.SyncType)
473         if w.Bool(info.derived) {
474                 w.Len(int(info.idx))
475                 w.derived = true
476         } else {
477                 w.Reloc(pkgbits.RelocType, info.idx)
478         }
479 }
480
481 // typIdx returns the index where the export data description of type
482 // can be read back in. If no such index exists yet, it's created.
483 //
484 // typIdx also reports whether typ is a derived type; that is, whether
485 // its identity depends on type parameters.
486 func (pw *pkgWriter) typIdx(typ types2.Type, dict *writerDict) typeInfo {
487         if idx, ok := pw.typsIdx[typ]; ok {
488                 return typeInfo{idx: idx, derived: false}
489         }
490         if dict != nil {
491                 if idx, ok := dict.derivedIdx[typ]; ok {
492                         return typeInfo{idx: idx, derived: true}
493                 }
494         }
495
496         w := pw.newWriter(pkgbits.RelocType, pkgbits.SyncTypeIdx)
497         w.dict = dict
498
499         switch typ := typ.(type) {
500         default:
501                 base.Fatalf("unexpected type: %v (%T)", typ, typ)
502
503         case *types2.Basic:
504                 switch kind := typ.Kind(); {
505                 case kind == types2.Invalid:
506                         base.Fatalf("unexpected types2.Invalid")
507
508                 case types2.Typ[kind] == typ:
509                         w.Code(pkgbits.TypeBasic)
510                         w.Len(int(kind))
511
512                 default:
513                         // Handle "byte" and "rune" as references to their TypeNames.
514                         obj := types2.Universe.Lookup(typ.Name())
515                         assert(obj.Type() == typ)
516
517                         w.Code(pkgbits.TypeNamed)
518                         w.obj(obj, nil)
519                 }
520
521         case *types2.Named:
522                 obj, targs := splitNamed(typ)
523
524                 // Defined types that are declared within a generic function (and
525                 // thus have implicit type parameters) are always derived types.
526                 if w.p.hasImplicitTypeParams(obj) {
527                         w.derived = true
528                 }
529
530                 w.Code(pkgbits.TypeNamed)
531                 w.obj(obj, targs)
532
533         case *types2.TypeParam:
534                 w.derived = true
535                 w.Code(pkgbits.TypeTypeParam)
536                 w.Len(w.dict.typeParamIndex(typ))
537
538         case *types2.Array:
539                 w.Code(pkgbits.TypeArray)
540                 w.Uint64(uint64(typ.Len()))
541                 w.typ(typ.Elem())
542
543         case *types2.Chan:
544                 w.Code(pkgbits.TypeChan)
545                 w.Len(int(typ.Dir()))
546                 w.typ(typ.Elem())
547
548         case *types2.Map:
549                 w.Code(pkgbits.TypeMap)
550                 w.typ(typ.Key())
551                 w.typ(typ.Elem())
552
553         case *types2.Pointer:
554                 w.Code(pkgbits.TypePointer)
555                 w.typ(typ.Elem())
556
557         case *types2.Signature:
558                 base.Assertf(typ.TypeParams() == nil, "unexpected type params: %v", typ)
559                 w.Code(pkgbits.TypeSignature)
560                 w.signature(typ)
561
562         case *types2.Slice:
563                 w.Code(pkgbits.TypeSlice)
564                 w.typ(typ.Elem())
565
566         case *types2.Struct:
567                 w.Code(pkgbits.TypeStruct)
568                 w.structType(typ)
569
570         case *types2.Interface:
571                 // Handle "any" as reference to its TypeName.
572                 if typ == anyTypeName.Type() {
573                         w.Code(pkgbits.TypeNamed)
574                         w.obj(anyTypeName, nil)
575                         break
576                 }
577
578                 w.Code(pkgbits.TypeInterface)
579                 w.interfaceType(typ)
580
581         case *types2.Union:
582                 w.Code(pkgbits.TypeUnion)
583                 w.unionType(typ)
584         }
585
586         if w.derived {
587                 idx := pkgbits.Index(len(dict.derived))
588                 dict.derived = append(dict.derived, derivedInfo{idx: w.Flush()})
589                 dict.derivedIdx[typ] = idx
590                 return typeInfo{idx: idx, derived: true}
591         }
592
593         pw.typsIdx[typ] = w.Idx
594         return typeInfo{idx: w.Flush(), derived: false}
595 }
596
597 func (w *writer) structType(typ *types2.Struct) {
598         w.Len(typ.NumFields())
599         for i := 0; i < typ.NumFields(); i++ {
600                 f := typ.Field(i)
601                 w.pos(f)
602                 w.selector(f)
603                 w.typ(f.Type())
604                 w.String(typ.Tag(i))
605                 w.Bool(f.Embedded())
606         }
607 }
608
609 func (w *writer) unionType(typ *types2.Union) {
610         w.Len(typ.Len())
611         for i := 0; i < typ.Len(); i++ {
612                 t := typ.Term(i)
613                 w.Bool(t.Tilde())
614                 w.typ(t.Type())
615         }
616 }
617
618 func (w *writer) interfaceType(typ *types2.Interface) {
619         // If typ has no embedded types but it's not a basic interface, then
620         // the natural description we write out below will fail to
621         // reconstruct it.
622         if typ.NumEmbeddeds() == 0 && !typ.IsMethodSet() {
623                 // Currently, this can only happen for the underlying Interface of
624                 // "comparable", which is needed to handle type declarations like
625                 // "type C comparable".
626                 assert(typ == comparableTypeName.Type().(*types2.Named).Underlying())
627
628                 // Export as "interface{ comparable }".
629                 w.Len(0)                         // NumExplicitMethods
630                 w.Len(1)                         // NumEmbeddeds
631                 w.Bool(false)                    // IsImplicit
632                 w.typ(comparableTypeName.Type()) // EmbeddedType(0)
633                 return
634         }
635
636         w.Len(typ.NumExplicitMethods())
637         w.Len(typ.NumEmbeddeds())
638
639         if typ.NumExplicitMethods() == 0 && typ.NumEmbeddeds() == 1 {
640                 w.Bool(typ.IsImplicit())
641         } else {
642                 // Implicit interfaces always have 0 explicit methods and 1
643                 // embedded type, so we skip writing out the implicit flag
644                 // otherwise as a space optimization.
645                 assert(!typ.IsImplicit())
646         }
647
648         for i := 0; i < typ.NumExplicitMethods(); i++ {
649                 m := typ.ExplicitMethod(i)
650                 sig := m.Type().(*types2.Signature)
651                 assert(sig.TypeParams() == nil)
652
653                 w.pos(m)
654                 w.selector(m)
655                 w.signature(sig)
656         }
657
658         for i := 0; i < typ.NumEmbeddeds(); i++ {
659                 w.typ(typ.EmbeddedType(i))
660         }
661 }
662
663 func (w *writer) signature(sig *types2.Signature) {
664         w.Sync(pkgbits.SyncSignature)
665         w.params(sig.Params())
666         w.params(sig.Results())
667         w.Bool(sig.Variadic())
668 }
669
670 func (w *writer) params(typ *types2.Tuple) {
671         w.Sync(pkgbits.SyncParams)
672         w.Len(typ.Len())
673         for i := 0; i < typ.Len(); i++ {
674                 w.param(typ.At(i))
675         }
676 }
677
678 func (w *writer) param(param *types2.Var) {
679         w.Sync(pkgbits.SyncParam)
680         w.pos(param)
681         w.localIdent(param)
682         w.typ(param.Type())
683 }
684
685 // @@@ Objects
686
687 // obj writes a use of the given object into the bitstream.
688 //
689 // If obj is a generic object, then explicits are the explicit type
690 // arguments used to instantiate it (i.e., used to substitute the
691 // object's own declared type parameters).
692 func (w *writer) obj(obj types2.Object, explicits *types2.TypeList) {
693         w.objInfo(w.p.objInstIdx(obj, explicits, w.dict))
694 }
695
696 // objInfo writes a use of the given encoded object into the
697 // bitstream.
698 func (w *writer) objInfo(info objInfo) {
699         w.Sync(pkgbits.SyncObject)
700         w.Bool(false) // TODO(mdempsky): Remove; was derived func inst.
701         w.Reloc(pkgbits.RelocObj, info.idx)
702
703         w.Len(len(info.explicits))
704         for _, info := range info.explicits {
705                 w.typInfo(info)
706         }
707 }
708
709 // objInstIdx returns the indices for an object and a corresponding
710 // list of type arguments used to instantiate it, adding them to the
711 // export data as needed.
712 func (pw *pkgWriter) objInstIdx(obj types2.Object, explicits *types2.TypeList, dict *writerDict) objInfo {
713         explicitInfos := make([]typeInfo, explicits.Len())
714         for i := range explicitInfos {
715                 explicitInfos[i] = pw.typIdx(explicits.At(i), dict)
716         }
717         return objInfo{idx: pw.objIdx(obj), explicits: explicitInfos}
718 }
719
720 // objIdx returns the index for the given Object, adding it to the
721 // export data as needed.
722 func (pw *pkgWriter) objIdx(obj types2.Object) pkgbits.Index {
723         // TODO(mdempsky): Validate that obj is a global object (or a local
724         // defined type, which we hoist to global scope anyway).
725
726         if idx, ok := pw.objsIdx[obj]; ok {
727                 return idx
728         }
729
730         dict := &writerDict{
731                 derivedIdx: make(map[types2.Type]pkgbits.Index),
732         }
733
734         if isDefinedType(obj) && obj.Pkg() == pw.curpkg {
735                 decl, ok := pw.typDecls[obj.(*types2.TypeName)]
736                 assert(ok)
737                 dict.implicits = decl.implicits
738         }
739
740         // We encode objects into 4 elements across different sections, all
741         // sharing the same index:
742         //
743         // - RelocName has just the object's qualified name (i.e.,
744         //   Object.Pkg and Object.Name) and the CodeObj indicating what
745         //   specific type of Object it is (Var, Func, etc).
746         //
747         // - RelocObj has the remaining public details about the object,
748         //   relevant to go/types importers.
749         //
750         // - RelocObjExt has additional private details about the object,
751         //   which are only relevant to cmd/compile itself. This is
752         //   separated from RelocObj so that go/types importers are
753         //   unaffected by internal compiler changes.
754         //
755         // - RelocObjDict has public details about the object's type
756         //   parameters and derived type's used by the object. This is
757         //   separated to facilitate the eventual introduction of
758         //   shape-based stenciling.
759         //
760         // TODO(mdempsky): Re-evaluate whether RelocName still makes sense
761         // to keep separate from RelocObj.
762
763         w := pw.newWriter(pkgbits.RelocObj, pkgbits.SyncObject1)
764         wext := pw.newWriter(pkgbits.RelocObjExt, pkgbits.SyncObject1)
765         wname := pw.newWriter(pkgbits.RelocName, pkgbits.SyncObject1)
766         wdict := pw.newWriter(pkgbits.RelocObjDict, pkgbits.SyncObject1)
767
768         pw.objsIdx[obj] = w.Idx // break cycles
769         assert(wext.Idx == w.Idx)
770         assert(wname.Idx == w.Idx)
771         assert(wdict.Idx == w.Idx)
772
773         w.dict = dict
774         wext.dict = dict
775
776         code := w.doObj(wext, obj)
777         w.Flush()
778         wext.Flush()
779
780         wname.qualifiedIdent(obj)
781         wname.Code(code)
782         wname.Flush()
783
784         wdict.objDict(obj, w.dict)
785         wdict.Flush()
786
787         return w.Idx
788 }
789
790 // doObj writes the RelocObj definition for obj to w, and the
791 // RelocObjExt definition to wext.
792 func (w *writer) doObj(wext *writer, obj types2.Object) pkgbits.CodeObj {
793         if obj.Pkg() != w.p.curpkg {
794                 return pkgbits.ObjStub
795         }
796
797         switch obj := obj.(type) {
798         default:
799                 w.p.unexpected("object", obj)
800                 panic("unreachable")
801
802         case *types2.Const:
803                 w.pos(obj)
804                 w.typ(obj.Type())
805                 w.Value(obj.Val())
806                 return pkgbits.ObjConst
807
808         case *types2.Func:
809                 decl, ok := w.p.funDecls[obj]
810                 assert(ok)
811                 sig := obj.Type().(*types2.Signature)
812
813                 w.pos(obj)
814                 w.typeParamNames(sig.TypeParams())
815                 w.signature(sig)
816                 w.pos(decl)
817                 wext.funcExt(obj)
818                 return pkgbits.ObjFunc
819
820         case *types2.TypeName:
821                 if obj.IsAlias() {
822                         w.pos(obj)
823                         w.typ(obj.Type())
824                         return pkgbits.ObjAlias
825                 }
826
827                 named := obj.Type().(*types2.Named)
828                 assert(named.TypeArgs() == nil)
829
830                 w.pos(obj)
831                 w.typeParamNames(named.TypeParams())
832                 wext.typeExt(obj)
833                 w.typ(named.Underlying())
834
835                 w.Len(named.NumMethods())
836                 for i := 0; i < named.NumMethods(); i++ {
837                         w.method(wext, named.Method(i))
838                 }
839
840                 return pkgbits.ObjType
841
842         case *types2.Var:
843                 w.pos(obj)
844                 w.typ(obj.Type())
845                 wext.varExt(obj)
846                 return pkgbits.ObjVar
847         }
848 }
849
850 // objDict writes the dictionary needed for reading the given object.
851 func (w *writer) objDict(obj types2.Object, dict *writerDict) {
852         // TODO(mdempsky): Split objDict into multiple entries? reader.go
853         // doesn't care about the type parameter bounds, and reader2.go
854         // doesn't care about referenced functions.
855
856         w.dict = dict // TODO(mdempsky): This is a bit sketchy.
857
858         w.Len(len(dict.implicits))
859
860         tparams := objTypeParams(obj)
861         ntparams := tparams.Len()
862         w.Len(ntparams)
863         for i := 0; i < ntparams; i++ {
864                 w.typ(tparams.At(i).Constraint())
865         }
866
867         nderived := len(dict.derived)
868         w.Len(nderived)
869         for _, typ := range dict.derived {
870                 w.Reloc(pkgbits.RelocType, typ.idx)
871                 w.Bool(typ.needed)
872         }
873
874         // Write runtime dictionary information.
875         //
876         // N.B., the go/types importer reads up to the section, but doesn't
877         // read any further, so it's safe to change. (See TODO above.)
878
879         // For each type parameter, write out whether the constraint is a
880         // basic interface. This is used to determine how aggressively we
881         // can shape corresponding type arguments.
882         //
883         // This is somewhat redundant with writing out the full type
884         // parameter constraints above, but the compiler currently skips
885         // over those. Also, we don't care about the *declared* constraints,
886         // but how the type parameters are actually *used*. E.g., if a type
887         // parameter is constrained to `int | uint` but then never used in
888         // arithmetic/conversions/etc, we could shape those together.
889         for _, implicit := range dict.implicits {
890                 tparam := implicit.Type().(*types2.TypeParam)
891                 w.Bool(tparam.Underlying().(*types2.Interface).IsMethodSet())
892         }
893         for i := 0; i < ntparams; i++ {
894                 tparam := tparams.At(i)
895                 w.Bool(tparam.Underlying().(*types2.Interface).IsMethodSet())
896         }
897
898         w.Len(len(dict.typeParamMethodExprs))
899         for _, info := range dict.typeParamMethodExprs {
900                 w.Len(info.typeParamIdx)
901                 w.selectorInfo(info.methodInfo)
902         }
903
904         w.Len(len(dict.subdicts))
905         for _, info := range dict.subdicts {
906                 w.objInfo(info)
907         }
908
909         w.Len(len(dict.rtypes))
910         for _, info := range dict.rtypes {
911                 w.typInfo(info)
912         }
913
914         w.Len(len(dict.itabs))
915         for _, info := range dict.itabs {
916                 w.typInfo(info.typ)
917                 w.typInfo(info.iface)
918         }
919
920         assert(len(dict.derived) == nderived)
921 }
922
923 func (w *writer) typeParamNames(tparams *types2.TypeParamList) {
924         w.Sync(pkgbits.SyncTypeParamNames)
925
926         ntparams := tparams.Len()
927         for i := 0; i < ntparams; i++ {
928                 tparam := tparams.At(i).Obj()
929                 w.pos(tparam)
930                 w.localIdent(tparam)
931         }
932 }
933
934 func (w *writer) method(wext *writer, meth *types2.Func) {
935         decl, ok := w.p.funDecls[meth]
936         assert(ok)
937         sig := meth.Type().(*types2.Signature)
938
939         w.Sync(pkgbits.SyncMethod)
940         w.pos(meth)
941         w.selector(meth)
942         w.typeParamNames(sig.RecvTypeParams())
943         w.param(sig.Recv())
944         w.signature(sig)
945
946         w.pos(decl) // XXX: Hack to workaround linker limitations.
947         wext.funcExt(meth)
948 }
949
950 // qualifiedIdent writes out the name of an object declared at package
951 // scope. (For now, it's also used to refer to local defined types.)
952 func (w *writer) qualifiedIdent(obj types2.Object) {
953         w.Sync(pkgbits.SyncSym)
954
955         name := obj.Name()
956         if isDefinedType(obj) && obj.Pkg() == w.p.curpkg {
957                 decl, ok := w.p.typDecls[obj.(*types2.TypeName)]
958                 assert(ok)
959                 if decl.gen != 0 {
960                         // For local defined types, we embed a scope-disambiguation
961                         // number directly into their name. types.SplitVargenSuffix then
962                         // knows to look for this.
963                         //
964                         // TODO(mdempsky): Find a better solution; this is terrible.
965                         name = fmt.Sprintf("%s·%v", name, decl.gen)
966                 }
967         }
968
969         w.pkg(obj.Pkg())
970         w.String(name)
971 }
972
973 // TODO(mdempsky): We should be able to omit pkg from both localIdent
974 // and selector, because they should always be known from context.
975 // However, past frustrations with this optimization in iexport make
976 // me a little nervous to try it again.
977
978 // localIdent writes the name of a locally declared object (i.e.,
979 // objects that can only be accessed by non-qualified name, within the
980 // context of a particular function).
981 func (w *writer) localIdent(obj types2.Object) {
982         assert(!isGlobal(obj))
983         w.Sync(pkgbits.SyncLocalIdent)
984         w.pkg(obj.Pkg())
985         w.String(obj.Name())
986 }
987
988 // selector writes the name of a field or method (i.e., objects that
989 // can only be accessed using selector expressions).
990 func (w *writer) selector(obj types2.Object) {
991         w.selectorInfo(w.p.selectorIdx(obj))
992 }
993
994 func (w *writer) selectorInfo(info selectorInfo) {
995         w.Sync(pkgbits.SyncSelector)
996         w.pkgRef(info.pkgIdx)
997         w.StringRef(info.nameIdx)
998 }
999
1000 func (pw *pkgWriter) selectorIdx(obj types2.Object) selectorInfo {
1001         pkgIdx := pw.pkgIdx(obj.Pkg())
1002         nameIdx := pw.StringIdx(obj.Name())
1003         return selectorInfo{pkgIdx: pkgIdx, nameIdx: nameIdx}
1004 }
1005
1006 // @@@ Compiler extensions
1007
1008 func (w *writer) funcExt(obj *types2.Func) {
1009         decl, ok := w.p.funDecls[obj]
1010         assert(ok)
1011
1012         // TODO(mdempsky): Extend these pragma validation flags to account
1013         // for generics. E.g., linkname probably doesn't make sense at
1014         // least.
1015
1016         pragma := asPragmaFlag(decl.Pragma)
1017         if pragma&ir.Systemstack != 0 && pragma&ir.Nosplit != 0 {
1018                 w.p.errorf(decl, "go:nosplit and go:systemstack cannot be combined")
1019         }
1020         wi := asWasmImport(decl.Pragma)
1021
1022         if decl.Body != nil {
1023                 if pragma&ir.Noescape != 0 {
1024                         w.p.errorf(decl, "can only use //go:noescape with external func implementations")
1025                 }
1026                 if wi != nil {
1027                         w.p.errorf(decl, "can only use //go:wasmimport with external func implementations")
1028                 }
1029                 if (pragma&ir.UintptrKeepAlive != 0 && pragma&ir.UintptrEscapes == 0) && pragma&ir.Nosplit == 0 {
1030                         // Stack growth can't handle uintptr arguments that may
1031                         // be pointers (as we don't know which are pointers
1032                         // when creating the stack map). Thus uintptrkeepalive
1033                         // functions (and all transitive callees) must be
1034                         // nosplit.
1035                         //
1036                         // N.B. uintptrescapes implies uintptrkeepalive but it
1037                         // is OK since the arguments must escape to the heap.
1038                         //
1039                         // TODO(prattmic): Add recursive nosplit check of callees.
1040                         // TODO(prattmic): Functions with no body (i.e.,
1041                         // assembly) must also be nosplit, but we can't check
1042                         // that here.
1043                         w.p.errorf(decl, "go:uintptrkeepalive requires go:nosplit")
1044                 }
1045         } else {
1046                 if base.Flag.Complete || decl.Name.Value == "init" {
1047                         // Linknamed functions are allowed to have no body. Hopefully
1048                         // the linkname target has a body. See issue 23311.
1049                         // Wasmimport functions are also allowed to have no body.
1050                         if _, ok := w.p.linknames[obj]; !ok && wi == nil {
1051                                 w.p.errorf(decl, "missing function body")
1052                         }
1053                 }
1054         }
1055
1056         sig, block := obj.Type().(*types2.Signature), decl.Body
1057         body, closureVars := w.p.bodyIdx(sig, block, w.dict)
1058         assert(len(closureVars) == 0)
1059
1060         w.Sync(pkgbits.SyncFuncExt)
1061         w.pragmaFlag(pragma)
1062         w.linkname(obj)
1063
1064         if buildcfg.GOARCH == "wasm" {
1065                 if wi != nil {
1066                         w.String(wi.Module)
1067                         w.String(wi.Name)
1068                 } else {
1069                         w.String("")
1070                         w.String("")
1071                 }
1072         }
1073
1074         w.Bool(false) // stub extension
1075         w.Reloc(pkgbits.RelocBody, body)
1076         w.Sync(pkgbits.SyncEOF)
1077 }
1078
1079 func (w *writer) typeExt(obj *types2.TypeName) {
1080         decl, ok := w.p.typDecls[obj]
1081         assert(ok)
1082
1083         w.Sync(pkgbits.SyncTypeExt)
1084
1085         w.pragmaFlag(asPragmaFlag(decl.Pragma))
1086
1087         // No LSym.SymIdx info yet.
1088         w.Int64(-1)
1089         w.Int64(-1)
1090 }
1091
1092 func (w *writer) varExt(obj *types2.Var) {
1093         w.Sync(pkgbits.SyncVarExt)
1094         w.linkname(obj)
1095 }
1096
1097 func (w *writer) linkname(obj types2.Object) {
1098         w.Sync(pkgbits.SyncLinkname)
1099         w.Int64(-1)
1100         w.String(w.p.linknames[obj])
1101 }
1102
1103 func (w *writer) pragmaFlag(p ir.PragmaFlag) {
1104         w.Sync(pkgbits.SyncPragma)
1105         w.Int(int(p))
1106 }
1107
1108 // @@@ Function bodies
1109
1110 // bodyIdx returns the index for the given function body (specified by
1111 // block), adding it to the export data
1112 func (pw *pkgWriter) bodyIdx(sig *types2.Signature, block *syntax.BlockStmt, dict *writerDict) (idx pkgbits.Index, closureVars []posVar) {
1113         w := pw.newWriter(pkgbits.RelocBody, pkgbits.SyncFuncBody)
1114         w.sig = sig
1115         w.dict = dict
1116
1117         w.declareParams(sig)
1118         if w.Bool(block != nil) {
1119                 w.stmts(block.List)
1120                 w.pos(block.Rbrace)
1121         }
1122
1123         return w.Flush(), w.closureVars
1124 }
1125
1126 func (w *writer) declareParams(sig *types2.Signature) {
1127         addLocals := func(params *types2.Tuple) {
1128                 for i := 0; i < params.Len(); i++ {
1129                         w.addLocal(params.At(i))
1130                 }
1131         }
1132
1133         if recv := sig.Recv(); recv != nil {
1134                 w.addLocal(recv)
1135         }
1136         addLocals(sig.Params())
1137         addLocals(sig.Results())
1138 }
1139
1140 // addLocal records the declaration of a new local variable.
1141 func (w *writer) addLocal(obj *types2.Var) {
1142         idx := len(w.localsIdx)
1143
1144         w.Sync(pkgbits.SyncAddLocal)
1145         if w.p.SyncMarkers() {
1146                 w.Int(idx)
1147         }
1148         w.varDictIndex(obj)
1149
1150         if w.localsIdx == nil {
1151                 w.localsIdx = make(map[*types2.Var]int)
1152         }
1153         w.localsIdx[obj] = idx
1154 }
1155
1156 // useLocal writes a reference to the given local or free variable
1157 // into the bitstream.
1158 func (w *writer) useLocal(pos syntax.Pos, obj *types2.Var) {
1159         w.Sync(pkgbits.SyncUseObjLocal)
1160
1161         if idx, ok := w.localsIdx[obj]; w.Bool(ok) {
1162                 w.Len(idx)
1163                 return
1164         }
1165
1166         idx, ok := w.closureVarsIdx[obj]
1167         if !ok {
1168                 if w.closureVarsIdx == nil {
1169                         w.closureVarsIdx = make(map[*types2.Var]int)
1170                 }
1171                 idx = len(w.closureVars)
1172                 w.closureVars = append(w.closureVars, posVar{pos, obj})
1173                 w.closureVarsIdx[obj] = idx
1174         }
1175         w.Len(idx)
1176 }
1177
1178 func (w *writer) openScope(pos syntax.Pos) {
1179         w.Sync(pkgbits.SyncOpenScope)
1180         w.pos(pos)
1181 }
1182
1183 func (w *writer) closeScope(pos syntax.Pos) {
1184         w.Sync(pkgbits.SyncCloseScope)
1185         w.pos(pos)
1186         w.closeAnotherScope()
1187 }
1188
1189 func (w *writer) closeAnotherScope() {
1190         w.Sync(pkgbits.SyncCloseAnotherScope)
1191 }
1192
1193 // @@@ Statements
1194
1195 // stmt writes the given statement into the function body bitstream.
1196 func (w *writer) stmt(stmt syntax.Stmt) {
1197         var stmts []syntax.Stmt
1198         if stmt != nil {
1199                 stmts = []syntax.Stmt{stmt}
1200         }
1201         w.stmts(stmts)
1202 }
1203
1204 func (w *writer) stmts(stmts []syntax.Stmt) {
1205         dead := false
1206         w.Sync(pkgbits.SyncStmts)
1207         for _, stmt := range stmts {
1208                 if dead {
1209                         // Any statements after a terminating statement are safe to
1210                         // omit, at least until the next labeled statement.
1211                         if _, ok := stmt.(*syntax.LabeledStmt); !ok {
1212                                 continue
1213                         }
1214                 }
1215                 w.stmt1(stmt)
1216                 dead = w.p.terminates(stmt)
1217         }
1218         w.Code(stmtEnd)
1219         w.Sync(pkgbits.SyncStmtsEnd)
1220 }
1221
1222 func (w *writer) stmt1(stmt syntax.Stmt) {
1223         switch stmt := stmt.(type) {
1224         default:
1225                 w.p.unexpected("statement", stmt)
1226
1227         case nil, *syntax.EmptyStmt:
1228                 return
1229
1230         case *syntax.AssignStmt:
1231                 switch {
1232                 case stmt.Rhs == nil:
1233                         w.Code(stmtIncDec)
1234                         w.op(binOps[stmt.Op])
1235                         w.expr(stmt.Lhs)
1236                         w.pos(stmt)
1237
1238                 case stmt.Op != 0 && stmt.Op != syntax.Def:
1239                         w.Code(stmtAssignOp)
1240                         w.op(binOps[stmt.Op])
1241                         w.expr(stmt.Lhs)
1242                         w.pos(stmt)
1243
1244                         var typ types2.Type
1245                         if stmt.Op != syntax.Shl && stmt.Op != syntax.Shr {
1246                                 typ = w.p.typeOf(stmt.Lhs)
1247                         }
1248                         w.implicitConvExpr(typ, stmt.Rhs)
1249
1250                 default:
1251                         w.assignStmt(stmt, stmt.Lhs, stmt.Rhs)
1252                 }
1253
1254         case *syntax.BlockStmt:
1255                 w.Code(stmtBlock)
1256                 w.blockStmt(stmt)
1257
1258         case *syntax.BranchStmt:
1259                 w.Code(stmtBranch)
1260                 w.pos(stmt)
1261                 w.op(branchOps[stmt.Tok])
1262                 w.optLabel(stmt.Label)
1263
1264         case *syntax.CallStmt:
1265                 w.Code(stmtCall)
1266                 w.pos(stmt)
1267                 w.op(callOps[stmt.Tok])
1268                 w.expr(stmt.Call)
1269
1270         case *syntax.DeclStmt:
1271                 for _, decl := range stmt.DeclList {
1272                         w.declStmt(decl)
1273                 }
1274
1275         case *syntax.ExprStmt:
1276                 w.Code(stmtExpr)
1277                 w.expr(stmt.X)
1278
1279         case *syntax.ForStmt:
1280                 w.Code(stmtFor)
1281                 w.forStmt(stmt)
1282
1283         case *syntax.IfStmt:
1284                 w.Code(stmtIf)
1285                 w.ifStmt(stmt)
1286
1287         case *syntax.LabeledStmt:
1288                 w.Code(stmtLabel)
1289                 w.pos(stmt)
1290                 w.label(stmt.Label)
1291                 w.stmt1(stmt.Stmt)
1292
1293         case *syntax.ReturnStmt:
1294                 w.Code(stmtReturn)
1295                 w.pos(stmt)
1296
1297                 resultTypes := w.sig.Results()
1298                 dstType := func(i int) types2.Type {
1299                         return resultTypes.At(i).Type()
1300                 }
1301                 w.multiExpr(stmt, dstType, syntax.UnpackListExpr(stmt.Results))
1302
1303         case *syntax.SelectStmt:
1304                 w.Code(stmtSelect)
1305                 w.selectStmt(stmt)
1306
1307         case *syntax.SendStmt:
1308                 chanType := types2.CoreType(w.p.typeOf(stmt.Chan)).(*types2.Chan)
1309
1310                 w.Code(stmtSend)
1311                 w.pos(stmt)
1312                 w.expr(stmt.Chan)
1313                 w.implicitConvExpr(chanType.Elem(), stmt.Value)
1314
1315         case *syntax.SwitchStmt:
1316                 w.Code(stmtSwitch)
1317                 w.switchStmt(stmt)
1318         }
1319 }
1320
1321 func (w *writer) assignList(expr syntax.Expr) {
1322         exprs := syntax.UnpackListExpr(expr)
1323         w.Len(len(exprs))
1324
1325         for _, expr := range exprs {
1326                 w.assign(expr)
1327         }
1328 }
1329
1330 func (w *writer) assign(expr syntax.Expr) {
1331         expr = syntax.Unparen(expr)
1332
1333         if name, ok := expr.(*syntax.Name); ok {
1334                 if name.Value == "_" {
1335                         w.Code(assignBlank)
1336                         return
1337                 }
1338
1339                 if obj, ok := w.p.info.Defs[name]; ok {
1340                         obj := obj.(*types2.Var)
1341
1342                         w.Code(assignDef)
1343                         w.pos(obj)
1344                         w.localIdent(obj)
1345                         w.typ(obj.Type())
1346
1347                         // TODO(mdempsky): Minimize locals index size by deferring
1348                         // this until the variables actually come into scope.
1349                         w.addLocal(obj)
1350                         return
1351                 }
1352         }
1353
1354         w.Code(assignExpr)
1355         w.expr(expr)
1356 }
1357
1358 func (w *writer) declStmt(decl syntax.Decl) {
1359         switch decl := decl.(type) {
1360         default:
1361                 w.p.unexpected("declaration", decl)
1362
1363         case *syntax.ConstDecl, *syntax.TypeDecl:
1364
1365         case *syntax.VarDecl:
1366                 w.assignStmt(decl, namesAsExpr(decl.NameList), decl.Values)
1367         }
1368 }
1369
1370 // assignStmt writes out an assignment for "lhs = rhs".
1371 func (w *writer) assignStmt(pos poser, lhs0, rhs0 syntax.Expr) {
1372         lhs := syntax.UnpackListExpr(lhs0)
1373         rhs := syntax.UnpackListExpr(rhs0)
1374
1375         w.Code(stmtAssign)
1376         w.pos(pos)
1377
1378         // As if w.assignList(lhs0).
1379         w.Len(len(lhs))
1380         for _, expr := range lhs {
1381                 w.assign(expr)
1382         }
1383
1384         dstType := func(i int) types2.Type {
1385                 dst := lhs[i]
1386
1387                 // Finding dstType is somewhat involved, because for VarDecl
1388                 // statements, the Names are only added to the info.{Defs,Uses}
1389                 // maps, not to info.Types.
1390                 if name, ok := syntax.Unparen(dst).(*syntax.Name); ok {
1391                         if name.Value == "_" {
1392                                 return nil // ok: no implicit conversion
1393                         } else if def, ok := w.p.info.Defs[name].(*types2.Var); ok {
1394                                 return def.Type()
1395                         } else if use, ok := w.p.info.Uses[name].(*types2.Var); ok {
1396                                 return use.Type()
1397                         } else {
1398                                 w.p.fatalf(dst, "cannot find type of destination object: %v", dst)
1399                         }
1400                 }
1401
1402                 return w.p.typeOf(dst)
1403         }
1404
1405         w.multiExpr(pos, dstType, rhs)
1406 }
1407
1408 func (w *writer) blockStmt(stmt *syntax.BlockStmt) {
1409         w.Sync(pkgbits.SyncBlockStmt)
1410         w.openScope(stmt.Pos())
1411         w.stmts(stmt.List)
1412         w.closeScope(stmt.Rbrace)
1413 }
1414
1415 func (w *writer) forStmt(stmt *syntax.ForStmt) {
1416         w.Sync(pkgbits.SyncForStmt)
1417         w.openScope(stmt.Pos())
1418
1419         if rang, ok := stmt.Init.(*syntax.RangeClause); w.Bool(ok) {
1420                 w.pos(rang)
1421                 w.assignList(rang.Lhs)
1422                 w.expr(rang.X)
1423
1424                 xtyp := w.p.typeOf(rang.X)
1425                 if _, isMap := types2.CoreType(xtyp).(*types2.Map); isMap {
1426                         w.rtype(xtyp)
1427                 }
1428                 {
1429                         lhs := syntax.UnpackListExpr(rang.Lhs)
1430                         assign := func(i int, src types2.Type) {
1431                                 if i >= len(lhs) {
1432                                         return
1433                                 }
1434                                 dst := syntax.Unparen(lhs[i])
1435                                 if name, ok := dst.(*syntax.Name); ok && name.Value == "_" {
1436                                         return
1437                                 }
1438
1439                                 var dstType types2.Type
1440                                 if rang.Def {
1441                                         // For `:=` assignments, the LHS names only appear in Defs,
1442                                         // not Types (as used by typeOf).
1443                                         dstType = w.p.info.Defs[dst.(*syntax.Name)].(*types2.Var).Type()
1444                                 } else {
1445                                         dstType = w.p.typeOf(dst)
1446                                 }
1447
1448                                 w.convRTTI(src, dstType)
1449                         }
1450
1451                         keyType, valueType := types2.RangeKeyVal(w.p.typeOf(rang.X))
1452                         assign(0, keyType)
1453                         assign(1, valueType)
1454                 }
1455
1456         } else {
1457                 if stmt.Cond != nil && w.p.staticBool(&stmt.Cond) < 0 { // always false
1458                         stmt.Post = nil
1459                         stmt.Body.List = nil
1460                 }
1461
1462                 w.pos(stmt)
1463                 w.stmt(stmt.Init)
1464                 w.optExpr(stmt.Cond)
1465                 w.stmt(stmt.Post)
1466         }
1467
1468         w.blockStmt(stmt.Body)
1469         w.Bool(w.distinctVars(stmt))
1470         w.closeAnotherScope()
1471 }
1472
1473 func (w *writer) distinctVars(stmt *syntax.ForStmt) bool {
1474         lv := base.Debug.LoopVar
1475         v := w.p.info.FileVersions[stmt.Pos().Base()]
1476         is122 := v.Major == 0 && v.Minor == 0 || v.Major == 1 && v.Minor >= 22
1477
1478         // Turning off loopvar for 1.22 is only possible with loopvarhash=qn
1479         //
1480         // Debug.LoopVar values to be preserved for 1.21 compatibility are 1 and 2,
1481         // which are also set (=1) by GOEXPERIMENT=loopvar.  The knobs for turning on
1482         // the new, unshared, loopvar behavior apply to versions less than 1.21 because
1483         // (1) 1.21 also did that and (2) this is believed to be the likely use case;
1484         // anyone checking to see if it affects their code will just run the GOEXPERIMENT
1485         // but will not also update all their go.mod files to 1.21.
1486         //
1487         // -gcflags=-d=loopvar=3 enables logging for 1.22 but does not turn loopvar on for <= 1.21.
1488
1489         return is122 || lv > 0 && lv != 3
1490 }
1491
1492 func (w *writer) ifStmt(stmt *syntax.IfStmt) {
1493         cond := w.p.staticBool(&stmt.Cond)
1494
1495         w.Sync(pkgbits.SyncIfStmt)
1496         w.openScope(stmt.Pos())
1497         w.pos(stmt)
1498         w.stmt(stmt.Init)
1499         w.expr(stmt.Cond)
1500         w.Int(cond)
1501         if cond >= 0 {
1502                 w.blockStmt(stmt.Then)
1503         } else {
1504                 w.pos(stmt.Then.Rbrace)
1505         }
1506         if cond <= 0 {
1507                 w.stmt(stmt.Else)
1508         }
1509         w.closeAnotherScope()
1510 }
1511
1512 func (w *writer) selectStmt(stmt *syntax.SelectStmt) {
1513         w.Sync(pkgbits.SyncSelectStmt)
1514
1515         w.pos(stmt)
1516         w.Len(len(stmt.Body))
1517         for i, clause := range stmt.Body {
1518                 if i > 0 {
1519                         w.closeScope(clause.Pos())
1520                 }
1521                 w.openScope(clause.Pos())
1522
1523                 w.pos(clause)
1524                 w.stmt(clause.Comm)
1525                 w.stmts(clause.Body)
1526         }
1527         if len(stmt.Body) > 0 {
1528                 w.closeScope(stmt.Rbrace)
1529         }
1530 }
1531
1532 func (w *writer) switchStmt(stmt *syntax.SwitchStmt) {
1533         w.Sync(pkgbits.SyncSwitchStmt)
1534
1535         w.openScope(stmt.Pos())
1536         w.pos(stmt)
1537         w.stmt(stmt.Init)
1538
1539         var iface, tagType types2.Type
1540         if guard, ok := stmt.Tag.(*syntax.TypeSwitchGuard); w.Bool(ok) {
1541                 iface = w.p.typeOf(guard.X)
1542
1543                 w.pos(guard)
1544                 if tag := guard.Lhs; w.Bool(tag != nil) {
1545                         w.pos(tag)
1546
1547                         // Like w.localIdent, but we don't have a types2.Object.
1548                         w.Sync(pkgbits.SyncLocalIdent)
1549                         w.pkg(w.p.curpkg)
1550                         w.String(tag.Value)
1551                 }
1552                 w.expr(guard.X)
1553         } else {
1554                 tag := stmt.Tag
1555
1556                 var tagValue constant.Value
1557                 if tag != nil {
1558                         tv := w.p.typeAndValue(tag)
1559                         tagType = tv.Type
1560                         tagValue = tv.Value
1561                 } else {
1562                         tagType = types2.Typ[types2.Bool]
1563                         tagValue = constant.MakeBool(true)
1564                 }
1565
1566                 if tagValue != nil {
1567                         // If the switch tag has a constant value, look for a case
1568                         // clause that we always branch to.
1569                         func() {
1570                                 var target *syntax.CaseClause
1571                         Outer:
1572                                 for _, clause := range stmt.Body {
1573                                         if clause.Cases == nil {
1574                                                 target = clause
1575                                         }
1576                                         for _, cas := range syntax.UnpackListExpr(clause.Cases) {
1577                                                 tv := w.p.typeAndValue(cas)
1578                                                 if tv.Value == nil {
1579                                                         return // non-constant case; give up
1580                                                 }
1581                                                 if constant.Compare(tagValue, token.EQL, tv.Value) {
1582                                                         target = clause
1583                                                         break Outer
1584                                                 }
1585                                         }
1586                                 }
1587                                 // We've found the target clause, if any.
1588
1589                                 if target != nil {
1590                                         if hasFallthrough(target.Body) {
1591                                                 return // fallthrough is tricky; give up
1592                                         }
1593
1594                                         // Rewrite as single "default" case.
1595                                         target.Cases = nil
1596                                         stmt.Body = []*syntax.CaseClause{target}
1597                                 } else {
1598                                         stmt.Body = nil
1599                                 }
1600
1601                                 // Clear switch tag (i.e., replace with implicit "true").
1602                                 tag = nil
1603                                 stmt.Tag = nil
1604                                 tagType = types2.Typ[types2.Bool]
1605                         }()
1606                 }
1607
1608                 // Walk is going to emit comparisons between the tag value and
1609                 // each case expression, and we want these comparisons to always
1610                 // have the same type. If there are any case values that can't be
1611                 // converted to the tag value's type, then convert everything to
1612                 // `any` instead.
1613         Outer:
1614                 for _, clause := range stmt.Body {
1615                         for _, cas := range syntax.UnpackListExpr(clause.Cases) {
1616                                 if casType := w.p.typeOf(cas); !types2.AssignableTo(casType, tagType) {
1617                                         tagType = types2.NewInterfaceType(nil, nil)
1618                                         break Outer
1619                                 }
1620                         }
1621                 }
1622
1623                 if w.Bool(tag != nil) {
1624                         w.implicitConvExpr(tagType, tag)
1625                 }
1626         }
1627
1628         w.Len(len(stmt.Body))
1629         for i, clause := range stmt.Body {
1630                 if i > 0 {
1631                         w.closeScope(clause.Pos())
1632                 }
1633                 w.openScope(clause.Pos())
1634
1635                 w.pos(clause)
1636
1637                 cases := syntax.UnpackListExpr(clause.Cases)
1638                 if iface != nil {
1639                         w.Len(len(cases))
1640                         for _, cas := range cases {
1641                                 if w.Bool(isNil(w.p, cas)) {
1642                                         continue
1643                                 }
1644                                 w.exprType(iface, cas)
1645                         }
1646                 } else {
1647                         // As if w.exprList(clause.Cases),
1648                         // but with implicit conversions to tagType.
1649
1650                         w.Sync(pkgbits.SyncExprList)
1651                         w.Sync(pkgbits.SyncExprs)
1652                         w.Len(len(cases))
1653                         for _, cas := range cases {
1654                                 w.implicitConvExpr(tagType, cas)
1655                         }
1656                 }
1657
1658                 if obj, ok := w.p.info.Implicits[clause]; ok {
1659                         // TODO(mdempsky): These pos details are quirkish, but also
1660                         // necessary so the variable's position is correct for DWARF
1661                         // scope assignment later. It would probably be better for us to
1662                         // instead just set the variable's DWARF scoping info earlier so
1663                         // we can give it the correct position information.
1664                         pos := clause.Pos()
1665                         if typs := syntax.UnpackListExpr(clause.Cases); len(typs) != 0 {
1666                                 pos = typeExprEndPos(typs[len(typs)-1])
1667                         }
1668                         w.pos(pos)
1669
1670                         obj := obj.(*types2.Var)
1671                         w.typ(obj.Type())
1672                         w.addLocal(obj)
1673                 }
1674
1675                 w.stmts(clause.Body)
1676         }
1677         if len(stmt.Body) > 0 {
1678                 w.closeScope(stmt.Rbrace)
1679         }
1680
1681         w.closeScope(stmt.Rbrace)
1682 }
1683
1684 func (w *writer) label(label *syntax.Name) {
1685         w.Sync(pkgbits.SyncLabel)
1686
1687         // TODO(mdempsky): Replace label strings with dense indices.
1688         w.String(label.Value)
1689 }
1690
1691 func (w *writer) optLabel(label *syntax.Name) {
1692         w.Sync(pkgbits.SyncOptLabel)
1693         if w.Bool(label != nil) {
1694                 w.label(label)
1695         }
1696 }
1697
1698 // @@@ Expressions
1699
1700 // expr writes the given expression into the function body bitstream.
1701 func (w *writer) expr(expr syntax.Expr) {
1702         base.Assertf(expr != nil, "missing expression")
1703
1704         expr = syntax.Unparen(expr) // skip parens; unneeded after typecheck
1705
1706         obj, inst := lookupObj(w.p, expr)
1707         targs := inst.TypeArgs
1708
1709         if tv, ok := w.p.maybeTypeAndValue(expr); ok {
1710                 if tv.IsType() {
1711                         w.p.fatalf(expr, "unexpected type expression %v", syntax.String(expr))
1712                 }
1713
1714                 if tv.Value != nil {
1715                         w.Code(exprConst)
1716                         w.pos(expr)
1717                         typ := idealType(tv)
1718                         assert(typ != nil)
1719                         w.typ(typ)
1720                         w.Value(tv.Value)
1721                         return
1722                 }
1723
1724                 if _, isNil := obj.(*types2.Nil); isNil {
1725                         w.Code(exprZero)
1726                         w.pos(expr)
1727                         w.typ(tv.Type)
1728                         return
1729                 }
1730
1731                 // With shape types (and particular pointer shaping), we may have
1732                 // an expression of type "go.shape.*uint8", but need to reshape it
1733                 // to another shape-identical type to allow use in field
1734                 // selection, indexing, etc.
1735                 if typ := tv.Type; !tv.IsBuiltin() && !isTuple(typ) && !isUntyped(typ) {
1736                         w.Code(exprReshape)
1737                         w.typ(typ)
1738                         // fallthrough
1739                 }
1740         }
1741
1742         if obj != nil {
1743                 if targs.Len() != 0 {
1744                         obj := obj.(*types2.Func)
1745
1746                         w.Code(exprFuncInst)
1747                         w.pos(expr)
1748                         w.funcInst(obj, targs)
1749                         return
1750                 }
1751
1752                 if isGlobal(obj) {
1753                         w.Code(exprGlobal)
1754                         w.obj(obj, nil)
1755                         return
1756                 }
1757
1758                 obj := obj.(*types2.Var)
1759                 assert(!obj.IsField())
1760
1761                 w.Code(exprLocal)
1762                 w.useLocal(expr.Pos(), obj)
1763                 return
1764         }
1765
1766         switch expr := expr.(type) {
1767         default:
1768                 w.p.unexpected("expression", expr)
1769
1770         case *syntax.CompositeLit:
1771                 w.Code(exprCompLit)
1772                 w.compLit(expr)
1773
1774         case *syntax.FuncLit:
1775                 w.Code(exprFuncLit)
1776                 w.funcLit(expr)
1777
1778         case *syntax.SelectorExpr:
1779                 sel, ok := w.p.info.Selections[expr]
1780                 assert(ok)
1781
1782                 switch sel.Kind() {
1783                 default:
1784                         w.p.fatalf(expr, "unexpected selection kind: %v", sel.Kind())
1785
1786                 case types2.FieldVal:
1787                         w.Code(exprFieldVal)
1788                         w.expr(expr.X)
1789                         w.pos(expr)
1790                         w.selector(sel.Obj())
1791
1792                 case types2.MethodVal:
1793                         w.Code(exprMethodVal)
1794                         typ := w.recvExpr(expr, sel)
1795                         w.pos(expr)
1796                         w.methodExpr(expr, typ, sel)
1797
1798                 case types2.MethodExpr:
1799                         w.Code(exprMethodExpr)
1800
1801                         tv := w.p.typeAndValue(expr.X)
1802                         assert(tv.IsType())
1803
1804                         index := sel.Index()
1805                         implicits := index[:len(index)-1]
1806
1807                         typ := tv.Type
1808                         w.typ(typ)
1809
1810                         w.Len(len(implicits))
1811                         for _, ix := range implicits {
1812                                 w.Len(ix)
1813                                 typ = deref2(typ).Underlying().(*types2.Struct).Field(ix).Type()
1814                         }
1815
1816                         recv := sel.Obj().(*types2.Func).Type().(*types2.Signature).Recv().Type()
1817                         if w.Bool(isPtrTo(typ, recv)) { // need deref
1818                                 typ = recv
1819                         } else if w.Bool(isPtrTo(recv, typ)) { // need addr
1820                                 typ = recv
1821                         }
1822
1823                         w.pos(expr)
1824                         w.methodExpr(expr, typ, sel)
1825                 }
1826
1827         case *syntax.IndexExpr:
1828                 _ = w.p.typeOf(expr.Index) // ensure this is an index expression, not an instantiation
1829
1830                 xtyp := w.p.typeOf(expr.X)
1831
1832                 var keyType types2.Type
1833                 if mapType, ok := types2.CoreType(xtyp).(*types2.Map); ok {
1834                         keyType = mapType.Key()
1835                 }
1836
1837                 w.Code(exprIndex)
1838                 w.expr(expr.X)
1839                 w.pos(expr)
1840                 w.implicitConvExpr(keyType, expr.Index)
1841                 if keyType != nil {
1842                         w.rtype(xtyp)
1843                 }
1844
1845         case *syntax.SliceExpr:
1846                 w.Code(exprSlice)
1847                 w.expr(expr.X)
1848                 w.pos(expr)
1849                 for _, n := range &expr.Index {
1850                         w.optExpr(n)
1851                 }
1852
1853         case *syntax.AssertExpr:
1854                 iface := w.p.typeOf(expr.X)
1855
1856                 w.Code(exprAssert)
1857                 w.expr(expr.X)
1858                 w.pos(expr)
1859                 w.exprType(iface, expr.Type)
1860                 w.rtype(iface)
1861
1862         case *syntax.Operation:
1863                 if expr.Y == nil {
1864                         w.Code(exprUnaryOp)
1865                         w.op(unOps[expr.Op])
1866                         w.pos(expr)
1867                         w.expr(expr.X)
1868                         break
1869                 }
1870
1871                 var commonType types2.Type
1872                 switch expr.Op {
1873                 case syntax.Shl, syntax.Shr:
1874                         // ok: operands are allowed to have different types
1875                 default:
1876                         xtyp := w.p.typeOf(expr.X)
1877                         ytyp := w.p.typeOf(expr.Y)
1878                         switch {
1879                         case types2.AssignableTo(xtyp, ytyp):
1880                                 commonType = ytyp
1881                         case types2.AssignableTo(ytyp, xtyp):
1882                                 commonType = xtyp
1883                         default:
1884                                 w.p.fatalf(expr, "failed to find common type between %v and %v", xtyp, ytyp)
1885                         }
1886                 }
1887
1888                 w.Code(exprBinaryOp)
1889                 w.op(binOps[expr.Op])
1890                 w.implicitConvExpr(commonType, expr.X)
1891                 w.pos(expr)
1892                 w.implicitConvExpr(commonType, expr.Y)
1893
1894         case *syntax.CallExpr:
1895                 tv := w.p.typeAndValue(expr.Fun)
1896                 if tv.IsType() {
1897                         assert(len(expr.ArgList) == 1)
1898                         assert(!expr.HasDots)
1899                         w.convertExpr(tv.Type, expr.ArgList[0], false)
1900                         break
1901                 }
1902
1903                 var rtype types2.Type
1904                 if tv.IsBuiltin() {
1905                         switch obj, _ := lookupObj(w.p, expr.Fun); obj.Name() {
1906                         case "make":
1907                                 assert(len(expr.ArgList) >= 1)
1908                                 assert(!expr.HasDots)
1909
1910                                 w.Code(exprMake)
1911                                 w.pos(expr)
1912                                 w.exprType(nil, expr.ArgList[0])
1913                                 w.exprs(expr.ArgList[1:])
1914
1915                                 typ := w.p.typeOf(expr)
1916                                 switch coreType := types2.CoreType(typ).(type) {
1917                                 default:
1918                                         w.p.fatalf(expr, "unexpected core type: %v", coreType)
1919                                 case *types2.Chan:
1920                                         w.rtype(typ)
1921                                 case *types2.Map:
1922                                         w.rtype(typ)
1923                                 case *types2.Slice:
1924                                         w.rtype(sliceElem(typ))
1925                                 }
1926
1927                                 return
1928
1929                         case "new":
1930                                 assert(len(expr.ArgList) == 1)
1931                                 assert(!expr.HasDots)
1932
1933                                 w.Code(exprNew)
1934                                 w.pos(expr)
1935                                 w.exprType(nil, expr.ArgList[0])
1936                                 return
1937
1938                         case "Sizeof":
1939                                 assert(len(expr.ArgList) == 1)
1940                                 assert(!expr.HasDots)
1941
1942                                 w.Code(exprSizeof)
1943                                 w.pos(expr)
1944                                 w.typ(w.p.typeOf(expr.ArgList[0]))
1945                                 return
1946
1947                         case "Alignof":
1948                                 assert(len(expr.ArgList) == 1)
1949                                 assert(!expr.HasDots)
1950
1951                                 w.Code(exprAlignof)
1952                                 w.pos(expr)
1953                                 w.typ(w.p.typeOf(expr.ArgList[0]))
1954                                 return
1955
1956                         case "Offsetof":
1957                                 assert(len(expr.ArgList) == 1)
1958                                 assert(!expr.HasDots)
1959                                 selector := syntax.Unparen(expr.ArgList[0]).(*syntax.SelectorExpr)
1960                                 index := w.p.info.Selections[selector].Index()
1961
1962                                 w.Code(exprOffsetof)
1963                                 w.pos(expr)
1964                                 w.typ(deref2(w.p.typeOf(selector.X)))
1965                                 w.Len(len(index) - 1)
1966                                 for _, idx := range index {
1967                                         w.Len(idx)
1968                                 }
1969                                 return
1970
1971                         case "append":
1972                                 rtype = sliceElem(w.p.typeOf(expr))
1973                         case "copy":
1974                                 typ := w.p.typeOf(expr.ArgList[0])
1975                                 if tuple, ok := typ.(*types2.Tuple); ok { // "copy(g())"
1976                                         typ = tuple.At(0).Type()
1977                                 }
1978                                 rtype = sliceElem(typ)
1979                         case "delete":
1980                                 typ := w.p.typeOf(expr.ArgList[0])
1981                                 if tuple, ok := typ.(*types2.Tuple); ok { // "delete(g())"
1982                                         typ = tuple.At(0).Type()
1983                                 }
1984                                 rtype = typ
1985                         case "Slice":
1986                                 rtype = sliceElem(w.p.typeOf(expr))
1987                         }
1988                 }
1989
1990                 writeFunExpr := func() {
1991                         fun := syntax.Unparen(expr.Fun)
1992
1993                         if selector, ok := fun.(*syntax.SelectorExpr); ok {
1994                                 if sel, ok := w.p.info.Selections[selector]; ok && sel.Kind() == types2.MethodVal {
1995                                         w.Bool(true) // method call
1996                                         typ := w.recvExpr(selector, sel)
1997                                         w.methodExpr(selector, typ, sel)
1998                                         return
1999                                 }
2000                         }
2001
2002                         w.Bool(false) // not a method call (i.e., normal function call)
2003
2004                         if obj, inst := lookupObj(w.p, fun); w.Bool(obj != nil && inst.TypeArgs.Len() != 0) {
2005                                 obj := obj.(*types2.Func)
2006
2007                                 w.pos(fun)
2008                                 w.funcInst(obj, inst.TypeArgs)
2009                                 return
2010                         }
2011
2012                         w.expr(fun)
2013                 }
2014
2015                 sigType := types2.CoreType(tv.Type).(*types2.Signature)
2016                 paramTypes := sigType.Params()
2017
2018                 w.Code(exprCall)
2019                 writeFunExpr()
2020                 w.pos(expr)
2021
2022                 paramType := func(i int) types2.Type {
2023                         if sigType.Variadic() && !expr.HasDots && i >= paramTypes.Len()-1 {
2024                                 return paramTypes.At(paramTypes.Len() - 1).Type().(*types2.Slice).Elem()
2025                         }
2026                         return paramTypes.At(i).Type()
2027                 }
2028
2029                 w.multiExpr(expr, paramType, expr.ArgList)
2030                 w.Bool(expr.HasDots)
2031                 if rtype != nil {
2032                         w.rtype(rtype)
2033                 }
2034         }
2035 }
2036
2037 func sliceElem(typ types2.Type) types2.Type {
2038         return types2.CoreType(typ).(*types2.Slice).Elem()
2039 }
2040
2041 func (w *writer) optExpr(expr syntax.Expr) {
2042         if w.Bool(expr != nil) {
2043                 w.expr(expr)
2044         }
2045 }
2046
2047 // recvExpr writes out expr.X, but handles any implicit addressing,
2048 // dereferencing, and field selections appropriate for the method
2049 // selection.
2050 func (w *writer) recvExpr(expr *syntax.SelectorExpr, sel *types2.Selection) types2.Type {
2051         index := sel.Index()
2052         implicits := index[:len(index)-1]
2053
2054         w.Code(exprRecv)
2055         w.expr(expr.X)
2056         w.pos(expr)
2057         w.Len(len(implicits))
2058
2059         typ := w.p.typeOf(expr.X)
2060         for _, ix := range implicits {
2061                 typ = deref2(typ).Underlying().(*types2.Struct).Field(ix).Type()
2062                 w.Len(ix)
2063         }
2064
2065         recv := sel.Obj().(*types2.Func).Type().(*types2.Signature).Recv().Type()
2066         if w.Bool(isPtrTo(typ, recv)) { // needs deref
2067                 typ = recv
2068         } else if w.Bool(isPtrTo(recv, typ)) { // needs addr
2069                 typ = recv
2070         }
2071
2072         return typ
2073 }
2074
2075 // funcInst writes a reference to an instantiated function.
2076 func (w *writer) funcInst(obj *types2.Func, targs *types2.TypeList) {
2077         info := w.p.objInstIdx(obj, targs, w.dict)
2078
2079         // Type arguments list contains derived types; we can emit a static
2080         // call to the shaped function, but need to dynamically compute the
2081         // runtime dictionary pointer.
2082         if w.Bool(info.anyDerived()) {
2083                 w.Len(w.dict.subdictIdx(info))
2084                 return
2085         }
2086
2087         // Type arguments list is statically known; we can emit a static
2088         // call with a statically reference to the respective runtime
2089         // dictionary.
2090         w.objInfo(info)
2091 }
2092
2093 // methodExpr writes out a reference to the method selected by
2094 // expr. sel should be the corresponding types2.Selection, and recv
2095 // the type produced after any implicit addressing, dereferencing, and
2096 // field selection. (Note: recv might differ from sel.Obj()'s receiver
2097 // parameter in the case of interface types, and is needed for
2098 // handling type parameter methods.)
2099 func (w *writer) methodExpr(expr *syntax.SelectorExpr, recv types2.Type, sel *types2.Selection) {
2100         fun := sel.Obj().(*types2.Func)
2101         sig := fun.Type().(*types2.Signature)
2102
2103         w.typ(recv)
2104         w.typ(sig)
2105         w.pos(expr)
2106         w.selector(fun)
2107
2108         // Method on a type parameter. These require an indirect call
2109         // through the current function's runtime dictionary.
2110         if typeParam, ok := recv.(*types2.TypeParam); w.Bool(ok) {
2111                 typeParamIdx := w.dict.typeParamIndex(typeParam)
2112                 methodInfo := w.p.selectorIdx(fun)
2113
2114                 w.Len(w.dict.typeParamMethodExprIdx(typeParamIdx, methodInfo))
2115                 return
2116         }
2117
2118         if isInterface(recv) != isInterface(sig.Recv().Type()) {
2119                 w.p.fatalf(expr, "isInterface inconsistency: %v and %v", recv, sig.Recv().Type())
2120         }
2121
2122         if !isInterface(recv) {
2123                 if named, ok := deref2(recv).(*types2.Named); ok {
2124                         obj, targs := splitNamed(named)
2125                         info := w.p.objInstIdx(obj, targs, w.dict)
2126
2127                         // Method on a derived receiver type. These can be handled by a
2128                         // static call to the shaped method, but require dynamically
2129                         // looking up the appropriate dictionary argument in the current
2130                         // function's runtime dictionary.
2131                         if w.p.hasImplicitTypeParams(obj) || info.anyDerived() {
2132                                 w.Bool(true) // dynamic subdictionary
2133                                 w.Len(w.dict.subdictIdx(info))
2134                                 return
2135                         }
2136
2137                         // Method on a fully known receiver type. These can be handled
2138                         // by a static call to the shaped method, and with a static
2139                         // reference to the receiver type's dictionary.
2140                         if targs.Len() != 0 {
2141                                 w.Bool(false) // no dynamic subdictionary
2142                                 w.Bool(true)  // static dictionary
2143                                 w.objInfo(info)
2144                                 return
2145                         }
2146                 }
2147         }
2148
2149         w.Bool(false) // no dynamic subdictionary
2150         w.Bool(false) // no static dictionary
2151 }
2152
2153 // multiExpr writes a sequence of expressions, where the i'th value is
2154 // implicitly converted to dstType(i). It also handles when exprs is a
2155 // single, multi-valued expression (e.g., the multi-valued argument in
2156 // an f(g()) call, or the RHS operand in a comma-ok assignment).
2157 func (w *writer) multiExpr(pos poser, dstType func(int) types2.Type, exprs []syntax.Expr) {
2158         w.Sync(pkgbits.SyncMultiExpr)
2159
2160         if len(exprs) == 1 {
2161                 expr := exprs[0]
2162                 if tuple, ok := w.p.typeOf(expr).(*types2.Tuple); ok {
2163                         assert(tuple.Len() > 1)
2164                         w.Bool(true) // N:1 assignment
2165                         w.pos(pos)
2166                         w.expr(expr)
2167
2168                         w.Len(tuple.Len())
2169                         for i := 0; i < tuple.Len(); i++ {
2170                                 src := tuple.At(i).Type()
2171                                 // TODO(mdempsky): Investigate not writing src here. I think
2172                                 // the reader should be able to infer it from expr anyway.
2173                                 w.typ(src)
2174                                 if dst := dstType(i); w.Bool(dst != nil && !types2.Identical(src, dst)) {
2175                                         if src == nil || dst == nil {
2176                                                 w.p.fatalf(pos, "src is %v, dst is %v", src, dst)
2177                                         }
2178                                         if !types2.AssignableTo(src, dst) {
2179                                                 w.p.fatalf(pos, "%v is not assignable to %v", src, dst)
2180                                         }
2181                                         w.typ(dst)
2182                                         w.convRTTI(src, dst)
2183                                 }
2184                         }
2185                         return
2186                 }
2187         }
2188
2189         w.Bool(false) // N:N assignment
2190         w.Len(len(exprs))
2191         for i, expr := range exprs {
2192                 w.implicitConvExpr(dstType(i), expr)
2193         }
2194 }
2195
2196 // implicitConvExpr is like expr, but if dst is non-nil and different
2197 // from expr's type, then an implicit conversion operation is inserted
2198 // at expr's position.
2199 func (w *writer) implicitConvExpr(dst types2.Type, expr syntax.Expr) {
2200         w.convertExpr(dst, expr, true)
2201 }
2202
2203 func (w *writer) convertExpr(dst types2.Type, expr syntax.Expr, implicit bool) {
2204         src := w.p.typeOf(expr)
2205
2206         // Omit implicit no-op conversions.
2207         identical := dst == nil || types2.Identical(src, dst)
2208         if implicit && identical {
2209                 w.expr(expr)
2210                 return
2211         }
2212
2213         if implicit && !types2.AssignableTo(src, dst) {
2214                 w.p.fatalf(expr, "%v is not assignable to %v", src, dst)
2215         }
2216
2217         w.Code(exprConvert)
2218         w.Bool(implicit)
2219         w.typ(dst)
2220         w.pos(expr)
2221         w.convRTTI(src, dst)
2222         w.Bool(isTypeParam(dst))
2223         w.Bool(identical)
2224         w.expr(expr)
2225 }
2226
2227 func (w *writer) compLit(lit *syntax.CompositeLit) {
2228         typ := w.p.typeOf(lit)
2229
2230         w.Sync(pkgbits.SyncCompLit)
2231         w.pos(lit)
2232         w.typ(typ)
2233
2234         if ptr, ok := types2.CoreType(typ).(*types2.Pointer); ok {
2235                 typ = ptr.Elem()
2236         }
2237         var keyType, elemType types2.Type
2238         var structType *types2.Struct
2239         switch typ0 := typ; typ := types2.CoreType(typ).(type) {
2240         default:
2241                 w.p.fatalf(lit, "unexpected composite literal type: %v", typ)
2242         case *types2.Array:
2243                 elemType = typ.Elem()
2244         case *types2.Map:
2245                 w.rtype(typ0)
2246                 keyType, elemType = typ.Key(), typ.Elem()
2247         case *types2.Slice:
2248                 elemType = typ.Elem()
2249         case *types2.Struct:
2250                 structType = typ
2251         }
2252
2253         w.Len(len(lit.ElemList))
2254         for i, elem := range lit.ElemList {
2255                 elemType := elemType
2256                 if structType != nil {
2257                         if kv, ok := elem.(*syntax.KeyValueExpr); ok {
2258                                 // use position of expr.Key rather than of elem (which has position of ':')
2259                                 w.pos(kv.Key)
2260                                 i = fieldIndex(w.p.info, structType, kv.Key.(*syntax.Name))
2261                                 elem = kv.Value
2262                         } else {
2263                                 w.pos(elem)
2264                         }
2265                         elemType = structType.Field(i).Type()
2266                         w.Len(i)
2267                 } else {
2268                         if kv, ok := elem.(*syntax.KeyValueExpr); w.Bool(ok) {
2269                                 // use position of expr.Key rather than of elem (which has position of ':')
2270                                 w.pos(kv.Key)
2271                                 w.implicitConvExpr(keyType, kv.Key)
2272                                 elem = kv.Value
2273                         }
2274                 }
2275                 w.pos(elem)
2276                 w.implicitConvExpr(elemType, elem)
2277         }
2278 }
2279
2280 func (w *writer) funcLit(expr *syntax.FuncLit) {
2281         sig := w.p.typeOf(expr).(*types2.Signature)
2282
2283         body, closureVars := w.p.bodyIdx(sig, expr.Body, w.dict)
2284
2285         w.Sync(pkgbits.SyncFuncLit)
2286         w.pos(expr)
2287         w.signature(sig)
2288
2289         w.Len(len(closureVars))
2290         for _, cv := range closureVars {
2291                 w.pos(cv.pos)
2292                 w.useLocal(cv.pos, cv.var_)
2293         }
2294
2295         w.Reloc(pkgbits.RelocBody, body)
2296 }
2297
2298 type posVar struct {
2299         pos  syntax.Pos
2300         var_ *types2.Var
2301 }
2302
2303 func (w *writer) exprList(expr syntax.Expr) {
2304         w.Sync(pkgbits.SyncExprList)
2305         w.exprs(syntax.UnpackListExpr(expr))
2306 }
2307
2308 func (w *writer) exprs(exprs []syntax.Expr) {
2309         w.Sync(pkgbits.SyncExprs)
2310         w.Len(len(exprs))
2311         for _, expr := range exprs {
2312                 w.expr(expr)
2313         }
2314 }
2315
2316 // rtype writes information so that the reader can construct an
2317 // expression of type *runtime._type representing typ.
2318 func (w *writer) rtype(typ types2.Type) {
2319         typ = types2.Default(typ)
2320
2321         info := w.p.typIdx(typ, w.dict)
2322         w.rtypeInfo(info)
2323 }
2324
2325 func (w *writer) rtypeInfo(info typeInfo) {
2326         w.Sync(pkgbits.SyncRType)
2327
2328         if w.Bool(info.derived) {
2329                 w.Len(w.dict.rtypeIdx(info))
2330         } else {
2331                 w.typInfo(info)
2332         }
2333 }
2334
2335 // varDictIndex writes out information for populating DictIndex for
2336 // the ir.Name that will represent obj.
2337 func (w *writer) varDictIndex(obj *types2.Var) {
2338         info := w.p.typIdx(obj.Type(), w.dict)
2339         if w.Bool(info.derived) {
2340                 w.Len(w.dict.rtypeIdx(info))
2341         }
2342 }
2343
2344 func isUntyped(typ types2.Type) bool {
2345         basic, ok := typ.(*types2.Basic)
2346         return ok && basic.Info()&types2.IsUntyped != 0
2347 }
2348
2349 func isTuple(typ types2.Type) bool {
2350         _, ok := typ.(*types2.Tuple)
2351         return ok
2352 }
2353
2354 func (w *writer) itab(typ, iface types2.Type) {
2355         typ = types2.Default(typ)
2356         iface = types2.Default(iface)
2357
2358         typInfo := w.p.typIdx(typ, w.dict)
2359         ifaceInfo := w.p.typIdx(iface, w.dict)
2360
2361         w.rtypeInfo(typInfo)
2362         w.rtypeInfo(ifaceInfo)
2363         if w.Bool(typInfo.derived || ifaceInfo.derived) {
2364                 w.Len(w.dict.itabIdx(typInfo, ifaceInfo))
2365         }
2366 }
2367
2368 // convRTTI writes information so that the reader can construct
2369 // expressions for converting from src to dst.
2370 func (w *writer) convRTTI(src, dst types2.Type) {
2371         w.Sync(pkgbits.SyncConvRTTI)
2372         w.itab(src, dst)
2373 }
2374
2375 func (w *writer) exprType(iface types2.Type, typ syntax.Expr) {
2376         base.Assertf(iface == nil || isInterface(iface), "%v must be nil or an interface type", iface)
2377
2378         tv := w.p.typeAndValue(typ)
2379         assert(tv.IsType())
2380
2381         w.Sync(pkgbits.SyncExprType)
2382         w.pos(typ)
2383
2384         if w.Bool(iface != nil && !iface.Underlying().(*types2.Interface).Empty()) {
2385                 w.itab(tv.Type, iface)
2386         } else {
2387                 w.rtype(tv.Type)
2388
2389                 info := w.p.typIdx(tv.Type, w.dict)
2390                 w.Bool(info.derived)
2391         }
2392 }
2393
2394 // isInterface reports whether typ is known to be an interface type.
2395 // If typ is a type parameter, then isInterface reports an internal
2396 // compiler error instead.
2397 func isInterface(typ types2.Type) bool {
2398         if _, ok := typ.(*types2.TypeParam); ok {
2399                 // typ is a type parameter and may be instantiated as either a
2400                 // concrete or interface type, so the writer can't depend on
2401                 // knowing this.
2402                 base.Fatalf("%v is a type parameter", typ)
2403         }
2404
2405         _, ok := typ.Underlying().(*types2.Interface)
2406         return ok
2407 }
2408
2409 // op writes an Op into the bitstream.
2410 func (w *writer) op(op ir.Op) {
2411         // TODO(mdempsky): Remove in favor of explicit codes? Would make
2412         // export data more stable against internal refactorings, but low
2413         // priority at the moment.
2414         assert(op != 0)
2415         w.Sync(pkgbits.SyncOp)
2416         w.Len(int(op))
2417 }
2418
2419 // @@@ Package initialization
2420
2421 // Caution: This code is still clumsy, because toolstash -cmp is
2422 // particularly sensitive to it.
2423
2424 type typeDeclGen struct {
2425         *syntax.TypeDecl
2426         gen int
2427
2428         // Implicit type parameters in scope at this type declaration.
2429         implicits []*types2.TypeName
2430 }
2431
2432 type fileImports struct {
2433         importedEmbed, importedUnsafe bool
2434 }
2435
2436 // declCollector is a visitor type that collects compiler-needed
2437 // information about declarations that types2 doesn't track.
2438 //
2439 // Notably, it maps declared types and functions back to their
2440 // declaration statement, keeps track of implicit type parameters, and
2441 // assigns unique type "generation" numbers to local defined types.
2442 type declCollector struct {
2443         pw         *pkgWriter
2444         typegen    *int
2445         file       *fileImports
2446         withinFunc bool
2447         implicits  []*types2.TypeName
2448 }
2449
2450 func (c *declCollector) withTParams(obj types2.Object) *declCollector {
2451         tparams := objTypeParams(obj)
2452         n := tparams.Len()
2453         if n == 0 {
2454                 return c
2455         }
2456
2457         copy := *c
2458         copy.implicits = copy.implicits[:len(copy.implicits):len(copy.implicits)]
2459         for i := 0; i < n; i++ {
2460                 copy.implicits = append(copy.implicits, tparams.At(i).Obj())
2461         }
2462         return &copy
2463 }
2464
2465 func (c *declCollector) Visit(n syntax.Node) syntax.Visitor {
2466         pw := c.pw
2467
2468         switch n := n.(type) {
2469         case *syntax.File:
2470                 pw.checkPragmas(n.Pragma, ir.GoBuildPragma, false)
2471
2472         case *syntax.ImportDecl:
2473                 pw.checkPragmas(n.Pragma, 0, false)
2474
2475                 switch pkgNameOf(pw.info, n).Imported().Path() {
2476                 case "embed":
2477                         c.file.importedEmbed = true
2478                 case "unsafe":
2479                         c.file.importedUnsafe = true
2480                 }
2481
2482         case *syntax.ConstDecl:
2483                 pw.checkPragmas(n.Pragma, 0, false)
2484
2485         case *syntax.FuncDecl:
2486                 pw.checkPragmas(n.Pragma, funcPragmas, false)
2487
2488                 obj := pw.info.Defs[n.Name].(*types2.Func)
2489                 pw.funDecls[obj] = n
2490
2491                 return c.withTParams(obj)
2492
2493         case *syntax.TypeDecl:
2494                 obj := pw.info.Defs[n.Name].(*types2.TypeName)
2495                 d := typeDeclGen{TypeDecl: n, implicits: c.implicits}
2496
2497                 if n.Alias {
2498                         pw.checkPragmas(n.Pragma, 0, false)
2499                 } else {
2500                         pw.checkPragmas(n.Pragma, 0, false)
2501
2502                         // Assign a unique ID to function-scoped defined types.
2503                         if c.withinFunc {
2504                                 *c.typegen++
2505                                 d.gen = *c.typegen
2506                         }
2507                 }
2508
2509                 pw.typDecls[obj] = d
2510
2511                 // TODO(mdempsky): Omit? Not strictly necessary; only matters for
2512                 // type declarations within function literals within parameterized
2513                 // type declarations, but types2 the function literals will be
2514                 // constant folded away.
2515                 return c.withTParams(obj)
2516
2517         case *syntax.VarDecl:
2518                 pw.checkPragmas(n.Pragma, 0, true)
2519
2520                 if p, ok := n.Pragma.(*pragmas); ok && len(p.Embeds) > 0 {
2521                         if err := checkEmbed(n, c.file.importedEmbed, c.withinFunc); err != nil {
2522                                 pw.errorf(p.Embeds[0].Pos, "%s", err)
2523                         }
2524                 }
2525
2526         case *syntax.BlockStmt:
2527                 if !c.withinFunc {
2528                         copy := *c
2529                         copy.withinFunc = true
2530                         return &copy
2531                 }
2532         }
2533
2534         return c
2535 }
2536
2537 func (pw *pkgWriter) collectDecls(noders []*noder) {
2538         var typegen int
2539         for _, p := range noders {
2540                 var file fileImports
2541
2542                 syntax.Walk(p.file, &declCollector{
2543                         pw:      pw,
2544                         typegen: &typegen,
2545                         file:    &file,
2546                 })
2547
2548                 pw.cgoPragmas = append(pw.cgoPragmas, p.pragcgobuf...)
2549
2550                 for _, l := range p.linknames {
2551                         if !file.importedUnsafe {
2552                                 pw.errorf(l.pos, "//go:linkname only allowed in Go files that import \"unsafe\"")
2553                                 continue
2554                         }
2555
2556                         switch obj := pw.curpkg.Scope().Lookup(l.local).(type) {
2557                         case *types2.Func, *types2.Var:
2558                                 if _, ok := pw.linknames[obj]; !ok {
2559                                         pw.linknames[obj] = l.remote
2560                                 } else {
2561                                         pw.errorf(l.pos, "duplicate //go:linkname for %s", l.local)
2562                                 }
2563
2564                         default:
2565                                 if types.AllowsGoVersion(1, 18) {
2566                                         pw.errorf(l.pos, "//go:linkname must refer to declared function or variable")
2567                                 }
2568                         }
2569                 }
2570         }
2571 }
2572
2573 func (pw *pkgWriter) checkPragmas(p syntax.Pragma, allowed ir.PragmaFlag, embedOK bool) {
2574         if p == nil {
2575                 return
2576         }
2577         pragma := p.(*pragmas)
2578
2579         for _, pos := range pragma.Pos {
2580                 if pos.Flag&^allowed != 0 {
2581                         pw.errorf(pos.Pos, "misplaced compiler directive")
2582                 }
2583         }
2584
2585         if !embedOK {
2586                 for _, e := range pragma.Embeds {
2587                         pw.errorf(e.Pos, "misplaced go:embed directive")
2588                 }
2589         }
2590 }
2591
2592 func (w *writer) pkgInit(noders []*noder) {
2593         w.Len(len(w.p.cgoPragmas))
2594         for _, cgoPragma := range w.p.cgoPragmas {
2595                 w.Strings(cgoPragma)
2596         }
2597
2598         w.pkgInitOrder()
2599
2600         w.Sync(pkgbits.SyncDecls)
2601         for _, p := range noders {
2602                 for _, decl := range p.file.DeclList {
2603                         w.pkgDecl(decl)
2604                 }
2605         }
2606         w.Code(declEnd)
2607
2608         w.Sync(pkgbits.SyncEOF)
2609 }
2610
2611 func (w *writer) pkgInitOrder() {
2612         // TODO(mdempsky): Write as a function body instead?
2613         w.Len(len(w.p.info.InitOrder))
2614         for _, init := range w.p.info.InitOrder {
2615                 w.Len(len(init.Lhs))
2616                 for _, v := range init.Lhs {
2617                         w.obj(v, nil)
2618                 }
2619                 w.expr(init.Rhs)
2620         }
2621 }
2622
2623 func (w *writer) pkgDecl(decl syntax.Decl) {
2624         switch decl := decl.(type) {
2625         default:
2626                 w.p.unexpected("declaration", decl)
2627
2628         case *syntax.ImportDecl:
2629
2630         case *syntax.ConstDecl:
2631                 w.Code(declOther)
2632                 w.pkgObjs(decl.NameList...)
2633
2634         case *syntax.FuncDecl:
2635                 if decl.Name.Value == "_" {
2636                         break // skip blank functions
2637                 }
2638
2639                 obj := w.p.info.Defs[decl.Name].(*types2.Func)
2640                 sig := obj.Type().(*types2.Signature)
2641
2642                 if sig.RecvTypeParams() != nil || sig.TypeParams() != nil {
2643                         break // skip generic functions
2644                 }
2645
2646                 if recv := sig.Recv(); recv != nil {
2647                         w.Code(declMethod)
2648                         w.typ(recvBase(recv))
2649                         w.selector(obj)
2650                         break
2651                 }
2652
2653                 w.Code(declFunc)
2654                 w.pkgObjs(decl.Name)
2655
2656         case *syntax.TypeDecl:
2657                 if len(decl.TParamList) != 0 {
2658                         break // skip generic type decls
2659                 }
2660
2661                 if decl.Name.Value == "_" {
2662                         break // skip blank type decls
2663                 }
2664
2665                 name := w.p.info.Defs[decl.Name].(*types2.TypeName)
2666                 // Skip type declarations for interfaces that are only usable as
2667                 // type parameter bounds.
2668                 if iface, ok := name.Type().Underlying().(*types2.Interface); ok && !iface.IsMethodSet() {
2669                         break
2670                 }
2671
2672                 w.Code(declOther)
2673                 w.pkgObjs(decl.Name)
2674
2675         case *syntax.VarDecl:
2676                 w.Code(declVar)
2677                 w.pkgObjs(decl.NameList...)
2678
2679                 var embeds []pragmaEmbed
2680                 if p, ok := decl.Pragma.(*pragmas); ok {
2681                         embeds = p.Embeds
2682                 }
2683                 w.Len(len(embeds))
2684                 for _, embed := range embeds {
2685                         w.pos(embed.Pos)
2686                         w.Strings(embed.Patterns)
2687                 }
2688         }
2689 }
2690
2691 func (w *writer) pkgObjs(names ...*syntax.Name) {
2692         w.Sync(pkgbits.SyncDeclNames)
2693         w.Len(len(names))
2694
2695         for _, name := range names {
2696                 obj, ok := w.p.info.Defs[name]
2697                 assert(ok)
2698
2699                 w.Sync(pkgbits.SyncDeclName)
2700                 w.obj(obj, nil)
2701         }
2702 }
2703
2704 // @@@ Helpers
2705
2706 // staticBool analyzes a boolean expression and reports whether it's
2707 // always true (positive result), always false (negative result), or
2708 // unknown (zero).
2709 //
2710 // It also simplifies the expression while preserving semantics, if
2711 // possible.
2712 func (pw *pkgWriter) staticBool(ep *syntax.Expr) int {
2713         if val := pw.typeAndValue(*ep).Value; val != nil {
2714                 if constant.BoolVal(val) {
2715                         return +1
2716                 } else {
2717                         return -1
2718                 }
2719         }
2720
2721         if e, ok := (*ep).(*syntax.Operation); ok {
2722                 switch e.Op {
2723                 case syntax.Not:
2724                         return pw.staticBool(&e.X)
2725
2726                 case syntax.AndAnd:
2727                         x := pw.staticBool(&e.X)
2728                         if x < 0 {
2729                                 *ep = e.X
2730                                 return x
2731                         }
2732
2733                         y := pw.staticBool(&e.Y)
2734                         if x > 0 || y < 0 {
2735                                 if pw.typeAndValue(e.X).Value != nil {
2736                                         *ep = e.Y
2737                                 }
2738                                 return y
2739                         }
2740
2741                 case syntax.OrOr:
2742                         x := pw.staticBool(&e.X)
2743                         if x > 0 {
2744                                 *ep = e.X
2745                                 return x
2746                         }
2747
2748                         y := pw.staticBool(&e.Y)
2749                         if x < 0 || y > 0 {
2750                                 if pw.typeAndValue(e.X).Value != nil {
2751                                         *ep = e.Y
2752                                 }
2753                                 return y
2754                         }
2755                 }
2756         }
2757
2758         return 0
2759 }
2760
2761 // hasImplicitTypeParams reports whether obj is a defined type with
2762 // implicit type parameters (e.g., declared within a generic function
2763 // or method).
2764 func (pw *pkgWriter) hasImplicitTypeParams(obj *types2.TypeName) bool {
2765         if obj.Pkg() == pw.curpkg {
2766                 decl, ok := pw.typDecls[obj]
2767                 assert(ok)
2768                 if len(decl.implicits) != 0 {
2769                         return true
2770                 }
2771         }
2772         return false
2773 }
2774
2775 // isDefinedType reports whether obj is a defined type.
2776 func isDefinedType(obj types2.Object) bool {
2777         if obj, ok := obj.(*types2.TypeName); ok {
2778                 return !obj.IsAlias()
2779         }
2780         return false
2781 }
2782
2783 // isGlobal reports whether obj was declared at package scope.
2784 //
2785 // Caveat: blank objects are not declared.
2786 func isGlobal(obj types2.Object) bool {
2787         return obj.Parent() == obj.Pkg().Scope()
2788 }
2789
2790 // lookupObj returns the object that expr refers to, if any. If expr
2791 // is an explicit instantiation of a generic object, then the instance
2792 // object is returned as well.
2793 func lookupObj(p *pkgWriter, expr syntax.Expr) (obj types2.Object, inst types2.Instance) {
2794         if index, ok := expr.(*syntax.IndexExpr); ok {
2795                 args := syntax.UnpackListExpr(index.Index)
2796                 if len(args) == 1 {
2797                         tv := p.typeAndValue(args[0])
2798                         if tv.IsValue() {
2799                                 return // normal index expression
2800                         }
2801                 }
2802
2803                 expr = index.X
2804         }
2805
2806         // Strip package qualifier, if present.
2807         if sel, ok := expr.(*syntax.SelectorExpr); ok {
2808                 if !isPkgQual(p.info, sel) {
2809                         return // normal selector expression
2810                 }
2811                 expr = sel.Sel
2812         }
2813
2814         if name, ok := expr.(*syntax.Name); ok {
2815                 obj = p.info.Uses[name]
2816                 inst = p.info.Instances[name]
2817         }
2818         return
2819 }
2820
2821 // isPkgQual reports whether the given selector expression is a
2822 // package-qualified identifier.
2823 func isPkgQual(info *types2.Info, sel *syntax.SelectorExpr) bool {
2824         if name, ok := sel.X.(*syntax.Name); ok {
2825                 _, isPkgName := info.Uses[name].(*types2.PkgName)
2826                 return isPkgName
2827         }
2828         return false
2829 }
2830
2831 // isNil reports whether expr is a (possibly parenthesized) reference
2832 // to the predeclared nil value.
2833 func isNil(p *pkgWriter, expr syntax.Expr) bool {
2834         tv := p.typeAndValue(expr)
2835         return tv.IsNil()
2836 }
2837
2838 // isBuiltin reports whether expr is a (possibly parenthesized)
2839 // referenced to the specified built-in function.
2840 func (pw *pkgWriter) isBuiltin(expr syntax.Expr, builtin string) bool {
2841         if name, ok := syntax.Unparen(expr).(*syntax.Name); ok && name.Value == builtin {
2842                 return pw.typeAndValue(name).IsBuiltin()
2843         }
2844         return false
2845 }
2846
2847 // recvBase returns the base type for the given receiver parameter.
2848 func recvBase(recv *types2.Var) *types2.Named {
2849         typ := recv.Type()
2850         if ptr, ok := typ.(*types2.Pointer); ok {
2851                 typ = ptr.Elem()
2852         }
2853         return typ.(*types2.Named)
2854 }
2855
2856 // namesAsExpr returns a list of names as a syntax.Expr.
2857 func namesAsExpr(names []*syntax.Name) syntax.Expr {
2858         if len(names) == 1 {
2859                 return names[0]
2860         }
2861
2862         exprs := make([]syntax.Expr, len(names))
2863         for i, name := range names {
2864                 exprs[i] = name
2865         }
2866         return &syntax.ListExpr{ElemList: exprs}
2867 }
2868
2869 // fieldIndex returns the index of the struct field named by key.
2870 func fieldIndex(info *types2.Info, str *types2.Struct, key *syntax.Name) int {
2871         field := info.Uses[key].(*types2.Var)
2872
2873         for i := 0; i < str.NumFields(); i++ {
2874                 if str.Field(i) == field {
2875                         return i
2876                 }
2877         }
2878
2879         panic(fmt.Sprintf("%s: %v is not a field of %v", key.Pos(), field, str))
2880 }
2881
2882 // objTypeParams returns the type parameters on the given object.
2883 func objTypeParams(obj types2.Object) *types2.TypeParamList {
2884         switch obj := obj.(type) {
2885         case *types2.Func:
2886                 sig := obj.Type().(*types2.Signature)
2887                 if sig.Recv() != nil {
2888                         return sig.RecvTypeParams()
2889                 }
2890                 return sig.TypeParams()
2891         case *types2.TypeName:
2892                 if !obj.IsAlias() {
2893                         return obj.Type().(*types2.Named).TypeParams()
2894                 }
2895         }
2896         return nil
2897 }
2898
2899 // splitNamed decomposes a use of a defined type into its original
2900 // type definition and the type arguments used to instantiate it.
2901 func splitNamed(typ *types2.Named) (*types2.TypeName, *types2.TypeList) {
2902         base.Assertf(typ.TypeParams().Len() == typ.TypeArgs().Len(), "use of uninstantiated type: %v", typ)
2903
2904         orig := typ.Origin()
2905         base.Assertf(orig.TypeArgs() == nil, "origin %v of %v has type arguments", orig, typ)
2906         base.Assertf(typ.Obj() == orig.Obj(), "%v has object %v, but %v has object %v", typ, typ.Obj(), orig, orig.Obj())
2907
2908         return typ.Obj(), typ.TypeArgs()
2909 }
2910
2911 func asPragmaFlag(p syntax.Pragma) ir.PragmaFlag {
2912         if p == nil {
2913                 return 0
2914         }
2915         return p.(*pragmas).Flag
2916 }
2917
2918 func asWasmImport(p syntax.Pragma) *WasmImport {
2919         if p == nil {
2920                 return nil
2921         }
2922         return p.(*pragmas).WasmImport
2923 }
2924
2925 // isPtrTo reports whether from is the type *to.
2926 func isPtrTo(from, to types2.Type) bool {
2927         ptr, ok := from.(*types2.Pointer)
2928         return ok && types2.Identical(ptr.Elem(), to)
2929 }
2930
2931 // hasFallthrough reports whether stmts ends in a fallthrough
2932 // statement.
2933 func hasFallthrough(stmts []syntax.Stmt) bool {
2934         last, ok := lastNonEmptyStmt(stmts).(*syntax.BranchStmt)
2935         return ok && last.Tok == syntax.Fallthrough
2936 }
2937
2938 // lastNonEmptyStmt returns the last non-empty statement in list, if
2939 // any.
2940 func lastNonEmptyStmt(stmts []syntax.Stmt) syntax.Stmt {
2941         for i := len(stmts) - 1; i >= 0; i-- {
2942                 stmt := stmts[i]
2943                 if _, ok := stmt.(*syntax.EmptyStmt); !ok {
2944                         return stmt
2945                 }
2946         }
2947         return nil
2948 }
2949
2950 // terminates reports whether stmt terminates normal control flow
2951 // (i.e., does not merely advance to the following statement).
2952 func (pw *pkgWriter) terminates(stmt syntax.Stmt) bool {
2953         switch stmt := stmt.(type) {
2954         case *syntax.BranchStmt:
2955                 if stmt.Tok == syntax.Goto {
2956                         return true
2957                 }
2958         case *syntax.ReturnStmt:
2959                 return true
2960         case *syntax.ExprStmt:
2961                 if call, ok := syntax.Unparen(stmt.X).(*syntax.CallExpr); ok {
2962                         if pw.isBuiltin(call.Fun, "panic") {
2963                                 return true
2964                         }
2965                 }
2966
2967                 // The handling of BlockStmt here is approximate, but it serves to
2968                 // allow dead-code elimination for:
2969                 //
2970                 //      if true {
2971                 //              return x
2972                 //      }
2973                 //      unreachable
2974         case *syntax.IfStmt:
2975                 cond := pw.staticBool(&stmt.Cond)
2976                 return (cond < 0 || pw.terminates(stmt.Then)) && (cond > 0 || pw.terminates(stmt.Else))
2977         case *syntax.BlockStmt:
2978                 return pw.terminates(lastNonEmptyStmt(stmt.List))
2979         }
2980
2981         return false
2982 }