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