]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/unified.go
cmd/compile: support lookup of functions from export data
[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/pkgbits"
10         "io"
11         "runtime"
12         "sort"
13         "strings"
14
15         "cmd/compile/internal/base"
16         "cmd/compile/internal/inline"
17         "cmd/compile/internal/ir"
18         "cmd/compile/internal/pgo"
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 // LookupMethodFunc returns the ir.Func for an arbitrary full symbol name if
31 // that function exists in the set of available export data.
32 //
33 // This allows lookup of arbitrary functions and methods that aren't otherwise
34 // referenced by the local package and thus haven't been read yet.
35 //
36 // TODO(prattmic): Does not handle instantiation of generic types. Currently
37 // profiles don't contain the original type arguments, so we won't be able to
38 // create the runtime dictionaries.
39 //
40 // TODO(prattmic): Hit rate of this function is usually fairly low, and errors
41 // are only used when debug logging is enabled. Consider constructing cheaper
42 // errors by default.
43 func LookupFunc(fullName string) (*ir.Func, error) {
44         pkgPath, symName, err := ir.ParseLinkFuncName(fullName)
45         if err != nil {
46                 return nil, fmt.Errorf("error parsing symbol name %q: %v", fullName, err)
47         }
48
49         pkg, ok := types.PkgMap()[pkgPath]
50         if !ok {
51                 return nil, fmt.Errorf("pkg %s doesn't exist in %v", pkgPath, types.PkgMap())
52         }
53
54         // Symbol naming is ambiguous. We can't necessarily distinguish between
55         // a method and a closure. e.g., is foo.Bar.func1 a closure defined in
56         // function Bar, or a method on type Bar? Thus we must simply attempt
57         // to lookup both.
58
59         fn, err := lookupFunction(pkg, symName)
60         if err == nil {
61                 return fn, nil
62         }
63
64         fn, mErr := lookupMethod(pkg, symName)
65         if mErr == nil {
66                 return fn, nil
67         }
68
69         return nil, fmt.Errorf("%s is not a function (%v) or method (%v)", fullName, err, mErr)
70 }
71
72 func lookupFunction(pkg *types.Pkg, symName string) (*ir.Func, error) {
73         sym := pkg.Lookup(symName)
74
75         // TODO(prattmic): Enclosed functions (e.g., foo.Bar.func1) are not
76         // present in objReader, only as OCLOSURE nodes in the enclosing
77         // function.
78         pri, ok := objReader[sym]
79         if !ok {
80                 return nil, fmt.Errorf("func sym %v missing objReader", sym)
81         }
82
83         name := pri.pr.objIdx(pri.idx, nil, nil, false).(*ir.Name)
84         if name.Op() != ir.ONAME || name.Class != ir.PFUNC {
85                 return nil, fmt.Errorf("func sym %v refers to non-function name: %v", sym, name)
86         }
87         return name.Func, nil
88 }
89
90 func lookupMethod(pkg *types.Pkg, symName string) (*ir.Func, error) {
91         // N.B. readPackage creates a Sym for every object in the package to
92         // initialize objReader and importBodyReader, even if the object isn't
93         // read.
94         //
95         // However, objReader is only initialized for top-level objects, so we
96         // must first lookup the type and use that to find the method rather
97         // than looking for the method directly.
98         typ, meth, err := ir.LookupMethodSelector(pkg, symName)
99         if err != nil {
100                 return nil, fmt.Errorf("error looking up method symbol %q: %v", symName, err)
101         }
102
103         pri, ok := objReader[typ]
104         if !ok {
105                 return nil, fmt.Errorf("type sym %v missing objReader", typ)
106         }
107
108         name := pri.pr.objIdx(pri.idx, nil, nil, false).(*ir.Name)
109         if name.Op() != ir.OTYPE {
110                 return nil, fmt.Errorf("type sym %v refers to non-type name: %v", typ, name)
111         }
112         if name.Alias() {
113                 return nil, fmt.Errorf("type sym %v refers to alias", typ)
114         }
115
116         for _, m := range name.Type().Methods() {
117                 if m.Sym == meth {
118                         fn := m.Nname.(*ir.Name).Func
119                         return fn, nil
120                 }
121         }
122
123         return nil, fmt.Errorf("method %s missing from method set of %v", symName, typ)
124 }
125
126 // unified constructs the local package's Internal Representation (IR)
127 // from its syntax tree (AST).
128 //
129 // The pipeline contains 2 steps:
130 //
131 //  1. Generate the export data "stub".
132 //
133 //  2. Generate the IR from the export data above.
134 //
135 // The package data "stub" at step (1) contains everything from the local package,
136 // but nothing that has been imported. When we're actually writing out export data
137 // to the output files (see writeNewExport), we run the "linker", which:
138 //
139 //   - Updates compiler extensions data (e.g. inlining cost, escape analysis results).
140 //
141 //   - Handles re-exporting any transitive dependencies.
142 //
143 //   - Prunes out any unnecessary details (e.g. non-inlineable functions, because any
144 //     downstream importers only care about inlinable functions).
145 //
146 // The source files are typechecked twice: once before writing the export data
147 // using types2, and again after reading the export data using gc/typecheck.
148 // The duplication of work will go away once we only use the types2 type checker,
149 // removing the gc/typecheck step. For now, it is kept because:
150 //
151 //   - It reduces the engineering costs in maintaining a fork of typecheck
152 //     (e.g. no need to backport fixes like CL 327651).
153 //
154 //   - It makes it easier to pass toolstash -cmp.
155 //
156 //   - Historically, we would always re-run the typechecker after importing a package,
157 //     even though we know the imported data is valid. It's not ideal, but it's
158 //     not causing any problems either.
159 //
160 //   - gc/typecheck is still in charge of some transformations, such as rewriting
161 //     multi-valued function calls or transforming ir.OINDEX to ir.OINDEXMAP.
162 //
163 // Using the syntax tree with types2, which has a complete representation of generics,
164 // the unified IR has the full typed AST needed for introspection during step (1).
165 // In other words, we have all the necessary information to build the generic IR form
166 // (see writer.captureVars for an example).
167 func unified(m posMap, noders []*noder) {
168         inline.InlineCall = unifiedInlineCall
169         typecheck.HaveInlineBody = unifiedHaveInlineBody
170         pgo.LookupFunc = LookupFunc
171
172         data := writePkgStub(m, noders)
173
174         target := typecheck.Target
175
176         localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
177         readPackage(localPkgReader, types.LocalPkg, true)
178
179         r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
180         r.pkgInit(types.LocalPkg, target)
181
182         readBodies(target, false)
183
184         // Check that nothing snuck past typechecking.
185         for _, fn := range target.Funcs {
186                 if fn.Typecheck() == 0 {
187                         base.FatalfAt(fn.Pos(), "missed typecheck: %v", fn)
188                 }
189
190                 // For functions, check that at least their first statement (if
191                 // any) was typechecked too.
192                 if len(fn.Body) != 0 {
193                         if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
194                                 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
195                         }
196                 }
197         }
198
199         // For functions originally came from package runtime,
200         // mark as norace to prevent instrumenting, see issue #60439.
201         for _, fn := range target.Funcs {
202                 if !base.Flag.CompilingRuntime && types.RuntimeSymName(fn.Sym()) != "" {
203                         fn.Pragma |= ir.Norace
204                 }
205         }
206
207         base.ExitIfErrors() // just in case
208 }
209
210 // readBodies iteratively expands all pending dictionaries and
211 // function bodies.
212 //
213 // If duringInlining is true, then the inline.InlineDecls is called as
214 // necessary on instantiations of imported generic functions, so their
215 // inlining costs can be computed.
216 func readBodies(target *ir.Package, duringInlining bool) {
217         var inlDecls []*ir.Func
218
219         // Don't use range--bodyIdx can add closures to todoBodies.
220         for {
221                 // The order we expand dictionaries and bodies doesn't matter, so
222                 // pop from the end to reduce todoBodies reallocations if it grows
223                 // further.
224                 //
225                 // However, we do at least need to flush any pending dictionaries
226                 // before reading bodies, because bodies might reference the
227                 // dictionaries.
228
229                 if len(todoDicts) > 0 {
230                         fn := todoDicts[len(todoDicts)-1]
231                         todoDicts = todoDicts[:len(todoDicts)-1]
232                         fn()
233                         continue
234                 }
235
236                 if len(todoBodies) > 0 {
237                         fn := todoBodies[len(todoBodies)-1]
238                         todoBodies = todoBodies[:len(todoBodies)-1]
239
240                         pri, ok := bodyReader[fn]
241                         assert(ok)
242                         pri.funcBody(fn)
243
244                         // Instantiated generic function: add to Decls for typechecking
245                         // and compilation.
246                         if fn.OClosure == nil && len(pri.dict.targs) != 0 {
247                                 // cmd/link does not support a type symbol referencing a method symbol
248                                 // across DSO boundary, so force re-compiling methods on a generic type
249                                 // even it was seen from imported package in linkshared mode, see #58966.
250                                 canSkipNonGenericMethod := !(base.Ctxt.Flag_linkshared && ir.IsMethod(fn))
251                                 if duringInlining && canSkipNonGenericMethod {
252                                         inlDecls = append(inlDecls, fn)
253                                 } else {
254                                         target.Funcs = append(target.Funcs, fn)
255                                 }
256                         }
257
258                         continue
259                 }
260
261                 break
262         }
263
264         todoDicts = nil
265         todoBodies = nil
266
267         if len(inlDecls) != 0 {
268                 // If we instantiated any generic functions during inlining, we need
269                 // to call CanInline on them so they'll be transitively inlined
270                 // correctly (#56280).
271                 //
272                 // We know these functions were already compiled in an imported
273                 // package though, so we don't need to actually apply InlineCalls or
274                 // save the function bodies any further than this.
275                 //
276                 // We can also lower the -m flag to 0, to suppress duplicate "can
277                 // inline" diagnostics reported against the imported package. Again,
278                 // we already reported those diagnostics in the original package, so
279                 // it's pointless repeating them here.
280
281                 oldLowerM := base.Flag.LowerM
282                 base.Flag.LowerM = 0
283                 inline.InlineDecls(nil, inlDecls, false)
284                 base.Flag.LowerM = oldLowerM
285
286                 for _, fn := range inlDecls {
287                         fn.Body = nil // free memory
288                 }
289         }
290 }
291
292 // writePkgStub type checks the given parsed source files,
293 // writes an export data package stub representing them,
294 // and returns the result.
295 func writePkgStub(m posMap, noders []*noder) string {
296         pkg, info := checkFiles(m, noders)
297
298         pw := newPkgWriter(m, pkg, info)
299
300         pw.collectDecls(noders)
301
302         publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
303         privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
304
305         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
306         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
307
308         {
309                 w := publicRootWriter
310                 w.pkg(pkg)
311                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
312
313                 scope := pkg.Scope()
314                 names := scope.Names()
315                 w.Len(len(names))
316                 for _, name := range names {
317                         w.obj(scope.Lookup(name), nil)
318                 }
319
320                 w.Sync(pkgbits.SyncEOF)
321                 w.Flush()
322         }
323
324         {
325                 w := privateRootWriter
326                 w.pkgInit(noders)
327                 w.Flush()
328         }
329
330         var sb strings.Builder
331         pw.DumpTo(&sb)
332
333         // At this point, we're done with types2. Make sure the package is
334         // garbage collected.
335         freePackage(pkg)
336
337         return sb.String()
338 }
339
340 // freePackage ensures the given package is garbage collected.
341 func freePackage(pkg *types2.Package) {
342         // The GC test below relies on a precise GC that runs finalizers as
343         // soon as objects are unreachable. Our implementation provides
344         // this, but other/older implementations may not (e.g., Go 1.4 does
345         // not because of #22350). To avoid imposing unnecessary
346         // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
347         // during bootstrapping.
348         if base.CompilerBootstrap || base.Debug.GCCheck == 0 {
349                 *pkg = types2.Package{}
350                 return
351         }
352
353         // Set a finalizer on pkg so we can detect if/when it's collected.
354         done := make(chan struct{})
355         runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
356
357         // Important: objects involved in cycles are not finalized, so zero
358         // out pkg to break its cycles and allow the finalizer to run.
359         *pkg = types2.Package{}
360
361         // It typically takes just 1 or 2 cycles to release pkg, but it
362         // doesn't hurt to try a few more times.
363         for i := 0; i < 10; i++ {
364                 select {
365                 case <-done:
366                         return
367                 default:
368                         runtime.GC()
369                 }
370         }
371
372         base.Fatalf("package never finalized")
373 }
374
375 // readPackage reads package export data from pr to populate
376 // importpkg.
377 //
378 // localStub indicates whether pr is reading the stub export data for
379 // the local package, as opposed to relocated export data for an
380 // import.
381 func readPackage(pr *pkgReader, importpkg *types.Pkg, localStub bool) {
382         {
383                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
384
385                 pkg := r.pkg()
386                 base.Assertf(pkg == importpkg, "have package %q (%p), want package %q (%p)", pkg.Path, pkg, importpkg.Path, importpkg)
387
388                 r.Bool() // TODO(mdempsky): Remove; was "has init"
389
390                 for i, n := 0, r.Len(); i < n; i++ {
391                         r.Sync(pkgbits.SyncObject)
392                         assert(!r.Bool())
393                         idx := r.Reloc(pkgbits.RelocObj)
394                         assert(r.Len() == 0)
395
396                         path, name, code := r.p.PeekObj(idx)
397                         if code != pkgbits.ObjStub {
398                                 objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil, nil, nil}
399                         }
400                 }
401
402                 r.Sync(pkgbits.SyncEOF)
403         }
404
405         if !localStub {
406                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
407
408                 if r.Bool() {
409                         sym := importpkg.Lookup(".inittask")
410                         task := ir.NewNameAt(src.NoXPos, sym, nil)
411                         task.Class = ir.PEXTERN
412                         sym.Def = task
413                 }
414
415                 for i, n := 0, r.Len(); i < n; i++ {
416                         path := r.String()
417                         name := r.String()
418                         idx := r.Reloc(pkgbits.RelocBody)
419
420                         sym := types.NewPkg(path, "").Lookup(name)
421                         if _, ok := importBodyReader[sym]; !ok {
422                                 importBodyReader[sym] = pkgReaderIndex{pr, idx, nil, nil, nil}
423                         }
424                 }
425
426                 r.Sync(pkgbits.SyncEOF)
427         }
428 }
429
430 // writeUnifiedExport writes to `out` the finalized, self-contained
431 // Unified IR export data file for the current compilation unit.
432 func writeUnifiedExport(out io.Writer) {
433         l := linker{
434                 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
435
436                 pkgs:   make(map[string]pkgbits.Index),
437                 decls:  make(map[*types.Sym]pkgbits.Index),
438                 bodies: make(map[*types.Sym]pkgbits.Index),
439         }
440
441         publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
442         privateRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPrivate)
443         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
444         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
445
446         var selfPkgIdx pkgbits.Index
447
448         {
449                 pr := localPkgReader
450                 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
451
452                 r.Sync(pkgbits.SyncPkg)
453                 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
454
455                 r.Bool() // TODO(mdempsky): Remove; was "has init"
456
457                 for i, n := 0, r.Len(); i < n; i++ {
458                         r.Sync(pkgbits.SyncObject)
459                         assert(!r.Bool())
460                         idx := r.Reloc(pkgbits.RelocObj)
461                         assert(r.Len() == 0)
462
463                         xpath, xname, xtag := pr.PeekObj(idx)
464                         assert(xpath == pr.PkgPath())
465                         assert(xtag != pkgbits.ObjStub)
466
467                         if types.IsExported(xname) {
468                                 l.relocIdx(pr, pkgbits.RelocObj, idx)
469                         }
470                 }
471
472                 r.Sync(pkgbits.SyncEOF)
473         }
474
475         {
476                 var idxs []pkgbits.Index
477                 for _, idx := range l.decls {
478                         idxs = append(idxs, idx)
479                 }
480                 sort.Slice(idxs, func(i, j int) bool { return idxs[i] < idxs[j] })
481
482                 w := publicRootWriter
483
484                 w.Sync(pkgbits.SyncPkg)
485                 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
486                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
487
488                 w.Len(len(idxs))
489                 for _, idx := range idxs {
490                         w.Sync(pkgbits.SyncObject)
491                         w.Bool(false)
492                         w.Reloc(pkgbits.RelocObj, idx)
493                         w.Len(0)
494                 }
495
496                 w.Sync(pkgbits.SyncEOF)
497                 w.Flush()
498         }
499
500         {
501                 type symIdx struct {
502                         sym *types.Sym
503                         idx pkgbits.Index
504                 }
505                 var bodies []symIdx
506                 for sym, idx := range l.bodies {
507                         bodies = append(bodies, symIdx{sym, idx})
508                 }
509                 sort.Slice(bodies, func(i, j int) bool { return bodies[i].idx < bodies[j].idx })
510
511                 w := privateRootWriter
512
513                 w.Bool(typecheck.Lookup(".inittask").Def != nil)
514
515                 w.Len(len(bodies))
516                 for _, body := range bodies {
517                         w.String(body.sym.Pkg.Path)
518                         w.String(body.sym.Name)
519                         w.Reloc(pkgbits.RelocBody, body.idx)
520                 }
521
522                 w.Sync(pkgbits.SyncEOF)
523                 w.Flush()
524         }
525
526         base.Ctxt.Fingerprint = l.pw.DumpTo(out)
527 }