]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/unified.go
cmd/compile: set LocalPkg.Path to -p flag
[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 constructs the local package's Internal Representation (IR)
33 // from its syntax tree (AST).
34 //
35 // The pipeline contains 2 steps:
36 //
37 //  1. Generate the export data "stub".
38 //
39 //  2. Generate the IR from the export data above.
40 //
41 // The package data "stub" at step (1) contains everything from the local package,
42 // but nothing that has been imported. When we're actually writing out export data
43 // to the output files (see writeNewExport), we run the "linker", which:
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 the export data
53 // using types2, and again after reading the export data using gc/typecheck.
54 // The duplication of work will go away once we only use the types2 type checker,
55 // removing the gc/typecheck step. For now, it is kept because:
56 //
57 //   - It reduces the 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 importing a package,
63 //     even though we know the imported data is valid. It's not ideal, but it's
64 //     not causing any problems either.
65 //
66 //   - gc/typecheck is still in charge of some transformations, such as rewriting
67 //     multi-valued function calls or transforming ir.OINDEX to ir.OINDEXMAP.
68 //
69 // Using the syntax tree with types2, which has a complete representation of generics,
70 // the unified IR has the full typed AST needed for introspection during step (1).
71 // In other words, we have all the 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         data := writePkgStub(noders)
77
78         // We already passed base.Flag.Lang to types2 to handle validating
79         // the user's source code. Bump it up now to the current version and
80         // re-parse, so typecheck doesn't complain if we construct IR that
81         // utilizes newer Go features.
82         base.Flag.Lang = fmt.Sprintf("go1.%d", goversion.Version)
83         types.ParseLangFlag()
84
85         types.LocalPkg.Height = 0 // reset so pkgReader.pkgIdx doesn't complain
86         target := typecheck.Target
87
88         typecheck.TypecheckAllowed = true
89
90         localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
91         readPackage(localPkgReader, types.LocalPkg)
92
93         r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
94         r.pkgInit(types.LocalPkg, target)
95
96         // Type-check any top-level assignments. We ignore non-assignments
97         // here because other declarations are typechecked as they're
98         // constructed.
99         for i, ndecls := 0, len(target.Decls); i < ndecls; i++ {
100                 switch n := target.Decls[i]; n.Op() {
101                 case ir.OAS, ir.OAS2:
102                         target.Decls[i] = typecheck.Stmt(n)
103                 }
104         }
105
106         readBodies(target)
107
108         // Check that nothing snuck past typechecking.
109         for _, n := range target.Decls {
110                 if n.Typecheck() == 0 {
111                         base.FatalfAt(n.Pos(), "missed typecheck: %v", n)
112                 }
113
114                 // For functions, check that at least their first statement (if
115                 // any) was typechecked too.
116                 if fn, ok := n.(*ir.Func); ok && len(fn.Body) != 0 {
117                         if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
118                                 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
119                         }
120                 }
121         }
122
123         base.ExitIfErrors() // just in case
124 }
125
126 // readBodies reads in bodies for any
127 func readBodies(target *ir.Package) {
128         // Don't use range--bodyIdx can add closures to todoBodies.
129         for len(todoBodies) > 0 {
130                 // The order we expand bodies doesn't matter, so pop from the end
131                 // to reduce todoBodies reallocations if it grows further.
132                 fn := todoBodies[len(todoBodies)-1]
133                 todoBodies = todoBodies[:len(todoBodies)-1]
134
135                 pri, ok := bodyReader[fn]
136                 assert(ok)
137                 pri.funcBody(fn)
138
139                 // Instantiated generic function: add to Decls for typechecking
140                 // and compilation.
141                 if fn.OClosure == nil && len(pri.dict.targs) != 0 {
142                         target.Decls = append(target.Decls, fn)
143                 }
144         }
145         todoBodies = nil
146 }
147
148 // writePkgStub type checks the given parsed source files,
149 // writes an export data package stub representing them,
150 // and returns the result.
151 func writePkgStub(noders []*noder) string {
152         m, pkg, info := checkFiles(noders)
153
154         pw := newPkgWriter(m, pkg, info)
155
156         pw.collectDecls(noders)
157
158         publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
159         privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
160
161         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
162         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
163
164         {
165                 w := publicRootWriter
166                 w.pkg(pkg)
167                 w.Bool(false) // has init; XXX
168
169                 scope := pkg.Scope()
170                 names := scope.Names()
171                 w.Len(len(names))
172                 for _, name := range scope.Names() {
173                         w.obj(scope.Lookup(name), nil)
174                 }
175
176                 w.Sync(pkgbits.SyncEOF)
177                 w.Flush()
178         }
179
180         {
181                 w := privateRootWriter
182                 w.pkgInit(noders)
183                 w.Flush()
184         }
185
186         var sb bytes.Buffer // TODO(mdempsky): strings.Builder after #44505 is resolved
187         pw.DumpTo(&sb)
188
189         // At this point, we're done with types2. Make sure the package is
190         // garbage collected.
191         freePackage(pkg)
192
193         return sb.String()
194 }
195
196 // freePackage ensures the given package is garbage collected.
197 func freePackage(pkg *types2.Package) {
198         // The GC test below relies on a precise GC that runs finalizers as
199         // soon as objects are unreachable. Our implementation provides
200         // this, but other/older implementations may not (e.g., Go 1.4 does
201         // not because of #22350). To avoid imposing unnecessary
202         // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
203         // during bootstrapping.
204         if base.CompilerBootstrap {
205                 return
206         }
207
208         // Set a finalizer on pkg so we can detect if/when it's collected.
209         done := make(chan struct{})
210         runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
211
212         // Important: objects involved in cycles are not finalized, so zero
213         // out pkg to break its cycles and allow the finalizer to run.
214         *pkg = types2.Package{}
215
216         // It typically takes just 1 or 2 cycles to release pkg, but it
217         // doesn't hurt to try a few more times.
218         for i := 0; i < 10; i++ {
219                 select {
220                 case <-done:
221                         return
222                 default:
223                         runtime.GC()
224                 }
225         }
226
227         base.Fatalf("package never finalized")
228 }
229
230 func readPackage(pr *pkgReader, importpkg *types.Pkg) {
231         r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
232
233         pkg := r.pkg()
234         base.Assertf(pkg == importpkg, "have package %q (%p), want package %q (%p)", pkg.Path, pkg, importpkg.Path, importpkg)
235
236         if r.Bool() {
237                 sym := pkg.Lookup(".inittask")
238                 task := ir.NewNameAt(src.NoXPos, sym)
239                 task.Class = ir.PEXTERN
240                 sym.Def = task
241         }
242
243         for i, n := 0, r.Len(); i < n; i++ {
244                 r.Sync(pkgbits.SyncObject)
245                 assert(!r.Bool())
246                 idx := r.Reloc(pkgbits.RelocObj)
247                 assert(r.Len() == 0)
248
249                 path, name, code := r.p.PeekObj(idx)
250                 if code != pkgbits.ObjStub {
251                         objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil}
252                 }
253         }
254 }
255
256 func writeUnifiedExport(out io.Writer) {
257         l := linker{
258                 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
259
260                 pkgs:  make(map[string]int),
261                 decls: make(map[*types.Sym]int),
262         }
263
264         publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
265         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
266
267         var selfPkgIdx int
268
269         {
270                 pr := localPkgReader
271                 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
272
273                 r.Sync(pkgbits.SyncPkg)
274                 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
275
276                 r.Bool() // has init
277
278                 for i, n := 0, r.Len(); i < n; i++ {
279                         r.Sync(pkgbits.SyncObject)
280                         assert(!r.Bool())
281                         idx := r.Reloc(pkgbits.RelocObj)
282                         assert(r.Len() == 0)
283
284                         xpath, xname, xtag := pr.PeekObj(idx)
285                         assert(xpath == pr.PkgPath())
286                         assert(xtag != pkgbits.ObjStub)
287
288                         if types.IsExported(xname) {
289                                 l.relocIdx(pr, pkgbits.RelocObj, idx)
290                         }
291                 }
292
293                 r.Sync(pkgbits.SyncEOF)
294         }
295
296         {
297                 var idxs []int
298                 for _, idx := range l.decls {
299                         idxs = append(idxs, idx)
300                 }
301                 sort.Ints(idxs)
302
303                 w := publicRootWriter
304
305                 w.Sync(pkgbits.SyncPkg)
306                 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
307
308                 w.Bool(typecheck.Lookup(".inittask").Def != nil)
309
310                 w.Len(len(idxs))
311                 for _, idx := range idxs {
312                         w.Sync(pkgbits.SyncObject)
313                         w.Bool(false)
314                         w.Reloc(pkgbits.RelocObj, idx)
315                         w.Len(0)
316                 }
317
318                 w.Sync(pkgbits.SyncEOF)
319                 w.Flush()
320         }
321
322         base.Ctxt.Fingerprint = l.pw.DumpTo(out)
323 }