diff --git a/cl/caller_tracking_precompute_test.go b/cl/caller_tracking_precompute_test.go new file mode 100644 index 0000000000..1c667f87c0 --- /dev/null +++ b/cl/caller_tracking_precompute_test.go @@ -0,0 +1,114 @@ +//go:build !llgo + +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cl + +import ( + "sync" + "testing" + + gossa "golang.org/x/tools/go/ssa" +) + +func TestCallerTrackingPrecomputeFreezesConcurrentReads(t *testing.T) { + var nilTracking *CallerTracking + nilTracking.Precompute(nil) + dep, root := buildCallerFrameSSAProgram(t, + "example.com/dep", `package dep +import "runtime" +func Where() { runtime.Caller(0) } +`, + "example.com/root", `package root +import "example.com/dep" +func Logs() { dep.Where() } +`) + tracking := NewCallerTracking() + tracking.Precompute([]*gossa.Package{root}) + tracking.Precompute(nil) + if !tracking.frozen { + t.Fatal("CallerTracking was not frozen after precomputation") + } + if !runtimeCallerBaseSet(tracking, dep)[dep.Func("Where")] { + t.Fatal("precomputed base set lost runtime caller function") + } + if !runtimeCallerFuncSet(tracking, root)[root.Func("Logs")] { + t.Fatal("precomputed extended set lost cross-package caller") + } + + var wg sync.WaitGroup + errs := make(chan struct{}, 32) + for range 32 { + wg.Add(1) + go func() { + defer wg.Done() + if !runtimeCallerBaseSet(tracking, dep)[dep.Func("Where")] || + !runtimeCallerFuncSet(tracking, root)[root.Func("Logs")] { + errs <- struct{}{} + } + }() + } + wg.Wait() + close(errs) + if len(errs) != 0 { + t.Fatal("concurrent read lost precomputed caller tracking data") + } + + delete(tracking.base, dep) + if got := runtimeCallerBaseSet(tracking, dep); got != nil { + t.Fatalf("frozen base lookup for unknown package = %v, want nil", got) + } + delete(tracking.extended, root) + if got := runtimeCallerFuncSet(tracking, root); got != nil { + t.Fatalf("frozen extended lookup for unknown package = %v, want nil", got) + } +} + +func TestNewPackageCallerTrackingMatchesWholeProgramPrecompute(t *testing.T) { + dep, root := buildCallerFrameSSAProgram(t, + "example.com/dep", `package dep +import "runtime" +func Where() { runtime.Caller(0) } +`, + "example.com/root", `package root +import "example.com/dep" +func Logs() { dep.Where() } +`) + + whole := NewCallerTracking() + whole.Precompute([]*gossa.Package{root}) + local := NewPackageCallerTracking( + root, + SummarizeCallerTracking(dep), + SummarizeCallerTracking(root), + ) + if !local.frozen { + t.Fatal("package caller tracking was not frozen") + } + if got, want := local.base[dep][dep.Func("Where")], whole.base[dep][dep.Func("Where")]; got != want { + t.Fatalf("dependency base tracking = %v, want %v", got, want) + } + if got, want := local.extended[root][root.Func("Logs")], whole.extended[root][root.Func("Logs")]; got != want { + t.Fatalf("root extended tracking = %v, want %v", got, want) + } + if len(local.extended) != 1 { + t.Fatalf("package snapshot computed %d extended package sets, want 1", len(local.extended)) + } + if len(local.base) != 2 { + t.Fatalf("package snapshot retained %d base package sets, want 2", len(local.base)) + } +} diff --git a/cl/compile.go b/cl/compile.go index 9032deb02b..f2c3cf1cf5 100644 --- a/cl/compile.go +++ b/cl/compile.go @@ -2084,11 +2084,27 @@ func (p *context) compileValues(b llssa.Builder, vals []ssa.Value, hasVArg int) type Patch struct { Alt *ssa.Package Types *types.Package + + skips map[string]none + skipall bool + prepared bool } // Patches is patches of some packages. type Patches = map[string]Patch +// PreparePatch creates the immutable merged type view imported by packages +// compiled before the patched package's own LLVM backend runs. +func PreparePatch(patch Patch, original *types.Package, files []*ast.File) Patch { + if patch.prepared || patch.Types == nil || original == nil { + return patch + } + patch.skips, patch.skipall = collectPatchSkips(files) + typepatch.MergePrepared(patch.Types, original, patch.skips, patch.skipall) + patch.prepared = true + return patch +} + // NewPackage compiles a Go package to LLVM IR package. // Deprecated: use NewPackageExWithEmbedMetaOptions with explicit Options. func NewPackage(prog llssa.Program, pkg *ssa.Package, files []*ast.File) (ret llssa.Package, err error) { @@ -2212,6 +2228,10 @@ func newPackageEx(prog llssa.Program, ct *CallerTracking, patches Patches, rewri if hasPatch { skips := ctx.skips + if patch.prepared { + skips = patch.skips + ctx.skipall = patch.skipall + } typepatch.Merge(pkgTypes, oldTypes, skips, ctx.skipall) ctx.skips = nil ctx.state = pkgInPatch @@ -2367,8 +2387,8 @@ func (p *context) _patchType(typ types.Type) (types.Type, bool) { return t, true } o := typ.Obj() - if pkg := o.Pkg(); typepatch.IsPatched(pkg) { - if patch, ok := p.patches[pkg.Path()]; ok { + if pkg := o.Pkg(); pkg != nil { + if patch, ok := p.patches[pkg.Path()]; ok && patch.Types != nil { if obj := patch.Types.Scope().Lookup(o.Name()); obj != nil { raw := p.prog.Type(instantiate(obj.Type(), typ), llssa.InGo).RawType() return raw, typ != raw diff --git a/cl/import.go b/cl/import.go index 85e4cfc9fd..8cab4cb801 100644 --- a/cl/import.go +++ b/cl/import.go @@ -136,7 +136,12 @@ func (p *context) importPkg(pkg *types.Package, i *pkgInfo) { kind, _ := pkgKindByScope(scope) if kind == PkgNormal { if patch, ok := p.patches[pkgPath]; ok { - pkg = patch.Alt.Pkg + switch { + case patch.Types != nil: + pkg = patch.Types + case patch.Alt != nil: + pkg = patch.Alt.Pkg + } scope = pkg.Scope() if kind, _ = pkgKindByScope(scope); kind != PkgNormal { goto start @@ -220,6 +225,27 @@ func (p *context) initFiles(pkgPath string, files []*ast.File, cPkg bool) { } } +func collectPatchSkips(files []*ast.File) (map[string]none, bool) { + ctx := &context{skips: make(map[string]none)} + for _, file := range files { + for _, decl := range file.Decls { + gen, ok := decl.(*ast.GenDecl) + if !ok { + continue + } + switch gen.Tok { + case token.CONST, token.TYPE: + ctx.collectSkipNamesByDoc(gen.Doc) + case token.IMPORT: + if gen.Doc != nil && len(gen.Doc.List) != 0 { + ctx.collectSkipNames(gen.Doc.List[len(gen.Doc.List)-1].Text) + } + } + } + } + return ctx.skips, ctx.skipall +} + // Collect skip names and skip other annotations, such as go: and llgo: // llgo:skip symbol1 symbol2 ... // llgo:skipall @@ -276,7 +302,7 @@ func (p *context) collectSkip(line string, prefix int) { } } -func collectLinknameByDoc(prog llssa.Program, doc *ast.CommentGroup, fullName, inPkgName string) { +func collectLinknameByDoc(prog llssa.Program, doc *ast.CommentGroup, fullName, inPkgName string) bool { directives := directive.ParseGroup(doc) for n := len(directives) - 1; n >= 0; n-- { directive := directives[n] @@ -286,9 +312,10 @@ func collectLinknameByDoc(prog llssa.Program, doc *ast.CommentGroup, fullName, i fields := strings.Fields(directive.Args) if len(fields) >= 2 && fields[0] == inPkgName { prog.SetLinkname(fullName, strings.Join(fields[1:], " ")) - return + return true } } + return false } func (p *context) processLinknameByDoc(doc *ast.CommentGroup, fullName, inPkgName string, isVar, allowExport bool) bool { @@ -773,7 +800,10 @@ func ParsePkgSyntax(prog llssa.Program, fset *token.FileSet, pkg *types.Package, return err } fullName, inPkgName := astFuncName(pkgPath, decl) - collectLinknameByDoc(prog, decl.Doc, fullName, inPkgName) + hasLinkname := collectLinknameByDoc(prog, decl.Doc, fullName, inPkgName) + if !hasLinkname && pkg.Name() == "C" && decl.Recv == nil && token.IsExported(inPkgName) { + prog.SetLinkname(fullName, strings.TrimPrefix(inPkgName, "X")) + } ctx.processNoInterfaceByDoc(decl.Doc, fullName) case *ast.GenDecl: if decl.Tok == token.VAR { diff --git a/cl/import_coverage_test.go b/cl/import_coverage_test.go index 4afa5b0110..4f9848b34d 100644 --- a/cl/import_coverage_test.go +++ b/cl/import_coverage_test.go @@ -257,6 +257,45 @@ func TestParsePkgSyntaxCollectsLinknames(t *testing.T) { } } +func TestParsePkgSyntaxCollectsCPackageExports(t *testing.T) { + const src = `package C + +func Xadd(a, b int) int { return a + b } +func Double(x float64) float64 { return 2 * x } +func hidden() {} + +//go:linkname Xnamed explicit_name +func Xnamed() +` + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "c.go", src, parser.ParseComments) + if err != nil { + t.Fatal(err) + } + prog := llssa.NewProgram(nil) + pkg := types.NewPackage("example.com/c", "C") + if err := ParsePkgSyntax(prog, fset, pkg, []*ast.File{file}); err != nil { + t.Fatal(err) + } + tests := []struct { + name string + want string + ok bool + }{ + {name: "Xadd", want: "add", ok: true}, + {name: "Double", want: "Double", ok: true}, + {name: "hidden"}, + {name: "Xnamed", want: "explicit_name", ok: true}, + } + for _, tt := range tests { + fullName := pkg.Path() + "." + tt.name + got, ok := prog.Linkname(fullName) + if got != tt.want || ok != tt.ok { + t.Errorf("Linkname(%q) = (%q, %v), want (%q, %v)", fullName, got, ok, tt.want, tt.ok) + } + } +} + func TestCollectLinknameByDocIgnoresOtherDirectives(t *testing.T) { prog := llssa.NewProgram(nil) doc := &ast.CommentGroup{List: []*ast.Comment{ diff --git a/cl/instr.go b/cl/instr.go index 7e091eee82..2f08d42e98 100644 --- a/cl/instr.go +++ b/cl/instr.go @@ -25,6 +25,7 @@ import ( "log" "os" "regexp" + "sort" "strings" "golang.org/x/tools/go/ssa" @@ -924,6 +925,9 @@ func runtimeCallerFuncSet(c *CallerTracking, pkg *ssa.Package) map[*ssa.Function if set, ok := c.extended[pkg]; ok { return set } + if c.frozen { + return nil + } base := runtimeCallerBaseSet(c, pkg) out := make(map[*ssa.Function]bool, len(base)) for fn := range base { @@ -970,19 +974,97 @@ func runtimeCallerFuncSet(c *CallerTracking, pkg *ssa.Package) map[*ssa.Function return out } -// CallerTracking memoizes the per-package caller-tracking sets for one -// compilation. Like Patches, it is compilation-scoped state owned by the -// driver: create one per compilation and pass it to every -// NewPackageExWithEmbed call of that compilation, so cross-package -// queries (criterion 2 below) hit the memoization. It must not outlive -// the compilation — the maps are keyed by *ssa.Package with -// *ssa.Function values, so anything longer-lived would pin every -// compiled package's go/types and go/ssa graphs. Plain maps are enough: -// packages of one compilation are compiled sequentially (the LLVM -// context is not thread-safe). +// CallerTracking memoizes per-package caller-tracking sets. A two-phase driver +// may create one compilation-scoped instance, call Precompute, and share the +// frozen result. A pipelined driver instead creates one instance per backend +// with NewPackageCallerTrackingForPackages, seeded by immutable summaries +// produced as SSA packages finish. Neither form may outlive the compilation: +// the maps are keyed by *ssa.Package with *ssa.Function values, so longer-lived +// state would pin every compiled package's go/types and go/ssa graphs. type CallerTracking struct { base map[*ssa.Package]map[*ssa.Function]bool extended map[*ssa.Package]map[*ssa.Function]bool + frozen bool +} + +// Precompute resolves every caller-tracking query before backend workers +// start, then freezes the maps for concurrent read-only access. +func (c *CallerTracking) Precompute(pkgs []*ssa.Package) { + if c == nil || c.frozen { + return + } + all := make(map[*ssa.Package]bool) + for _, pkg := range pkgs { + if pkg == nil { + continue + } + all[pkg] = true + if pkg.Prog != nil { + for _, programPkg := range pkg.Prog.AllPackages() { + if programPkg != nil { + all[programPkg] = true + } + } + } + } + ordered := make([]*ssa.Package, 0, len(all)) + for pkg := range all { + ordered = append(ordered, pkg) + } + sort.Slice(ordered, func(i, j int) bool { + left, right := "", "" + if ordered[i].Pkg != nil { + left = ordered[i].Pkg.Path() + } + if ordered[j].Pkg != nil { + right = ordered[j].Pkg.Path() + } + return left < right + }) + for _, pkg := range ordered { + runtimeCallerBaseSet(c, pkg) + } + for _, pkg := range ordered { + runtimeCallerFuncSet(c, pkg) + } + c.frozen = true +} + +// CallerTrackingSummary is the immutable caller-tracking state computed when +// one package finishes SSA construction. +type CallerTrackingSummary struct { + pkg *ssa.Package + base map[*ssa.Function]bool +} + +// SummarizeCallerTracking computes the package-local caller base set once. +func SummarizeCallerTracking(pkg *ssa.Package) CallerTrackingSummary { + return CallerTrackingSummary{pkg: pkg, base: computeRuntimeCallerBaseSet(pkg)} +} + +// NewPackageCallerTracking computes and freezes the extended caller-tracking +// state needed to compile pkg. summaries should contain pkg and its effective +// dependencies, allowing package backends to reuse the package-local analysis +// performed as each package completed SSA construction. +func NewPackageCallerTracking(pkg *ssa.Package, summaries ...CallerTrackingSummary) *CallerTracking { + return NewPackageCallerTrackingForPackages([]*ssa.Package{pkg}, summaries...) +} + +// NewPackageCallerTrackingForPackages is NewPackageCallerTracking for a +// backend that compiles more than one SSA package, such as an alternate-package +// patch. +func NewPackageCallerTrackingForPackages(pkgs []*ssa.Package, summaries ...CallerTrackingSummary) *CallerTracking { + c := NewCallerTracking() + for _, summary := range summaries { + if summary.pkg != nil { + c.base[summary.pkg] = summary.base + } + } + for _, pkg := range pkgs { + runtimeCallerFuncSet(c, pkg) + } + c.frozen = true + return c } // NewCallerTracking creates the caller-tracking memoization for one @@ -1012,6 +1094,9 @@ func runtimeCallerBaseSet(c *CallerTracking, pkg *ssa.Package) map[*ssa.Function if set, ok := c.base[pkg]; ok { return set } + if c.frozen { + return nil + } set := computeRuntimeCallerBaseSet(pkg) c.base[pkg] = set return set diff --git a/cl/patch_prepare_test.go b/cl/patch_prepare_test.go new file mode 100644 index 0000000000..ecabbd9828 --- /dev/null +++ b/cl/patch_prepare_test.go @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cl + +import ( + "go/ast" + "go/parser" + "go/token" + "go/types" + "testing" + + "github.com/goplus/llgo/internal/typepatch" +) + +func TestPreparePatchBuildsImmutableMergedTypes(t *testing.T) { + original := types.NewPackage("example.com/p", "p") + original.Scope().Insert(types.NewVar(token.NoPos, original, "Keep", types.Typ[types.Int])) + original.Scope().Insert(types.NewVar(token.NoPos, original, "Skip", types.Typ[types.Int])) + alternate := types.NewPackage("example.com/p", "p") + alternate.Scope().Insert(types.NewVar(token.NoPos, alternate, "Alt", types.Typ[types.Int])) + + file, err := parser.ParseFile(token.NewFileSet(), "p.go", `package p +//llgo:skip Skip +type T int +`, parser.ParseComments) + if err != nil { + t.Fatal(err) + } + prepared := PreparePatch(Patch{Types: typepatch.Clone(alternate)}, original, []*ast.File{file}) + if !prepared.prepared { + t.Fatal("patch was not marked prepared") + } + for _, name := range []string{"Alt", "Keep"} { + if prepared.Types.Scope().Lookup(name) == nil { + t.Fatalf("prepared patch is missing %s", name) + } + } + if prepared.Types.Scope().Lookup("Skip") != nil { + t.Fatal("prepared patch retained skipped declaration") + } + if typepatch.IsPatched(original) { + t.Fatal("preparing a patch modified the original types package") + } + if original.Scope().Lookup("Keep") == nil || original.Scope().Lookup("Skip") == nil { + t.Fatal("preparing a patch modified the original package scope") + } +} + +func TestPreparePatchHandlesSkipAllAndNoopInputs(t *testing.T) { + original := types.NewPackage("example.com/p", "p") + original.Scope().Insert(types.NewVar(token.NoPos, original, "Keep", types.Typ[types.Int])) + alternate := types.NewPackage("example.com/p", "p") + alternate.Scope().Insert(types.NewVar(token.NoPos, alternate, "Alt", types.Typ[types.Int])) + + file, err := parser.ParseFile(token.NewFileSet(), "p.go", `package p +//llgo:skipall +import "unsafe" +var V int +func F() {} +`, parser.ParseComments) + if err != nil { + t.Fatal(err) + } + prepared := PreparePatch(Patch{Types: typepatch.Clone(alternate)}, original, []*ast.File{file}) + if !prepared.prepared || !prepared.skipall { + t.Fatalf("prepared patch flags = (prepared=%v, skipall=%v), want true, true", prepared.prepared, prepared.skipall) + } + if prepared.Types.Scope().Lookup("Keep") != nil { + t.Fatal("skipall merged an original declaration") + } + + alreadyPrepared := Patch{Types: prepared.Types, prepared: true} + if got := PreparePatch(alreadyPrepared, original, nil); !got.prepared || got.Types != alreadyPrepared.Types { + t.Fatal("PreparePatch changed an already prepared patch") + } + if got := PreparePatch(Patch{}, original, nil); got.prepared { + t.Fatal("PreparePatch prepared a patch without a type package") + } + if got := PreparePatch(Patch{Types: prepared.Types}, nil, nil); got.prepared { + t.Fatal("PreparePatch prepared a patch without an original package") + } +} diff --git a/cmd/internal/build/build.go b/cmd/internal/build/build.go index 5547577b29..76ef359e73 100644 --- a/cmd/internal/build/build.go +++ b/cmd/internal/build/build.go @@ -42,6 +42,7 @@ func init() { flags.AddCommonFlags(&Cmd.Flag) flags.AddCompilerVerboseFlag(&Cmd.Flag) flags.AddBuildFlags(&Cmd.Flag) + flags.AddBuildTraceFlag(&Cmd.Flag) flags.AddBuildModeFlags(&Cmd.Flag) flags.AddEmulatorFlags(&Cmd.Flag) flags.AddEmbeddedFlags(&Cmd.Flag) @@ -59,6 +60,7 @@ func runCmd(cmd *base.Command, args []string) { fmt.Fprintln(os.Stderr, err) mockable.Exit(1) } + conf.BuildTrace = flags.BuildTrace if err := flags.ApplyGoBuildFlags(conf, goBuildFlags.Args); err != nil { fmt.Fprintln(os.Stderr, err) mockable.Exit(1) diff --git a/cmd/internal/build/build_test.go b/cmd/internal/build/build_test.go index 22d71b0f43..36e64938ac 100644 --- a/cmd/internal/build/build_test.go +++ b/cmd/internal/build/build_test.go @@ -57,3 +57,13 @@ func TestRunCmdPassesGoBuildFlags(t *testing.T) { t.Fatalf("stderr = %q, want missing-package diagnostic", data) } } + +func TestBuildCommandHasSchedulerTraceFlag(t *testing.T) { + flag := Cmd.Flag.Lookup("debug-trace") + if flag == nil { + t.Fatal("llgo build has no -debug-trace flag") + } + if !strings.Contains(flag.Usage, "Chrome/Perfetto") { + t.Fatalf("-debug-trace usage = %q", flag.Usage) + } +} diff --git a/cmd/internal/flags/flags.go b/cmd/internal/flags/flags.go index 2d9a72d1f7..2d8984f69a 100644 --- a/cmd/internal/flags/flags.go +++ b/cmd/internal/flags/flags.go @@ -48,6 +48,7 @@ var SizeFormat string var SizeLevel string var ForceRebuild bool var PrintCommands bool +var BuildTrace string var DeadcodeDrop bool var PthreadStackSize byteSizeFlag var OptLevel optlevel.Level @@ -236,6 +237,14 @@ func AddBuildFlags(fs *flag.FlagSet) { fs.StringVar(&SizeLevel, "size-level", "", "Size report aggregation level (full,module,package). Default module.") } +// AddBuildTraceFlag adds the build-scheduler trace flag. It is intentionally +// separate from AddBuildFlags because only "llgo build" owns a single trace +// output file; test and run may coordinate multiple child invocations. +func AddBuildTraceFlag(fs *flag.FlagSet) { + BuildTrace = "" + fs.StringVar(&BuildTrace, "debug-trace", "", "Write a Chrome/Perfetto build trace to file") +} + func AddBuildModeFlags(fs *flag.FlagSet) { fs.StringVar(&BuildMode, "buildmode", "exe", "Build mode (exe, c-archive, c-shared)") } diff --git a/go.mod b/go.mod index c55f42ffd4..4c5087f7a1 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/goplus/mod v0.21.1 github.com/mattn/go-tty v0.0.8 github.com/qiniu/x v1.18.0 - github.com/xgo-dev/llvm v0.9.5 + github.com/xgo-dev/llvm v0.9.6 github.com/xgo-dev/plan9asm v0.3.5 go.bug.st/serial v1.6.4 go.yaml.in/yaml/v3 v3.0.5 diff --git a/go.sum b/go.sum index db139c2acc..435f9955c4 100644 --- a/go.sum +++ b/go.sum @@ -22,8 +22,8 @@ github.com/qiniu/x v1.18.0 h1:iMfc7Gqy1au+akr+Tl5Z40px7TR8VBLLkJsIeajKIbc= github.com/qiniu/x v1.18.0/go.mod h1:Sx3Wy+0GI9OsX4a53mYj6A0o7mHJ94PUvraqGYb4EIs= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/xgo-dev/llvm v0.9.5 h1:RijI/6vGu7DGw5ldlaqvpK2uFcg9OXY9OXB/RmywtEk= -github.com/xgo-dev/llvm v0.9.5/go.mod h1:42vav2/cI5BAIcL543DZSMO9do8/aCK2z7JERH+AE+M= +github.com/xgo-dev/llvm v0.9.6 h1:DtjcgENgDItbf7LyUukssMwnnWXDpERSzGQ9jRQ1CRM= +github.com/xgo-dev/llvm v0.9.6/go.mod h1:42vav2/cI5BAIcL543DZSMO9do8/aCK2z7JERH+AE+M= github.com/xgo-dev/plan9asm v0.3.5 h1:886BmpjMK6JfJ03VWA3nPK01jkVZA1a7/mZia3BOsdg= github.com/xgo-dev/plan9asm v0.3.5/go.mod h1:0yM4CCIp2PyT8h+Ro3Ukro3lHL8ji9mzHEv5yfhOckc= go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A= diff --git a/internal/build/backend_program_test.go b/internal/build/backend_program_test.go new file mode 100644 index 0000000000..a4c712b3d8 --- /dev/null +++ b/internal/build/backend_program_test.go @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "errors" + "go/ast" + "go/parser" + "go/token" + "go/types" + "testing" + + "github.com/goplus/llgo/cl" + "github.com/goplus/llgo/internal/packages" + llssa "github.com/goplus/llgo/ssa" +) + +func TestBackendProgramTemplateCreatesIsolatedSessions(t *testing.T) { + conf := &Config{Goos: "linux", Goarch: "amd64"} + template := newBackendProgramTemplate( + &llssa.Target{GOOS: conf.Goos, GOARCH: conf.Goarch}, + conf, + true, + true, + ) + first, err := template.newSession() + if err != nil { + t.Fatal(err) + } + defer first.prog.Dispose() + second, err := template.newSession() + if err != nil { + t.Fatal(err) + } + defer second.prog.Dispose() + if first.transformer == nil || second.transformer == nil { + t.Fatal("backend session missing C ABI transformer") + } + if !first.prog.FuncInfoMetadataEnabled() || !first.prog.FuncInfoSitesEnabled() { + t.Fatal("backend template did not preserve funcinfo configuration") + } + firstModule := first.prog.NewPackage("first", "example.com/first").Module() + secondModule := second.prog.NewPackage("second", "example.com/second").Module() + if firstModule.Context().C == secondModule.Context().C { + t.Fatal("backend sessions share an LLVM context") + } +} + +func TestRetainedBackendProgramsKeepModulesUntilExplicitDispose(t *testing.T) { + ctx := &context{} + pkgs := make([]*aPackage, 2) + for i := range pkgs { + prog := llssa.NewProgram(nil) + pkg := &aPackage{LPkg: prog.NewPackage("p", "example.com/p")} + pkgs[i] = pkg + ctx.retainBackendProgram(pkg, prog) + } + + if got := len(ctx.retained.programs); got != len(pkgs) { + t.Fatalf("retained Programs = %d, want %d", got, len(pkgs)) + } + for _, pkg := range pkgs { + if pkg.LPkg == nil || pkg.LPkg.Module().IsNil() { + t.Fatal("retained package module was cleared before whole-program use") + } + } + + ctx.disposeRetainedBackendPrograms() + if got := len(ctx.retained.programs); got != 0 { + t.Fatalf("retained Programs after dispose = %d, want 0", got) + } + for _, pkg := range pkgs { + if pkg.LPkg != nil { + t.Fatal("retained package still references LPkg after dispose") + } + } + ctx.disposeRetainedBackendPrograms() +} + +func TestRetainedBackendProgramsReleaseOnErrorAndPanic(t *testing.T) { + retain := func(ctx *context) *aPackage { + prog := llssa.NewProgram(nil) + pkg := &aPackage{LPkg: prog.NewPackage("p", "example.com/p")} + ctx.retainBackendProgram(pkg, prog) + return pkg + } + + ctx := &context{} + errorPkg := retain(ctx) + wantErr := errors.New("link failed") + runError := func() (err error) { + defer ctx.disposeRetainedBackendPrograms() + return wantErr + } + if err := runError(); !errors.Is(err, wantErr) { + t.Fatalf("error unwind = %v, want %v", err, wantErr) + } + if errorPkg.LPkg != nil || len(ctx.retained.programs) != 0 { + t.Fatal("error unwind retained a backend Program") + } + + panicPkg := retain(ctx) + func() { + defer func() { + if got := recover(); got != "link panic" { + t.Fatalf("panic unwind recovered %v", got) + } + }() + defer ctx.disposeRetainedBackendPrograms() + panic("link panic") + }() + if panicPkg.LPkg != nil || len(ctx.retained.programs) != 0 { + t.Fatal("panic unwind retained a backend Program") + } +} + +func TestBackendProgramTemplateOptionalState(t *testing.T) { + conf := &Config{Goos: "linux", Goarch: "amd64", DisableBoundsChecks: true, PthreadStackSize: 4096} + template := newBackendProgramTemplate(nil, conf, false, false) + template.typeSizes = &types.StdSizes{WordSize: 8, MaxAlign: 8} + template.runtimePackage = types.NewPackage(llssa.PkgRuntime, "runtime") + template.pythonPackage = types.NewPackage(llssa.PkgPython, "python") + prog := template.newProgram() + defer prog.Dispose() + if prog.Target() == nil { + t.Fatal("backend program created without a default target") + } + + validTypes := types.NewPackage("example.com/valid", "valid") + valid := &packages.Package{PkgPath: "example.com/valid", Types: validTypes} + duplicate := &packages.Package{PkgPath: "example.com/duplicate", Types: validTypes} + missingTypes := &packages.Package{PkgPath: "example.com/missing"} + illTyped := &packages.Package{PkgPath: "example.com/ill", Types: types.NewPackage("example.com/ill", "ill"), IllTyped: true} + inputs := collectBackendProgramInputs(prog, []*packages.Package{missingTypes, illTyped, valid, duplicate}) + if len(inputs) != 1 || inputs[0].pkg != validTypes { + t.Fatalf("backend inputs = %#v, want one deduplicated package", inputs) + } + + patched := backendProgramTemplate{} + appendPatchedBackendInputs(&patched, cl.Patches{ + "example.com/missing": {}, + "example.com/other": {}, + }, packages.NewDeduper()) + if len(patched.inputs) != 0 { + t.Fatalf("missing patched packages produced inputs: %#v", patched.inputs) + } +} + +func TestBackendProgramTemplateReplaysCPackageExports(t *testing.T) { + const src = `package C +func Xadd(a, b int) int { return a + b } +` + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "c.go", src, parser.ParseComments) + if err != nil { + t.Fatal(err) + } + pkg := types.NewPackage("example.com/c", "C") + template := backendProgramTemplate{ + inputs: []backendProgramInput{{ + fset: fset, + pkg: pkg, + files: []*ast.File{file}, + parseSyntax: true, + }}, + } + session, err := template.newSession() + if err != nil { + t.Fatal(err) + } + defer session.prog.Dispose() + const fullName = "example.com/c.Xadd" + if got, ok := session.prog.Linkname(fullName); !ok || got != "add" { + t.Fatalf("replayed Linkname(%q) = (%q, %v), want (%q, true)", fullName, got, ok, "add") + } +} diff --git a/internal/build/build.go b/internal/build/build.go index 9607c9d00a..ae6f52ccb8 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -175,7 +175,10 @@ type Config struct { // BuildParallelism is the package-level concurrency requested by Go's -p // build flag for llgo test. Zero uses the Go default, GOMAXPROCS. BuildParallelism int - LinkOptions LinkOptions + // BuildTrace is an optional Chrome Trace Event JSON output path. Relative + // paths are resolved from the build invocation directory. + BuildTrace string + LinkOptions LinkOptions // OmitDWARFByDefault controls linked builds only when -w was not // explicitly specified. Explicit -w and -w=false always win. OmitDWARFByDefault bool @@ -205,6 +208,10 @@ type Config struct { GlobalRewrites map[string]Rewrites ModuleHook ModuleHook Overlay map[string][]byte + + // packagePipelineObserver is used by focused scheduler tests. It must be + // safe for concurrent calls. + packagePipelineObserver func(packagePipelineStage, string, bool) } type Rewrites map[string]string @@ -347,6 +354,13 @@ func (c *Config) packageMetaEnabled() bool { return c.CollectPackageMeta || c.deadcodeDropEnabled() } +func (c *Config) parallelism() int { + if c != nil && c.BuildParallelism > 0 { + return c.BuildParallelism + } + return max(1, runtime.GOMAXPROCS(0)) +} + // ----------------------------------------------------------------------------- const ( @@ -363,7 +377,7 @@ func Do(args []string, conf *Config) ([]Package, error) { } // Build executes one build invocation. -func Build(inv Invocation) ([]Package, error) { +func Build(inv Invocation) (result []Package, resultErr error) { dir := inv.Dir if dir == "" { var err error @@ -378,6 +392,20 @@ func Build(inv Invocation) ([]Package, error) { if err != nil { return nil, err } + buildTrace, err := startBuildTrace(conf.BuildTrace, dir, conf.parallelism()) + if err != nil { + return nil, fmt.Errorf("start build trace: %w", err) + } + buildSpan := buildTrace.startCoordinator("build", map[string]any{ + "packages": slices.Clone(inv.Args), + }) + defer func() { + buildSpan.done() + if closeErr := buildTrace.close(); closeErr != nil && resultErr == nil { + result = nil + resultErr = fmt.Errorf("write build trace: %w", closeErr) + } + }() // Handle crosscompile configuration first to set correct GOOS/GOARCH forceEspClang := conf.ForceEspClang || conf.Target != "" export, err := crosscompile.Use(conf.Goos, conf.Goarch, conf.Target, IsWasiThreadsEnabled(), forceEspClang, conf.OptLevel, conf.ltoMode(), conf.goGlobalDCEEnabled()) @@ -445,8 +473,14 @@ func Build(inv Invocation) ([]Package, error) { OptLevel: conf.OptLevel, } - prog := llssa.NewProgram(target) - prog.DisableBoundsChecks(conf.DisableBoundsChecks) + funcInfo := conf.Mode != ModeGen && conf.PCLNMode != PCLNNone + backendTemplate := newBackendProgramTemplate( + target, + conf, + funcInfo, + shouldEnablePCLNSites(conf, funcInfo, emitDebugInfo), + ) + prog := backendTemplate.newProgram() if conf.Mode != ModeGen { // ModeGen callers (llgen and the golden suites) read LPkg.String() // after Do returns and dispose the program themselves; every other @@ -456,24 +490,17 @@ func Build(inv Invocation) ([]Package, error) { // harness) otherwise accumulate every compile's C++-side memory. defer prog.Dispose() } - prog.EnableGoGlobalDCE(conf.goGlobalDCEEnabled()) - prog.EnableDeadcodeDrop(conf.deadcodeDropEnabled()) - if conf.PthreadStackSize > 0 { - prog.SetPthreadStackSize(uint64(conf.PthreadStackSize)) - } - prog.EnableLTOPluginMarkers(conf.LTOPlugin.Enabled()) - funcInfo := conf.Mode != ModeGen && conf.PCLNMode != PCLNNone - prog.EnableFuncInfoMetadata(funcInfo) - // Site records are inline-asm fragments inside function bodies. Darwin - // DWARF builds avoid them because they disturb LLDB lexical scopes; Linux - // still needs them because its restricted dynamic symbol table cannot - // reconstruct every Go entry PC through dlsym. External mode always needs - // final-PC sites for sidecar construction. - prog.EnableFuncInfoSites(shouldEnablePCLNSites(conf, funcInfo, emitDebugInfo)) + var backendTypeSizes types.Sizes + var backendTypeSizesMu sync.Mutex sizes := func(sizes types.Sizes, compiler, arch string) types.Sizes { if arch == "wasm" { sizes = &types.StdSizes{WordSize: 4, MaxAlign: 4} } + backendTypeSizesMu.Lock() + if backendTypeSizes == nil { + backendTypeSizes = sizes + } + backendTypeSizesMu.Unlock() return prog.TypeSizes(sizes) } dedup := packages.NewDeduper() @@ -527,7 +554,11 @@ func Build(inv Invocation) ([]Package, error) { return parser.ParseFile(fset, filename, src, mode) } + loadSpan := buildTrace.startCoordinator("load packages", map[string]any{ + "patterns": slices.Clone(patterns), + }) initial, err := packages.LoadExWithGoVersion(dedup, sizes, cfg, conf.GoVersion, patterns...) + loadSpan.done() if err != nil { return nil, err } @@ -564,7 +595,11 @@ func Build(inv Invocation) ([]Package, error) { altPkgPaths := altPkgs(initial, conf, llssa.PkgRuntime) altCfg := *cfg altCfg.Dir = env.LLGoRuntimeDir() + loadAltSpan := buildTrace.startCoordinator("load runtime packages", map[string]any{ + "packages": slices.Clone(altPkgPaths), + }) altPkgs, err := packages.LoadEx(dedup, sizes, &altCfg, altPkgPaths...) + loadAltSpan.done() if err != nil { return nil, err } @@ -576,11 +611,23 @@ func Build(inv Invocation) ([]Package, error) { return altPkgs[0].Types }) prog.SetPython(func() *types.Package { - return dedup.Check(llssa.PkgPython).Types + if pkg := dedup.Check(llssa.PkgPython); pkg != nil { + return pkg.Types + } + return nil }) if err := prepareLocalVariables(prog, initial, altPkgs); err != nil { return nil, err } + backendTemplate.typeSizes = backendTypeSizes + backendTemplate.runtimePackage = altPkgs[0].Types + if pkg := dedup.Check(llssa.PkgPython); pkg != nil { + backendTemplate.pythonPackage = pkg.Types + } + backendTemplate.inputs = collectBackendProgramInputs(prog, initial, altPkgs) + backendTemplate.localities = prog.SnapshotLocalityState() + backendTemplate.llvmTarget = export.LLVMTarget + backendTemplate.targetABI = export.TargetABI buildMode := ssaBuildMode cabiOptimize := true @@ -595,9 +642,11 @@ func Build(inv Invocation) ([]Package, error) { if !IsOptimizeEnabled() { buildMode |= ssa.NaiveForm } + backendTemplate.cabiOptimize = cabiOptimize progSSA := ssa.NewProgram(initial[0].Fset, buildMode) patches := make(cl.Patches, len(altPkgPaths)) - altSSAPkgs(progSSA, patches, altPkgs[1:], conf, verbose) + altEntries := registerAltSSAPkgs(progSSA, patches, altPkgs[1:], conf, verbose) + appendPatchedBackendInputs(&backendTemplate, patches, dedup) output := conf.OutFile != "" ctx := &context{conf: cfg, progSSA: progSSA, prog: prog, dedup: dedup, @@ -613,24 +662,38 @@ func Build(inv Invocation) ([]Package, error) { commands: commands, frontendOptions: frontendOptions, cTransformer: cabi.NewTransformer(prog, export.LLVMTarget, export.TargetABI, conf.AbiMode, cabiOptimize), + backend: backendTemplate, + buildTrace: buildTrace, } defer ctx.closePackageMetas() + defer ctx.closePackageArchiveBuffers() + // Isolated backends use independent LLVM contexts. Keep Programs needed by + // whole-program consumers alive through deadcode analysis and strong ABI type + // override emission, then release them on every normal, error, or panic path. + defer ctx.disposeRetainedBackendPrograms() // default runtime globals must be registered before packages are built addGlobalString(conf, "runtime.defaultGOROOT="+runtime.GOROOT(), nil) addGlobalString(conf, "runtime.buildVersion="+runtime.Version(), nil) - pkgs, err := buildSSAPkgs(ctx, initial, verbose) + pkgs, pkgEntries, err := registerSSAPkgs(ctx, initial, verbose) if err != nil { return nil, err } - depPkgs, err := buildSSAPkgs(ctx, altPkgs, verbose) + depPkgs, depEntries, err := registerSSAPkgs(ctx, altPkgs, verbose) if err != nil { return nil, err } - allPkgs := append([]*aPackage{}, pkgs...) allPkgs = append(allPkgs, depPkgs...) - allPkgs, err = buildAllPkgs(ctx, allPkgs, verbose) + ssaEntries := append(append(altEntries, pkgEntries...), depEntries...) + if ctx.canUseIsolatedBackend() { + preparePackagePatches(ctx, allPkgs) + allPkgs, err = buildPackagePipeline(ctx, ssaEntries, allPkgs, verbose) + } else { + buildSSAPkgs(ctx, ssaEntries) + ctx.callerTracking.Precompute(ctx.progSSA.AllPackages()) + allPkgs, err = buildAllPkgs(ctx, allPkgs, verbose) + } if err != nil { return nil, err } @@ -656,7 +719,12 @@ func Build(inv Invocation) ([]Package, error) { resolveOutputs(ctx.commands.dir, outFmts) // Link main package using the output path from buildOutFmts + linkSpan := buildTrace.startCoordinator("link "+pkg.PkgPath, map[string]any{ + "package": pkg.PkgPath, + "output": outFmts.Out, + }) err = linkMainPkg(ctx, pkg, allPkgs, outFmts.Out, verbose) + linkSpan.done() if err != nil { return nil, err } @@ -730,6 +798,7 @@ func Build(inv Invocation) ([]Package, error) { } } } + ctx.disposeRetainedBackendPrograms() if mode == ModeTest && ctx.testFail { mockable.Exit(1) @@ -859,6 +928,7 @@ type context struct { callerTracking *cl.CallerTracking built map[string]none fingerprinting map[string]bool + cacheDisabled map[string]none initial []*packages.Package pkgs map[*packages.Package]Package // cache for lookup pkgByID map[string]Package // cache for lookup by pkg.ID @@ -873,6 +943,8 @@ type context struct { frontendOptions cl.Options cTransformer *cabi.Transformer + backend backendProgramTemplate + retained retainedBackendPrograms testFail bool @@ -881,16 +953,56 @@ type context struct { llvmVersion string // go list derived file lists (SFiles, etc.) - sfilesCache map[string][]string // pkg.ID -> absolute .s/.S file paths + sfilesCache map[string][]string // pkg.ID -> absolute .s/.S file paths + sfilesFrozen bool // plan9asm package policy parsed from env. - plan9asmOnce sync.Once - plan9asmMode plan9asmPkgsEnvMode - plan9asmPkgs map[string]bool + plan9asmOnce sync.Once + plan9asmReady bool + plan9asmMode plan9asmPkgsEnvMode + plan9asmPkgs map[string]bool + plan9asmSigs map[string]map[string]struct{} // pclnExternal is populated while generating the synthetic main module // and completed with final linked PCs by the post-link externalizer. pclnExternal *pclnmap.Data + + buildTrace *buildTracer +} + +type retainedBackendProgram struct { + pkg *aPackage + prog llssa.Program +} + +// retainedBackendPrograms owns Programs transferred from successful isolated +// workers. Workers may finish concurrently; disposal happens only after the +// coordinator has joined them and completed whole-program consumers. +type retainedBackendPrograms struct { + mu sync.Mutex + programs []retainedBackendProgram +} + +func (c *context) retainBackendProgram(pkg *aPackage, prog llssa.Program) { + c.retained.mu.Lock() + c.retained.programs = append(c.retained.programs, retainedBackendProgram{pkg: pkg, prog: prog}) + c.retained.mu.Unlock() +} + +func (c *context) disposeRetainedBackendPrograms() { + c.retained.mu.Lock() + programs := c.retained.programs + c.retained.programs = nil + c.retained.mu.Unlock() + + // Clear every package reference before destroying any LLVM context so no + // later observer can retain a dangling cross-context module. + for _, retained := range programs { + retained.pkg.LPkg = nil + } + for _, retained := range programs { + retained.prog.Dispose() + } } // closePackageMetas releases metadata mappings owned by this build. Metadata @@ -905,6 +1017,155 @@ func (c *context) closePackageMetas() { } } +type backendProgramInput struct { + fset *token.FileSet + pkg *types.Package + info *types.Info + files []*ast.File + parseSyntax bool +} + +// backendProgramTemplate contains only immutable build-local inputs. Creating +// a session allocates a new llssa.Program, LLVM context, TargetMachine, and C +// ABI transformer; no LLVM-owned state is shared between sessions. +type backendProgramTemplate struct { + target *llssa.Target + disableBoundsChecks bool + typeSizes types.Sizes + goGlobalDCE bool + deadcodeDrop bool + pthreadStackSize int64 + ltoPluginMarkers bool + funcInfoMetadata bool + funcInfoSites bool + runtimePackage *types.Package + pythonPackage *types.Package + inputs []backendProgramInput + localities llssa.LocalityState + llvmTarget string + targetABI string + abiMode cabi.Mode + cabiOptimize bool +} + +type backendSession struct { + prog llssa.Program + transformer *cabi.Transformer +} + +func newBackendProgramTemplate(target *llssa.Target, conf *Config, funcInfoMetadata, funcInfoSites bool) backendProgramTemplate { + var targetCopy *llssa.Target + if target != nil { + copy := *target + targetCopy = © + } + return backendProgramTemplate{ + target: targetCopy, + disableBoundsChecks: conf.DisableBoundsChecks, + goGlobalDCE: conf.goGlobalDCEEnabled(), + deadcodeDrop: conf.deadcodeDropEnabled(), + pthreadStackSize: conf.PthreadStackSize, + ltoPluginMarkers: conf.LTOPlugin.Enabled(), + funcInfoMetadata: funcInfoMetadata, + funcInfoSites: funcInfoSites, + abiMode: conf.AbiMode, + } +} + +func (t backendProgramTemplate) newProgram() llssa.Program { + var target *llssa.Target + if t.target != nil { + copy := *t.target + target = © + } + prog := llssa.NewProgram(target) + prog.DisableBoundsChecks(t.disableBoundsChecks) + if t.typeSizes != nil { + prog.TypeSizes(t.typeSizes) + } + prog.EnableGoGlobalDCE(t.goGlobalDCE) + prog.EnableDeadcodeDrop(t.deadcodeDrop) + if t.pthreadStackSize > 0 { + prog.SetPthreadStackSize(uint64(t.pthreadStackSize)) + } + prog.EnableLTOPluginMarkers(t.ltoPluginMarkers) + prog.EnableFuncInfoMetadata(t.funcInfoMetadata) + prog.EnableFuncInfoSites(t.funcInfoSites) + if t.runtimePackage != nil { + prog.SetRuntime(t.runtimePackage) + } + if t.pythonPackage != nil { + prog.SetPython(t.pythonPackage) + } + return prog +} + +func (t backendProgramTemplate) newSession() (backendSession, error) { + prog := t.newProgram() + if err := t.replayProgramState(prog); err != nil { + prog.Dispose() + return backendSession{}, err + } + return backendSession{ + prog: prog, + transformer: cabi.NewTransformer(prog, t.llvmTarget, t.targetABI, t.abiMode, t.cabiOptimize), + }, nil +} + +func (t backendProgramTemplate) replayProgramState(prog llssa.Program) error { + for _, input := range t.inputs { + if input.parseSyntax { + if err := cl.ParsePkgSyntax(prog, input.fset, input.pkg, input.files); err != nil { + return err + } + } + } + prog.RestoreLocalityState(t.localities) + return nil +} + +func collectBackendProgramInputs(prog llssa.Program, groups ...[]*packages.Package) []backendProgramInput { + seen := make(map[*types.Package]bool) + var inputs []backendProgramInput + for _, roots := range groups { + packages.Visit(roots, nil, func(pkg *packages.Package) { + if pkg == nil || pkg.Types == nil || pkg.IllTyped || seen[pkg.Types] { + return + } + seen[pkg.Types] = true + parsed := prog.PackageSyntaxParsed(pkg.Types) + inputs = append(inputs, backendProgramInput{ + fset: pkg.Fset, + pkg: pkg.Types, + info: pkg.TypesInfo, + files: slices.Clone(pkg.Syntax), + parseSyntax: parsed && !llruntime.SkipToBuild(pkg.PkgPath), + }) + }) + } + return inputs +} + +func appendPatchedBackendInputs(template *backendProgramTemplate, patches cl.Patches, dedup packages.Deduper) { + paths := make([]string, 0, len(patches)) + for pkgPath := range patches { + paths = append(paths, pkgPath) + } + slices.Sort(paths) + for _, pkgPath := range paths { + alt := dedup.Check(altPkgPathPrefix + pkgPath) + if alt == nil || len(alt.Syntax) == 0 { + continue + } + template.inputs = append(template.inputs, backendProgramInput{ + fset: alt.Fset, + pkg: types.NewPackage(pkgPath, ""), + files: slices.Clone(alt.Syntax), + parseSyntax: true, + }) + } +} + func (c *context) compiler() *clang.Cmd { config := clang.NewConfig( c.crossCompile.CC, @@ -944,12 +1205,13 @@ func (c *context) hasAltPkg(pkgPath string) bool { return hasAltPkgForTarget(c.buildConf, pkgPath) } -// normalizeToArchive creates an archive from object files and sets ArchiveFile. +// normalizeToArchive creates an archive from file and memory members and sets ArchiveFile. // This ensures the link step always consumes .a archives regardless of cache state. func normalizeToArchive(ctx *context, aPkg *aPackage, verbose bool) error { - if len(aPkg.ObjFiles) == 0 { + if len(aPkg.ObjFiles) == 0 && len(aPkg.ObjBuffers) == 0 { return nil } + defer aPkg.disposeArchiveBuffers() archiveFile, err := os.CreateTemp("", "pkg-*.a") if err != nil { @@ -958,7 +1220,7 @@ func normalizeToArchive(ctx *context, aPkg *aPackage, verbose bool) error { archiveFile.Close() archivePath := archiveFile.Name() - if err := ctx.createArchiveFile(archivePath, aPkg.ObjFiles, verbose); err != nil { + if err := ctx.createPackageArchiveFile(archivePath, aPkg, verbose); err != nil { os.Remove(archivePath) return fmt.Errorf("create archive for %s: %w", aPkg.PkgPath, err) } @@ -969,114 +1231,145 @@ func normalizeToArchive(ctx *context, aPkg *aPackage, verbose bool) error { } func buildAllPkgs(ctx *context, pkgs []*aPackage, verbose bool) ([]*aPackage, error) { - built := ctx.built - - // Split packages into runtime tree vs others so we can defer runtime build. - var runtimePkgs []*aPackage - var normalPkgs []*aPackage + tasks := make([]*packageBuildTask, 0, len(pkgs)) for _, p := range pkgs { - if isRuntimePkg(p.PkgPath) { - runtimePkgs = append(runtimePkgs, p) - } else { - normalPkgs = append(normalPkgs, p) - } + tasks = append(tasks, newPackageBuildTask(p)) + } + if err := prePackageBuilds(ctx, tasks, verbose); err != nil { + return nil, err } + ctx.sfilesFrozen = true var needRuntime, needPyInit bool - buildOne := func(aPkg *aPackage) error { - pkg := aPkg.Package - if _, ok := built[pkg.ID]; ok { - // Already built, skip but keep ExportFile for linking - return nil - } - built[pkg.ID] = none{} - - switch kind, param := cl.PkgKindOf(pkg.Types); kind { - case cl.PkgDeclOnly: - pkg.ExportFile = "" - case cl.PkgLinkIR, cl.PkgLinkExtern, cl.PkgPyModule: - if len(pkg.GoFiles) > 0 { - if err := ctx.collectFingerprint(aPkg); err != nil { - return err - } - ctx.tryLoadFromCache(aPkg) - if verbose { - if aPkg.CacheHit { - fmt.Fprintf(os.Stderr, "CACHE HIT: %s\n", pkg.PkgPath) - } else { - fmt.Fprintf(os.Stderr, "CACHE MISS: %s\n", pkg.PkgPath) - } - } - if err := buildPkg(ctx, aPkg, verbose); err != nil { - return err - } - if !aPkg.CacheHit { - if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { - return err - } - if kind == cl.PkgLinkExtern { - appendExternalLinkArgs(ctx, aPkg, param) - } - if err := ctx.saveToCache(aPkg); err != nil && verbose { - fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", pkg.PkgPath, err) - } - } - } else { - pkg.ExportFile = "" - if kind == cl.PkgLinkExtern { - appendExternalLinkArgs(ctx, aPkg, param) - } - } - default: - if err := ctx.collectFingerprint(aPkg); err != nil { - return err - } - ctx.tryLoadFromCache(aPkg) - if verbose { - if aPkg.CacheHit { - fmt.Fprintf(os.Stderr, "CACHE HIT: %s\n", pkg.PkgPath) - } else { - fmt.Fprintf(os.Stderr, "CACHE MISS: %s\n", pkg.PkgPath) - } - } - if err := buildPkg(ctx, aPkg, verbose); err != nil { - return err - } - aPkg.setNeedRuntimeOrPyInit(aPkg.LPkg.NeedRuntime, aPkg.LPkg.NeedPyInit) - needRuntime = needRuntime || aPkg.NeedRt - needPyInit = needPyInit || aPkg.NeedPyInit - if !aPkg.CacheHit { - if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { - return err - } - if err := ctx.saveToCache(aPkg); err != nil && verbose { - fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", pkg.PkgPath, err) - } - } - } - return nil - } - // Build non-runtime packages first, so we know whether runtime is actually needed. - for _, p := range normalPkgs { - if err := buildOne(p); err != nil { - return nil, err - } + normalResults, err := buildPrePackageGroup( + ctx, packageBuildTasksForRuntime(tasks, false), verbose) + if err != nil { + return nil, err + } + for _, result := range normalResults { + needRuntime = needRuntime || result.needRuntime + needPyInit = needPyInit || result.needPyInit } // Only build runtime packages when required (or host build with empty Target). if needRuntime || needPyInit || ctx.buildConf.Target == "" { - for _, p := range runtimePkgs { - if err := buildOne(p); err != nil { - return nil, err - } + if _, err := buildPrePackageGroup( + ctx, packageBuildTasksForRuntime(tasks, true), verbose); err != nil { + return nil, err } } return pkgs, nil } +// buildOnePackage is the serial package pipeline. Its explicit stages are the +// contract used by later package workers; this commit deliberately preserves +// serial LLVM execution. +func buildOnePackage(ctx *context, task *packageBuildTask, verbose bool) (packageBuildResult, error) { + if err := prePackageBuild(ctx, task, verbose); err != nil || task.skip { + return packageBuildResultFor(task), err + } + backendSpan := ctx.buildTrace.startWorker("backend", task.pkg.PkgPath) + backendSpan.setArg("class", "coordinator") + result, err := executeAndFinalizePackage(ctx, task, verbose, func() error { + return executePackageBuild(ctx, task, verbose) + }) + backendSpan.done() + return result, err +} + +// prePackageBuild performs classification, fingerprinting, and cache +// lookup without creating or transforming an LLVM module. +func prePackageBuild(ctx *context, task *packageBuildTask, verbose bool) error { + aPkg := task.pkg + pkg := aPkg.Package + traceSpan := ctx.buildTrace.startPackageCoordinator("pre", pkg.PkgPath) + defer func() { + traceSpan.setArg("cache_hit", aPkg.CacheHit) + traceSpan.setArg("skip", task.skip) + traceSpan.done() + }() + if _, ok := ctx.built[pkg.ID]; ok { + task.skip = true + return nil + } + ctx.built[pkg.ID] = none{} + if task.isDeclOnly() { + pkg.ExportFile = "" + task.skip = true + aPkg.Summary = summarizePackage(aPkg) + return ctx.collectFingerprint(aPkg) + } + if task.isLinkOnly() && !task.hasSource() { + pkg.ExportFile = "" + if task.kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, task.kindParam) + } + task.skip = true + aPkg.Summary = summarizePackage(aPkg) + return ctx.collectFingerprint(aPkg) + } + if err := ctx.collectFingerprint(aPkg); err != nil { + return err + } + ctx.tryLoadFromCache(aPkg) + if err := preparePackageSFiles(ctx, aPkg); err != nil { + return err + } + if verbose { + status := "MISS" + if aPkg.CacheHit { + status = "HIT" + } + fmt.Fprintf(os.Stderr, "CACHE %s: %s\n", status, pkg.PkgPath) + } + return nil +} + +// executePackageBuild creates the package module and runs its LLVM backend. +func executePackageBuild(ctx *context, task *packageBuildTask, verbose bool) error { + aPkg := task.pkg + if err := buildPkg(ctx, aPkg, verbose); err != nil { + return err + } + if task.needsRuntimeSignals() && aPkg.LPkg != nil { + aPkg.setNeedRuntimeOrPyInit(aPkg.LPkg.NeedRuntime, aPkg.LPkg.NeedPyInit) + } + return nil +} + +// finalizePackageBuild publishes the archive and cache metadata. Cache hits +// already carry both and therefore require no publication. +func finalizePackageBuild(ctx *context, task *packageBuildTask, verbose bool) (packageBuildResult, error) { + aPkg := task.pkg + traceSpan := ctx.buildTrace.startPackageCoordinator("publish", aPkg.PkgPath) + traceSpan.setArg("cache_hit", aPkg.CacheHit) + defer traceSpan.done() + if aPkg.CacheHit { + return packageBuildResultFor(task), nil + } + if err := normalizeToArchive(ctx, aPkg, verbose); err != nil { + return packageBuildResultFor(task), err + } + if task.kind == cl.PkgLinkExtern { + appendExternalLinkArgs(ctx, aPkg, task.kindParam) + } + if aPkg.Summary == nil { + aPkg.Summary = summarizePackage(aPkg) + } else { + aPkg.Summary.LinkArgs = append(aPkg.Summary.LinkArgs[:0], aPkg.LinkArgs...) + aPkg.Summary.ArchiveFile = aPkg.ArchiveFile + aPkg.Summary.NeedRuntime = aPkg.NeedRt + aPkg.Summary.NeedPyInit = aPkg.NeedPyInit + } + if err := ctx.saveToCache(aPkg); err != nil && verbose { + fmt.Fprintf(os.Stderr, "warning: failed to save cache for %s: %v\n", aPkg.PkgPath, err) + } + return packageBuildResultFor(task), nil +} + func appendExternalLinkArgs(ctx *context, aPkg *aPackage, spec string) { // need to be linked with external library // format: ';' separated alternative link methods. e.g. @@ -1086,7 +1379,7 @@ func appendExternalLinkArgs(ctx *context, aPkg *aPackage, spec string) { for _, alt := range altParts { alt = strings.TrimSpace(alt) if strings.ContainsRune(alt, '$') { - expdArgs = append(expdArgs, xenv.ExpandEnvToArgs(alt)...) + expdArgs = append(expdArgs, xenv.ExpandEnvToArgsWith(alt, ctx.commands.dir, ctx.commands.environ)...) atomic.AddInt32(&ctx.nLibdir, 1) } else { fields := strings.Fields(alt) @@ -1321,39 +1614,47 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa aPkg = ctx.pkgByID[p.ID] } if p.ExportFile != "" && aPkg != nil { // skip packages that only contain declarations + if aPkg.Summary == nil && isRuntimePkg(aPkg.PkgPath) { + return + } linkedPkgs[p.ID] = true linkedOrder = append(linkedOrder, aPkg) } }) + linkedSummaries := make([]*PackageSummary, len(linkedOrder)) + for i, aPkg := range linkedOrder { + if aPkg.Summary == nil { + return fmt.Errorf("package %s has no linker summary", aPkg.PkgPath) + } + linkedSummaries[i] = aPkg.Summary + } // packages.Visit with a post callback yields dependencies before importers. // Reverse that order so static archives are linked after the objects that use them. for i := len(linkedOrder) - 1; i >= 0; i-- { - aPkg := linkedOrder[i] - p := aPkg.Package + summary := linkedSummaries[i] // Defer linking runtime packages unless we actually need the runtime. - if isRuntimePkg(p.PkgPath) { - rtLinkArgs = append(rtLinkArgs, aPkg.LinkArgs...) - if aPkg.ArchiveFile != "" { - rtLinkInputs = append(rtLinkInputs, aPkg.ArchiveFile) + if isRuntimePkg(summary.PkgPath) { + rtLinkArgs = append(rtLinkArgs, summary.LinkArgs...) + if summary.ArchiveFile != "" { + rtLinkInputs = append(rtLinkInputs, summary.ArchiveFile) } continue } // Only let non-runtime packages influence whether runtime is needed. - need1, need2 := aPkg.isNeedRuntimeOrPyInit() - needRuntime = needRuntime || need1 - needPyInit = needPyInit || need2 - needAbiInit |= aPkg.LPkg.NeedAbiInit - for k, _ := range aPkg.LPkg.MethodByIndex { - methodByIndex[k] = none{} + needRuntime = needRuntime || summary.NeedRuntime + needPyInit = needPyInit || summary.NeedPyInit + needAbiInit |= summary.NeedAbiInit + for _, method := range summary.MethodByIndex { + methodByIndex[method] = none{} } - for k, _ := range aPkg.LPkg.MethodByName { - methodByName[k] = none{} + for _, method := range summary.MethodByName { + methodByName[method] = none{} } - linkArgs = append(linkArgs, aPkg.LinkArgs...) - if aPkg.ArchiveFile != "" { - archiveInputs = append(archiveInputs, aPkg.ArchiveFile) + linkArgs = append(linkArgs, summary.LinkArgs...) + if summary.ArchiveFile != "" { + archiveInputs = append(archiveInputs, summary.ArchiveFile) } } @@ -1370,9 +1671,9 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa var pcLineInfo []pcLineRecord var funcInfoStubs []funcInfoStubRecord if ctx.buildConf.PCLNMode != PCLNNone { - funcInfo = prepareFuncInfoTableRecords(collectFuncInfo(linkedOrder), nil) - pcLineInfo = collectPCLineInfo(linkedOrder) - funcInfoStubs = collectFuncInfoStubRecords(linkedOrder, funcInfo) + funcInfo = prepareFuncInfoTableRecords(collectFuncInfoSummaries(linkedSummaries), nil) + pcLineInfo = collectPCLineInfoSummaries(linkedSummaries) + funcInfoStubs = collectFuncInfoStubRecordsSummaries(linkedSummaries, funcInfo) } entryPkg := genMainModule(ctx, llssa.PkgRuntime, pkg, &genConfig{ rtInit: needRuntime, @@ -1380,7 +1681,8 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa abiInit: needAbiInit, methodByIndex: methodByIndex, methodByName: methodByName, - abiSymbols: linkedModuleGlobals(linkedOrder), + abiSymbols: linkedPackageGlobals(linkedSummaries), + abiTypes: abiTypesForSummaries(linkedSummaries), funcInfo: funcInfo, pcLineInfo: pcLineInfo, funcInfoStubs: funcInfoStubs, @@ -1420,7 +1722,7 @@ func linkMainPkg(ctx *context, pkg *packages.Package, pkgs []*aPackage, outputPa } } } - linkArgs = append(linkArgs, cSharedExportArgs(ctx, linkedOrder)...) + linkArgs = append(linkArgs, cSharedExportArgsSummaries(ctx, linkedSummaries)...) err = linkObjFiles(ctx, outputPath, linkInputs, linkArgs, verbose) if err != nil { @@ -1478,19 +1780,22 @@ func dceEntryRootCandidates(pkgs []Package, needRuntime bool) []string { } func linkedModuleGlobals(pkgs []Package) map[string]none { - if len(pkgs) == 0 { + return linkedPackageGlobals(summariesForPackages(pkgs)) +} + +func linkedPackageGlobals(summaries []*PackageSummary) map[string]none { + if len(summaries) == 0 { return nil } seen := make(map[string]none) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for g := pkg.LPkg.Module().FirstGlobal(); !g.IsNil(); g = gllvm.NextGlobal(g) { - if g.IsDeclaration() { - continue + for _, name := range summary.GlobalSymbols { + if name != "" { + seen[name] = none{} } - seen[g.Name()] = none{} } } return seen @@ -1569,22 +1874,26 @@ func linkObjFiles(ctx *context, app string, objFiles, linkArgs []string, verbose // shared-library link roots. They live in package archives and otherwise remain // unreferenced, so the linker can omit both their object files and symbols. func cSharedExportArgs(ctx *context, pkgs []*aPackage) []string { + return cSharedExportArgsSummaries(ctx, summariesForPackages(pkgs)) +} + +func cSharedExportArgsSummaries(ctx *context, summaries []*PackageSummary) []string { if ctx == nil || ctx.buildConf == nil || ctx.buildConf.BuildMode != BuildModeCShared { return nil } exports := make(map[string]none) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for _, name := range pkg.LPkg.ExportFuncs() { + for _, name := range summary.CSharedExports { if name != "" { exports[name] = none{} } } - if ctx.mode == ModeTest && pkg.Package != nil && pkg.Name == "main" && strings.HasSuffix(pkg.PkgPath, ".test") { - exports[pkg.PkgPath+".init"] = none{} - exports[pkg.PkgPath+".main"] = none{} + if ctx.mode == ModeTest && summary.Name == "main" && strings.HasSuffix(summary.PkgPath, ".test") { + exports[summary.PkgPath+".init"] = none{} + exports[summary.PkgPath+".main"] = none{} } } names := make([]string, 0, len(exports)) @@ -1790,6 +2099,15 @@ func is32Bits(goarch string) bool { } func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { + externs, err := preparePackageModule(ctx, aPkg, verbose) + if err != nil || aPkg.CacheHit || aPkg.LPkg == nil { + return err + } + return compilePackageModule(ctx, aPkg, externs, verbose) +} + +// preparePackageModule runs the frontend and creates the package LLVM module. +func preparePackageModule(ctx *context, aPkg *aPackage, verbose bool) ([]string, error) { pkg := aPkg.Package pkgPath := pkg.PkgPath if debugBuild || verbose { @@ -1799,7 +2117,7 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { } if llruntime.SkipToBuild(pkgPath) { pkg.ExportFile = "" - return nil + return nil, nil } var syntax = pkg.Syntax if altPkg := aPkg.AltPkg; altPkg != nil { @@ -1812,7 +2130,7 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { } embedMap, err := goembed.LoadDirectives(ctx.conf.Fset, syntax) if err != nil { - return fmt.Errorf("load go:embed directives for %s failed: %w", pkgPath, err) + return nil, fmt.Errorf("load go:embed directives for %s failed: %w", pkgPath, err) } ret, externs, err := cl.NewPackageExWithEmbedMetaOptions( ctx.prog, ctx.callerTracking, ctx.patches, aPkg.rewriteVars, @@ -1829,8 +2147,16 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { // If cache hit, we only needed to register types - skip compilation if aPkg.CacheHit { - return nil + return nil, nil } + return externs, nil +} + +// compilePackageModule applies LLVM transforms and emits package objects. +func compilePackageModule(ctx *context, aPkg *aPackage, externs []string, verbose bool) error { + pkg := aPkg.Package + pkgPath := pkg.PkgPath + ret := aPkg.LPkg ctx.cTransformer.SetSkipFuncs(cabiSkipFuncsForPlan9Asm(ctx, pkgPath, ret.Module())) llabi.LowerLargeAggregates(ctx.prog.TargetData(), ret.Module()) @@ -1844,7 +2170,7 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { mod.SetTarget(ctx.prog.Target().Spec().Triple) pbo := gllvm.NewPassBuilderOptions() defer pbo.Dispose() - if err = gllvm.VerifyModule(mod, gllvm.ReturnStatusAction); err != nil { + if err := gllvm.VerifyModule(mod, gllvm.ReturnStatusAction); err != nil { return fmt.Errorf("verify LLVM module for %v failed: %w", pkgPath, err) } if err := mod.RunPasses(llvmPassPipeline(ctx.buildConf.OptLevel, ctx.buildConf.ltoMode()), ctx.prog.TargetMachine(), pbo); err != nil { @@ -1896,11 +2222,15 @@ func buildPkg(ctx *context, aPkg *aPackage, verbose bool) error { aPkg.LinkArgs = append(aPkg.LinkArgs, goCgoLinkArgs(ctx.buildConf.Goos, aPkg.AltPkg.Syntax)...) } if pkg.ExportFile != "" { - exportFile, err := exportObject(ctx, pkg.PkgPath, pkg.ExportFile, ret) + exportFile, exportBuffer, err := exportPackageObject(ctx, pkg.PkgPath, pkg.ExportFile, ret) if err != nil { return fmt.Errorf("export object of %v failed: %v", pkgPath, err) } - aPkg.ObjFiles = append(aPkg.ObjFiles, exportFile) + if exportFile != "" { + aPkg.ObjFiles = append(aPkg.ObjFiles, exportFile) + } else { + aPkg.ObjBuffers = append(aPkg.ObjBuffers, exportBuffer) + } if debugBuild || verbose { fmt.Fprintf(os.Stderr, "==> Export %s: %s\n", aPkg.PkgPath, pkg.ExportFile) } @@ -1921,6 +2251,28 @@ func exportObject(ctx *context, pkgPath string, exportFile string, pkg llssa.Pac return exportObjectWithClang(ctx, pkgPath, exportFile, []byte(pkg.String())) } +func exportPackageObject(ctx *context, pkgPath string, exportFile string, pkg llssa.Package) (string, packageArchiveBuffer, error) { + if !useInMemoryNativeCodegen(ctx) { + path, err := exportObjectWithClang(ctx, pkgPath, exportFile, []byte(pkg.String())) + return path, packageArchiveBuffer{}, err + } + if ctx.buildConf.CheckLLFiles || ctx.buildConf.GenLL { + if err := dumpLLVMIRIfNeeded(ctx, pkgPath, exportFile, pkg.String()); err != nil { + return "", packageArchiveBuffer{}, err + } + } + buf, kind, err := emitObjectToMemoryBuffer(ctx, pkg) + if err != nil { + return "", packageArchiveBuffer{}, err + } + name := filepath.Base(exportFile) + ".o" + if ctx.shouldPrintCommands(false) { + fmt.Fprintf(os.Stderr, "# compiling archive member %s for pkg: %s\n", name, pkgPath) + fmt.Fprintf(os.Stderr, "# using %s\n", kind) + } + return "", packageArchiveBuffer{name: name, buffer: buf}, nil +} + func useInMemoryNativeCodegen(ctx *context) bool { return useInMemoryNativeCodegenConf(ctx.buildConf) } @@ -1977,6 +2329,15 @@ func exportObjectInMemory(ctx *context, pkgPath string, exportFile string, pkg l return "", err } } + buf, kind, err := emitObjectToMemoryBuffer(ctx, pkg) + if err != nil { + return "", err + } + defer buf.Dispose() + return writeObjectBufferToFile(ctx, pkgPath, exportFile, buf, kind) +} + +func emitObjectToMemoryBuffer(ctx *context, pkg llssa.Package) (gllvm.MemoryBuffer, string, error) { ltoMode := ctx.buildConf.ltoMode() var ( buf gllvm.MemoryBuffer @@ -1995,11 +2356,13 @@ func exportObjectInMemory(ctx *context, pkgPath string, exportFile string, pkg l default: buf, err = ctx.prog.TargetMachine().EmitToMemoryBuffer(pkg.Module(), gllvm.ObjectFile) if err != nil { - return "", err + return gllvm.MemoryBuffer{}, "", err } } - defer buf.Dispose() + return buf, kind, nil +} +func writeObjectBufferToFile(ctx *context, pkgPath, exportFile string, buf gllvm.MemoryBuffer, kind string) (string, error) { base := filepath.Base(exportFile) objFile, err := os.CreateTemp("", base+"-*.o") if err != nil { @@ -2129,13 +2492,21 @@ func prepareLocalVariables(prog llssa.Program, groups ...[]*packages.Package) er return nil } -func altSSAPkgs(prog *ssa.Program, patches cl.Patches, alts []*packages.Package, conf *Config, verbose bool) { +type ssaBuildEntry struct { + pkg *ssa.Package + syntax []*ast.File + fixOrder bool +} + +func registerAltSSAPkgs(prog *ssa.Program, patches cl.Patches, alts []*packages.Package, conf *Config, verbose bool) []ssaBuildEntry { + var entries []ssaBuildEntry packages.Visit(alts, nil, func(p *packages.Package) { if typs := p.Types; typs != nil && !p.IllTyped { if debugBuild || verbose { log.Println("==> BuildSSA", p.ID) } pkgSSA := prog.CreatePackage(typs, p.Syntax, p.TypesInfo, true) + entries = append(entries, ssaBuildEntry{pkg: pkgSSA, syntax: p.Syntax}) if strings.HasPrefix(p.ID, altPkgPathPrefix) { path := p.ID[len(altPkgPathPrefix):] // Even if an alt package exists and is pulled in as a dependency of other @@ -2151,21 +2522,23 @@ func altSSAPkgs(prog *ssa.Program, patches cl.Patches, alts []*packages.Package, } } }) - prog.Build() + return entries } type aPackage struct { *packages.Package - SSA *ssa.Package - AltPkg *packages.Cached - LPkg llssa.Package + SSA *ssa.Package + AltPkg *packages.Cached + LPkg llssa.Package + Summary *PackageSummary NeedRt bool NeedPyInit bool LinkArgs []string - ObjFiles []string // object files: .o or .ll (output of compiler, input to archiver) - ArchiveFile string // archive file: .a (output of archiver, used for linking) + ObjFiles []string // file-backed archive members: .o or .ll + ObjBuffers []packageArchiveBuffer // LLVM-produced in-memory archive members + ArchiveFile string // archive file: .a (output of archiver, used for linking) Meta *meta.PackageMeta rewriteVars map[string]string @@ -2177,9 +2550,10 @@ type aPackage struct { type Package = *aPackage -func buildSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*aPackage, error) { +func registerSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*aPackage, []ssaBuildEntry, error) { prog := ctx.progSSA var all []*aPackage + var entries []ssaBuildEntry var errs []*packages.Package packages.Visit(initial, nil, func(p *packages.Package) { if p.Types != nil && !p.IllTyped { @@ -2189,7 +2563,10 @@ func buildSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*a return } var altPkg *packages.Cached - var ssaPkg = createSSAPkg(ctx, prog, p, verbose) + ssaPkg, created := createSSAPkg(ctx, prog, p, verbose) + if created { + entries = append(entries, ssaBuildEntry{pkg: ssaPkg, syntax: p.Syntax, fixOrder: true}) + } if ctx.hasAltPkg(pkgPath) { if altPkg = ctx.dedup.Check(altPkgPathPrefix + pkgPath); altPkg == nil { return @@ -2221,9 +2598,53 @@ func buildSSAPkgs(ctx *context, initial []*packages.Package, verbose bool) ([]*a } fmt.Fprintln(os.Stderr, "cannot build SSA for package", errPkg) } - return nil, fmt.Errorf("cannot build SSA for packages") + return nil, nil, fmt.Errorf("cannot build SSA for packages") + } + return all, entries, nil +} + +// buildSSAPkgs builds registered packages with the requested bound, then +// performs ordering repair serially because it mutates instruction slices. +func buildSSAPkgs(ctx *context, entries []ssaBuildEntry) { + if len(entries) == 0 { + return + } + unique := make([]ssaBuildEntry, 0, len(entries)) + index := make(map[*ssa.Package]int, len(entries)) + for _, entry := range entries { + if entry.pkg == nil { + continue + } + if i, ok := index[entry.pkg]; ok { + unique[i].fixOrder = unique[i].fixOrder || entry.fixOrder + continue + } + index[entry.pkg] = len(unique) + unique = append(unique, entry) + } + jobs := make(chan ssaBuildEntry, len(unique)) + var wg sync.WaitGroup + for range min(ctx.buildConf.parallelism(), len(unique)) { + wg.Add(1) + go func() { + defer wg.Done() + for entry := range jobs { + traceSpan := ctx.buildTrace.startWorker("ssa", packagePipelineSSAPath(entry.pkg)) + entry.pkg.Build() + traceSpan.done() + } + }() + } + for _, entry := range unique { + jobs <- entry + } + close(jobs) + wg.Wait() + for _, entry := range unique { + if entry.fixOrder { + fixSSAOrder(entry.pkg, entry.syntax) + } } - return all, nil } func formatPackageError(err packages.Error, noColumn bool) string { @@ -2371,7 +2792,7 @@ func applyPatches(ctx *context, p *packages.Package, verbose bool) { } } -func createSSAPkg(ctx *context, prog *ssa.Program, p *packages.Package, verbose bool) *ssa.Package { +func createSSAPkg(ctx *context, prog *ssa.Program, p *packages.Package, verbose bool) (*ssa.Package, bool) { pkgSSA := prog.ImportedPackage(p.ID) if pkgSSA == nil { if debugBuild || verbose { @@ -2379,11 +2800,9 @@ func createSSAPkg(ctx *context, prog *ssa.Program, p *packages.Package, verbose } applyPatches(ctx, p, verbose) pkgSSA = prog.CreatePackage(p.Types, p.Syntax, p.TypesInfo, true) - pkgSSA.Build() // TODO(xsw): build concurrently - // Apply local SSA fixups once when package SSA is first built. - fixSSAOrder(pkgSSA, p.Syntax) + return pkgSSA, true } - return pkgSSA + return pkgSSA, false } /* @@ -2531,7 +2950,7 @@ func clFiles(ctx *context, files string, pkg *packages.Package, procFile func(li args := make([]string, 0, 16) if strings.HasPrefix(files, "$") { // has cflags if pos := strings.IndexByte(files, ':'); pos > 0 { - cflags := xenv.ExpandEnvToArgs(files[:pos]) + cflags := xenv.ExpandEnvToArgsWith(files[:pos], ctx.commands.dir, ctx.commands.environ) files = files[pos+1:] args = append(args, cflags...) } diff --git a/internal/build/build_test.go b/internal/build/build_test.go index 5d67a571b2..3533874664 100644 --- a/internal/build/build_test.go +++ b/internal/build/build_test.go @@ -6,6 +6,7 @@ package build import ( "bytes" "debug/macho" + "encoding/json" "fmt" "go/ast" gobuild "go/build" @@ -21,6 +22,7 @@ import ( "slices" "strconv" "strings" + "sync" "testing" "github.com/goplus/llgo/cl" @@ -216,6 +218,51 @@ func TestConcurrentInvocationsIsolateFrontendOptions(t *testing.T) { } } +func TestConcurrentDeadcodeBuildsUseIndependentWorkerContexts(t *testing.T) { + if !buildenv.Dev { + t.Skip("deadcode drop requires a development build") + } + repoRoot, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + fixture := filepath.Join(repoRoot, "cl", "_testdrop", "direct_method") + t.Setenv("LLGO_ROOT", repoRoot) + t.Setenv(llgoBuildCache, "0") + + type result struct { + output string + err error + } + results := make(chan result, 2) + for i := range 2 { + output := filepath.Join(t.TempDir(), fmt.Sprintf("direct-method-%d", i)) + conf := NewDefaultConf(ModeBuild) + conf.DeadcodeDrop = true + conf.PCLNMode = PCLNNone + conf.BuildParallelism = 2 + conf.OutFile = output + go func() { + _, err := Build(Invocation{Args: []string{"."}, Config: conf, Dir: fixture}) + results <- result{output: output, err: err} + }() + } + + for range 2 { + got := <-results + if got.err != nil { + t.Fatal(got.err) + } + data, err := exec.Command(got.output).CombinedOutput() + if err != nil { + t.Fatalf("run %s: %v\n%s", got.output, err, data) + } + if strings.TrimSpace(string(data)) != "42" { + t.Fatalf("run %s output = %q, want 42", got.output, data) + } + } +} + func TestResolveOutputsUsesInvocationDirectory(t *testing.T) { dir := t.TempDir() out := &OutFmtDetails{ @@ -516,7 +563,80 @@ func TestRun(t *testing.T) { func TestTest(t *testing.T) { // FIXME(zzy): with builtin package test in a llgo test ./... will cause duplicate symbol error - mockRun([]string{"../../cl/_testgo/runtest"}, &Config{Mode: ModeTest}) + var mu sync.Mutex + var events []struct { + stage packagePipelineStage + start bool + } + active, maximum := 0, 0 + exclusive, exclusiveViolation := false, false + tracePath := filepath.Join(t.TempDir(), "build-trace.json") + conf := &Config{Mode: ModeTest, BuildParallelism: 2, BuildTrace: tracePath} + conf.packagePipelineObserver = func(stage packagePipelineStage, _ string, start bool) { + mu.Lock() + defer mu.Unlock() + events = append(events, struct { + stage packagePipelineStage + start bool + }{stage: stage, start: start}) + if start { + if exclusive || (stage == pipelineStagePatchedBackend && active != 0) { + exclusiveViolation = true + } + active++ + maximum = max(maximum, active) + if stage == pipelineStagePatchedBackend { + exclusive = true + } + } else { + active-- + if stage == pipelineStagePatchedBackend { + exclusive = false + } + } + } + mockRun([]string{"../../cl/_testgo/runtest"}, conf) + + traceData, err := os.ReadFile(tracePath) + if err != nil { + t.Fatal(err) + } + var traceEvents []buildTraceEvent + if err := json.Unmarshal(traceData, &traceEvents); err != nil { + t.Fatalf("invalid build trace: %v", err) + } + var tracedSSA, tracedBackend bool + for _, event := range traceEvents { + tracedSSA = tracedSSA || event.Phase == "X" && event.Category == "llgo.ssa" + tracedBackend = tracedBackend || event.Phase == "X" && strings.HasPrefix(event.Category, "llgo.backend") + } + if !tracedSSA || !tracedBackend { + t.Fatalf("build trace stages: ssa=%v backend=%v", tracedSSA, tracedBackend) + } + + mu.Lock() + defer mu.Unlock() + if active != 0 { + t.Fatalf("pipeline left %d active tasks", active) + } + if maximum > conf.BuildParallelism { + t.Fatalf("pipeline active tasks = %d, want at most %d", maximum, conf.BuildParallelism) + } + if exclusiveViolation { + t.Fatal("patched backend overlapped another pipeline task") + } + firstBackend, lastSSA := -1, -1 + for i, event := range events { + if event.stage != pipelineStageSSA && event.start && firstBackend < 0 { + firstBackend = i + } + if event.stage == pipelineStageSSA && !event.start { + lastSSA = i + } + } + if firstBackend < 0 || lastSSA < 0 || firstBackend >= lastSSA { + t.Fatalf("pipeline did not overlap SSA and backend work: first backend event %d, last SSA event %d", firstBackend, lastSSA) + } } func TestExtest(t *testing.T) { diff --git a/internal/build/build_trace.go b/internal/build/build_trace.go new file mode 100644 index 0000000000..f687b9c0e3 --- /dev/null +++ b/internal/build/build_trace.go @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "bufio" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync" + "time" +) + +const buildTracePID = 1 + +// buildTraceEvent follows the Chrome Trace Event format accepted by both +// chrome://tracing and Perfetto. +type buildTraceEvent struct { + Name string `json:"name"` + Category string `json:"cat,omitempty"` + Phase string `json:"ph"` + Time int64 `json:"ts,omitempty"` + Duration int64 `json:"dur,omitempty"` + PID int `json:"pid"` + TID int `json:"tid"` + ID uint64 `json:"id,omitempty"` + Bind string `json:"bp,omitempty"` + Args map[string]any `json:"args,omitempty"` +} + +// buildTracer is owned by one Build invocation. The lane semaphore mirrors +// the build's -p limit, so overlapping worker-lane events visualize the same +// concurrency budget used by SSA and LLVM backend work. +type buildTracer struct { + mu sync.Mutex + file *os.File + writer *bufio.Writer + first bool + writeErr error + + lanes chan int + + nextFlowID uint64 + closeOnce sync.Once + closeErr error +} + +type buildTraceSpan struct { + tracer *buildTracer + name string + cat string + args map[string]any + start time.Time + lane int + worker bool + + end time.Time + once sync.Once +} + +func startBuildTrace(path, dir string, parallelism int) (*buildTracer, error) { + if path == "" { + return nil, nil + } + if !filepath.IsAbs(path) { + path = filepath.Join(dir, path) + } + if filepath.Ext(path) == ".go" { + return nil, fmt.Errorf("refusing to overwrite Go source file %s", path) + } + file, err := os.Create(path) + if err != nil { + return nil, err + } + tracer := &buildTracer{ + file: file, + writer: bufio.NewWriter(file), + first: true, + lanes: make(chan int, max(1, parallelism)), + } + for lane := 1; lane <= cap(tracer.lanes); lane++ { + tracer.lanes <- lane + } + if _, err := tracer.writer.WriteString("[\n"); err != nil { + _ = file.Close() + return nil, err + } + tracer.writeEvent(buildTraceEvent{ + Name: "process_name", + Phase: "M", + PID: buildTracePID, + Args: map[string]any{"name": "llgo build"}, + }) + tracer.writeEvent(buildTraceEvent{ + Name: "thread_name", + Phase: "M", + PID: buildTracePID, + TID: 0, + Args: map[string]any{"name": "coordinator"}, + }) + for lane := 1; lane <= cap(tracer.lanes); lane++ { + tracer.writeEvent(buildTraceEvent{ + Name: "thread_name", + Phase: "M", + PID: buildTracePID, + TID: lane, + Args: map[string]any{"name": fmt.Sprintf("worker %d", lane)}, + }) + } + return tracer, nil +} + +func (t *buildTracer) startCoordinator(name string, args map[string]any) *buildTraceSpan { + if t == nil { + return nil + } + return &buildTraceSpan{ + tracer: t, + name: name, + cat: "llgo.build", + args: args, + start: time.Now(), + } +} + +func (t *buildTracer) startPackageCoordinator(stage, pkgPath string) *buildTraceSpan { + if t == nil { + return nil + } + return t.startCoordinator(stage+" "+pkgPath, map[string]any{ + "package": pkgPath, + "stage": stage, + }) +} + +func (t *buildTracer) startWorker(stage, pkgPath string) *buildTraceSpan { + if t == nil { + return nil + } + lane := <-t.lanes + return &buildTraceSpan{ + tracer: t, + name: stage + " " + pkgPath, + cat: "llgo." + stage, + args: map[string]any{ + "package": pkgPath, + "stage": stage, + }, + start: time.Now(), + lane: lane, + worker: true, + } +} + +func (s *buildTraceSpan) setArg(name string, value any) { + if s == nil { + return + } + if s.args == nil { + s.args = make(map[string]any) + } + s.args[name] = value +} + +func (s *buildTraceSpan) done() { + if s == nil { + return + } + s.once.Do(func() { + s.end = time.Now() + s.tracer.writeEvent(buildTraceEvent{ + Name: s.name, + Category: s.cat, + Phase: "X", + Time: traceMicros(s.start), + Duration: max(0, traceMicros(s.end)-traceMicros(s.start)), + PID: buildTracePID, + TID: s.lane, + Args: s.args, + }) + if s.worker { + s.tracer.lanes <- s.lane + } + }) +} + +// flow records a dependency arrow from a completed producer to a started +// consumer, matching the flow events emitted by Go's build trace. +func (t *buildTracer) flow(from, to *buildTraceSpan) { + if t == nil || from == nil || to == nil || from.end.IsZero() { + return + } + t.mu.Lock() + t.nextFlowID++ + id := t.nextFlowID + t.mu.Unlock() + name := from.name + " -> " + to.name + t.writeEvent(buildTraceEvent{ + Name: name, + Category: "flow", + Phase: "s", + Time: traceMicros(from.end), + PID: buildTracePID, + TID: from.lane, + ID: id, + }) + t.writeEvent(buildTraceEvent{ + Name: name, + Category: "flow", + Phase: "f", + Time: traceMicros(to.start), + PID: buildTracePID, + TID: to.lane, + ID: id, + Bind: "e", + }) +} + +func (t *buildTracer) writeEvent(event buildTraceEvent) { + if t == nil { + return + } + data, err := json.Marshal(event) + t.mu.Lock() + defer t.mu.Unlock() + if t.writeErr != nil { + return + } + if err != nil { + t.writeErr = err + return + } + if !t.first { + if _, err := t.writer.WriteString(",\n"); err != nil { + t.writeErr = err + return + } + } + t.first = false + if _, err := t.writer.Write(data); err != nil { + t.writeErr = err + } +} + +func (t *buildTracer) close() error { + if t == nil { + return nil + } + t.closeOnce.Do(func() { + t.mu.Lock() + defer t.mu.Unlock() + if t.writeErr == nil { + _, t.writeErr = t.writer.WriteString("\n]\n") + } + if err := t.writer.Flush(); t.writeErr == nil { + t.writeErr = err + } + if err := t.file.Close(); t.writeErr == nil { + t.writeErr = err + } + t.closeErr = t.writeErr + }) + return t.closeErr +} + +func traceMicros(t time.Time) int64 { + return t.UnixNano() / int64(time.Microsecond) +} diff --git a/internal/build/build_trace_test.go b/internal/build/build_trace_test.go new file mode 100644 index 0000000000..488b146310 --- /dev/null +++ b/internal/build/build_trace_test.go @@ -0,0 +1,145 @@ +//go:build !llgo + +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "encoding/json" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestBuildTraceWritesChromeEvents(t *testing.T) { + dir := t.TempDir() + tracer, err := startBuildTrace("trace.json", dir, 2) + if err != nil { + t.Fatal(err) + } + buildSpan := tracer.startCoordinator("build", map[string]any{"packages": []string{"./..."}}) + ssaSpan := tracer.startWorker("ssa", "example.com/p") + ssaSpan.done() + backendSpan := tracer.startWorker("backend", "example.com/p") + backendSpan.setArg("class", "isolated") + tracer.flow(ssaSpan, backendSpan) + backendSpan.done() + buildSpan.done() + if err := tracer.close(); err != nil { + t.Fatal(err) + } + + data, err := os.ReadFile(filepath.Join(dir, "trace.json")) + if err != nil { + t.Fatal(err) + } + var events []buildTraceEvent + if err := json.Unmarshal(data, &events); err != nil { + t.Fatalf("trace is not valid Chrome Trace JSON: %v\n%s", err, data) + } + var metadata, complete, flowStart, flowEnd bool + for _, event := range events { + switch event.Phase { + case "M": + metadata = true + case "X": + complete = true + if event.Name == "backend example.com/p" { + if got := event.Args["class"]; got != "isolated" { + t.Fatalf("backend class = %v, want isolated", got) + } + } + case "s": + flowStart = true + case "f": + flowEnd = event.Bind == "e" + } + } + if !metadata || !complete || !flowStart || !flowEnd { + t.Fatalf("trace phases: metadata=%v complete=%v flowStart=%v flowEnd=%v", metadata, complete, flowStart, flowEnd) + } +} + +func TestBuildTraceWorkerLanesRespectParallelism(t *testing.T) { + tracer, err := startBuildTrace(filepath.Join(t.TempDir(), "trace.json"), "", 2) + if err != nil { + t.Fatal(err) + } + var active atomic.Int32 + var maximum atomic.Int32 + var wg sync.WaitGroup + for i := range 12 { + wg.Add(1) + go func() { + defer wg.Done() + span := tracer.startWorker("backend", string(rune('a'+i))) + current := active.Add(1) + for { + previous := maximum.Load() + if current <= previous || maximum.CompareAndSwap(previous, current) { + break + } + } + time.Sleep(time.Millisecond) + active.Add(-1) + span.done() + }() + } + wg.Wait() + if got := maximum.Load(); got > 2 { + t.Fatalf("maximum active traced workers = %d, want <= 2", got) + } + if err := tracer.close(); err != nil { + t.Fatal(err) + } +} + +func TestBuildTraceRefusesGoSourceOutput(t *testing.T) { + if _, err := startBuildTrace("trace.go", t.TempDir(), 1); err == nil { + t.Fatal("startBuildTrace(trace.go) succeeded") + } +} + +func TestBuildTraceDisabledAndErrors(t *testing.T) { + tracer, err := startBuildTrace("", t.TempDir(), 1) + if err != nil || tracer != nil { + t.Fatalf("disabled trace = (%v, %v), want (nil, nil)", tracer, err) + } + var span *buildTraceSpan + span.setArg("ignored", true) + span.done() + + if _, err := startBuildTrace(filepath.Join(t.TempDir(), "missing", "trace.json"), "", 1); err == nil { + t.Fatal("startBuildTrace in missing directory succeeded") + } + + tracer, err = startBuildTrace(filepath.Join(t.TempDir(), "trace.json"), "", 1) + if err != nil { + t.Fatal(err) + } + tracer.writeEvent(buildTraceEvent{ + Name: "invalid", + Phase: "X", + Args: map[string]any{"function": func() {}}, + }) + if err := tracer.close(); err == nil { + t.Fatal("closing trace after JSON encoding error succeeded") + } +} diff --git a/internal/build/cgo_test.go b/internal/build/cgo_test.go index 91fba3f534..926b30b518 100644 --- a/internal/build/cgo_test.go +++ b/internal/build/cgo_test.go @@ -77,6 +77,98 @@ func TestParseCgoDeclFlags(t *testing.T) { } } +func TestParseCgoDeclWithCommandEnvBranches(t *testing.T) { + commands := commandEnv{dir: t.TempDir(), environ: []string{"CGO_TEST_MARKER=1"}} + tests := []struct { + name string + line string + want []cgoDecl + wantErr string + }{ + { + name: "LDFLAGS with tag", + line: "#cgo darwin LDFLAGS: -framework CoreFoundation -lz", + want: []cgoDecl{{tag: "darwin", ldflags: []string{"-framework CoreFoundation", "-lz"}}}, + }, + {name: "missing colon", line: "#cgo CFLAGS -I/missing", wantErr: "invalid cgo format"}, + {name: "missing directive", line: "CFLAGS: -I/missing", wantErr: "invalid cgo directive"}, + {name: "unsupported flag", line: "#cgo FOOFLAGS: -unsupported", wantErr: "unsupported cgo flag type"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := parseCgoDeclWithCommandEnv(commands, tt.line) + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("parseCgoDeclWithCommandEnv(%q) error = %v, want %q", tt.line, err, tt.wantErr) + } + return + } + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, tt.want) { + t.Fatalf("parseCgoDeclWithCommandEnv(%q) = %#v, want %#v", tt.line, got, tt.want) + } + }) + } +} + +func TestParseCgoDeclWithCommandEnvPkgConfig(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("test helper uses a shell script") + } + + dir := t.TempDir() + tool := filepath.Join(dir, "pkg-config") + script := `#!/bin/sh +if [ "$PKG_CONFIG_TEST_FAIL" = "$1" ]; then + exit 1 +fi +if [ "$1" = "--libs" ]; then + printf '%s\n' '-L/request/lib -lrequest' + exit 0 +fi +printf '%s\n' '-I/request/include -DREQUEST="request value"' +` + if err := os.WriteFile(tool, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + + commands := commandEnv{dir: dir, environ: []string{"PATH=" + dir}} + got, err := parseCgoDeclWithCommandEnv(commands, "#cgo linux pkg-config: request") + if err != nil { + t.Fatal(err) + } + want := []cgoDecl{{ + tag: "linux", + cflags: []string{"-I/request/include", `-DREQUEST="request value"`}, + ldflags: []string{"-L/request/lib", "-lrequest"}, + }} + if !reflect.DeepEqual(got, want) { + t.Fatalf("parseCgoDeclWithCommandEnv(pkg-config) = %#v, want %#v", got, want) + } + + for _, arg := range []string{"--libs", "--cflags"} { + t.Run("failed "+arg, func(t *testing.T) { + commands := commandEnv{dir: dir, environ: []string{"PATH=" + dir, "PKG_CONFIG_TEST_FAIL=" + arg}} + if _, err := parseCgoDeclWithCommandEnv(commands, "#cgo pkg-config: request"); err == nil || !strings.Contains(err.Error(), "pkg-config") { + t.Fatalf("parseCgoDeclWithCommandEnv(pkg-config) error = %v, want pkg-config failure", err) + } + }) + } +} + +func TestParseCgoPreambleDelegatesToCommandEnvParser(t *testing.T) { + preamble, decls, err := parseCgoPreamble(token.Position{Filename: "request.go", Line: 7}, "#cgo CFLAGS: -I/request/include") + if err != nil { + t.Fatal(err) + } + if preamble.goFile != "request.go" || preamble.src == "" || !reflect.DeepEqual(decls, []cgoDecl{{cflags: []string{"-I/request/include"}}}) { + t.Fatalf("parseCgoPreamble() = %#v, %#v", preamble, decls) + } +} + func TestCollectCgoSymbolsStripsPackagePrefix(t *testing.T) { externs := []string{ "command-line-arguments._cgo_96608f8de8c8_Cfunc_fputs", diff --git a/internal/build/collect.go b/internal/build/collect.go index 66da887c21..7d3c65166b 100644 --- a/internal/build/collect.go +++ b/internal/build/collect.go @@ -23,7 +23,6 @@ import ( "os/exec" "path/filepath" "runtime" - "sort" "strconv" "strings" @@ -42,7 +41,11 @@ func (c *context) collectFingerprint(pkg *aPackage) error { c.fingerprinting = make(map[string]bool) } if c.fingerprinting[pkg.ID] { - return fmt.Errorf("fingerprint cycle detected for %s", pkg.ID) + // Alternate runtime replacements can close a cycle after the complete + // SSA graph is registered. Such a cycle has no stable per-package key, + // so rebuild its members instead of reporting a false cache hit. + c.disablePackageCache(c.fingerprinting) + return nil } c.fingerprinting[pkg.ID] = true defer delete(c.fingerprinting, pkg.ID) @@ -70,6 +73,20 @@ func (c *context) collectFingerprint(pkg *aPackage) error { return nil } +func (c *context) disablePackageCache(pkgs map[string]bool) { + if c.cacheDisabled == nil { + c.cacheDisabled = make(map[string]none, len(pkgs)) + } + for id := range pkgs { + c.cacheDisabled[id] = none{} + } +} + +func (c *context) packageCacheDisabled(id string) bool { + _, disabled := c.cacheDisabled[id] + return disabled +} + // collectEnvInputs collects environment-related inputs. func (c *context) collectEnvInputs(m *manifestBuilder) { m.env.Goos = c.buildConf.Goos @@ -197,21 +214,7 @@ func (c *context) collectPackageInputs(m *manifestBuilder, pkg *aPackage) error // collectDependencyInputs adds dependency fingerprints/versions into manifest. func (c *context) collectDependencyInputs(m *manifestBuilder, pkg *aPackage) error { - if len(pkg.Imports) == 0 { - return nil - } - - deps := make([]*packages.Package, 0, len(pkg.Imports)) - for _, dep := range pkg.Imports { - if dep == nil || dep.ID == pkg.ID { - continue - } - deps = append(deps, dep) - } - - sort.Slice(deps, func(i, j int) bool { return deps[i].ID < deps[j].ID }) - - for _, dep := range deps { + for _, dep := range effectiveDependencies(pkg) { depEntry, err := c.dependencyFingerprint(dep) if err != nil { return err @@ -328,6 +331,12 @@ func (c *context) tryLoadFromCache(pkg *aPackage) bool { if !cacheEnabled() { return false } + if c.packageCacheDisabled(pkg.ID) { + return false + } + if c.buildConf != nil && (c.buildConf.BuildMode == BuildModeCArchive || c.buildConf.BuildMode == BuildModeCShared) { + return false + } // Main packages are intentionally not written to the build cache because // each executable's entry module is linked against the current main archive. @@ -371,6 +380,9 @@ func (c *context) tryLoadFromCache(pkg *aPackage) bool { if err != nil { return false } + if meta.Summary == nil { + return false + } // Use the .a archive directly for linking (no extraction needed) pkg.ArchiveFile = paths.Archive @@ -379,6 +391,7 @@ func (c *context) tryLoadFromCache(pkg *aPackage) bool { pkg.NeedPyInit = meta.NeedPyInit pkg.Meta = pkgMeta pkg.CacheHit = true + pkg.Summary = summaryFromMetadata(pkg, meta) return true } @@ -393,6 +406,7 @@ func parseManifestMetadata(content string) (*cacheArchiveMetadata, error) { meta.LinkArgs = append([]string(nil), data.Metadata.LinkArgs...) meta.NeedRt = data.Metadata.NeedRt meta.NeedPyInit = data.Metadata.NeedPyInit + meta.Summary = data.Metadata.Summary } return meta, nil } @@ -446,6 +460,7 @@ type cacheArchiveMetadata struct { LinkArgs []string NeedRt bool NeedPyInit bool + Summary *packageSummaryMetadata } // saveToCache saves a built package to cache. @@ -453,6 +468,9 @@ func (c *context) saveToCache(pkg *aPackage) error { if !cacheEnabled() { return nil } + if c.packageCacheDisabled(pkg.ID) { + return nil + } if pkg.Fingerprint == "" || pkg.Manifest == "" { return nil @@ -502,16 +520,16 @@ func (c *context) saveToCache(pkg *aPackage) error { return fmt.Errorf("decode manifest: %w", err) } + if pkg.Summary == nil { + pkg.Summary = summarizePackage(pkg) + } meta := &manifestMetadata{ LinkArgs: append([]string(nil), pkg.LinkArgs...), NeedRt: pkg.NeedRt, NeedPyInit: pkg.NeedPyInit, + Summary: pkg.Summary.metadata(), } - if len(meta.LinkArgs) == 0 && !meta.NeedRt && !meta.NeedPyInit { - data.Metadata = nil - } else { - data.Metadata = meta - } + data.Metadata = meta manifestWithMeta, err := buildManifestYAML(data) if err != nil { diff --git a/internal/build/collect_test.go b/internal/build/collect_test.go index d6a8c585d5..7b0716af14 100644 --- a/internal/build/collect_test.go +++ b/internal/build/collect_test.go @@ -22,6 +22,7 @@ import ( "os" "os/exec" "path/filepath" + "reflect" "runtime" "strings" "testing" @@ -135,6 +136,88 @@ func TestCollectFingerprintDeterminism(t *testing.T) { } } +func TestDisablePackageCache(t *testing.T) { + ctx := &context{} + ctx.disablePackageCache(map[string]bool{ + "example.com/a": true, + "example.com/b": false, + }) + + for _, id := range []string{"example.com/a", "example.com/b"} { + if !ctx.packageCacheDisabled(id) { + t.Fatalf("package cache for %q remains enabled", id) + } + } + if ctx.packageCacheDisabled("example.com/c") { + t.Fatal("unlisted package cache was disabled") + } +} + +func TestDisabledPackageCacheSkipsLoadAndSave(t *testing.T) { + t.Setenv(llgoBuildCache, "1") + pkg := &aPackage{Package: &packages.Package{ID: "example.com/disabled", PkgPath: "example.com/disabled"}} + ctx := &context{buildConf: &Config{}, cacheDisabled: map[string]none{pkg.ID: {}}} + if ctx.tryLoadFromCache(pkg) { + t.Fatal("tryLoadFromCache loaded a disabled package") + } + if err := ctx.saveToCache(pkg); err != nil { + t.Fatalf("saveToCache disabled package: %v", err) + } + + ctx.cacheDisabled = nil + ctx.buildConf.BuildMode = BuildModeCArchive + if ctx.tryLoadFromCache(pkg) { + t.Fatal("tryLoadFromCache loaded a C archive package") + } +} + +func TestTryLoadFromCacheRejectsMissingSummary(t *testing.T) { + t.Setenv(llgoBuildCache, "1") + td := t.TempDir() + oldFunc := cacheRootFunc + cacheRootFunc = func() string { return td } + defer func() { cacheRootFunc = oldFunc }() + + ctx := &context{ + buildConf: &Config{Goos: "linux", Goarch: "amd64"}, + crossCompile: crosscompile.Export{ + LLVMTarget: "x86_64-unknown-linux-gnu", + }, + } + pkg := &aPackage{Package: &packages.Package{ + ID: "example.com/no-summary", + PkgPath: "example.com/no-summary", + Name: "no-summary", + }, Fingerprint: "missing-summary"} + paths := ctx.ensureCacheManager().PackagePaths(ctx.targetTriple(), pkg.PkgPath, pkg.Fingerprint) + if err := ctx.cacheManager.EnsureDir(paths); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(paths.Archive, []byte("archive"), 0o644); err != nil { + t.Fatal(err) + } + manifest := newManifestBuilder() + manifest.env.Goos = "linux" + manifest.pkg.PkgPath = pkg.PkgPath + if err := writeManifest(paths.Manifest, manifest.Build()); err != nil { + t.Fatal(err) + } + if ctx.tryLoadFromCache(pkg) { + t.Fatal("tryLoadFromCache accepted manifest without package summary") + } +} + +func TestCollectFingerprintDisablesCycles(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ID: "example.com/cycle", PkgPath: "example.com/cycle"}} + ctx := &context{fingerprinting: map[string]bool{pkg.ID: true}} + if err := ctx.collectFingerprint(pkg); err != nil { + t.Fatal(err) + } + if !ctx.packageCacheDisabled(pkg.ID) { + t.Fatal("fingerprint cycle did not disable package cache") + } +} + func TestCollectFingerprintIncludesEmitDWARF(t *testing.T) { td := t.TempDir() goFile := filepath.Join(td, "main.go") @@ -1014,8 +1097,8 @@ func TestSaveToCache_Success(t *testing.T) { if data.Env.Goos != "darwin" { t.Errorf("manifest should contain original env content") } - if data.Metadata != nil { - t.Errorf("metadata should be empty when no link args/runtime flags") + if data.Metadata == nil || data.Metadata.Summary == nil { + t.Errorf("metadata should preserve an empty linker summary") } // Check archive exists @@ -1189,6 +1272,7 @@ func TestTryLoadFromCacheIgnoresMetaWhenPackageMetaDisabled(t *testing.T) { m := newManifestBuilder() m.env.Goos = "darwin" m.pkg.PkgPath = "example.com/nometa" + m.meta = &manifestMetadata{Summary: &packageSummaryMetadata{}} if err := writeManifest(paths.Manifest, m.Build()); err != nil { t.Fatal(err) } @@ -1204,6 +1288,86 @@ func TestTryLoadFromCacheIgnoresMetaWhenPackageMetaDisabled(t *testing.T) { } } +func TestTryLoadFromCacheRestoresPackageSummary(t *testing.T) { + td := t.TempDir() + oldFunc := cacheRootFunc + cacheRootFunc = func() string { return td } + defer func() { cacheRootFunc = oldFunc }() + + ctx := &context{ + conf: &packages.Config{}, + buildConf: &Config{Goos: "darwin", Goarch: "arm64"}, + crossCompile: crosscompile.Export{ + LLVMTarget: "arm64-apple-darwin", + }, + } + pkg := &aPackage{ + Package: &packages.Package{ + ID: "example.com/cached", + PkgPath: "example.com/cached", + Name: "cached", + }, + Fingerprint: "summary-test", + Manifest: func() string { + m := newManifestBuilder() + m.env.Goos = "darwin" + m.pkg.PkgPath = "example.com/cached" + return m.Build() + }(), + NeedRt: true, + NeedPyInit: true, + LinkArgs: []string{"-lcached"}, + Summary: &PackageSummary{ + ID: "example.com/cached", + PkgPath: "example.com/cached", + Name: "cached", + LinkArgs: []string{"-lcached"}, + NeedRuntime: true, + NeedPyInit: true, + NeedAbiInit: 3, + MethodByIndex: []int{1}, + MethodByName: []string{"Method"}, + GlobalSymbols: []string{"example.com/cached.global"}, + FuncInfo: []funcInfoRecord{{symbol: "example.com/cached.fn", name: "Fn", file: "p.go", line: 7}}, + PCLineInfo: []pcLineRecord{{id: 9, symbol: "example.com/cached.fn", file: "p.go", line: 8}}, + FuncInfoStubs: []string{closureStubPrefix + "example.com/cached.fn"}, + CSharedExports: []string{"Cached"}, + }, + } + want := *pkg.Summary + obj, err := os.CreateTemp(td, "cached-*.o") + if err != nil { + t.Fatal(err) + } + if _, err := obj.WriteString("object"); err != nil { + t.Fatal(err) + } + if err := obj.Close(); err != nil { + t.Fatal(err) + } + pkg.ObjFiles = []string{obj.Name()} + if err := ctx.saveToCache(pkg); err != nil { + t.Fatalf("saveToCache: %v", err) + } + + pkg.ObjFiles = nil + pkg.ArchiveFile = "" + pkg.LinkArgs = nil + pkg.NeedRt = false + pkg.NeedPyInit = false + pkg.Summary = nil + if !ctx.tryLoadFromCache(pkg) { + t.Fatal("tryLoadFromCache = false, want summary cache hit") + } + if pkg.Summary == nil { + t.Fatal("cache hit did not restore package summary") + } + want.ArchiveFile = pkg.ArchiveFile + if !reflect.DeepEqual(pkg.Summary, &want) { + t.Fatalf("restored summary = %#v, want %#v", pkg.Summary, &want) + } +} + func TestGetLLVMVersion(t *testing.T) { ctx := &context{ crossCompile: crosscompile.Export{}, diff --git a/internal/build/deadcode_test.go b/internal/build/deadcode_test.go index 41951fe373..f54f5ec870 100644 --- a/internal/build/deadcode_test.go +++ b/internal/build/deadcode_test.go @@ -21,8 +21,13 @@ func TestApplyDeadcodeDropOverridesWritesStrongTypeOverride(t *testing.T) { Goarch: "amd64", }, } + defer ctx.prog.Dispose() - srcPkg := ctx.prog.NewPackage("pkg", "pkg") + // Isolated package workers and the synthetic entry module deliberately use + // different LLVM contexts. Keep this test faithful to that production path. + srcProg := llssa.NewProgram(nil) + defer srcProg.Dispose() + srcPkg := srcProg.NewPackage("pkg", "pkg") addMethodTypeGlobal(srcPkg.Module(), "_llgo_pkg.T") pkgMeta := buildDeadcodeMeta(t) defer pkgMeta.Close() @@ -50,6 +55,9 @@ func TestApplyDeadcodeDropOverridesWritesStrongTypeOverride(t *testing.T) { if strings.Contains(out, `ptr @"pkg.(*T).N"`) || strings.Contains(out, `ptr @pkg.T.N`) { t.Fatalf("dead method slot still references N functions:\n%s", out) } + if err := llvm.VerifyModule(entryPkg.LPkg.Module(), llvm.ReturnStatusAction); err != nil { + t.Fatalf("cross-context strong type override produced invalid entry module: %v\n%s", err, out) + } } func TestDCEEntryRootCandidates(t *testing.T) { diff --git a/internal/build/dependencies.go b/internal/build/dependencies.go new file mode 100644 index 0000000000..39f5233217 --- /dev/null +++ b/internal/build/dependencies.go @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "sort" + + "github.com/goplus/llgo/internal/packages" +) + +// effectiveDependencies returns every package whose source contributes to an +// aPackage. Alternate packages may add imports absent from the original graph. +func effectiveDependencies(pkg *aPackage) []*packages.Package { + if pkg == nil || pkg.Package == nil { + return nil + } + deps := make(map[string]*packages.Package) + add := func(imports map[string]*packages.Package) { + for _, dep := range imports { + if dep == nil || dep.ID == pkg.ID || (pkg.AltPkg != nil && dep.ID == pkg.AltPkg.ID) { + continue + } + deps[dep.ID] = dep + } + } + add(pkg.Imports) + if pkg.AltPkg != nil { + add(pkg.AltPkg.Imports) + } + ret := make([]*packages.Package, 0, len(deps)) + for _, dep := range deps { + ret = append(ret, dep) + } + sort.Slice(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID }) + return ret +} diff --git a/internal/build/dependencies_test.go b/internal/build/dependencies_test.go new file mode 100644 index 0000000000..78fa352e56 --- /dev/null +++ b/internal/build/dependencies_test.go @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "reflect" + "testing" + + "github.com/goplus/llgo/internal/packages" +) + +func TestEffectiveDependenciesIncludesAlternateImports(t *testing.T) { + base := &packages.Package{ID: "base"} + shared := &packages.Package{ID: "shared"} + altOnly := &packages.Package{ID: "alt-only"} + alt := &packages.Package{ + ID: "alt", + Imports: map[string]*packages.Package{"shared": shared, "alt-only": altOnly}, + } + pkg := &aPackage{ + Package: &packages.Package{ID: "pkg", Imports: map[string]*packages.Package{"base": base, "shared": shared}}, + AltPkg: &packages.Cached{Package: alt}, + } + deps := effectiveDependencies(pkg) + got := make([]string, len(deps)) + for i, dep := range deps { + got[i] = dep.ID + } + if want := []string{"alt-only", "base", "shared"}; !reflect.DeepEqual(got, want) { + t.Fatalf("effectiveDependencies = %v, want %v", got, want) + } +} + +func TestEffectiveDependenciesHandlesNilPackage(t *testing.T) { + if deps := effectiveDependencies(nil); deps != nil { + t.Fatalf("effectiveDependencies(nil) = %v, want nil", deps) + } +} diff --git a/internal/build/fingerprint.go b/internal/build/fingerprint.go index ecc55298ab..781ec180f6 100644 --- a/internal/build/fingerprint.go +++ b/internal/build/fingerprint.go @@ -37,9 +37,10 @@ type depEntry struct { // manifestMetadata stores metadata produced during build but not part of the fingerprint. type manifestMetadata struct { - LinkArgs []string `yaml:"link_args,omitempty"` - NeedRt bool `yaml:"need_rt,omitempty"` - NeedPyInit bool `yaml:"need_py_init,omitempty"` + LinkArgs []string `yaml:"link_args,omitempty"` + NeedRt bool `yaml:"need_rt,omitempty"` + NeedPyInit bool `yaml:"need_py_init,omitempty"` + Summary *packageSummaryMetadata `yaml:"summary,omitempty"` } // manifestData is the structured representation of manifest content. diff --git a/internal/build/funcinfo_table.go b/internal/build/funcinfo_table.go index b36aa29654..f86fd972a1 100644 --- a/internal/build/funcinfo_table.go +++ b/internal/build/funcinfo_table.go @@ -86,12 +86,16 @@ type funcInfoSymbolIndexRecord struct { } func collectFuncInfo(pkgs []Package) []funcInfoRecord { + return collectFuncInfoSummaries(summariesForPackages(pkgs)) +} + +func collectFuncInfoSummaries(summaries []*PackageSummary) []funcInfoRecord { seen := make(map[string]funcInfoRecord) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for _, rec := range readFuncInfo(pkg.LPkg.Module()) { + for _, rec := range summary.FuncInfo { if rec.symbol == "" { continue } @@ -114,13 +118,17 @@ func collectFuncInfo(pkgs []Package) []funcInfoRecord { } func collectPCLineInfo(pkgs []Package) []pcLineRecord { + return collectPCLineInfoSummaries(summariesForPackages(pkgs)) +} + +func collectPCLineInfoSummaries(summaries []*PackageSummary) []pcLineRecord { var out []pcLineRecord seen := make(map[uint64]none) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - for _, rec := range readPCLineInfo(pkg.LPkg.Module()) { + for _, rec := range summary.PCLineInfo { if rec.id == 0 || rec.symbol == "" { continue } @@ -144,6 +152,10 @@ func collectPCLineInfo(pkgs []Package) []pcLineRecord { } func collectFuncInfoStubRecords(pkgs []Package, records []funcInfoRecord) []funcInfoStubRecord { + return collectFuncInfoStubRecordsSummaries(summariesForPackages(pkgs), records) +} + +func collectFuncInfoStubRecordsSummaries(summaries []*PackageSummary, records []funcInfoRecord) []funcInfoStubRecord { if len(records) == 0 { return nil } @@ -154,23 +166,16 @@ func collectFuncInfoStubRecords(pkgs []Package, records []funcInfoRecord) []func } } seen := make(map[string]funcInfoStubRecord) - for _, pkg := range pkgs { - if pkg == nil || pkg.LPkg == nil { + for _, summary := range summaries { + if summary == nil { continue } - fn := pkg.LPkg.Module().FirstFunction() - for !fn.IsNil() { - if fn.IsDeclaration() || fn.BasicBlocksCount() == 0 { - fn = llvm.NextFunction(fn) - continue - } - name := fn.Name() + for _, name := range summary.FuncInfoStubs { if target, ok := strings.CutPrefix(name, closureStubPrefix); ok { if idx := recordBySymbol[target]; idx != 0 { seen[name] = funcInfoStubRecord{symbol: name, funcIndex: idx} } } - fn = llvm.NextFunction(fn) } } if len(seen) == 0 { diff --git a/internal/build/llvm_emit_test.go b/internal/build/llvm_emit_test.go index 40bfb45bb1..2e30777172 100644 --- a/internal/build/llvm_emit_test.go +++ b/internal/build/llvm_emit_test.go @@ -1,10 +1,15 @@ package build import ( + "os" + "path/filepath" "runtime" + "strings" "testing" + "github.com/goplus/llgo/internal/crosscompile" "github.com/goplus/llgo/internal/lto" + llssa "github.com/goplus/llgo/ssa" ) func TestUseInMemoryNativeCodegenConf(t *testing.T) { @@ -55,3 +60,52 @@ func TestUseInMemoryNativeCodegenConf(t *testing.T) { } }) } + +func TestExportPackageObjectErrors(t *testing.T) { + prog := llssa.NewProgram(nil) + defer prog.Dispose() + pkg := prog.NewPackage("p", "example.com/p") + + t.Run("clang", func(t *testing.T) { + ctx := &context{ + buildConf: &Config{Target: "embedded"}, + crossCompile: crosscompile.Export{ + CC: filepath.Join(t.TempDir(), "missing-clang"), + }, + commands: commandEnv{environ: os.Environ()}, + } + path, member, err := exportPackageObject(ctx, pkg.Path(), "p.o", pkg) + if path != "" { + defer os.Remove(path) + } + if err == nil { + member.buffer.Dispose() + t.Fatal("exportPackageObject succeeded with a missing clang") + } + if !member.buffer.IsNil() { + member.buffer.Dispose() + t.Fatal("clang export returned an in-memory archive member") + } + }) + + t.Run("IR dump", func(t *testing.T) { + ctx := &context{buildConf: &Config{ + Goos: runtime.GOOS, + Goarch: runtime.GOARCH, + CheckLLFiles: true, + }} + exportFile := strings.Repeat("x", 300) + path, member, err := exportPackageObject(ctx, pkg.Path(), exportFile, pkg) + if path != "" { + defer os.Remove(path) + } + if err == nil { + member.buffer.Dispose() + t.Fatal("exportPackageObject succeeded with an overlong IR dump prefix") + } + if !member.buffer.IsNil() { + member.buffer.Dispose() + t.Fatal("failed IR dump returned an in-memory archive member") + } + }) +} diff --git a/internal/build/main_module.go b/internal/build/main_module.go index eb57ee8b49..5fff6effdc 100644 --- a/internal/build/main_module.go +++ b/internal/build/main_module.go @@ -42,6 +42,7 @@ type genConfig struct { methodByIndex map[int]none methodByName map[string]none abiSymbols map[string]none + abiTypes []llssa.AbiTypeInfo funcInfo []funcInfoRecord pcLineInfo []pcLineRecord funcInfoStubs []funcInfoStubRecord @@ -94,6 +95,7 @@ func genMainModule(ctx *context, rtPkgPath string, pkg *packages.Package, cfg *g var abiInit llssa.Function if cfg.abiInit != 0 { + mainPkg.RegisterAbiTypes(cfg.abiTypes) abiInit = mainPkg.InitAbiTypesFor("init$abitypes", func(sym *llssa.AbiSymbol) bool { if _, ok := cfg.abiSymbols[sym.Name]; !ok { return false diff --git a/internal/build/package_archive.go b/internal/build/package_archive.go new file mode 100644 index 0000000000..87b732d7f5 --- /dev/null +++ b/internal/build/package_archive.go @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "fmt" + "os" + "path/filepath" + + gllvm "github.com/xgo-dev/llvm" +) + +// packageArchiveBuffer owns an LLVM-produced archive member until package +// publication. +type packageArchiveBuffer struct { + name string + buffer gllvm.MemoryBuffer +} + +func (p *aPackage) disposeArchiveBuffers() { + for i := range p.ObjBuffers { + member := &p.ObjBuffers[i] + if member.buffer.IsNil() { + continue + } + member.buffer.Dispose() + member.buffer = gllvm.MemoryBuffer{} + } + p.ObjBuffers = nil +} + +func (c *context) closePackageArchiveBuffers() { + for _, pkg := range c.pkgs { + pkg.disposeArchiveBuffers() + } +} + +// createPackageArchiveFile writes path-backed auxiliary objects and +// LLVM-produced memory buffers into one archive. LLVM performs archive symbol +// indexing in-process; no temporary object is needed for memory members. +func (c *context) createPackageArchiveFile(archivePath string, pkg *aPackage, verbose bool) error { + if len(pkg.ObjFiles) == 0 && len(pkg.ObjBuffers) == 0 { + return fmt.Errorf("no object files provided for archive %s", archivePath) + } + if len(pkg.ObjBuffers) == 0 { + return c.createArchiveFile(archivePath, pkg.ObjFiles, verbose) + } + + if err := os.MkdirAll(filepath.Dir(archivePath), 0o755); err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(archivePath), filepath.Base(archivePath)+".tmp-*") + if err != nil { + return err + } + tmpName := tmp.Name() + if err := tmp.Close(); err != nil { + os.Remove(tmpName) + return err + } + if err := os.Remove(tmpName); err != nil { + return err + } + + members := make([]gllvm.ArchiveMember, 0, len(pkg.ObjFiles)+len(pkg.ObjBuffers)) + for _, path := range pkg.ObjFiles { + members = append(members, gllvm.NewArchiveMemberFromFile(path)) + } + for _, member := range pkg.ObjBuffers { + members = append(members, gllvm.NewArchiveMemberFromMemoryBuffer(member.name, member.buffer)) + } + if c.shouldPrintCommands(verbose) { + fmt.Fprintf(os.Stderr, "# llvm archive %s (%d file members, %d memory members)\n", + tmpName, len(pkg.ObjFiles), len(pkg.ObjBuffers)) + } + if err := gllvm.WriteArchive(tmpName, c.targetTriple(), members); err != nil { + os.Remove(tmpName) + return fmt.Errorf("create archive %s: %w", archivePath, err) + } + if err := os.Rename(tmpName, archivePath); err != nil { + os.Remove(tmpName) + return fmt.Errorf("publish archive %s: %w", archivePath, err) + } + return nil +} diff --git a/internal/build/package_archive_test.go b/internal/build/package_archive_test.go new file mode 100644 index 0000000000..f76987b88b --- /dev/null +++ b/internal/build/package_archive_test.go @@ -0,0 +1,173 @@ +//go:build !llgo +// +build !llgo + +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/goplus/llgo/internal/crosscompile" + "github.com/goplus/llgo/internal/packages" + gllvm "github.com/xgo-dev/llvm" +) + +func TestNormalizeToArchiveUsesMemoryBuffer(t *testing.T) { + llvmCtx := gllvm.NewContext() + defer llvmCtx.Dispose() + mod := llvmCtx.NewModule("archive") + defer mod.Dispose() + mod.SetTarget("x86_64-unknown-linux-gnu") + gllvm.AddFunction(mod, "memory_symbol", gllvm.FunctionType(llvmCtx.Int32Type(), nil, false)) + + memoryBuf := gllvm.WriteBitcodeToMemoryBuffer(mod) + ctx := &context{ + buildConf: &Config{Goos: "linux", Goarch: "amd64"}, + crossCompile: crosscompile.Export{ + LLVMTarget: "x86_64-unknown-linux-gnu", + }, + } + fileBuf := gllvm.WriteBitcodeToMemoryBuffer(mod) + defer fileBuf.Dispose() + filePath := filepath.Join(t.TempDir(), "file-member.bc") + if err := os.WriteFile(filePath, fileBuf.Bytes(), 0o644); err != nil { + memoryBuf.Dispose() + t.Fatal(err) + } + + pkg := &aPackage{ + Package: &packages.Package{PkgPath: "example.com/archive"}, + ObjFiles: []string{filePath}, + ObjBuffers: []packageArchiveBuffer{{ + name: "memory-member.bc", + buffer: memoryBuf, + }}, + } + if err := normalizeToArchive(ctx, pkg, true); err != nil { + t.Fatal(err) + } + defer os.Remove(pkg.ArchiveFile) + + if len(pkg.ObjFiles) != 0 || len(pkg.ObjBuffers) != 0 { + t.Fatalf("package members were not released: files=%v buffers=%v", pkg.ObjFiles, pkg.ObjBuffers) + } + data, err := os.ReadFile(pkg.ArchiveFile) + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(data, []byte("!\n")) { + t.Fatalf("archive has invalid magic: %q", data[:8]) + } + for _, name := range []string{"file-member.bc", "memory-member.bc"} { + if !bytes.Contains(data, []byte(name)) { + t.Errorf("archive does not contain member %q", name) + } + } +} + +func TestPackageArchiveEdgeCases(t *testing.T) { + empty := &aPackage{} + if err := (&context{}).createPackageArchiveFile(filepath.Join(t.TempDir(), "empty.a"), empty, false); err == nil { + t.Fatal("createPackageArchiveFile succeeded without members") + } + fileOnly := &aPackage{ObjFiles: []string{filepath.Join(t.TempDir(), "missing.o")}} + if err := (&context{buildConf: &Config{Goos: "linux", Goarch: "amd64"}}).createPackageArchiveFile(filepath.Join(t.TempDir(), "file-only.a"), fileOnly, false); err == nil { + t.Fatal("file-only archive succeeded with a missing member") + } + empty.ObjBuffers = []packageArchiveBuffer{{}} + empty.disposeArchiveBuffers() + if empty.ObjBuffers != nil { + t.Fatal("disposeArchiveBuffers retained nil members") + } + + llvmCtx := gllvm.NewContext() + defer llvmCtx.Dispose() + mod := llvmCtx.NewModule("archive-errors") + defer mod.Dispose() + mod.SetTarget("x86_64-unknown-linux-gnu") + gllvm.AddFunction(mod, "archive_error_symbol", gllvm.FunctionType(llvmCtx.Int32Type(), nil, false)) + buffer := gllvm.WriteBitcodeToMemoryBuffer(mod) + defer buffer.Dispose() + pkg := &aPackage{ObjBuffers: []packageArchiveBuffer{{name: "member.bc", buffer: buffer}}} + ctx := &context{ + buildConf: &Config{Goos: "linux", Goarch: "amd64"}, + crossCompile: crosscompile.Export{LLVMTarget: "x86_64-unknown-linux-gnu"}, + } + + blocker := filepath.Join(t.TempDir(), "blocker") + if err := os.WriteFile(blocker, []byte("not a directory"), 0o644); err != nil { + t.Fatal(err) + } + if err := ctx.createPackageArchiveFile(filepath.Join(blocker, "archive.a"), pkg, false); err == nil { + t.Fatal("createPackageArchiveFile succeeded below a regular file") + } + tooLong := filepath.Join(t.TempDir(), strings.Repeat("a", 300)+".a") + if err := ctx.createPackageArchiveFile(tooLong, pkg, false); err == nil { + t.Fatal("createPackageArchiveFile succeeded with an overlong temporary-file prefix") + } + + archiveDir := filepath.Join(t.TempDir(), "archive.a") + if err := os.Mkdir(archiveDir, 0o755); err != nil { + t.Fatal(err) + } + if err := ctx.createPackageArchiveFile(archiveDir, pkg, false); err == nil { + t.Fatal("createPackageArchiveFile replaced a directory") + } +} + +func TestNormalizeToArchiveFailsWithoutObjectFallback(t *testing.T) { + llvmCtx := gllvm.NewContext() + defer llvmCtx.Dispose() + mod := llvmCtx.NewModule("archive-error") + defer mod.Dispose() + mod.SetTarget("x86_64-unknown-linux-gnu") + gllvm.AddFunction(mod, "memory_symbol", gllvm.FunctionType(llvmCtx.Int32Type(), nil, false)) + + memoryBuf := gllvm.WriteBitcodeToMemoryBuffer(mod) + ctx := &context{ + buildConf: &Config{Goos: "linux", Goarch: "amd64"}, + crossCompile: crosscompile.Export{ + LLVMTarget: "x86_64-unknown-linux-gnu", + }, + } + pkg := &aPackage{ + Package: &packages.Package{PkgPath: "example.com/archive-error"}, + ObjFiles: []string{filepath.Join(t.TempDir(), "missing.o")}, + ObjBuffers: []packageArchiveBuffer{{ + name: "memory-member.bc", + buffer: memoryBuf, + }}, + } + _, err := finalizePackageBuild(ctx, &packageBuildTask{pkg: pkg}, false) + if err == nil { + t.Fatal("finalizePackageBuild succeeded with a missing member") + } + if !strings.Contains(err.Error(), "missing.o") { + t.Fatalf("normalizeToArchive error = %v, want missing member", err) + } + if len(pkg.ObjBuffers) != 0 { + t.Fatal("memory buffer was retained after archive failure") + } + if pkg.ArchiveFile != "" { + t.Fatalf("ArchiveFile = %q after failure", pkg.ArchiveFile) + } +} diff --git a/internal/build/package_build.go b/internal/build/package_build.go new file mode 100644 index 0000000000..5503af19de --- /dev/null +++ b/internal/build/package_build.go @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "fmt" + "sync" + + "github.com/goplus/llgo/cl" + "github.com/goplus/llgo/internal/packages" +) + +type packageBuildTask struct { + pkg *aPackage + kind int + kindParam string + skip bool +} + +func newPackageBuildTask(pkg *aPackage) *packageBuildTask { + kind, kindParam := cl.PkgKindOf(pkg.Types) + return &packageBuildTask{ + pkg: pkg, + kind: kind, + kindParam: kindParam, + } +} + +func (t *packageBuildTask) isRuntime() bool { + return isRuntimePkg(t.pkg.PkgPath) +} + +func (t *packageBuildTask) isDeclOnly() bool { + return t.kind == cl.PkgDeclOnly +} + +func (t *packageBuildTask) isLinkOnly() bool { + return t.kind == cl.PkgLinkIR || t.kind == cl.PkgLinkExtern || t.kind == cl.PkgPyModule +} + +func (t *packageBuildTask) hasSource() bool { + return len(t.pkg.GoFiles) > 0 +} + +func (t *packageBuildTask) needsRuntimeSignals() bool { + return !t.isLinkOnly() && !t.isDeclOnly() +} + +type packageBuildResult struct { + needRuntime bool + needPyInit bool +} + +func prePackageBuilds(ctx *context, tasks []*packageBuildTask, verbose bool) error { + for _, task := range tasks { + if err := prePackageBuild(ctx, task, verbose); err != nil { + return err + } + } + return nil +} + +func packageBuildTasksForRuntime(tasks []*packageBuildTask, runtime bool) []*packageBuildTask { + filtered := make([]*packageBuildTask, 0, len(tasks)) + for _, task := range tasks { + if task.isRuntime() == runtime { + filtered = append(filtered, task) + } + } + return filtered +} + +// buildPrePackageGroup keeps backend execution and archive publication +// in one package task. A completed backend therefore writes its archive and +// cache metadata immediately instead of contributing to a later I/O burst. +func buildPrePackageGroup(ctx *context, tasks []*packageBuildTask, verbose bool) ([]packageBuildResult, error) { + if len(tasks) == 0 { + return nil, nil + } + // cacheManager is lazily initialized. Resolve it on the coordinator before + // package workers can enter saveToCache concurrently. + if cacheEnabled() { + ctx.ensureCacheManager() + } + + patched, coordinator, isolated, err := partitionPackageExecutions(ctx, tasks) + if err != nil { + return nil, err + } + results := make([]packageBuildResult, len(tasks)) + for _, index := range patched { + task := tasks[index] + traceSpan := ctx.buildTrace.startWorker("backend-patched", task.pkg.PkgPath) + traceSpan.setArg("class", "patched") + result, err := executeAndFinalizePackage(ctx, task, verbose, func() error { + return executePrePackage(ctx, task, verbose) + }) + traceSpan.done() + if err != nil { + return nil, err + } + results[index] = result + } + for _, index := range coordinator { + task := tasks[index] + traceSpan := ctx.buildTrace.startWorker("backend-coordinator", task.pkg.PkgPath) + traceSpan.setArg("class", "coordinator") + result, err := executeAndFinalizePackage(ctx, task, verbose, func() error { + return executePackageBuild(ctx, task, verbose) + }) + traceSpan.done() + if err != nil { + return nil, err + } + results[index] = result + } + if err := executeIsolatedPackages(ctx, tasks, isolated, results, verbose); err != nil { + return nil, err + } + return results, nil +} + +func partitionPackageExecutions(ctx *context, tasks []*packageBuildTask) (patched, coordinator, isolated []int, err error) { + for i, task := range tasks { + if _, ok := ctx.patches[task.pkg.PkgPath]; ok { + patched = append(patched, i) + continue + } + serial, serialErr := ctx.packageRequiresCoordinator(task) + if serialErr != nil { + return nil, nil, nil, serialErr + } + if serial { + coordinator = append(coordinator, i) + } else { + isolated = append(isolated, i) + } + } + return +} + +func executePrePackage(ctx *context, task *packageBuildTask, verbose bool) error { + if task.skip { + return nil + } + serial, err := ctx.packageRequiresCoordinator(task) + if err != nil { + return err + } + if serial { + return executePackageBuild(ctx, task, verbose) + } + return ctx.executeIsolatedPackage(task, verbose) +} + +func executeIsolatedPackages(ctx *context, tasks []*packageBuildTask, indexes []int, results []packageBuildResult, verbose bool) error { + if len(indexes) == 0 { + return nil + } + return runBoundedPackageJobs(ctx.buildConf.parallelism(), indexes, func(index int) error { + task := tasks[index] + traceSpan := ctx.buildTrace.startWorker("backend", task.pkg.PkgPath) + traceSpan.setArg("class", "isolated") + result, err := executeAndFinalizePackage(ctx, task, verbose, func() error { + return ctx.executeIsolatedPackage(task, verbose) + }) + traceSpan.done() + results[index] = result + return err + }) +} + +type packageBuildStep func() error +type packageFinalizeStep func() (packageBuildResult, error) + +func executeAndFinalizePackage(ctx *context, task *packageBuildTask, verbose bool, execute packageBuildStep) (packageBuildResult, error) { + return runPackageBuildTask(task, execute, func() (packageBuildResult, error) { + return finalizePackageBuild(ctx, task, verbose) + }) +} + +// runPackageBuildTask defines the worker lifetime: publication is part of the +// package task and runs immediately after a successful backend. +func runPackageBuildTask(task *packageBuildTask, execute packageBuildStep, finalize packageFinalizeStep) (packageBuildResult, error) { + if task.skip { + return packageBuildResultFor(task), nil + } + if err := execute(); err != nil { + return packageBuildResultFor(task), err + } + return finalize() +} + +func runBoundedPackageJobs(parallelism int, indexes []int, run func(index int) error) error { + if len(indexes) == 0 { + return nil + } + workers := min(max(1, parallelism), len(indexes)) + jobs := make(chan int, len(indexes)) + errs := make(map[int]error, len(indexes)) + var errsMu sync.Mutex + var wg sync.WaitGroup + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + for index := range jobs { + if err := runPackageJob(index, run); err != nil { + errsMu.Lock() + errs[index] = err + errsMu.Unlock() + } + } + }() + } + for _, index := range indexes { + jobs <- index + } + close(jobs) + wg.Wait() + for _, index := range indexes { + if err := errs[index]; err != nil { + return err + } + } + return nil +} + +func runPackageJob(index int, run func(index int) error) (err error) { + defer func() { + if value := recover(); value != nil { + if recovered, ok := value.(error); ok { + err = recovered + } else { + err = fmt.Errorf("package job %d panicked: %v", index, value) + } + } + }() + return run(index) +} + +func (ctx *context) canUseIsolatedBackend() bool { + return ctx.mode != ModeGen && + ctx.buildConf.BuildMode == BuildModeExe && + ctx.buildConf.ModuleHook == nil +} + +func (ctx *context) packageRequiresCoordinator(task *packageBuildTask) (bool, error) { + if !ctx.canUseIsolatedBackend() { + return true, nil + } + usesPlan9, err := ctx.packageUsesPlan9Asm(task.pkg) + if err != nil { + return false, err + } + return usesPlan9, nil +} + +func (ctx *context) packageUsesPlan9Asm(pkg *aPackage) (bool, error) { + check := func(p *packages.Package) (bool, error) { + if p == nil { + return false, nil + } + sfiles, err := pkgSFiles(ctx, p) + if err != nil { + return false, err + } + return len(sfiles) != 0 && ctx.plan9asmEnabled(p.PkgPath), nil + } + if yes, err := check(pkg.Package); err != nil || yes { + return yes, err + } + if pkg.AltPkg != nil { + return check(pkg.AltPkg.Package) + } + return false, nil +} + +func (ctx *context) executeIsolatedPackage(task *packageBuildTask, verbose bool) error { + return ctx.executeIsolatedPackageWithCallerTracking(task, ctx.callerTracking, verbose) +} + +func (ctx *context) executeIsolatedPackageWithCallerTracking(task *packageBuildTask, tracking *cl.CallerTracking, verbose bool) error { + session, err := ctx.backend.newSession() + if err != nil { + return fmt.Errorf("create backend session for %s: %w", task.pkg.PkgPath, err) + } + owned := true + defer func() { + if owned { + task.pkg.LPkg = nil + session.prog.Dispose() + } + }() + backendCtx := ctx.newBackendTaskWithCallerTracking(session, tracking) + + if err := buildPkg(backendCtx, task.pkg, verbose); err != nil { + return err + } + if task.pkg.LPkg == nil { + if task.pkg.Summary == nil { + task.pkg.Summary = summarizePackage(task.pkg) + } + return nil + } + if !task.pkg.CacheHit { + if task.needsRuntimeSignals() { + task.pkg.setNeedRuntimeOrPyInit(task.pkg.LPkg.NeedRuntime, task.pkg.LPkg.NeedPyInit) + } + task.pkg.Summary = summarizePackage(task.pkg) + } else { + task.pkg.Summary.AbiTypes = session.prog.AbiTypes() + } + if task.pkg.Summary == nil { + return fmt.Errorf("package %s produced no linker summary", task.pkg.PkgPath) + } + if ctx.buildConf != nil && ctx.buildConf.deadcodeDropEnabled() { + // Whole-program method analysis and strong ABI type overrides still read + // LPkg.Module and ExportFuncs. Transfer ownership to the coordinator until + // every link has completed; its deferred cleanup also covers errors/panics. + // + // TODO: move these remaining DCE facts into PackageSummary so package + // workers can always release their LLVM contexts immediately. + ctx.retainBackendProgram(task.pkg, session.prog) + owned = false + } + return nil +} + +func preparePackageSFiles(ctx *context, pkg *aPackage) error { + if _, err := pkgSFiles(ctx, pkg.Package); err != nil { + return err + } + if pkg.AltPkg != nil { + if _, err := pkgSFiles(ctx, pkg.AltPkg.Package); err != nil { + return err + } + } + return nil +} + +func (ctx *context) newBackendTask(session backendSession) *context { + return ctx.newBackendTaskWithCallerTracking(session, ctx.callerTracking) +} + +func (ctx *context) newBackendTaskWithCallerTracking(session backendSession, tracking *cl.CallerTracking) *context { + return &context{ + conf: ctx.conf, + progSSA: ctx.progSSA, + prog: session.prog, + dedup: ctx.dedup, + patches: ctx.patches, + callerTracking: tracking, + initial: ctx.initial, + pkgs: ctx.pkgs, + pkgByID: ctx.pkgByID, + mode: ctx.mode, + output: ctx.output, + passOpt: ctx.passOpt, + buildConf: ctx.buildConf, + crossCompile: ctx.crossCompile, + commands: ctx.commands, + frontendOptions: ctx.frontendOptions, + cTransformer: session.transformer, + backend: ctx.backend, + buildTrace: ctx.buildTrace, + sfilesCache: ctx.sfilesCache, + sfilesFrozen: true, + plan9asmReady: true, + plan9asmMode: ctx.plan9asmMode, + plan9asmPkgs: ctx.plan9asmPkgs, + plan9asmSigs: make(map[string]map[string]struct{}), + } +} + +func (ctx *context) executeCoordinatorPackageWithCallerTracking(task *packageBuildTask, tracking *cl.CallerTracking, verbose bool) error { + backendCtx := *ctx + backendCtx.callerTracking = tracking + return executePackageBuild(&backendCtx, task, verbose) +} + +func packageBuildResultFor(task *packageBuildTask) packageBuildResult { + return packageBuildResult{ + needRuntime: task.pkg.NeedRt, + needPyInit: task.pkg.NeedPyInit, + } +} diff --git a/internal/build/package_build_test.go b/internal/build/package_build_test.go new file mode 100644 index 0000000000..ee7bea44f6 --- /dev/null +++ b/internal/build/package_build_test.go @@ -0,0 +1,612 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "errors" + "go/ast" + "go/parser" + "go/token" + "go/types" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/goplus/llgo/cl" + "github.com/goplus/llgo/internal/env" + "github.com/goplus/llgo/internal/packages" + "golang.org/x/tools/go/ssa" +) + +func TestPackageBuildTaskAndResult(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + PkgPath: "example.com/p", + GoFiles: []string{"p.go"}, + Types: types.NewPackage("example.com/p", "p"), + }, NeedRt: true, NeedPyInit: true} + task := newPackageBuildTask(pkg) + if task.isDeclOnly() || task.isLinkOnly() || !task.hasSource() || task.isRuntime() || !task.needsRuntimeSignals() { + t.Fatalf("unexpected normal package task: %+v", task) + } + result := packageBuildResultFor(task) + if !result.needRuntime || !result.needPyInit { + t.Fatalf("unexpected package result: %+v", result) + } +} + +func TestPackageBuildTaskSpecialKinds(t *testing.T) { + decl := newPackageBuildTask(&aPackage{Package: &packages.Package{ + PkgPath: "unsafe", + Types: types.Unsafe, + }}) + if !decl.isDeclOnly() || decl.needsRuntimeSignals() { + t.Fatalf("unexpected declaration-only task: %+v", decl) + } + runtime := newPackageBuildTask(&aPackage{Package: &packages.Package{ + PkgPath: env.LLGoRuntimePkg, + Types: types.NewPackage(env.LLGoRuntimePkg, "runtime"), + }}) + if !runtime.isRuntime() { + t.Fatalf("runtime package was not marked runtime: %+v", runtime) + } +} + +func TestConfigParallelism(t *testing.T) { + if got := (&Config{BuildParallelism: 3}).parallelism(); got != 3 { + t.Fatalf("parallelism = %d, want 3", got) + } + if got := (&Config{}).parallelism(); got < 1 { + t.Fatalf("default parallelism = %d, want positive value", got) + } +} + +func TestPreparePackageModuleReturnsEmbedError(t *testing.T) { + fset := token.NewFileSet() + filename := filepath.Join(t.TempDir(), "p.go") + file, err := parser.ParseFile(fset, filename, `package p + +//go:embed missing.txt +var content string +`, parser.ParseComments) + if err != nil { + t.Fatal(err) + } + pkg := &aPackage{Package: &packages.Package{ + ID: "example.com/p", + PkgPath: "example.com/p", + Syntax: []*ast.File{file}, + }} + ctx := &context{ + conf: &packages.Config{Fset: fset}, + buildConf: &Config{}, + } + externs, err := preparePackageModule(ctx, pkg, true) + if err == nil || !strings.Contains(err.Error(), "only allowed in Go files that import") { + t.Fatalf("preparePackageModule embed error = %v", err) + } + if externs != nil { + t.Fatalf("preparePackageModule externs = %v, want nil", externs) + } +} + +func TestBuildOnePackageReturnsFrontendError(t *testing.T) { + t.Setenv(llgoBuildCache, "off") + fset := token.NewFileSet() + filename := filepath.Join(t.TempDir(), "p.go") + file, err := parser.ParseFile(fset, filename, `package p + +//go:embed missing.txt +var content string +`, parser.ParseComments) + if err != nil { + t.Fatal(err) + } + pkg := &aPackage{ + Package: &packages.Package{ + ID: "example.com/frontend-error", + PkgPath: "example.com/frontend-error", + GoFiles: []string{filename}, + Syntax: []*ast.File{file}, + Types: types.NewPackage("example.com/frontend-error", "p"), + }, + Manifest: "already fingerprinted", + Fingerprint: "frontend-error", + } + ctx := &context{ + conf: &packages.Config{Fset: fset}, + buildConf: &Config{}, + built: make(map[string]none), + } + + _, err = buildOnePackage(ctx, newPackageBuildTask(pkg), false) + if err == nil || !strings.Contains(err.Error(), "only allowed in Go files that import") { + t.Fatalf("buildOnePackage frontend error = %v", err) + } +} + +func TestPrePackageBuildErrorsAndCacheHit(t *testing.T) { + t.Run("fingerprint error", func(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "example.com/missing-source", + PkgPath: "example.com/missing-source", + GoFiles: []string{filepath.Join(t.TempDir(), "missing.go")}, + Types: types.NewPackage("example.com/missing-source", "missing"), + }} + ctx := &context{ + buildConf: &Config{}, + built: make(map[string]none), + llvmVersion: "test", + } + task := newPackageBuildTask(pkg) + err := prePackageBuild(ctx, task, false) + if err == nil || !strings.Contains(err.Error(), "digest go files") { + t.Fatalf("pre fingerprint error = %v", err) + } + if task.skip { + t.Fatal("pre skipped package after fingerprint error") + } + }) + + t.Run("cache hit", func(t *testing.T) { + t.Setenv(llgoBuildCache, "off") + pkg := &aPackage{ + Package: &packages.Package{ + ID: "example.com/cache-hit", + PkgPath: "example.com/cache-hit", + GoFiles: []string{"cached.go"}, + Types: types.NewPackage("example.com/cache-hit", "cached"), + }, + Manifest: "already fingerprinted", + Fingerprint: "cache-hit", + CacheHit: true, + } + ctx := &context{buildConf: &Config{}, built: make(map[string]none)} + task := newPackageBuildTask(pkg) + err := prePackageBuild(ctx, task, true) + if err != nil { + t.Fatal(err) + } + if task.skip || !pkg.CacheHit { + t.Fatalf("pre cache hit = skip %v, cache hit %v", task.skip, pkg.CacheHit) + } + }) +} + +func TestBuildOnePackageSkipsAlreadyBuiltPackage(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "example.com/already-built", + PkgPath: "example.com/already-built", + GoFiles: []string{"already.go"}, + Types: types.NewPackage("example.com/already-built", "already"), + }, NeedRt: true} + ctx := &context{built: map[string]none{pkg.ID: {}}} + + result, err := buildOnePackage(ctx, newPackageBuildTask(pkg), false) + if err != nil { + t.Fatal(err) + } + if !result.needRuntime { + t.Fatalf("build result = %+v, want runtime requirement preserved", result) + } +} + +func TestPrePackageBuildSkipsDeclarationOnlyPackage(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "unsafe", + PkgPath: "unsafe", + Types: types.Unsafe, + ExportFile: "stale.a", + }} + ctx := &context{ + conf: &packages.Config{}, + buildConf: &Config{Goos: "linux", Goarch: "amd64", ForceRebuild: true}, + built: make(map[string]none), + } + + task := newPackageBuildTask(pkg) + err := prePackageBuild(ctx, task, false) + if err != nil { + t.Fatal(err) + } + if !task.skip { + t.Fatal("declaration-only package was not skipped") + } + if pkg.ExportFile != "" { + t.Fatalf("ExportFile = %q, want empty", pkg.ExportFile) + } + if _, ok := ctx.built[pkg.ID]; !ok { + t.Fatal("declaration-only package was not recorded as built") + } +} + +func TestPrePackageBuildSkipsExternalLinkOnlyPackage(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "example.com/linkonly", + PkgPath: "example.com/linkonly", + Name: "linkonly", + Types: types.NewPackage("example.com/linkonly", "linkonly"), + ExportFile: "stale.a", + }} + ctx := &context{ + conf: &packages.Config{}, + buildConf: &Config{Goos: "linux", Goarch: "amd64", ForceRebuild: true}, + built: make(map[string]none), + } + task := &packageBuildTask{pkg: pkg, kind: cl.PkgLinkExtern, kindParam: "-lexample"} + err := prePackageBuild(ctx, task, false) + if err != nil { + t.Fatal(err) + } + if !task.skip || pkg.ExportFile != "" || pkg.Summary == nil { + t.Fatalf("external link-only pre = skip %v, export %q, summary %#v", task.skip, pkg.ExportFile, pkg.Summary) + } + if len(pkg.LinkArgs) != 1 || pkg.LinkArgs[0] != "-lexample" { + t.Fatalf("external link args = %q, want [-lexample]", pkg.LinkArgs) + } +} + +func TestFinalizePackageBuildReturnsCachedResult(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "example.com/cached", + PkgPath: "example.com/cached", + Types: types.NewPackage("example.com/cached", "cached"), + }, CacheHit: true, NeedPyInit: true} + + result, err := finalizePackageBuild(&context{}, newPackageBuildTask(pkg), false) + if err != nil { + t.Fatal(err) + } + if !result.needPyInit { + t.Fatalf("build result = %+v, want Python initialization requirement preserved", result) + } +} + +func TestBuildSSAPkgsEmptyAndNilEntries(t *testing.T) { + ctx := &context{buildConf: &Config{}} + buildSSAPkgs(ctx, nil) + buildSSAPkgs(ctx, []ssaBuildEntry{{}, {fixOrder: true}}) + + prog := ssa.NewProgram(token.NewFileSet(), ssa.SanityCheckFunctions) + pkg := prog.CreatePackage(types.NewPackage("example.com/ssa", "ssa"), nil, nil, true) + buildSSAPkgs(ctx, []ssaBuildEntry{{pkg: pkg}, {pkg: pkg}}) +} + +func TestPreFingerprintsSkippedPackage(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "unsafe", + PkgPath: "unsafe", + Types: types.Unsafe, + }} + ctx := &context{ + conf: &packages.Config{}, + buildConf: &Config{Goos: "linux", Goarch: "amd64", ForceRebuild: true}, + built: make(map[string]none), + } + task := newPackageBuildTask(pkg) + err := prePackageBuild(ctx, task, false) + if err != nil { + t.Fatal(err) + } + if !task.skip || pkg.Fingerprint == "" || pkg.Manifest == "" || pkg.Summary == nil { + t.Fatalf("skipped package was not fully prepared: skip=%v fingerprint=%q manifest=%q summary=%#v", task.skip, pkg.Fingerprint, pkg.Manifest, pkg.Summary) + } +} +func TestCanUseIsolatedBackend(t *testing.T) { + ctx := &context{ + mode: ModeBuild, + buildConf: &Config{BuildMode: BuildModeExe}, + } + if !ctx.canUseIsolatedBackend() { + t.Fatal("normal executable build should use isolated backends") + } + ctx.mode = ModeGen + if ctx.canUseIsolatedBackend() { + t.Fatal("generation mode should remain on the coordinator") + } + ctx.mode = ModeTest + if !ctx.canUseIsolatedBackend() { + t.Fatal("test mode should use isolated executable backends") + } + ctx.buildConf.BuildMode = BuildModeCShared + if ctx.canUseIsolatedBackend() { + t.Fatal("c-shared mode should remain on the coordinator") + } + ctx.buildConf.BuildMode = BuildModeExe + ctx.buildConf.ModuleHook = func(*aPackage) {} + if ctx.canUseIsolatedBackend() { + t.Fatal("module hooks should remain on the coordinator") + } +} + +func TestPartitionPackageExecutions(t *testing.T) { + patchedPkg := &aPackage{Package: &packages.Package{ + ID: "example.com/patched", + PkgPath: "example.com/patched", + }} + normalPkg := &aPackage{Package: &packages.Package{ + ID: "example.com/normal", + PkgPath: "example.com/normal", + }} + ctx := &context{ + mode: ModeBuild, + buildConf: &Config{BuildMode: BuildModeExe}, + patches: cl.Patches{"example.com/patched": {}}, + sfilesCache: make(map[string][]string), + } + patched, coordinator, isolated, err := partitionPackageExecutions(ctx, []*packageBuildTask{ + {pkg: patchedPkg}, + {pkg: normalPkg}, + }) + if err != nil { + t.Fatal(err) + } + if len(patched) != 1 || patched[0] != 0 { + t.Fatalf("patched = %v, want [0]", patched) + } + if len(coordinator) != 0 { + t.Fatalf("coordinator = %v, want empty", coordinator) + } + if len(isolated) != 1 || isolated[0] != 1 { + t.Fatalf("isolated = %v, want [1]", isolated) + } +} + +func TestPkgSFilesRejectsUnpreparedBackendRead(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "asm.s"), []byte("TEXT ·f(SB),$0-0\n\tRET\n"), 0o644); err != nil { + t.Fatal(err) + } + ctx := &context{ + sfilesCache: make(map[string][]string), + sfilesFrozen: true, + } + _, err := pkgSFiles(ctx, &packages.Package{ + ID: "example.com/asm", + PkgPath: "example.com/asm", + Dir: dir, + }) + if err == nil { + t.Fatal("expected frozen SFiles cache to reject an unprepared package") + } +} + +func TestRunBoundedPackageJobs(t *testing.T) { + started := make(chan int, 4) + release := make(chan struct{}) + done := make(chan error, 1) + var active atomic.Int32 + var maximum atomic.Int32 + go func() { + done <- runBoundedPackageJobs(2, []int{0, 1, 2, 3}, func(index int) error { + current := active.Add(1) + for { + old := maximum.Load() + if current <= old || maximum.CompareAndSwap(old, current) { + break + } + } + started <- index + <-release + active.Add(-1) + return nil + }) + }() + + for range 2 { + select { + case <-started: + case <-time.After(5 * time.Second): + close(release) + t.Fatal("two package workers did not start concurrently") + } + } + if got := maximum.Load(); got != 2 { + close(release) + t.Fatalf("maximum concurrent jobs = %d, want 2", got) + } + close(release) + if err := <-done; err != nil { + t.Fatal(err) + } + if got := maximum.Load(); got != 2 { + t.Fatalf("maximum concurrent jobs = %d after completion, want 2", got) + } +} + +func TestRunBoundedPackageJobsReturnsFirstOrderedError(t *testing.T) { + first := errors.New("first") + second := errors.New("second") + err := runBoundedPackageJobs(3, []int{3, 1, 2}, func(index int) error { + switch index { + case 3: + return first + case 1: + return second + default: + return nil + } + }) + if !errors.Is(err, first) { + t.Fatalf("error = %v, want first submitted error", err) + } +} + +func TestRunBoundedPackageJobsConvertsPanicToError(t *testing.T) { + boom := errors.New("boom") + err := runBoundedPackageJobs(2, []int{0, 1}, func(index int) error { + if index == 0 { + panic(boom) + } + return nil + }) + if !errors.Is(err, boom) { + t.Fatalf("error = %v, want recovered panic %v", err, boom) + } +} +func TestPackageBuildStageEmptyAndSkippedInputs(t *testing.T) { + runtimePkg := &aPackage{Package: &packages.Package{PkgPath: env.LLGoRuntimePkg}} + normalPkg := &aPackage{Package: &packages.Package{PkgPath: "example.com/normal"}} + tasks := []*packageBuildTask{ + {pkg: runtimePkg}, + {pkg: normalPkg}, + } + if got := packageBuildTasksForRuntime(tasks, true); len(got) != 1 || got[0].pkg != runtimePkg { + t.Fatalf("runtime tasks = %+v, want runtime package", got) + } + if got := packageBuildTasksForRuntime(tasks, false); len(got) != 1 || got[0].pkg != normalPkg { + t.Fatalf("non-runtime tasks = %+v, want normal package", got) + } + + ctx := &context{buildConf: &Config{}} + if err := prePackageBuilds(ctx, nil, false); err != nil { + t.Fatalf("empty pre = %v", err) + } + results, err := buildPrePackageGroup(ctx, nil, false) + if err != nil || results != nil { + t.Fatalf("empty package group = %#v, %v", results, err) + } + if err := executePrePackage(ctx, &packageBuildTask{skip: true}, false); err != nil { + t.Fatal(err) + } + if err := executeIsolatedPackages(ctx, nil, nil, nil, false); err != nil { + t.Fatal(err) + } + if err := runBoundedPackageJobs(0, nil, func(int) error { + t.Fatal("empty package jobs invoked callback") + return nil + }); err != nil { + t.Fatal(err) + } + if err := runPackageJob(7, func(int) error { panic("boom") }); err == nil || !strings.Contains(err.Error(), "package job 7 panicked: boom") { + t.Fatalf("non-error panic = %v", err) + } +} + +func TestRunPackageBuildTaskPublishesImmediately(t *testing.T) { + task := &packageBuildTask{pkg: &aPackage{Package: &packages.Package{PkgPath: "example.com/p"}}} + var steps []string + wantResult := packageBuildResult{needRuntime: true} + result, err := runPackageBuildTask( + task, + func() error { + steps = append(steps, "backend") + return nil + }, + func() (packageBuildResult, error) { + steps = append(steps, "publish") + return wantResult, nil + }, + ) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(steps, []string{"backend", "publish"}) { + t.Fatalf("package task steps = %v, want backend then publish", steps) + } + if result != wantResult { + t.Fatalf("package task result = %+v, want %+v", result, wantResult) + } +} + +func TestRunPackageBuildTaskStopsBeforePublish(t *testing.T) { + task := &packageBuildTask{pkg: &aPackage{Package: &packages.Package{PkgPath: "example.com/p"}}} + backendErr := errors.New("backend failed") + published := false + _, err := runPackageBuildTask( + task, + func() error { return backendErr }, + func() (packageBuildResult, error) { + published = true + return packageBuildResult{}, nil + }, + ) + if !errors.Is(err, backendErr) { + t.Fatalf("package task error = %v, want %v", err, backendErr) + } + if published { + t.Fatal("package task published after backend failure") + } +} + +func TestNewBackendTaskUsesPackageLocalState(t *testing.T) { + coordinator := &context{ + conf: &packages.Config{}, + mode: ModeBuild, + buildConf: &Config{BuildMode: BuildModeExe}, + commands: commandEnv{dir: t.TempDir()}, + frontendOptions: cl.Options{Debug: true}, + sfilesCache: map[string][]string{"example.com/p": {"asm.s"}}, + plan9asmReady: true, + plan9asmMode: plan9asmEnvSelected, + plan9asmPkgs: map[string]bool{"example.com/p": true}, + } + + task := coordinator.newBackendTask(backendSession{}) + if task == coordinator { + t.Fatal("backend task aliases coordinator") + } + if task.buildConf != coordinator.buildConf || task.conf != coordinator.conf { + t.Fatal("backend task did not retain immutable build inputs") + } + if !task.sfilesFrozen || !task.plan9asmReady || task.plan9asmMode != plan9asmEnvSelected { + t.Fatalf("backend task state = %+v", task) + } + if !task.frontendOptions.Debug || task.commands.dir != coordinator.commands.dir { + t.Fatal("backend task lost invocation settings") + } + task.plan9asmSigs["example.com/p"] = map[string]struct{}{"f": {}} + if coordinator.plan9asmSigs != nil { + t.Fatal("backend task signature cache aliases coordinator") + } +} + +func TestPrePackageBuildsRecordsSkippedPackages(t *testing.T) { + pkg := &aPackage{Package: &packages.Package{ + ID: "example.com/already-built", + PkgPath: "example.com/already-built", + }} + ctx := &context{built: map[string]none{pkg.ID: {}}} + task := &packageBuildTask{pkg: pkg} + if err := prePackageBuilds(ctx, []*packageBuildTask{task}, false); err != nil { + t.Fatal(err) + } + if !task.skip || task.pkg != pkg { + t.Fatalf("pre task = %#v, want skipped package", task) + } +} + +func TestPackageSchedulingHandlesNonBackendPackages(t *testing.T) { + task := &packageBuildTask{pkg: &aPackage{}} + ctx := &context{mode: ModeGen, buildConf: &Config{BuildMode: BuildModeExe}} + serial, err := ctx.packageRequiresCoordinator(task) + if err != nil || !serial { + t.Fatalf("generation package coordinator = %v, %v; want true, nil", serial, err) + } + + usesPlan9, err := (&context{}).packageUsesPlan9Asm(task.pkg) + if err != nil || usesPlan9 { + t.Fatalf("nil package Plan9 asm = %v, %v; want false, nil", usesPlan9, err) + } + patched, coordinator, isolated, err := partitionPackageExecutions(ctx, nil) + if err != nil || patched != nil || coordinator != nil || isolated != nil { + t.Fatalf("empty partition = %v, %v, %v, %v", patched, coordinator, isolated, err) + } +} diff --git a/internal/build/package_pipeline.go b/internal/build/package_pipeline.go new file mode 100644 index 0000000000..166ec70ea3 --- /dev/null +++ b/internal/build/package_pipeline.go @@ -0,0 +1,553 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "fmt" + "go/ast" + + "github.com/goplus/llgo/cl" + "golang.org/x/tools/go/ssa" +) + +func preparePackagePatches(ctx *context, pkgs []*aPackage) { + for _, pkg := range pkgs { + patch, ok := ctx.patches[pkg.PkgPath] + if !ok { + continue + } + files := append([]*ast.File(nil), pkg.Syntax...) + if pkg.AltPkg != nil { + files = append(files, pkg.AltPkg.Syntax...) + } + ctx.patches[pkg.PkgPath] = cl.PreparePatch(patch, pkg.Types, files) + } +} + +type packagePipelineClass uint8 + +const ( + pipelineIsolated packagePipelineClass = iota + pipelineCoordinator +) + +type packagePipelineStage uint8 + +const ( + pipelineStageSSA packagePipelineStage = iota + pipelineStageBackend + pipelineStagePatchedBackend +) + +type packagePipelineSSA struct { + entry ssaBuildEntry + order int + done bool + callerSummary cl.CallerTrackingSummary + traceSpan *buildTraceSpan +} + +type packagePipelineTask struct { + index int + build *packageBuildTask + class packagePipelineClass + ownSSA *packagePipelineSSA + ssaDeps []*packagePipelineSSA + callerRoots []*ssa.Package + callerNodes []*packagePipelineSSA + enabled bool + running bool + done bool + patched bool +} + +type packagePipelineEvent struct { + ssa *packagePipelineSSA + task *packagePipelineTask + err error +} + +// buildPackagePipeline overlaps completed Go SSA packages with isolated LLVM +// backends. SSA and backend work share one concurrency budget, so -p remains a +// bound on CPU-heavy package work rather than creating two independent pools. +func buildPackagePipeline(ctx *context, entries []ssaBuildEntry, pkgs []*aPackage, verbose bool) ([]*aPackage, error) { + buildTasks := make([]*packageBuildTask, len(pkgs)) + for i, pkg := range pkgs { + buildTasks[i] = newPackageBuildTask(pkg) + } + if err := prePackageBuilds(ctx, buildTasks, verbose); err != nil { + return nil, err + } + // Publication is part of each backend task. Initialize the shared cache + // descriptor on the coordinator before any task can call saveToCache. + if cacheEnabled() { + ctx.ensureCacheManager() + } + ctx.sfilesFrozen = true + + ssaNodes, ssaByPackage := newPackagePipelineSSANodes(entries) + tasks, serialOrder, err := newPackagePipelineTasks(ctx, buildTasks, ssaByPackage) + if err != nil { + return nil, err + } + ssaNodes = orderPackagePipelineSSA(ssaNodes, tasks) + + hostRuntime := ctx.buildConf.Target == "" + normalRemaining := 0 + backendFailed := false + var needRuntime, needPyInit bool + for _, task := range tasks { + task.enabled = !task.build.isRuntime() || hostRuntime + if task.build.skip { + task.done = true + if !task.build.isRuntime() { + result := packageBuildResultFor(task.build) + needRuntime = needRuntime || result.needRuntime + needPyInit = needPyInit || result.needPyInit + } + continue + } + if !task.build.isRuntime() { + normalRemaining++ + } + } + + runtimeResolved := hostRuntime + resolveRuntime := func() { + if runtimeResolved || normalRemaining != 0 { + return + } + runtimeResolved = true + buildRuntime := !backendFailed && (needRuntime || needPyInit) + for _, task := range tasks { + if !task.build.isRuntime() || task.done { + continue + } + task.enabled = buildRuntime + if !buildRuntime { + task.done = true + } + } + } + resolveRuntime() + + parallelism := ctx.buildConf.parallelism() + events := make(chan packagePipelineEvent, parallelism) + active := 0 + ssaActive := 0 + nextSSA := 0 + ssaDone := 0 + serialPos := 0 + serialActive := false + exclusiveActive := false + var ssaErr error + backendErrs := make(map[int]error) + + advanceSerial := func() { + for serialPos < len(serialOrder) && serialOrder[serialPos].done { + serialPos++ + } + } + advanceSerial() + + ready := func(task *packagePipelineTask) bool { + if task == nil || !task.enabled || task.running || task.done { + return false + } + // Legacy patch compilation rewrites shared go/ssa package type pointers. + // Its immutable merged type view is prepared up front for ordinary + // backends, but the patched package itself still runs exclusively after + // SSA construction has stopped mutating the program. + if task.patched && ssaDone != len(ssaNodes) { + return false + } + if task.ownSSA != nil && !task.ownSSA.done { + return false + } + for _, dep := range task.ssaDeps { + if !dep.done { + return false + } + } + return true + } + nextBackend := func() *packagePipelineTask { + advanceSerial() + if !serialActive && serialPos < len(serialOrder) { + task := serialOrder[serialPos] + if task.patched && ssaDone == len(ssaNodes) { + if active == 0 && ready(task) { + return task + } + return nil + } + if ready(task) { + return task + } + } + for _, task := range tasks { + if task.class == pipelineIsolated && ready(task) { + return task + } + } + return nil + } + allBackendsDone := func() bool { + for _, task := range tasks { + if !task.done { + return false + } + } + return true + } + launchSSA := func() bool { + if nextSSA >= len(ssaNodes) { + return false + } + node := ssaNodes[nextSSA] + nextSSA++ + active++ + ssaActive++ + go func() { + pkgPath := packagePipelineSSAPath(node.entry.pkg) + node.traceSpan = ctx.buildTrace.startWorker("ssa", pkgPath) + observePackagePipeline(ctx, pipelineStageSSA, pkgPath, true) + runErr := buildPackagePipelineSSA(node.entry) + observePackagePipeline(ctx, pipelineStageSSA, pkgPath, false) + node.traceSpan.done() + events <- packagePipelineEvent{ssa: node, err: runErr} + }() + return true + } + + for ssaDone != len(ssaNodes) || !allBackendsDone() || active != 0 { + for ssaErr == nil && active < parallelism { + if exclusiveActive { + break + } + // Keep at least one SSA producer active while packages remain. At + // -p=1 this preserves the legacy all-SSA-then-backend order; with + // more workers, the remaining slots consume ready backend work. + if ssaActive == 0 && launchSSA() { + continue + } + if task := nextBackend(); task != nil { + task.running = true + if task.class == pipelineCoordinator { + serialActive = true + } + if task.patched { + exclusiveActive = true + } + active++ + go func() { + stage := pipelineStageBackend + traceStage := "backend" + if task.patched { + stage = pipelineStagePatchedBackend + traceStage = "backend-patched" + } + traceSpan := ctx.buildTrace.startWorker(traceStage, task.build.pkg.PkgPath) + if task.class == pipelineCoordinator { + traceSpan.setArg("class", "coordinator") + } else { + traceSpan.setArg("class", "isolated") + } + if ctx.buildTrace != nil { + // Draw direct SSA dependencies only. Transitive scheduler + // dependencies are implied by these edges and would make + // traces for large repositories unnecessarily quadratic. + for _, dependency := range task.callerNodes { + ctx.buildTrace.flow(dependency.traceSpan, traceSpan) + } + } + observePackagePipeline(ctx, stage, task.build.pkg.PkgPath, true) + runErr := runPackageJob(task.index, func(int) error { + summaries := make([]cl.CallerTrackingSummary, 0, len(task.callerNodes)) + for _, node := range task.callerNodes { + summaries = append(summaries, node.callerSummary) + } + tracking := cl.NewPackageCallerTrackingForPackages(task.callerRoots, summaries...) + _, err := executeAndFinalizePackage(ctx, task.build, verbose, func() error { + if task.class == pipelineCoordinator { + return ctx.executeCoordinatorPackageWithCallerTracking(task.build, tracking, verbose) + } + return ctx.executeIsolatedPackageWithCallerTracking(task.build, tracking, verbose) + }) + return err + }) + observePackagePipeline(ctx, stage, task.build.pkg.PkgPath, false) + traceSpan.done() + events <- packagePipelineEvent{task: task, err: runErr} + }() + continue + } + if launchSSA() { + continue + } + break + } + + if active == 0 { + if ssaErr != nil { + return nil, ssaErr + } + resolveRuntime() + if allBackendsDone() && ssaDone == len(ssaNodes) { + break + } + return nil, fmt.Errorf("package pipeline stalled with %d/%d SSA packages complete", ssaDone, len(ssaNodes)) + } + + event := <-events + active-- + switch { + case event.ssa != nil: + ssaActive-- + if event.err == nil { + event.ssa.callerSummary, event.err = finishPackagePipelineSSA(event.ssa.entry) + } + if event.err != nil { + if ssaErr == nil { + ssaErr = event.err + } + continue + } + event.ssa.done = true + ssaDone++ + case event.task != nil: + task := event.task + task.running = false + task.done = true + if task.class == pipelineCoordinator { + serialActive = false + } + if task.patched { + exclusiveActive = false + } + if event.err != nil { + backendErrs[task.index] = event.err + backendFailed = true + } + if !task.build.isRuntime() { + normalRemaining-- + } + if event.err == nil && !task.build.isRuntime() { + result := packageBuildResultFor(task.build) + needRuntime = needRuntime || result.needRuntime + needPyInit = needPyInit || result.needPyInit + } + resolveRuntime() + advanceSerial() + } + } + + if ssaErr != nil { + return nil, ssaErr + } + for i := range tasks { + if err := backendErrs[i]; err != nil { + return nil, err + } + } + return pkgs, nil +} + +func observePackagePipeline(ctx *context, stage packagePipelineStage, pkgPath string, start bool) { + if observer := ctx.buildConf.packagePipelineObserver; observer != nil { + observer(stage, pkgPath, start) + } +} + +func packagePipelineSSAPath(pkg *ssa.Package) string { + if pkg == nil || pkg.Pkg == nil { + return "" + } + return pkg.Pkg.Path() +} + +func newPackagePipelineSSANodes(entries []ssaBuildEntry) ([]*packagePipelineSSA, map[*ssa.Package]*packagePipelineSSA) { + nodes := make([]*packagePipelineSSA, 0, len(entries)) + byPackage := make(map[*ssa.Package]*packagePipelineSSA, len(entries)) + for _, entry := range entries { + if entry.pkg == nil { + continue + } + if node := byPackage[entry.pkg]; node != nil { + node.entry.fixOrder = node.entry.fixOrder || entry.fixOrder + continue + } + node := &packagePipelineSSA{entry: entry, order: len(nodes)} + nodes = append(nodes, node) + byPackage[entry.pkg] = node + } + return nodes, byPackage +} + +func newPackagePipelineTasks( + ctx *context, + buildTasks []*packageBuildTask, + ssaByPackage map[*ssa.Package]*packagePipelineSSA, +) ([]*packagePipelineTask, []*packagePipelineTask, error) { + tasks := make([]*packagePipelineTask, len(buildTasks)) + var patchedNormal, coordinatorNormal, patchedRuntime, coordinatorRuntime []*packagePipelineTask + for i, buildTask := range buildTasks { + task := &packagePipelineTask{ + index: i, + build: buildTask, + ownSSA: ssaByPackage[buildTask.pkg.SSA], + } + if buildTask.pkg.SSA != nil { + task.callerRoots = append(task.callerRoots, buildTask.pkg.SSA) + } + seenCallerNodes := make(map[*packagePipelineSSA]bool) + addCallerNode := func(pkg *ssa.Package) { + node := ssaByPackage[pkg] + if node == nil || seenCallerNodes[node] { + return + } + seenCallerNodes[node] = true + task.callerNodes = append(task.callerNodes, node) + } + addCallerNode(buildTask.pkg.SSA) + seen := make(map[*packagePipelineSSA]bool) + addDep := func(pkg *ssa.Package) { + node := ssaByPackage[pkg] + if node == nil || node == task.ownSSA || seen[node] { + return + } + seen[node] = true + task.ssaDeps = append(task.ssaDeps, node) + } + visitedDeps := make(map[string]bool) + var addPackageDeps func(*aPackage) + addPackageDeps = func(pkg *aPackage) { + if pkg == nil || visitedDeps[pkg.ID] { + return + } + visitedDeps[pkg.ID] = true + addDep(pkg.SSA) + for _, dep := range effectiveDependencies(pkg) { + addPackageDeps(ctx.pkgByID[dep.ID]) + } + } + for _, dep := range effectiveDependencies(buildTask.pkg) { + depPkg := ctx.pkgByID[dep.ID] + if depPkg != nil { + addCallerNode(depPkg.SSA) + } + addPackageDeps(depPkg) + } + if patch, ok := ctx.patches[buildTask.pkg.PkgPath]; ok { + addDep(patch.Alt) + addCallerNode(patch.Alt) + if patch.Alt != nil && patch.Alt != buildTask.pkg.SSA { + task.callerRoots = append(task.callerRoots, patch.Alt) + } + } + + patched := false + if _, ok := ctx.patches[buildTask.pkg.PkgPath]; ok { + patched = true + task.patched = true + task.class = pipelineCoordinator + } else { + serial, err := ctx.packageRequiresCoordinator(buildTask) + if err != nil { + return nil, nil, err + } + if serial { + task.class = pipelineCoordinator + } + } + if task.class == pipelineCoordinator && !buildTask.skip { + switch { + case !buildTask.isRuntime() && patched: + patchedNormal = append(patchedNormal, task) + case !buildTask.isRuntime(): + coordinatorNormal = append(coordinatorNormal, task) + case patched: + patchedRuntime = append(patchedRuntime, task) + default: + coordinatorRuntime = append(coordinatorRuntime, task) + } + } + tasks[i] = task + } + serial := append(patchedNormal, coordinatorNormal...) + serial = append(serial, patchedRuntime...) + serial = append(serial, coordinatorRuntime...) + return tasks, serial, nil +} + +func orderPackagePipelineSSA(nodes []*packagePipelineSSA, tasks []*packagePipelineTask) []*packagePipelineSSA { + deps := make(map[*packagePipelineSSA][]*packagePipelineSSA) + for _, task := range tasks { + if task.ownSSA == nil { + continue + } + deps[task.ownSSA] = append(deps[task.ownSSA], task.ssaDeps...) + } + ordered := make([]*packagePipelineSSA, 0, len(nodes)) + state := make(map[*packagePipelineSSA]uint8, len(nodes)) + var visit func(*packagePipelineSSA) + visit = func(node *packagePipelineSSA) { + if node == nil || state[node] == 2 { + return + } + if state[node] == 1 { + return + } + state[node] = 1 + for _, dep := range deps[node] { + visit(dep) + } + state[node] = 2 + ordered = append(ordered, node) + } + for _, node := range nodes { + visit(node) + } + return ordered +} + +func buildPackagePipelineSSA(entry ssaBuildEntry) (err error) { + pkgPath := packagePipelineSSAPath(entry.pkg) + defer func() { + if value := recover(); value != nil { + err = fmt.Errorf("build SSA for %s: %v", pkgPath, value) + } + }() + if entry.pkg == nil { + return fmt.Errorf("build SSA for %s: nil package", pkgPath) + } + entry.pkg.Build() + return nil +} + +func finishPackagePipelineSSA(entry ssaBuildEntry) (summary cl.CallerTrackingSummary, err error) { + pkgPath := packagePipelineSSAPath(entry.pkg) + defer func() { + if value := recover(); value != nil { + err = fmt.Errorf("fix SSA order for %s: %v", pkgPath, value) + } + }() + if entry.fixOrder { + fixSSAOrder(entry.pkg, entry.syntax) + } + return cl.SummarizeCallerTracking(entry.pkg), nil +} diff --git a/internal/build/package_pipeline_test.go b/internal/build/package_pipeline_test.go new file mode 100644 index 0000000000..6df093db81 --- /dev/null +++ b/internal/build/package_pipeline_test.go @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "go/token" + "go/types" + "testing" + + "golang.org/x/tools/go/ssa" +) + +func TestNewPackagePipelineSSANodesDeduplicates(t *testing.T) { + first := new(ssa.Package) + second := new(ssa.Package) + nodes, byPackage := newPackagePipelineSSANodes([]ssaBuildEntry{ + {pkg: first}, + {pkg: nil, fixOrder: true}, + {pkg: second}, + {pkg: first, fixOrder: true}, + }) + + if len(nodes) != 2 { + t.Fatalf("node count = %d, want 2", len(nodes)) + } + if nodes[0] != byPackage[first] || nodes[1] != byPackage[second] { + t.Fatal("package lookup does not preserve first-seen order") + } + if !nodes[0].entry.fixOrder { + t.Fatal("duplicate package did not retain fixOrder") + } + if nodes[0].order != 0 || nodes[1].order != 1 { + t.Fatalf("node order = (%d, %d), want (0, 1)", nodes[0].order, nodes[1].order) + } +} + +func TestOrderPackagePipelineSSADependenciesFirst(t *testing.T) { + first := &packagePipelineSSA{order: 0} + second := &packagePipelineSSA{order: 1} + third := &packagePipelineSSA{order: 2} + tasks := []*packagePipelineTask{ + {ownSSA: first, ssaDeps: []*packagePipelineSSA{second}}, + {ownSSA: second, ssaDeps: []*packagePipelineSSA{third}}, + } + + got := orderPackagePipelineSSA([]*packagePipelineSSA{first, second, third}, tasks) + want := []*packagePipelineSSA{third, second, first} + if len(got) != len(want) { + t.Fatalf("ordered node count = %d, want %d", len(got), len(want)) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("ordered node %d = %p, want %p", i, got[i], want[i]) + } + } +} + +func TestOrderPackagePipelineSSAToleratesCyclesAndEmptyTasks(t *testing.T) { + first := &packagePipelineSSA{order: 0} + second := &packagePipelineSSA{order: 1} + tasks := []*packagePipelineTask{ + {}, + {ownSSA: first, ssaDeps: []*packagePipelineSSA{second}}, + {ownSSA: second, ssaDeps: []*packagePipelineSSA{first}}, + } + + got := orderPackagePipelineSSA([]*packagePipelineSSA{nil, first, second, first}, tasks) + if len(got) != 2 { + t.Fatalf("ordered node count = %d, want 2", len(got)) + } + seen := map[*packagePipelineSSA]bool{} + for _, node := range got { + if seen[node] { + t.Fatalf("SSA node %p was returned more than once", node) + } + seen[node] = true + } + if !seen[first] || !seen[second] { + t.Fatalf("ordered nodes = %v, want both cycle members", got) + } +} + +func TestBuildPackagePipelineSSARejectsNilPackage(t *testing.T) { + if err := buildPackagePipelineSSA(ssaBuildEntry{}); err == nil { + t.Fatal("nil SSA package was accepted") + } +} + +func TestBuildPackagePipelineSSAConvertsPanicsToErrors(t *testing.T) { + prog := ssa.NewProgram(token.NewFileSet(), 0) + pkg := prog.CreatePackage(types.NewPackage("example.com/p", "p"), nil, &types.Info{}, true) + pkg.Prog = nil + if err := buildPackagePipelineSSA(ssaBuildEntry{pkg: pkg}); err == nil { + t.Fatal("SSA build panic was not converted to an error") + } + if _, err := finishPackagePipelineSSA(ssaBuildEntry{}); err == nil { + t.Fatal("SSA finalization panic was not converted to an error") + } +} diff --git a/internal/build/package_summary.go b/internal/build/package_summary.go new file mode 100644 index 0000000000..fc8ab1517b --- /dev/null +++ b/internal/build/package_summary.go @@ -0,0 +1,261 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "sort" + "strings" + + llssa "github.com/goplus/llgo/ssa" + "github.com/xgo-dev/llvm" +) + +// PackageSummary is the immutable, LLVM-free output one package contributes +// to the final link. A backend can emit its object, capture this summary, and +// normally release its Program and LLVM context before whole-program linking. +// Deadcode-drop builds temporarily retain isolated Programs because method DCE +// still reads package modules and exports; they are released after all links. +// +// C archive/shared header declarations still consume LPkg and therefore stay +// on the serial compatibility path. +type PackageSummary struct { + ID string + PkgPath string + Name string + + LinkArgs []string + ArchiveFile string + NeedRuntime bool + NeedPyInit bool + + NeedAbiInit int + MethodByIndex []int + MethodByName []string + GlobalSymbols []string + + FuncInfo []funcInfoRecord + PCLineInfo []pcLineRecord + FuncInfoStubs []string + CSharedExports []string + AbiTypes []llssa.AbiTypeInfo +} + +type packageSummaryMetadata struct { + NeedAbiInit int `yaml:"need_abi_init,omitempty"` + MethodByIndex []int `yaml:"method_by_index,omitempty"` + MethodByName []string `yaml:"method_by_name,omitempty"` + GlobalSymbols []string `yaml:"global_symbols,omitempty"` + + FuncInfo []funcInfoMetadata `yaml:"func_info,omitempty"` + PCLineInfo []pcLineMetadata `yaml:"pcline_info,omitempty"` + FuncInfoStubs []string `yaml:"func_info_stubs,omitempty"` + CSharedExports []string `yaml:"c_shared_exports,omitempty"` +} + +type funcInfoMetadata struct { + Symbol string `yaml:"symbol"` + Name string `yaml:"name,omitempty"` + File string `yaml:"file,omitempty"` + Line uint32 `yaml:"line,omitempty"` + Column uint32 `yaml:"column,omitempty"` +} + +type pcLineMetadata struct { + ID uint64 `yaml:"id"` + Symbol string `yaml:"symbol"` + File string `yaml:"file,omitempty"` + Line uint32 `yaml:"line,omitempty"` + Column uint32 `yaml:"column,omitempty"` +} + +func summarizePackage(pkg *aPackage) *PackageSummary { + if pkg == nil { + return nil + } + summary := &PackageSummary{ + LinkArgs: append([]string(nil), pkg.LinkArgs...), + ArchiveFile: pkg.ArchiveFile, + NeedRuntime: pkg.NeedRt, + NeedPyInit: pkg.NeedPyInit, + } + if pkg.Package != nil { + summary.ID = pkg.ID + summary.PkgPath = pkg.PkgPath + summary.Name = pkg.Name + } + if pkg.LPkg == nil { + return summary + } + + lpkg := pkg.LPkg + if summary.PkgPath == "" { + summary.PkgPath = lpkg.Path() + } + summary.NeedAbiInit = lpkg.NeedAbiInit + for method := range lpkg.MethodByIndex { + summary.MethodByIndex = append(summary.MethodByIndex, method) + } + sort.Ints(summary.MethodByIndex) + for method := range lpkg.MethodByName { + summary.MethodByName = append(summary.MethodByName, method) + } + sort.Strings(summary.MethodByName) + + mod := lpkg.Module() + for global := mod.FirstGlobal(); !global.IsNil(); global = llvm.NextGlobal(global) { + if !global.IsDeclaration() { + summary.GlobalSymbols = append(summary.GlobalSymbols, global.Name()) + } + } + sort.Strings(summary.GlobalSymbols) + summary.FuncInfo = readFuncInfo(mod) + summary.PCLineInfo = readPCLineInfo(mod) + summary.AbiTypes = lpkg.Prog.AbiTypes() + for fn := mod.FirstFunction(); !fn.IsNil(); fn = llvm.NextFunction(fn) { + if fn.IsDeclaration() || fn.BasicBlocksCount() == 0 { + continue + } + if _, ok := strings.CutPrefix(fn.Name(), closureStubPrefix); ok { + summary.FuncInfoStubs = append(summary.FuncInfoStubs, fn.Name()) + } + } + sort.Strings(summary.FuncInfoStubs) + for _, name := range lpkg.ExportFuncs() { + if name != "" { + summary.CSharedExports = append(summary.CSharedExports, name) + } + } + sort.Strings(summary.CSharedExports) + return summary +} + +func (s *PackageSummary) metadata() *packageSummaryMetadata { + if s == nil { + return nil + } + meta := &packageSummaryMetadata{ + NeedAbiInit: s.NeedAbiInit, + MethodByIndex: append([]int(nil), s.MethodByIndex...), + MethodByName: append([]string(nil), s.MethodByName...), + GlobalSymbols: append([]string(nil), s.GlobalSymbols...), + FuncInfoStubs: append([]string(nil), s.FuncInfoStubs...), + CSharedExports: append([]string(nil), s.CSharedExports...), + } + for _, rec := range s.FuncInfo { + meta.FuncInfo = append(meta.FuncInfo, funcInfoMetadata{ + Symbol: rec.symbol, + Name: rec.name, + File: rec.file, + Line: rec.line, + Column: rec.column, + }) + } + for _, rec := range s.PCLineInfo { + meta.PCLineInfo = append(meta.PCLineInfo, pcLineMetadata{ + ID: rec.id, + Symbol: rec.symbol, + File: rec.file, + Line: rec.line, + Column: rec.column, + }) + } + return meta +} + +func summaryFromMetadata(pkg *aPackage, meta *cacheArchiveMetadata) *PackageSummary { + if pkg == nil || pkg.Package == nil || meta == nil || meta.Summary == nil { + return nil + } + summary := &PackageSummary{ + ID: pkg.ID, + PkgPath: pkg.PkgPath, + Name: pkg.Name, + LinkArgs: append([]string(nil), pkg.LinkArgs...), + ArchiveFile: pkg.ArchiveFile, + NeedRuntime: pkg.NeedRt, + NeedPyInit: pkg.NeedPyInit, + NeedAbiInit: meta.Summary.NeedAbiInit, + MethodByIndex: append([]int(nil), meta.Summary.MethodByIndex...), + MethodByName: append([]string(nil), meta.Summary.MethodByName...), + GlobalSymbols: append([]string(nil), meta.Summary.GlobalSymbols...), + FuncInfoStubs: append([]string(nil), meta.Summary.FuncInfoStubs...), + CSharedExports: append([]string(nil), meta.Summary.CSharedExports...), + } + for _, rec := range meta.Summary.FuncInfo { + summary.FuncInfo = append(summary.FuncInfo, funcInfoRecord{ + symbol: rec.Symbol, + name: rec.Name, + file: rec.File, + line: rec.Line, + column: rec.Column, + }) + } + for _, rec := range meta.Summary.PCLineInfo { + summary.PCLineInfo = append(summary.PCLineInfo, pcLineRecord{ + id: rec.ID, + symbol: rec.Symbol, + file: rec.File, + line: rec.Line, + column: rec.Column, + }) + } + return summary +} + +func summariesForPackages(pkgs []Package) []*PackageSummary { + summaries := make([]*PackageSummary, 0, len(pkgs)) + for _, pkg := range pkgs { + if pkg == nil { + continue + } + summary := pkg.Summary + if summary == nil { + summary = summarizePackage(pkg) + } + if summary != nil { + summaries = append(summaries, summary) + } + } + return summaries +} + +func abiTypesForSummaries(summaries []*PackageSummary) []llssa.AbiTypeInfo { + byName := make(map[string]llssa.AbiTypeInfo) + for _, summary := range summaries { + if summary == nil { + continue + } + for _, info := range summary.AbiTypes { + if info.Name == "" || info.Raw == nil { + continue + } + if _, ok := byName[info.Name]; !ok { + byName[info.Name] = info + } + } + } + names := make([]string, 0, len(byName)) + for name := range byName { + names = append(names, name) + } + sort.Strings(names) + ret := make([]llssa.AbiTypeInfo, 0, len(names)) + for _, name := range names { + ret = append(ret, byName[name]) + } + return ret +} diff --git a/internal/build/package_summary_test.go b/internal/build/package_summary_test.go new file mode 100644 index 0000000000..7357df8647 --- /dev/null +++ b/internal/build/package_summary_test.go @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "go/types" + "reflect" + "testing" + + "github.com/xgo-dev/llvm" + + "github.com/goplus/llgo/internal/packages" + llssa "github.com/goplus/llgo/ssa" +) + +func TestPackageSummaryCapturesLinkerFacts(t *testing.T) { + prog := llssa.NewProgram(nil) + defer prog.Dispose() + lpkg := prog.NewPackage("p", "example.com/p") + lpkg.NeedAbiInit = 3 + lpkg.RecordReflectMethodByIndex("example.com/p.Method", 4) + lpkg.RecordReflectMethodByIndex("example.com/p.Method", 1) + lpkg.RecordReflectMethodByName("example.com/p.MethodByName", "B") + lpkg.RecordReflectMethodByName("example.com/p.MethodByName", "A") + lpkg.SetExport("example.com/p.Export", "Export") + lpkg.EmitFuncInfo("example.com/p.live", "example.com/p.Live", "p.go", 17, 2) + lpkg.EmitPCLineInfo(42, "example.com/p.live", "p.go", 18, 3) + lpkg.NewFunc(closureStubPrefix+"example.com/p.live", llssa.NoArgsNoRet, llssa.InGo).MakeBody(1).Return() + + i32 := lpkg.Module().Context().Int32Type() + defined := llvm.AddGlobal(lpkg.Module(), i32, "example.com/p.defined") + defined.SetInitializer(llvm.ConstInt(i32, 1, false)) + llvm.AddGlobal(lpkg.Module(), i32, "example.com/p.declared") + + pkg := &aPackage{ + Package: &packages.Package{ + ID: "example.com/p", + PkgPath: "example.com/p", + Name: "p", + Types: types.NewPackage("example.com/p", "p"), + }, + LPkg: lpkg, + NeedRt: true, + NeedPyInit: true, + LinkArgs: []string{"-lp"}, + ArchiveFile: "p.a", + } + summary := summarizePackage(pkg) + if got, want := summary.MethodByIndex, []int{1, 4}; !reflect.DeepEqual(got, want) { + t.Fatalf("MethodByIndex = %v, want %v", got, want) + } + if got, want := summary.MethodByName, []string{"A", "B"}; !reflect.DeepEqual(got, want) { + t.Fatalf("MethodByName = %v, want %v", got, want) + } + if got, want := summary.GlobalSymbols, []string{"example.com/p.defined"}; !reflect.DeepEqual(got, want) { + t.Fatalf("GlobalSymbols = %v, want %v", got, want) + } + if got, want := summary.FuncInfoStubs, []string{closureStubPrefix + "example.com/p.live"}; !reflect.DeepEqual(got, want) { + t.Fatalf("FuncInfoStubs = %v, want %v", got, want) + } + if got := collectFuncInfoSummaries([]*PackageSummary{summary}); len(got) != 1 || got[0].symbol != "example.com/p.live" { + t.Fatalf("func info from summary = %+v, want live record", got) + } + if got := linkedPackageGlobals([]*PackageSummary{summary}); len(got) != 1 { + t.Fatalf("globals from summary = %#v, want one defined global", got) + } + + loadedPkg := &aPackage{ + Package: pkg.Package, + LinkArgs: []string{"-lp"}, + ArchiveFile: "p.a", + NeedRt: true, + NeedPyInit: true, + } + loaded := summaryFromMetadata(loadedPkg, &cacheArchiveMetadata{Summary: summary.metadata()}) + if !reflect.DeepEqual(loaded, summary) { + t.Fatalf("cache summary round trip = %#v, want %#v", loaded, summary) + } +} + +func TestPackageSummaryEmptyInputs(t *testing.T) { + if got := summarizePackage(nil); got != nil { + t.Fatalf("summarizePackage(nil) = %#v", got) + } + var summary *PackageSummary + if got := summary.metadata(); got != nil { + t.Fatalf("nil summary metadata = %#v", got) + } + if got := summaryFromMetadata(nil, nil); got != nil { + t.Fatalf("summaryFromMetadata(nil, nil) = %#v", got) + } + if got := linkedPackageGlobals(nil); got != nil { + t.Fatalf("linkedPackageGlobals(nil) = %#v", got) + } + if got := linkedPackageGlobals([]*PackageSummary{nil}); len(got) != 0 { + t.Fatalf("linkedPackageGlobals([nil]) = %#v", got) + } + if got := collectFuncInfoSummaries([]*PackageSummary{nil, {FuncInfo: []funcInfoRecord{{}}}}); got != nil { + t.Fatalf("collectFuncInfoSummaries(empty) = %#v", got) + } + if got := collectPCLineInfoSummaries([]*PackageSummary{nil, {PCLineInfo: []pcLineRecord{{}}}}); len(got) != 0 { + t.Fatalf("collectPCLineInfoSummaries(empty) = %#v", got) + } + if got := collectFuncInfoStubRecordsSummaries([]*PackageSummary{nil}, nil); got != nil { + t.Fatalf("collectFuncInfoStubRecordsSummaries(nil) = %#v", got) + } + if got := collectFuncInfoStubRecordsSummaries([]*PackageSummary{nil}, []funcInfoRecord{{symbol: "target"}}); len(got) != 0 { + t.Fatalf("collectFuncInfoStubRecordsSummaries([nil]) = %#v", got) + } + sharedCtx := &context{buildConf: &Config{BuildMode: BuildModeCShared}} + if got := cSharedExportArgsSummaries(sharedCtx, []*PackageSummary{nil}); len(got) != 0 { + t.Fatalf("cSharedExportArgsSummaries([nil]) = %#v", got) + } +} + +func TestAbiTypesForSummariesDeduplicatesBySymbol(t *testing.T) { + first := llssa.AbiTypeInfo{Name: "_llgo_int", Raw: types.Typ[types.Int]} + second := llssa.AbiTypeInfo{Name: "_llgo_string", Raw: types.Typ[types.String]} + got := abiTypesForSummaries([]*PackageSummary{ + nil, + {AbiTypes: []llssa.AbiTypeInfo{second, first}}, + {AbiTypes: []llssa.AbiTypeInfo{first, {}}}, + }) + want := []llssa.AbiTypeInfo{first, second} + if !reflect.DeepEqual(got, want) { + t.Fatalf("ABI types = %#v, want %#v", got, want) + } +} diff --git a/internal/build/plan9asm.go b/internal/build/plan9asm.go index 30077f5f72..6f7703b67f 100644 --- a/internal/build/plan9asm.go +++ b/internal/build/plan9asm.go @@ -8,7 +8,6 @@ import ( "os/exec" "path/filepath" "strings" - "sync" llabi "github.com/goplus/llgo/internal/abi" "github.com/goplus/llgo/internal/cabi" @@ -166,13 +165,6 @@ func shouldSkipDarwinDynimportTrampolineAsm(enabled bool, sfile string, src []by bytes.Contains(src, []byte("_trampoline_addr(SB)")) } -type plan9AsmSigCacheKey struct { - ctx *context - pkgPath string -} - -var plan9AsmSigCache sync.Map // key: plan9AsmSigCacheKey, value: map[string]struct{} - func archSupportsPlan9AsmDefaults(goarch string) bool { return goarch == "arm64" || goarch == "amd64" } @@ -225,18 +217,20 @@ func plan9asmSigsForPkg(ctx *context, pkgPath string) (map[string]struct{}, erro if ctx == nil || pkgPath == "" { return nil, nil } - key := plan9AsmSigCacheKey{ctx: ctx, pkgPath: pkgPath} - if v, ok := plan9AsmSigCache.Load(key); ok { - return v.(map[string]struct{}), nil + if ctx.plan9asmSigs == nil { + ctx.plan9asmSigs = make(map[string]map[string]struct{}) + } + if sigs, ok := ctx.plan9asmSigs[pkgPath]; ok { + return sigs, nil } sigs := make(map[string]struct{}) if !ctx.plan9asmEnabled(pkgPath) { - plan9AsmSigCache.Store(key, sigs) + ctx.plan9asmSigs[pkgPath] = sigs return sigs, nil } - if hasAltPkgForTarget(ctx.buildConf, pkgPath) && !llruntime.HasAdditiveAltPkgForGOARCH(pkgPath, ctx.buildConf.Goarch) { - plan9AsmSigCache.Store(key, sigs) + if ctx.hasAltPkgWithResolvedPlan9(pkgPath) && !llruntime.HasAdditiveAltPkgForGOARCH(pkgPath, ctx.buildConf.Goarch) { + ctx.plan9asmSigs[pkgPath] = sigs return sigs, nil } @@ -248,7 +242,7 @@ func plan9asmSigsForPkg(ctx *context, pkgPath string) (map[string]struct{}, erro } } if pkg == nil { - plan9AsmSigCache.Store(key, sigs) + ctx.plan9asmSigs[pkgPath] = sigs return sigs, nil } @@ -272,7 +266,7 @@ func plan9asmSigsForPkg(ctx *context, pkgPath string) (map[string]struct{}, erro sigs[name] = struct{}{} } } - plan9AsmSigCache.Store(key, sigs) + ctx.plan9asmSigs[pkgPath] = sigs return sigs, nil } @@ -306,19 +300,22 @@ func cabiSkipFuncsForPlan9Asm(ctx *context, pkgPath string, mod gllvm.Module) [] } func (ctx *context) plan9asmEnabled(pkgPath string) bool { - ctx.plan9asmOnce.Do(func() { - cfg := parsePlan9AsmPkgsEnv(Plan9ASMPkgs()) - ctx.plan9asmMode = cfg.mode - switch cfg.mode { - case plan9asmEnvSelected: - ctx.plan9asmPkgs = make(map[string]bool, len(cfg.pkgs)) - for p := range cfg.pkgs { - ctx.plan9asmPkgs[p] = true + if !ctx.plan9asmReady { + ctx.plan9asmOnce.Do(func() { + cfg := parsePlan9AsmPkgsEnv(Plan9ASMPkgs()) + ctx.plan9asmMode = cfg.mode + switch cfg.mode { + case plan9asmEnvSelected: + ctx.plan9asmPkgs = make(map[string]bool, len(cfg.pkgs)) + for p := range cfg.pkgs { + ctx.plan9asmPkgs[p] = true + } + default: + ctx.plan9asmPkgs = make(map[string]bool) } - default: - ctx.plan9asmPkgs = make(map[string]bool) - } - }) + ctx.plan9asmReady = true + }) + } switch ctx.plan9asmMode { case plan9asmEnvAll: @@ -334,6 +331,30 @@ func (ctx *context) plan9asmEnabled(pkgPath string) bool { } } +func (ctx *context) hasAltPkgWithResolvedPlan9(pkgPath string) bool { + conf := ctx.buildConf + if conf == nil || !llruntime.HasAltPkgForGOARCH(pkgPath, conf.Goarch) { + return false + } + if llruntime.HasAdditiveAltPkgForGOARCH(pkgPath, conf.Goarch) { + return true + } + if plan9asmEnabledByDefault(conf, pkgPath) && ctx.plan9asmMode != plan9asmEnvNone { + return false + } + if conf.AbiMode != cabi.ModeAllFunc { + switch ctx.plan9asmMode { + case plan9asmEnvAll: + return false + case plan9asmEnvSelected: + if ctx.plan9asmPkgs[pkgPath] { + return false + } + } + } + return true +} + func hasAltPkgForTarget(conf *Config, pkgPath string) bool { if conf == nil || !llruntime.HasAltPkgForGOARCH(pkgPath, conf.Goarch) { return false @@ -379,26 +400,32 @@ func pkgSFiles(ctx *context, pkg *packages.Package) ([]string, error) { if pkg == nil || pkg.PkgPath == "" { return nil, nil } + if ctx.sfilesCache == nil { + if ctx.sfilesFrozen { + return nil, fmt.Errorf("package %s assembly files were not prepared before backend execution", pkg.PkgPath) + } + ctx.sfilesCache = make(map[string][]string) + } + if v, ok := ctx.sfilesCache[pkg.ID]; ok { + return v, nil + } // Some unit tests construct synthetic packages that are not loadable via // `go list` (PkgPath not in any module, and Dir/Standard/Goroot unset). // In that case, treat the package as having no selected .s files. if pkg.Dir == "" { + ctx.sfilesCache[pkg.ID] = nil return nil, nil } // Fast path: if directory has no .s/.S at all, skip `go list`. - if pkg.Dir != "" { - if ss, _ := filepath.Glob(filepath.Join(pkg.Dir, "*.s")); len(ss) == 0 { - if ss, _ := filepath.Glob(filepath.Join(pkg.Dir, "*.S")); len(ss) == 0 { - return nil, nil - } + if ss, _ := filepath.Glob(filepath.Join(pkg.Dir, "*.s")); len(ss) == 0 { + if ss, _ := filepath.Glob(filepath.Join(pkg.Dir, "*.S")); len(ss) == 0 { + ctx.sfilesCache[pkg.ID] = nil + return nil, nil } } - if ctx.sfilesCache == nil { - ctx.sfilesCache = make(map[string][]string) - } - if v, ok := ctx.sfilesCache[pkg.ID]; ok { - return v, nil + if ctx.sfilesFrozen { + return nil, fmt.Errorf("package %s assembly files were not prepared before backend execution", pkg.PkgPath) } args := []string{"list", "-json"} diff --git a/internal/build/plan9asm_env_test.go b/internal/build/plan9asm_env_test.go new file mode 100644 index 0000000000..8a427741ae --- /dev/null +++ b/internal/build/plan9asm_env_test.go @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package build + +import ( + "testing" + + "github.com/goplus/llgo/internal/cabi" + "golang.org/x/tools/go/packages" +) + +func TestParsePlan9AsmPkgsEnv(t *testing.T) { + tests := []struct { + raw string + mode plan9asmPkgsEnvMode + pkgs map[string]bool + }{ + {raw: "", mode: plan9asmEnvDefaults}, + {raw: " off ", mode: plan9asmEnvNone}, + {raw: "FALSE", mode: plan9asmEnvNone}, + {raw: "*", mode: plan9asmEnvAll}, + {raw: "On", mode: plan9asmEnvAll}, + {raw: "runtime, net ; crypto\t net\n", mode: plan9asmEnvSelected, pkgs: map[string]bool{"runtime": true, "net": true, "crypto": true}}, + } + for _, tt := range tests { + got := parsePlan9AsmPkgsEnv(tt.raw) + if got.mode != tt.mode { + t.Fatalf("parsePlan9AsmPkgsEnv(%q).mode = %v, want %v", tt.raw, got.mode, tt.mode) + } + if len(got.pkgs) != len(tt.pkgs) { + t.Fatalf("parsePlan9AsmPkgsEnv(%q).pkgs = %v, want %v", tt.raw, got.pkgs, tt.pkgs) + } + for pkg := range tt.pkgs { + if !got.pkgs[pkg] { + t.Fatalf("parsePlan9AsmPkgsEnv(%q) did not retain %q", tt.raw, pkg) + } + } + } +} + +func TestPlan9AsmEnvironmentHelpers(t *testing.T) { + t.Setenv(llgoPlan9ASMPkgs, "off") + if !plan9asmDisabledByEnv() { + t.Fatal("plan9asmDisabledByEnv = false, want true") + } + if plan9asmEnabledByEnv("runtime") { + t.Fatal("plan9asmEnabledByEnv(runtime) = true with disabled environment") + } + + t.Setenv(llgoPlan9ASMPkgs, "runtime") + if plan9asmDisabledByEnv() { + t.Fatal("plan9asmDisabledByEnv = true for selected package") + } + if !plan9asmEnabledByEnv("runtime") { + t.Fatal("plan9asmEnabledByEnv(runtime) = false, want true") + } + if plan9asmEnabledByEnv("reflect") { + t.Fatal("plan9asmEnabledByEnv(reflect) = true, want false") + } + + t.Setenv(llgoPlan9ASMPkgs, "all") + if !plan9asmEnabledByEnv("example.com/pkg") { + t.Fatal("plan9asmEnabledByEnv(example.com/pkg) = false with all enabled") + } +} + +func TestPlan9AsmSignatureCacheBoundaries(t *testing.T) { + if got, err := plan9asmSigsForPkg(nil, "runtime"); err != nil || got != nil { + t.Fatalf("plan9asmSigsForPkg(nil) = (%v, %v), want (nil, nil)", got, err) + } + + disabled := &context{ + buildConf: &Config{Goarch: "amd64"}, + plan9asmReady: true, + plan9asmMode: plan9asmEnvNone, + } + got, err := plan9asmSigsForPkg(disabled, "runtime") + if err != nil || len(got) != 0 { + t.Fatalf("disabled plan9asmSigsForPkg = (%v, %v), want empty signatures", got, err) + } + if cached := disabled.plan9asmSigs["runtime"]; cached == nil { + t.Fatal("disabled package signatures were not cached") + } + if again, err := plan9asmSigsForPkg(disabled, "runtime"); err != nil || len(again) != 0 { + t.Fatalf("cached plan9asmSigsForPkg = (%v, %v), want empty signatures", again, err) + } + + missing := &context{ + buildConf: &Config{Goarch: "amd64"}, + plan9asmReady: true, + plan9asmMode: plan9asmEnvAll, + } + got, err = plan9asmSigsForPkg(missing, "example.com/missing") + if err != nil || len(got) != 0 { + t.Fatalf("missing package plan9asmSigsForPkg = (%v, %v), want empty signatures", got, err) + } + if (&context{}).hasAltPkgWithResolvedPlan9("runtime") { + t.Fatal("context without a build configuration resolved an alternate package") + } + + resolvedAlt := &context{ + buildConf: &Config{Goarch: "amd64", AbiMode: cabi.ModeAllFunc}, + plan9asmReady: true, + plan9asmMode: plan9asmEnvAll, + } + got, err = plan9asmSigsForPkg(resolvedAlt, "runtime") + if err != nil || len(got) != 0 { + t.Fatalf("alternate package plan9asmSigsForPkg = (%v, %v), want empty signatures", got, err) + } +} + +func TestPlan9AsmPolicyBoundaries(t *testing.T) { + additive := &context{buildConf: &Config{Goarch: "amd64", AbiMode: cabi.ModeAllFunc}} + if !additive.hasAltPkgWithResolvedPlan9("internal/runtime/sys") { + t.Fatal("additive alternate package was not resolved") + } + + replacement := &context{buildConf: &Config{Goarch: "amd64", AbiMode: cabi.ModeAllFunc}} + if !replacement.hasAltPkgWithResolvedPlan9("runtime") { + t.Fatal("replacement alternate package was not resolved in all-function ABI mode") + } + + nonAll := &context{ + buildConf: &Config{Goarch: "amd64"}, + plan9asmMode: plan9asmEnvAll, + } + if nonAll.hasAltPkgWithResolvedPlan9("runtime") { + t.Fatal("explicit all Plan9 asm policy retained the replacement package") + } + nonAll.plan9asmMode = plan9asmEnvSelected + nonAll.plan9asmPkgs = map[string]bool{"runtime": true} + if nonAll.hasAltPkgWithResolvedPlan9("runtime") { + t.Fatal("selected Plan9 asm policy retained the replacement package") + } + nonAll.plan9asmPkgs = nil + if !nonAll.hasAltPkgWithResolvedPlan9("runtime") { + t.Fatal("unselected Plan9 asm policy did not resolve the replacement package") + } + + t.Setenv(llgoPlan9ASMPkgs, "runtime") + selected := &context{buildConf: &Config{Goarch: "amd64"}} + if !selected.plan9asmEnabled("runtime") || selected.plan9asmEnabled("reflect") { + t.Fatal("selected Plan9 asm policy was not initialized from the environment") + } + + frozen := &context{sfilesFrozen: true} + if _, err := pkgSFiles(frozen, &packages.Package{ID: "p", PkgPath: "example.com/p"}); err == nil { + t.Fatal("frozen assembly file cache accepted an unprepared package") + } +} diff --git a/internal/dcepass/dcepass.go b/internal/dcepass/dcepass.go index db37db6725..ccbbd8c157 100644 --- a/internal/dcepass/dcepass.go +++ b/internal/dcepass/dcepass.go @@ -41,10 +41,15 @@ func EmitStrongTypeOverrides(dst llvm.Module, srcMods []llvm.Module, liveSlots m type overrideEmitter struct { dst llvm.Module values map[llvm.Value]llvm.Value + types map[llvm.Type]llvm.Type } func newOverrideEmitter(dst llvm.Module) *overrideEmitter { - return &overrideEmitter{dst: dst, values: make(map[llvm.Value]llvm.Value)} + return &overrideEmitter{ + dst: dst, + values: make(map[llvm.Value]llvm.Value), + types: make(map[llvm.Type]llvm.Type), + } } func (e *overrideEmitter) emitTypeOverride(srcType, methodsVal llvm.Value, elemTy llvm.Type, keepIdx map[int]bool, verbose bool) { @@ -59,6 +64,7 @@ func (e *overrideEmitter) emitTypeOverride(srcType, methodsVal llvm.Value, elemT } unreachableMethod := e.unreachableMethod() + dstElemTy := e.cloneType(elemTy) methods := make([]llvm.Value, methodsVal.OperandsCount()) for i := range methods { orig := methodsVal.Operand(i) @@ -71,16 +77,16 @@ func (e *overrideEmitter) emitTypeOverride(srcType, methodsVal llvm.Value, elemT } name := e.cloneConst(orig.Operand(0)) mtype := e.cloneConst(orig.Operand(1)) - methods[i] = llvm.ConstNamedStruct(elemTy, []llvm.Value{ + methods[i] = llvm.ConstNamedStruct(dstElemTy, []llvm.Value{ name, mtype, unreachableMethod, unreachableMethod, }) } - fields[fieldCount-1] = llvm.ConstArray(elemTy, methods) + fields[fieldCount-1] = llvm.ConstArray(dstElemTy, methods) - dstType.SetInitializer(constStructOfType(init.Type(), fields)) + dstType.SetInitializer(constStructOfType(e.cloneType(init.Type()), fields)) dstType.SetGlobalConstant(true) dstType.SetLinkage(llvm.ExternalLinkage) copyGlobalAttrs(dstType, srcType) @@ -99,7 +105,7 @@ func (e *overrideEmitter) ensureOverrideGlobal(src llvm.Value) llvm.Value { name := src.Name() dst := e.dst.NamedGlobal(name) if dst.IsNil() { - dst = llvm.AddGlobal(e.dst, src.GlobalValueType(), name) + dst = llvm.AddGlobal(e.dst, e.cloneType(src.GlobalValueType()), name) } e.values[src] = dst return dst @@ -112,12 +118,142 @@ func (e *overrideEmitter) cloneConst(v llvm.Value) llvm.Value { if gv := v.IsAGlobalValue(); !gv.IsNil() { return e.cloneGlobalValue(gv) } + dstTy := e.cloneType(v.Type()) + if v.IsNull() || !v.IsAConstantAggregateZero().IsNil() { + return llvm.ConstNull(dstTy) + } + if !v.IsAUndefValue().IsNil() { + return llvm.Undef(dstTy) + } + if !v.IsAConstantInt().IsNil() { + return llvm.ConstInt(dstTy, v.ZExtValue(), false) + } + if !v.IsAConstantFP().IsNil() { + value, _ := v.DoubleValue() + return llvm.ConstFloat(dstTy, value) + } + if v.IsConstantString() { + return e.dst.Context().ConstString(v.ConstGetAsString(), false) + } if !v.IsAConstantStruct().IsNil() { - clone := constStructOfType(v.Type(), e.cloneOperands(v)) + clone := constStructOfType(dstTy, e.cloneOperands(v)) + e.values[v] = clone + return clone + } + if !v.IsAConstantArray().IsNil() { + clone := llvm.ConstArray(dstTy.ElementType(), e.cloneOperands(v)) + e.values[v] = clone + return clone + } + if !v.IsAConstantVector().IsNil() { + clone := llvm.ConstVector(e.cloneOperands(v), false) e.values[v] = clone return clone } - return v + if !v.IsAConstantExpr().IsNil() { + return e.cloneConstExpr(v, dstTy) + } + panic(fmt.Sprintf("dcepass: unsupported constant %s", v.String())) +} + +func (e *overrideEmitter) cloneConstExpr(v llvm.Value, dstTy llvm.Type) llvm.Value { + ops := e.cloneOperands(v) + var clone llvm.Value + switch v.Opcode() { + case llvm.GetElementPtr: + clone = llvm.ConstGEP(e.cloneType(v.GEPSourceElementType()), ops[0], ops[1:]) + case llvm.BitCast: + clone = llvm.ConstBitCast(ops[0], dstTy) + case llvm.IntToPtr: + clone = llvm.ConstIntToPtr(ops[0], dstTy) + case llvm.PtrToInt: + clone = llvm.ConstPtrToInt(ops[0], dstTy) + case llvm.Trunc: + clone = llvm.ConstTrunc(ops[0], dstTy) + case llvm.Add: + clone = llvm.ConstAdd(ops[0], ops[1]) + case llvm.Sub: + clone = llvm.ConstSub(ops[0], ops[1]) + case llvm.Xor: + clone = llvm.ConstXor(ops[0], ops[1]) + default: + panic(fmt.Sprintf("dcepass: unsupported constant expression %s", v.String())) + } + e.values[v] = clone + return clone +} + +// cloneType re-interns an LLVM type in the destination module's Context. +// Returning a source-context type is invalid even when its printed spelling is +// identical; LLVM otherwise permits malformed mixed-context constants that +// fail verification and can crash while either Context is disposed. +func (e *overrideEmitter) cloneType(src llvm.Type) llvm.Type { + if dst, ok := e.types[src]; ok { + return dst + } + ctx := e.dst.Context() + var dst llvm.Type + switch src.TypeKind() { + case llvm.VoidTypeKind: + dst = ctx.VoidType() + case llvm.FloatTypeKind: + dst = ctx.FloatType() + case llvm.DoubleTypeKind: + dst = ctx.DoubleType() + case llvm.X86_FP80TypeKind: + dst = ctx.X86FP80Type() + case llvm.FP128TypeKind: + dst = ctx.FP128Type() + case llvm.PPC_FP128TypeKind: + dst = ctx.PPCFP128Type() + case llvm.LabelTypeKind: + dst = ctx.LabelType() + case llvm.IntegerTypeKind: + dst = ctx.IntType(src.IntTypeWidth()) + case llvm.FunctionTypeKind: + params := src.ParamTypes() + for i := range params { + params[i] = e.cloneType(params[i]) + } + dst = llvm.FunctionType(e.cloneType(src.ReturnType()), params, src.IsFunctionVarArg()) + case llvm.StructTypeKind: + name := src.StructName() + if name != "" { + dst = e.dst.GetTypeByName(name) + if dst.IsNil() { + dst = ctx.StructCreateNamed(name) + } + e.types[src] = dst + if dst.StructElementTypesCount() == 0 && src.StructElementTypesCount() != 0 { + dst.StructSetBody(e.cloneTypes(src.StructElementTypes()), src.IsStructPacked()) + } + return dst + } + dst = ctx.StructType(e.cloneTypes(src.StructElementTypes()), src.IsStructPacked()) + case llvm.ArrayTypeKind: + dst = llvm.ArrayType(e.cloneType(src.ElementType()), src.ArrayLength()) + case llvm.PointerTypeKind: + // LLVM uses opaque pointers; the element type only selects the Context. + dst = llvm.PointerType(ctx.Int8Type(), src.PointerAddressSpace()) + case llvm.VectorTypeKind: + dst = llvm.VectorType(e.cloneType(src.ElementType()), src.VectorSize()) + case llvm.MetadataTypeKind: + dst = ctx.MetadataType() + case llvm.TokenTypeKind: + dst = ctx.TokenType() + default: + panic(fmt.Sprintf("dcepass: unsupported LLVM type kind %d", src.TypeKind())) + } + e.types[src] = dst + return dst +} + +func (e *overrideEmitter) cloneTypes(src []llvm.Type) []llvm.Type { + dst := make([]llvm.Type, len(src)) + for i := range src { + dst[i] = e.cloneType(src[i]) + } + return dst } func (e *overrideEmitter) cloneOperands(v llvm.Value) []llvm.Value { @@ -136,7 +272,7 @@ func (e *overrideEmitter) cloneGlobalValue(v llvm.Value) llvm.Value { if fn := v.IsAFunction(); !fn.IsNil() { dstFn := e.dst.NamedFunction(fn.Name()) if dstFn.IsNil() { - dstFn = llvm.AddFunction(e.dst, fn.Name(), fn.GlobalValueType()) + dstFn = llvm.AddFunction(e.dst, fn.Name(), e.cloneType(fn.GlobalValueType())) } e.values[v] = dstFn return dstFn @@ -155,14 +291,14 @@ func (e *overrideEmitter) cloneGlobalVariable(src llvm.Value) llvm.Value { if name != "" && !isLocalLinkage(src.Linkage()) { dst := e.dst.NamedGlobal(name) if dst.IsNil() { - dst = llvm.AddGlobal(e.dst, src.GlobalValueType(), name) + dst = llvm.AddGlobal(e.dst, e.cloneType(src.GlobalValueType()), name) dst.SetLinkage(llvm.ExternalLinkage) } e.values[src] = dst return dst } - dst := llvm.AddGlobal(e.dst, src.GlobalValueType(), "") + dst := llvm.AddGlobal(e.dst, e.cloneType(src.GlobalValueType()), "") e.values[src] = dst copyGlobalAttrs(dst, src) dst.SetLinkage(src.Linkage()) @@ -212,8 +348,9 @@ func isLocalLinkage(linkage llvm.Linkage) bool { } func constStructOfType(typ llvm.Type, fields []llvm.Value) llvm.Value { - if typ.StructName() != "" { - return llvm.ConstNamedStruct(typ, fields) - } - return llvm.ConstStruct(fields, typ.IsStructPacked()) + // LLVMConstNamedStruct accepts both identified and literal struct types. Use + // the exact cloned type: LLVMConstStruct(InContext) may manufacture another + // structurally identical literal type that is not pointer-identical to a + // global's declared value type, which the verifier correctly rejects. + return llvm.ConstNamedStruct(typ, fields) } diff --git a/internal/dcepass/dcepass_test.go b/internal/dcepass/dcepass_test.go index c275804e30..ceb4e66aad 100644 --- a/internal/dcepass/dcepass_test.go +++ b/internal/dcepass/dcepass_test.go @@ -29,15 +29,25 @@ func TestEmitStrongTypeOverrides(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx := llvm.NewContext() - defer ctx.Dispose() + srcCtx := llvm.NewContext() + defer srcCtx.Dispose() + dstCtx := llvm.NewContext() + defer dstCtx.Dispose() dir := filepath.Join("testdata", tt.name) - src := parseModule(t, &ctx, filepath.Join(dir, "in.ll")) + src := parseModule(t, &srcCtx, filepath.Join(dir, "in.ll")) defer src.Dispose() - dst := ctx.NewModule("dst") + dst := dstCtx.NewModule("dst") defer dst.Dispose() EmitStrongTypeOverrides(dst, []llvm.Module{src}, tt.liveSlots, true) + for global := dst.FirstGlobal(); !global.IsNil(); global = llvm.NextGlobal(global) { + if init := global.Initializer(); !init.IsNil() && global.GlobalValueType().C != init.Type().C { + t.Errorf("global %s type %s does not match initializer type %s", global.Name(), global.GlobalValueType(), init.Type()) + } + } + if err := llvm.VerifyModule(dst, llvm.ReturnStatusAction); err != nil { + t.Fatalf("cross-context override is invalid: %v\n%s", err, dst.String()) + } want, err := os.ReadFile(filepath.Join(dir, "expect.ll")) if err != nil { t.Fatal(err) diff --git a/internal/dcepass/testdata/method_slots/expect.ll b/internal/dcepass/testdata/method_slots/expect.ll index b57057c77e..38a442cd59 100644 --- a/internal/dcepass/testdata/method_slots/expect.ll +++ b/internal/dcepass/testdata/method_slots/expect.ll @@ -9,7 +9,7 @@ source_filename = "dst" %"github.com/goplus/llgo/runtime/abi.Method" = type { %runtime.String, ptr, ptr, ptr } %"runtime/abi.PtrType" = type { %"runtime/abi.Type", ptr } %"runtime/abi.FuncType" = type { %"runtime/abi.Type", %runtime.Slice, %runtime.Slice } -%Task = type {} +%Task = type opaque @_llgo_main.Task = constant { %"runtime/abi.StructType", %"runtime/abi.UncommonType", [2 x %"github.com/goplus/llgo/runtime/abi.Method"] } { %"runtime/abi.StructType" { %"runtime/abi.Type" { i64 0, i64 0, i32 1, i8 13, i8 1, i8 1, i8 25, { ptr, ptr } { ptr @memequal0, ptr @_llgo_main.Task }, ptr null, %runtime.String { ptr @0, i64 9 }, ptr @"*_llgo_main.Task" }, %runtime.String zeroinitializer, %runtime.Slice zeroinitializer }, %"runtime/abi.UncommonType" { %runtime.String { ptr @1, i64 4 }, i16 2, i16 2, i32 24 }, [2 x %"github.com/goplus/llgo/runtime/abi.Method"] [%"github.com/goplus/llgo/runtime/abi.Method" { %runtime.String { ptr @2, i64 4 }, ptr @"_llgo_func$run", ptr @"github.com/goplus/llgo/runtime/internal/runtime.unreachableMethod", ptr @"github.com/goplus/llgo/runtime/internal/runtime.unreachableMethod" }, %"github.com/goplus/llgo/runtime/abi.Method" { %runtime.String { ptr @3, i64 3 }, ptr @"_llgo_func$run", ptr @"main.(*Task).Run", ptr @__llgo_stub.main.Task.Run }] }, align 8 @0 = private constant [9 x i8] c"main.Task", align 1 diff --git a/internal/typepatch/patch.go b/internal/typepatch/patch.go index 1f3cc12b00..020e9215e0 100644 --- a/internal/typepatch/patch.go +++ b/internal/typepatch/patch.go @@ -82,6 +82,13 @@ func Clone(alt *types.Package) *types.Package { func Merge(alt, pkg *types.Package, skips map[string]struct{}, skipall bool) { setPatched(pkg) + MergePrepared(alt, pkg, skips, skipall) +} + +// MergePrepared merges pkg into the cloned alternate package without +// modifying pkg. It is used by build preflight to publish an immutable patch +// type view before any LLVM backend starts. +func MergePrepared(alt, pkg *types.Package, skips map[string]struct{}, skipall bool) { if skipall { return } diff --git a/internal/typepatch/patch_test.go b/internal/typepatch/patch_test.go new file mode 100644 index 0000000000..bb0b2c700b --- /dev/null +++ b/internal/typepatch/patch_test.go @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026 The XGo Authors (xgo.dev). All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package typepatch + +import ( + "go/token" + "go/types" + "testing" +) + +func packageWithVars(path string, names ...string) *types.Package { + pkg := types.NewPackage(path, "p") + for _, name := range names { + pkg.Scope().Insert(types.NewVar(token.NoPos, pkg, name, types.Typ[types.Int])) + } + return pkg +} + +func TestMergePreparedDoesNotMarkOriginal(t *testing.T) { + original := packageWithVars("example.com/original", "Keep", "Skip") + merged := Clone(packageWithVars("example.com/alternate", "Alt")) + + MergePrepared(merged, original, map[string]struct{}{"Skip": {}}, false) + + for _, name := range []string{"Alt", "Keep"} { + if merged.Scope().Lookup(name) == nil { + t.Fatalf("merged package is missing %s", name) + } + } + if merged.Scope().Lookup("Skip") != nil { + t.Fatal("merged package retained skipped declaration") + } + if IsPatched(original) { + t.Fatal("MergePrepared marked the original package as patched") + } + if original.Scope().Lookup("Keep") == nil || original.Scope().Lookup("Skip") == nil { + t.Fatal("MergePrepared modified the original package scope") + } +} + +func TestMergePreparedSkipAll(t *testing.T) { + original := packageWithVars("example.com/original", "Keep") + merged := Clone(packageWithVars("example.com/alternate", "Alt")) + + MergePrepared(merged, original, nil, true) + + if merged.Scope().Lookup("Keep") != nil { + t.Fatal("skipall merged an original declaration") + } + if merged.Scope().Lookup("Alt") == nil { + t.Fatal("skipall removed an alternate declaration") + } +} + +func TestMergeMarksOriginal(t *testing.T) { + original := packageWithVars("example.com/original", "Keep") + merged := Clone(packageWithVars("example.com/alternate", "Alt")) + + Merge(merged, original, nil, false) + + if !IsPatched(original) { + t.Fatal("Merge did not mark the original package as patched") + } + if merged.Scope().Lookup("Keep") == nil { + t.Fatal("Merge did not include the original declaration") + } +} diff --git a/ssa/abitype.go b/ssa/abitype.go index 4cc1cb8c6d..75be21618a 100644 --- a/ssa/abitype.go +++ b/ssa/abitype.go @@ -458,6 +458,21 @@ func (b Builder) abiUncommonMethodSet(t types.Type) (mset *types.MethodSet, ok b return } +func abiUncommonMethodSetForDeclaration(t types.Type) (mset *types.MethodSet, ok bool) { + switch t := types.Unalias(t).(type) { + case *types.Named: + if _, isInterface := t.Underlying().(*types.Interface); isInterface { + return &types.MethodSet{}, true + } + return types.NewMethodSet(t), true + case *types.Struct, *types.Pointer: + if mset := types.NewMethodSet(t); mset.Len() != 0 { + return mset, true + } + } + return +} + /* type UncommonType struct { PkgPath_ string // import path; empty for built-in types like int, string @@ -672,6 +687,65 @@ func (b Builder) abiType(t types.Type) Expr { return ret } +// AbiTypes snapshots the runtime type descriptors materialized by this +// Program without retaining any LLVM-owned values. +func (p Program) AbiTypes() []AbiTypeInfo { + if len(p.abiSymbol) == 0 { + return nil + } + names := make([]string, 0, len(p.abiSymbol)) + for name := range p.abiSymbol { + names = append(names, name) + } + sort.Strings(names) + ret := make([]AbiTypeInfo, 0, len(names)) + for _, name := range names { + sym := p.abiSymbol[name] + ret = append(ret, AbiTypeInfo{Name: name, Raw: sym.Raw}) + } + return ret +} + +// RegisterAbiTypes declares runtime type descriptors owned by other Programs. +// It records only Go type identity and target-local LLVM types; descriptor +// definitions remain in the package modules that materialized them. +func (p Package) RegisterAbiTypes(infos []AbiTypeInfo) { + builder := &aBuilder{Prog: p.Prog, Pkg: p} + for _, info := range infos { + if info.Raw == nil { + continue + } + if _, ok := p.Prog.abiSymbol[info.Name]; ok { + continue + } + + t := info.Raw + mset, hasUncommon := abiUncommonMethodSetForDeclaration(t) + var methods []*types.Selection + if hasUncommon { + methods = builder.abiInterfaceMethods(mset) + } + rt := p.Prog.rtNamed(p.Prog.abi.RuntimeName(t)) + var typ types.Type = rt + if hasUncommon { + ut := p.Prog.rtNamed("uncommonType") + mt := p.Prog.rtNamed("Method") + typ = types.NewStruct([]*types.Var{ + types.NewVar(token.NoPos, nil, "T", rt), + types.NewVar(token.NoPos, nil, "U", ut), + types.NewVar(token.NoPos, nil, "M", types.NewArray(mt, int64(len(methods)))), + }, nil) + } + p.Prog.abiSymbol[info.Name] = &AbiSymbol{ + Name: info.Name, + PkgPath: p.Path(), + Raw: t, + Typ: p.Prog.Type(types.NewPointer(typ), InGo), + MSet: mset, + } + } +} + func (p Package) getAbiTypesFor(name string, filter func(sym *AbiSymbol) bool) Expr { prog := p.Prog var names []string diff --git a/ssa/locality.go b/ssa/locality.go index 0e9b41e6cd..cd3402b773 100644 --- a/ssa/locality.go +++ b/ssa/locality.go @@ -61,6 +61,17 @@ type localityInfos struct { parsedPackages map[*types.Package]struct{} } +// LocalityState is a copyable snapshot of the Go-side locality metadata owned +// by one Program. It contains no LLVM objects and can therefore be replayed +// safely into an independent backend Program. +type LocalityState struct { + entries map[string]VariableLocality + ownerlessEntries map[string]VariableLocality + declarationEntries map[string]map[string]VariableLocality + activePackages map[string]struct{} + parsedPackages map[*types.Package]struct{} +} + func newLocalityInfos() *localityInfos { return &localityInfos{ entries: make(map[string]VariableLocality), @@ -71,6 +82,64 @@ func newLocalityInfos() *localityInfos { } } +// SnapshotLocalityState returns an independent snapshot of p's locality +// metadata. Callers may use it after preflight has completed to seed isolated +// backend sessions without sharing mutable Program state. +func (p Program) SnapshotLocalityState() LocalityState { + p.localities.mu.RLock() + defer p.localities.mu.RUnlock() + state := LocalityState{ + entries: cloneLocalityEntries(p.localities.entries), + ownerlessEntries: cloneLocalityEntries(p.localities.ownerlessEntries), + activePackages: cloneLocalitySet(p.localities.activePackages), + parsedPackages: cloneParsedPackages(p.localities.parsedPackages), + } + state.declarationEntries = make(map[string]map[string]VariableLocality, len(p.localities.declarationEntries)) + for name, entries := range p.localities.declarationEntries { + state.declarationEntries[name] = cloneLocalityEntries(entries) + } + return state +} + +// RestoreLocalityState replaces p's locality metadata with an independent +// copy of state. The copied maps keep backend sessions independent. +func (p Program) RestoreLocalityState(state LocalityState) { + p.localities.mu.Lock() + p.localities.entries = cloneLocalityEntries(state.entries) + p.localities.ownerlessEntries = cloneLocalityEntries(state.ownerlessEntries) + p.localities.activePackages = cloneLocalitySet(state.activePackages) + p.localities.parsedPackages = cloneParsedPackages(state.parsedPackages) + p.localities.declarationEntries = make(map[string]map[string]VariableLocality, len(state.declarationEntries)) + for name, entries := range state.declarationEntries { + p.localities.declarationEntries[name] = cloneLocalityEntries(entries) + } + p.localities.mu.Unlock() +} + +func cloneLocalityEntries(entries map[string]VariableLocality) map[string]VariableLocality { + ret := make(map[string]VariableLocality, len(entries)) + for name, entry := range entries { + ret[name] = entry + } + return ret +} + +func cloneLocalitySet(entries map[string]struct{}) map[string]struct{} { + ret := make(map[string]struct{}, len(entries)) + for name := range entries { + ret[name] = struct{}{} + } + return ret +} + +func cloneParsedPackages(entries map[*types.Package]struct{}) map[*types.Package]struct{} { + ret := make(map[*types.Package]struct{}, len(entries)) + for pkg := range entries { + ret[pkg] = struct{}{} + } + return ret +} + func (p *localityInfos) update(name string, update func(*VariableLocality)) { p.mu.Lock() info := p.entries[name] diff --git a/ssa/locality_test.go b/ssa/locality_test.go index 1d6ad63cb5..b2a79f0ad1 100644 --- a/ssa/locality_test.go +++ b/ssa/locality_test.go @@ -63,6 +63,34 @@ func TestLocalityInfos(t *testing.T) { } } +func TestLocalityStateSnapshotIsIndependent(t *testing.T) { + source := NewProgram(nil) + defer source.Dispose() + pkg := types.NewPackage("example.com/p", "p") + name := "example.com/p.state" + source.DeclareLocality(pkg, "state", LocalityInfo{Locality: GoroutineLocal, HasInitializer: true}) + source.SetLocalStorageFor(pkg, name, LocalStoragePackage) + source.ActivateLocalitiesFor(pkg) + source.MarkPackageSyntaxParsed(pkg) + + dest := NewProgram(nil) + defer dest.Dispose() + dest.RestoreLocalityState(source.SnapshotLocalityState()) + got, ok := dest.VariableLocalityFor(pkg, name) + if !ok || got.Locality != GoroutineLocal || got.LocalStorage != LocalStoragePackage { + t.Fatalf("restored locality = %+v, %v", got, ok) + } + if !dest.NeedsLocalContext() || !dest.PackageSyntaxParsed(pkg) { + t.Fatal("restored locality state lost active or parsed metadata") + } + + source.SetLocalStorageFor(pkg, name, LocalStorageNativeTLS) + got, ok = dest.VariableLocalityFor(pkg, name) + if !ok || got.LocalStorage != LocalStoragePackage { + t.Fatalf("restored locality aliased source state: %+v, %v", got, ok) + } +} + func TestPackageLocalitiesRetainDeclarationOwners(t *testing.T) { prog := NewProgram(nil) std := types.NewPackage("runtime", "runtime") diff --git a/ssa/package.go b/ssa/package.go index db41bae4ab..535066bdae 100644 --- a/ssa/package.go +++ b/ssa/package.go @@ -254,6 +254,13 @@ type AbiSymbol struct { MSet *types.MethodSet } +// AbiTypeInfo is the LLVM-free identity needed to declare one runtime type +// descriptor in another Program. +type AbiTypeInfo struct { + Name string + Raw types.Type +} + // A Program presents a program. type Program = *aProgram diff --git a/ssa/ssa_test.go b/ssa/ssa_test.go index 36ba6b46e7..470cfc99d5 100644 --- a/ssa/ssa_test.go +++ b/ssa/ssa_test.go @@ -2845,6 +2845,57 @@ func TestInitAbiTypesForSubset(t *testing.T) { } } +func TestRegisterAbiTypesAcrossPrograms(t *testing.T) { + runtimePkg, err := importer.For("source", nil).Import(PkgRuntime) + if err != nil { + t.Fatal(err) + } + newProgram := func() Program { + prog := NewProgram(nil) + prog.sizes = types.SizesFor("gc", runtime.GOARCH) + prog.SetRuntime(runtimePkg) + return prog + } + + source := newProgram() + defer source.Dispose() + sourcePkg := source.NewPackage("source", "example.com/source") + sourceFn := sourcePkg.NewFunc("source", NoArgsNoRet, InC) + sourceBuilder := sourceFn.MakeBody(1) + sourceBuilder.abiType(types.NewSlice(types.Typ[types.Int])) + named := types.NewNamed( + types.NewTypeName(token.NoPos, types.NewPackage("example.com/source", "source"), "Named", nil), + types.NewStruct(nil, nil), + nil, + ) + sourceBuilder.abiType(named) + sourceBuilder.Return() + infos := source.AbiTypes() + if len(infos) == 0 { + t.Fatal("source Program produced no ABI type snapshot") + } + + target := newProgram() + defer target.Dispose() + targetPkg := target.NewPackage("target", "example.com/target") + targetPkg.RegisterAbiTypes(infos) + targetPkg.RegisterAbiTypes(append(infos, AbiTypeInfo{})) + for _, info := range infos { + if _, ok := target.abiSymbol[info.Name]; !ok { + t.Fatalf("target Program did not recreate ABI type %q", info.Name) + } + } + if targetPkg.InitAbiTypes("init$abitypes") == nil { + t.Fatal("recreated ABI types did not produce typelist initializer") + } + for _, info := range infos { + global := targetPkg.Module().NamedGlobal(info.Name) + if global.IsNil() || !global.IsDeclaration() { + t.Fatalf("target descriptor %q is not an external declaration", info.Name) + } + } +} + func TestInitAbiTypesForEmptySelection(t *testing.T) { prog := NewProgram(nil) pkg := prog.NewPackage("bar", "foo/bar") diff --git a/xtool/env/env.go b/xtool/env/env.go index 469b7e97f2..1c14c07121 100644 --- a/xtool/env/env.go +++ b/xtool/env/env.go @@ -20,6 +20,7 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "regexp" "strings" @@ -32,7 +33,19 @@ var ( ) func ExpandEnvToArgs(s string) []string { - r, config := expandEnvWithCmd(s) + r, config := expandEnvWithCmd(s, "", nil) + return expandedArgs(r, config) +} + +// ExpandEnvToArgsWith expands variables and supported helper commands using +// the supplied request directory and environment. A non-nil environ prevents +// subprocesses and variable expansion from consulting process-global state. +func ExpandEnvToArgsWith(s, dir string, environ []string) []string { + r, config := expandEnvWithCmd(s, dir, environ) + return expandedArgs(r, config) +} + +func expandedArgs(r string, config bool) []string { if r == "" { return nil } @@ -43,11 +56,11 @@ func ExpandEnvToArgs(s string) []string { } func ExpandEnv(s string) string { - r, _ := expandEnvWithCmd(s) + r, _ := expandEnvWithCmd(s, "", nil) return r } -func expandEnvWithCmd(s string) (string, bool) { +func expandEnvWithCmd(s, dir string, environ []string) (string, bool) { var config bool expanded := reSubcmd.ReplaceAllStringFunc(s, func(m string) string { subcmd := strings.TrimSpace(m[2 : len(m)-1]) @@ -61,7 +74,16 @@ func expandEnvWithCmd(s string) (string, bool) { var out []byte var err error - out, err = exec.Command(cmd, args[1:]...).Output() + executable := cmd + if environ != nil { + executable = lookPathInEnvironment(cmd, dir, environ) + } + command := exec.Command(executable, args[1:]...) + command.Dir = dir + if environ != nil { + command.Env = append([]string(nil), environ...) + } + out, err = command.Output() if err != nil { // TODO(kindy): log in verbose mode @@ -70,7 +92,46 @@ func expandEnvWithCmd(s string) (string, bool) { return strings.Replace(strings.TrimSpace(string(out)), "\n", " ", -1) }) - return strings.TrimSpace(os.Expand(expanded, os.Getenv)), config + lookup := os.Getenv + if environ != nil { + lookup = func(key string) string { + prefix := key + "=" + for i := len(environ) - 1; i >= 0; i-- { + if strings.HasPrefix(environ[i], prefix) { + return strings.TrimPrefix(environ[i], prefix) + } + } + return "" + } + } + return strings.TrimSpace(os.Expand(expanded, lookup)), config +} + +func lookPathInEnvironment(name, dir string, environ []string) string { + if strings.ContainsRune(name, filepath.Separator) { + return name + } + path := "" + prefix := "PATH=" + for i := len(environ) - 1; i >= 0; i-- { + if strings.HasPrefix(environ[i], prefix) { + path = strings.TrimPrefix(environ[i], prefix) + break + } + } + for _, entry := range filepath.SplitList(path) { + if entry == "" { + entry = "." + } + if !filepath.IsAbs(entry) && dir != "" { + entry = filepath.Join(dir, entry) + } + candidate := filepath.Join(entry, name) + if info, err := os.Stat(candidate); err == nil && !info.IsDir() && info.Mode()&0o111 != 0 { + return candidate + } + } + return name } func parseSubcmd(s string) []string { diff --git a/xtool/env/env_test.go b/xtool/env/env_test.go new file mode 100644 index 0000000000..51c485733d --- /dev/null +++ b/xtool/env/env_test.go @@ -0,0 +1,75 @@ +package env + +import ( + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +func TestExpandEnvToArgsWithUsesExplicitEnvironment(t *testing.T) { + t.Setenv("LLGO_ENV_TEST", "ambient") + got := ExpandEnvToArgsWith("$LLGO_ENV_TEST", "", []string{"LLGO_ENV_TEST=request"}) + if want := []string{"request"}; !reflect.DeepEqual(got, want) { + t.Fatalf("ExpandEnvToArgsWith = %q, want %q", got, want) + } +} + +func TestExpandEnvUsesProcessEnvironment(t *testing.T) { + t.Setenv("LLGO_ENV_TEST", "ambient") + if got := ExpandEnv("$LLGO_ENV_TEST"); got != "ambient" { + t.Fatalf("ExpandEnv = %q, want %q", got, "ambient") + } + if got := ExpandEnvToArgs("$LLGO_ENV_TEST"); !reflect.DeepEqual(got, []string{"ambient"}) { + t.Fatalf("ExpandEnvToArgs = %q, want %q", got, []string{"ambient"}) + } + if got := ExpandEnvToArgs(""); got != nil { + t.Fatalf("ExpandEnvToArgs(empty) = %q, want nil", got) + } +} + +func TestExpandEnvToArgsWithConfiguresSubprocess(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("shell fixture is Unix-only") + } + dir := t.TempDir() + tool := filepath.Join(dir, "pkg-config") + script := "#!/bin/sh\nprintf '%s' \"-L$LLGO_ENV_TEST -I$PWD\"\n" + if err := os.WriteFile(tool, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + got := ExpandEnvToArgsWith( + "$(pkg-config --libs fixture)", + dir, + []string{"PATH=" + dir, "LLGO_ENV_TEST=request"}, + ) + resolvedDir, err := filepath.EvalSymlinks(dir) + if err != nil { + t.Fatal(err) + } + want := []string{"-Lrequest", "-I" + resolvedDir} + if !reflect.DeepEqual(got, want) { + t.Fatalf("ExpandEnvToArgsWith = %q, want %q", got, want) + } +} + +func TestLookPathInEnvironmentBoundaries(t *testing.T) { + dir := t.TempDir() + tool := filepath.Join(dir, "fixture-tool") + if err := os.WriteFile(tool, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + if got := lookPathInEnvironment("fixture-tool", dir, []string{"PATH=" + string(os.PathListSeparator)}); got != tool { + t.Fatalf("lookPathInEnvironment with empty entry = %q, want %q", got, tool) + } + if got := lookPathInEnvironment(filepath.Join("bin", "tool"), dir, nil); got != filepath.Join("bin", "tool") { + t.Fatalf("lookPathInEnvironment with separator = %q", got) + } + if got := lookPathInEnvironment("missing-tool", dir, []string{"PATH=" + t.TempDir()}); got != "missing-tool" { + t.Fatalf("lookPathInEnvironment missing tool = %q", got) + } + if got := ExpandEnvToArgsWith("$LLGO_ENV_MISSING", dir, []string{"PATH=" + dir}); got != nil { + t.Fatalf("missing explicit environment variable = %q, want nil", got) + } +}