]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/unified.go
cmd/compile: redo IsRuntimePkg/IsReflectPkg predicate
[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         "fmt"
9         "internal/goversion"
10         "internal/pkgbits"
11         "io"
12         "runtime"
13         "sort"
14         "strings"
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(m posMap, noders []*noder) {
72         inline.InlineCall = unifiedInlineCall
73         typecheck.HaveInlineBody = unifiedHaveInlineBody
74
75         data := writePkgStub(m, noders)
76
77         // We already passed base.Flag.Lang to types2 to handle validating
78         // the user's source code. Bump it up now to the current version and
79         // re-parse, so typecheck doesn't complain if we construct IR that
80         // utilizes newer Go features.
81         base.Flag.Lang = fmt.Sprintf("go1.%d", goversion.Version)
82         types.ParseLangFlag()
83
84         target := typecheck.Target
85
86         localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
87         readPackage(localPkgReader, types.LocalPkg, true)
88
89         r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
90         r.pkgInit(types.LocalPkg, target)
91
92         readBodies(target, false)
93
94         // Check that nothing snuck past typechecking.
95         for _, fn := range target.Funcs {
96                 if fn.Typecheck() == 0 {
97                         base.FatalfAt(fn.Pos(), "missed typecheck: %v", fn)
98                 }
99
100                 // For functions, check that at least their first statement (if
101                 // any) was typechecked too.
102                 if len(fn.Body) != 0 {
103                         if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
104                                 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
105                         }
106                 }
107         }
108
109         // For functions originally came from package runtime,
110         // mark as norace to prevent instrumenting, see issue #60439.
111         for _, fn := range target.Funcs {
112                 if !base.Flag.CompilingRuntime && types.RuntimeSymName(fn.Sym()) != "" {
113                         fn.Pragma |= ir.Norace
114                 }
115         }
116
117         base.ExitIfErrors() // just in case
118 }
119
120 // readBodies iteratively expands all pending dictionaries and
121 // function bodies.
122 //
123 // If duringInlining is true, then the inline.InlineDecls is called as
124 // necessary on instantiations of imported generic functions, so their
125 // inlining costs can be computed.
126 func readBodies(target *ir.Package, duringInlining bool) {
127         var inlDecls []*ir.Func
128
129         // Don't use range--bodyIdx can add closures to todoBodies.
130         for {
131                 // The order we expand dictionaries and bodies doesn't matter, so
132                 // pop from the end to reduce todoBodies reallocations if it grows
133                 // further.
134                 //
135                 // However, we do at least need to flush any pending dictionaries
136                 // before reading bodies, because bodies might reference the
137                 // dictionaries.
138
139                 if len(todoDicts) > 0 {
140                         fn := todoDicts[len(todoDicts)-1]
141                         todoDicts = todoDicts[:len(todoDicts)-1]
142                         fn()
143                         continue
144                 }
145
146                 if len(todoBodies) > 0 {
147                         fn := todoBodies[len(todoBodies)-1]
148                         todoBodies = todoBodies[:len(todoBodies)-1]
149
150                         pri, ok := bodyReader[fn]
151                         assert(ok)
152                         pri.funcBody(fn)
153
154                         // Instantiated generic function: add to Decls for typechecking
155                         // and compilation.
156                         if fn.OClosure == nil && len(pri.dict.targs) != 0 {
157                                 // cmd/link does not support a type symbol referencing a method symbol
158                                 // across DSO boundary, so force re-compiling methods on a generic type
159                                 // even it was seen from imported package in linkshared mode, see #58966.
160                                 canSkipNonGenericMethod := !(base.Ctxt.Flag_linkshared && ir.IsMethod(fn))
161                                 if duringInlining && canSkipNonGenericMethod {
162                                         inlDecls = append(inlDecls, fn)
163                                 } else {
164                                         target.Funcs = append(target.Funcs, fn)
165                                 }
166                         }
167
168                         continue
169                 }
170
171                 break
172         }
173
174         todoDicts = nil
175         todoBodies = nil
176
177         if len(inlDecls) != 0 {
178                 // If we instantiated any generic functions during inlining, we need
179                 // to call CanInline on them so they'll be transitively inlined
180                 // correctly (#56280).
181                 //
182                 // We know these functions were already compiled in an imported
183                 // package though, so we don't need to actually apply InlineCalls or
184                 // save the function bodies any further than this.
185                 //
186                 // We can also lower the -m flag to 0, to suppress duplicate "can
187                 // inline" diagnostics reported against the imported package. Again,
188                 // we already reported those diagnostics in the original package, so
189                 // it's pointless repeating them here.
190
191                 oldLowerM := base.Flag.LowerM
192                 base.Flag.LowerM = 0
193                 inline.InlineDecls(nil, inlDecls, false)
194                 base.Flag.LowerM = oldLowerM
195
196                 for _, fn := range inlDecls {
197                         fn.Body = nil // free memory
198                 }
199         }
200 }
201
202 // writePkgStub type checks the given parsed source files,
203 // writes an export data package stub representing them,
204 // and returns the result.
205 func writePkgStub(m posMap, noders []*noder) string {
206         pkg, info := checkFiles(m, noders)
207
208         pw := newPkgWriter(m, pkg, info)
209
210         pw.collectDecls(noders)
211
212         publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
213         privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
214
215         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
216         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
217
218         {
219                 w := publicRootWriter
220                 w.pkg(pkg)
221                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
222
223                 scope := pkg.Scope()
224                 names := scope.Names()
225                 w.Len(len(names))
226                 for _, name := range names {
227                         w.obj(scope.Lookup(name), nil)
228                 }
229
230                 w.Sync(pkgbits.SyncEOF)
231                 w.Flush()
232         }
233
234         {
235                 w := privateRootWriter
236                 w.pkgInit(noders)
237                 w.Flush()
238         }
239
240         var sb strings.Builder
241         pw.DumpTo(&sb)
242
243         // At this point, we're done with types2. Make sure the package is
244         // garbage collected.
245         freePackage(pkg)
246
247         return sb.String()
248 }
249
250 // freePackage ensures the given package is garbage collected.
251 func freePackage(pkg *types2.Package) {
252         // The GC test below relies on a precise GC that runs finalizers as
253         // soon as objects are unreachable. Our implementation provides
254         // this, but other/older implementations may not (e.g., Go 1.4 does
255         // not because of #22350). To avoid imposing unnecessary
256         // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
257         // during bootstrapping.
258         if base.CompilerBootstrap || base.Debug.GCCheck == 0 {
259                 *pkg = types2.Package{}
260                 return
261         }
262
263         // Set a finalizer on pkg so we can detect if/when it's collected.
264         done := make(chan struct{})
265         runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
266
267         // Important: objects involved in cycles are not finalized, so zero
268         // out pkg to break its cycles and allow the finalizer to run.
269         *pkg = types2.Package{}
270
271         // It typically takes just 1 or 2 cycles to release pkg, but it
272         // doesn't hurt to try a few more times.
273         for i := 0; i < 10; i++ {
274                 select {
275                 case <-done:
276                         return
277                 default:
278                         runtime.GC()
279                 }
280         }
281
282         base.Fatalf("package never finalized")
283 }
284
285 // readPackage reads package export data from pr to populate
286 // importpkg.
287 //
288 // localStub indicates whether pr is reading the stub export data for
289 // the local package, as opposed to relocated export data for an
290 // import.
291 func readPackage(pr *pkgReader, importpkg *types.Pkg, localStub bool) {
292         {
293                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
294
295                 pkg := r.pkg()
296                 base.Assertf(pkg == importpkg, "have package %q (%p), want package %q (%p)", pkg.Path, pkg, importpkg.Path, importpkg)
297
298                 r.Bool() // TODO(mdempsky): Remove; was "has init"
299
300                 for i, n := 0, r.Len(); i < n; i++ {
301                         r.Sync(pkgbits.SyncObject)
302                         assert(!r.Bool())
303                         idx := r.Reloc(pkgbits.RelocObj)
304                         assert(r.Len() == 0)
305
306                         path, name, code := r.p.PeekObj(idx)
307                         if code != pkgbits.ObjStub {
308                                 objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil, nil, nil}
309                         }
310                 }
311
312                 r.Sync(pkgbits.SyncEOF)
313         }
314
315         if !localStub {
316                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
317
318                 if r.Bool() {
319                         sym := importpkg.Lookup(".inittask")
320                         task := ir.NewNameAt(src.NoXPos, sym, nil)
321                         task.Class = ir.PEXTERN
322                         sym.Def = task
323                 }
324
325                 for i, n := 0, r.Len(); i < n; i++ {
326                         path := r.String()
327                         name := r.String()
328                         idx := r.Reloc(pkgbits.RelocBody)
329
330                         sym := types.NewPkg(path, "").Lookup(name)
331                         if _, ok := importBodyReader[sym]; !ok {
332                                 importBodyReader[sym] = pkgReaderIndex{pr, idx, nil, nil, nil}
333                         }
334                 }
335
336                 r.Sync(pkgbits.SyncEOF)
337         }
338 }
339
340 // writeUnifiedExport writes to `out` the finalized, self-contained
341 // Unified IR export data file for the current compilation unit.
342 func writeUnifiedExport(out io.Writer) {
343         l := linker{
344                 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
345
346                 pkgs:   make(map[string]pkgbits.Index),
347                 decls:  make(map[*types.Sym]pkgbits.Index),
348                 bodies: make(map[*types.Sym]pkgbits.Index),
349         }
350
351         publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
352         privateRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPrivate)
353         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
354         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
355
356         var selfPkgIdx pkgbits.Index
357
358         {
359                 pr := localPkgReader
360                 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
361
362                 r.Sync(pkgbits.SyncPkg)
363                 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
364
365                 r.Bool() // TODO(mdempsky): Remove; was "has init"
366
367                 for i, n := 0, r.Len(); i < n; i++ {
368                         r.Sync(pkgbits.SyncObject)
369                         assert(!r.Bool())
370                         idx := r.Reloc(pkgbits.RelocObj)
371                         assert(r.Len() == 0)
372
373                         xpath, xname, xtag := pr.PeekObj(idx)
374                         assert(xpath == pr.PkgPath())
375                         assert(xtag != pkgbits.ObjStub)
376
377                         if types.IsExported(xname) {
378                                 l.relocIdx(pr, pkgbits.RelocObj, idx)
379                         }
380                 }
381
382                 r.Sync(pkgbits.SyncEOF)
383         }
384
385         {
386                 var idxs []pkgbits.Index
387                 for _, idx := range l.decls {
388                         idxs = append(idxs, idx)
389                 }
390                 sort.Slice(idxs, func(i, j int) bool { return idxs[i] < idxs[j] })
391
392                 w := publicRootWriter
393
394                 w.Sync(pkgbits.SyncPkg)
395                 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
396                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
397
398                 w.Len(len(idxs))
399                 for _, idx := range idxs {
400                         w.Sync(pkgbits.SyncObject)
401                         w.Bool(false)
402                         w.Reloc(pkgbits.RelocObj, idx)
403                         w.Len(0)
404                 }
405
406                 w.Sync(pkgbits.SyncEOF)
407                 w.Flush()
408         }
409
410         {
411                 type symIdx struct {
412                         sym *types.Sym
413                         idx pkgbits.Index
414                 }
415                 var bodies []symIdx
416                 for sym, idx := range l.bodies {
417                         bodies = append(bodies, symIdx{sym, idx})
418                 }
419                 sort.Slice(bodies, func(i, j int) bool { return bodies[i].idx < bodies[j].idx })
420
421                 w := privateRootWriter
422
423                 w.Bool(typecheck.Lookup(".inittask").Def != nil)
424
425                 w.Len(len(bodies))
426                 for _, body := range bodies {
427                         w.String(body.sym.Pkg.Path)
428                         w.String(body.sym.Name)
429                         w.Reloc(pkgbits.RelocBody, body.idx)
430                 }
431
432                 w.Sync(pkgbits.SyncEOF)
433                 w.Flush()
434         }
435
436         base.Ctxt.Fingerprint = l.pw.DumpTo(out)
437 }