]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/unified.go
internal/pkgbits: extract unified IR coding-level logic
[gostls13.git] / src / cmd / compile / internal / noder / unified.go
1 // UNREVIEWED
2
3 // Copyright 2021 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 package noder
8
9 import (
10         "bytes"
11         "fmt"
12         "internal/goversion"
13         "internal/pkgbits"
14         "io"
15         "runtime"
16         "sort"
17
18         "cmd/compile/internal/base"
19         "cmd/compile/internal/inline"
20         "cmd/compile/internal/ir"
21         "cmd/compile/internal/typecheck"
22         "cmd/compile/internal/types"
23         "cmd/compile/internal/types2"
24         "cmd/internal/src"
25 )
26
27 // localPkgReader holds the package reader used for reading the local
28 // package. It exists so the unified IR linker can refer back to it
29 // later.
30 var localPkgReader *pkgReader
31
32 // unified construct the local package's IR from syntax's AST.
33 //
34 // The pipeline contains 2 steps:
35 //
36 // (1) Generate package export data "stub".
37 //
38 // (2) Generate package IR from package export data.
39 //
40 // The package data "stub" at step (1) contains everything from the local package,
41 // but nothing that have been imported. When we're actually writing out export data
42 // to the output files (see writeNewExport function), we run the "linker", which does
43 // a few things:
44 //
45 // + Updates compiler extensions data (e.g., inlining cost, escape analysis results).
46 //
47 // + Handles re-exporting any transitive dependencies.
48 //
49 // + Prunes out any unnecessary details (e.g., non-inlineable functions, because any
50 //   downstream importers only care about inlinable functions).
51 //
52 // The source files are typechecked twice, once before writing export data
53 // using types2 checker, once after read export data using gc/typecheck.
54 // This duplication of work will go away once we always use types2 checker,
55 // we can remove the gc/typecheck pass. The reason it is still here:
56 //
57 // + It reduces engineering costs in maintaining a fork of typecheck
58 //   (e.g., no need to backport fixes like CL 327651).
59 //
60 // + It makes it easier to pass toolstash -cmp.
61 //
62 // + Historically, we would always re-run the typechecker after import, even though
63 //   we know the imported data is valid. It's not ideal, but also not causing any
64 //   problem either.
65 //
66 // + There's still transformation that being done during gc/typecheck, like rewriting
67 //   multi-valued function call, or transform ir.OINDEX -> ir.OINDEXMAP.
68 //
69 // Using syntax+types2 tree, which already has a complete representation of generics,
70 // the unified IR has the full typed AST for doing introspection during step (1).
71 // In other words, we have all necessary information to build the generic IR form
72 // (see writer.captureVars for an example).
73 func unified(noders []*noder) {
74         inline.NewInline = InlineCall
75
76         writeNewExportFunc = writeNewExport
77
78         newReadImportFunc = func(data string, pkg1 *types.Pkg, ctxt *types2.Context, packages map[string]*types2.Package) (pkg2 *types2.Package, err error) {
79                 pr := pkgbits.NewPkgDecoder(pkg1.Path, data)
80
81                 // Read package descriptors for both types2 and compiler backend.
82                 readPackage(newPkgReader(pr), pkg1)
83                 pkg2 = readPackage2(ctxt, packages, pr)
84                 return
85         }
86
87         data := writePkgStub(noders)
88
89         // We already passed base.Flag.Lang to types2 to handle validating
90         // the user's source code. Bump it up now to the current version and
91         // re-parse, so typecheck doesn't complain if we construct IR that
92         // utilizes newer Go features.
93         base.Flag.Lang = fmt.Sprintf("go1.%d", goversion.Version)
94         types.ParseLangFlag()
95
96         assert(types.LocalPkg.Path == "")
97         types.LocalPkg.Height = 0 // reset so pkgReader.pkgIdx doesn't complain
98         target := typecheck.Target
99
100         typecheck.TypecheckAllowed = true
101
102         localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
103         readPackage(localPkgReader, types.LocalPkg)
104
105         r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
106         r.pkgInit(types.LocalPkg, target)
107
108         // Type-check any top-level assignments. We ignore non-assignments
109         // here because other declarations are typechecked as they're
110         // constructed.
111         for i, ndecls := 0, len(target.Decls); i < ndecls; i++ {
112                 switch n := target.Decls[i]; n.Op() {
113                 case ir.OAS, ir.OAS2:
114                         target.Decls[i] = typecheck.Stmt(n)
115                 }
116         }
117
118         // Don't use range--bodyIdx can add closures to todoBodies.
119         for len(todoBodies) > 0 {
120                 // The order we expand bodies doesn't matter, so pop from the end
121                 // to reduce todoBodies reallocations if it grows further.
122                 fn := todoBodies[len(todoBodies)-1]
123                 todoBodies = todoBodies[:len(todoBodies)-1]
124
125                 pri, ok := bodyReader[fn]
126                 assert(ok)
127                 pri.funcBody(fn)
128
129                 // Instantiated generic function: add to Decls for typechecking
130                 // and compilation.
131                 if fn.OClosure == nil && len(pri.dict.targs) != 0 {
132                         target.Decls = append(target.Decls, fn)
133                 }
134         }
135         todoBodies = nil
136         todoBodiesDone = true
137
138         // Check that nothing snuck past typechecking.
139         for _, n := range target.Decls {
140                 if n.Typecheck() == 0 {
141                         base.FatalfAt(n.Pos(), "missed typecheck: %v", n)
142                 }
143
144                 // For functions, check that at least their first statement (if
145                 // any) was typechecked too.
146                 if fn, ok := n.(*ir.Func); ok && len(fn.Body) != 0 {
147                         if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
148                                 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
149                         }
150                 }
151         }
152
153         base.ExitIfErrors() // just in case
154 }
155
156 // writePkgStub type checks the given parsed source files,
157 // writes an export data package stub representing them,
158 // and returns the result.
159 func writePkgStub(noders []*noder) string {
160         m, pkg, info := checkFiles(noders)
161
162         pw := newPkgWriter(m, pkg, info)
163
164         pw.collectDecls(noders)
165
166         publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
167         privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
168
169         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
170         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
171
172         {
173                 w := publicRootWriter
174                 w.pkg(pkg)
175                 w.Bool(false) // has init; XXX
176
177                 scope := pkg.Scope()
178                 names := scope.Names()
179                 w.Len(len(names))
180                 for _, name := range scope.Names() {
181                         w.obj(scope.Lookup(name), nil)
182                 }
183
184                 w.Sync(pkgbits.SyncEOF)
185                 w.Flush()
186         }
187
188         {
189                 w := privateRootWriter
190                 w.pkgInit(noders)
191                 w.Flush()
192         }
193
194         var sb bytes.Buffer // TODO(mdempsky): strings.Builder after #44505 is resolved
195         pw.DumpTo(&sb)
196
197         // At this point, we're done with types2. Make sure the package is
198         // garbage collected.
199         freePackage(pkg)
200
201         return sb.String()
202 }
203
204 // freePackage ensures the given package is garbage collected.
205 func freePackage(pkg *types2.Package) {
206         // The GC test below relies on a precise GC that runs finalizers as
207         // soon as objects are unreachable. Our implementation provides
208         // this, but other/older implementations may not (e.g., Go 1.4 does
209         // not because of #22350). To avoid imposing unnecessary
210         // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
211         // during bootstrapping.
212         if base.CompilerBootstrap {
213                 return
214         }
215
216         // Set a finalizer on pkg so we can detect if/when it's collected.
217         done := make(chan struct{})
218         runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
219
220         // Important: objects involved in cycles are not finalized, so zero
221         // out pkg to break its cycles and allow the finalizer to run.
222         *pkg = types2.Package{}
223
224         // It typically takes just 1 or 2 cycles to release pkg, but it
225         // doesn't hurt to try a few more times.
226         for i := 0; i < 10; i++ {
227                 select {
228                 case <-done:
229                         return
230                 default:
231                         runtime.GC()
232                 }
233         }
234
235         base.Fatalf("package never finalized")
236 }
237
238 func readPackage(pr *pkgReader, importpkg *types.Pkg) {
239         r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
240
241         pkg := r.pkg()
242         assert(pkg == importpkg)
243
244         if r.Bool() {
245                 sym := pkg.Lookup(".inittask")
246                 task := ir.NewNameAt(src.NoXPos, sym)
247                 task.Class = ir.PEXTERN
248                 sym.Def = task
249         }
250
251         for i, n := 0, r.Len(); i < n; i++ {
252                 r.Sync(pkgbits.SyncObject)
253                 assert(!r.Bool())
254                 idx := r.Reloc(pkgbits.RelocObj)
255                 assert(r.Len() == 0)
256
257                 path, name, code := r.p.PeekObj(idx)
258                 if code != pkgbits.ObjStub {
259                         objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil}
260                 }
261         }
262 }
263
264 func writeNewExport(out io.Writer) {
265         l := linker{
266                 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
267
268                 pkgs:  make(map[string]int),
269                 decls: make(map[*types.Sym]int),
270         }
271
272         publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
273         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
274
275         var selfPkgIdx int
276
277         {
278                 pr := localPkgReader
279                 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
280
281                 r.Sync(pkgbits.SyncPkg)
282                 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
283
284                 r.Bool() // has init
285
286                 for i, n := 0, r.Len(); i < n; i++ {
287                         r.Sync(pkgbits.SyncObject)
288                         assert(!r.Bool())
289                         idx := r.Reloc(pkgbits.RelocObj)
290                         assert(r.Len() == 0)
291
292                         xpath, xname, xtag := pr.PeekObj(idx)
293                         assert(xpath == pr.PkgPath())
294                         assert(xtag != pkgbits.ObjStub)
295
296                         if types.IsExported(xname) {
297                                 l.relocIdx(pr, pkgbits.RelocObj, idx)
298                         }
299                 }
300
301                 r.Sync(pkgbits.SyncEOF)
302         }
303
304         {
305                 var idxs []int
306                 for _, idx := range l.decls {
307                         idxs = append(idxs, idx)
308                 }
309                 sort.Ints(idxs)
310
311                 w := publicRootWriter
312
313                 w.Sync(pkgbits.SyncPkg)
314                 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
315
316                 w.Bool(typecheck.Lookup(".inittask").Def != nil)
317
318                 w.Len(len(idxs))
319                 for _, idx := range idxs {
320                         w.Sync(pkgbits.SyncObject)
321                         w.Bool(false)
322                         w.Reloc(pkgbits.RelocObj, idx)
323                         w.Len(0)
324                 }
325
326                 w.Sync(pkgbits.SyncEOF)
327                 w.Flush()
328         }
329
330         l.pw.DumpTo(out)
331 }