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