compiler: add //go:linkname support for globals

We previously used our own //go:extern but //go:linkname is probably the
better choice since it's used in the math/bits package.
This commit is contained in:
Ayke van Laethem
2025-02-25 13:04:34 +01:00
parent 38e3d55e64
commit adc0cae960
3 changed files with 14 additions and 2 deletions
+7 -2
View File
@@ -688,20 +688,25 @@ func (c *compilerContext) getGlobalInfo(g *ssa.Global) globalInfo {
// Check for //go: pragmas, which may change the link name (among others).
doc := c.astComments[info.linkName]
if doc != nil {
info.parsePragmas(doc)
info.parsePragmas(doc, g)
}
return info
}
// Parse //go: pragma comments from the source. In particular, it parses the
// //go:extern pragma on globals.
func (info *globalInfo) parsePragmas(doc *ast.CommentGroup) {
func (info *globalInfo) parsePragmas(doc *ast.CommentGroup, g *ssa.Global) {
for _, comment := range doc.List {
if !strings.HasPrefix(comment.Text, "//go:") {
continue
}
parts := strings.Fields(comment.Text)
switch parts[0] {
case "//go:linkname":
if len(parts) == 3 && g.Name() == parts[1] {
info.linkName = parts[2]
info.extern = true
}
case "//go:extern":
info.extern = true
if len(parts) == 2 {
+6
View File
@@ -2,6 +2,12 @@ package main
import _ "unsafe"
// Use the go:linkname mechanism to link this global to a different package.
// This is used in math/bits.
//
//go:linkname linknamedGlobal runtime.testLinknamedGlobal
var linknamedGlobal int
// Creates an external global with name extern_global.
//
//go:extern extern_global
+1
View File
@@ -3,6 +3,7 @@ source_filename = "pragma.go"
target datalayout = "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20"
target triple = "wasm32-unknown-wasi"
@runtime.testLinknamedGlobal = external global i32, align 4
@extern_global = external global [0 x i8], align 1
@main.alignedGlobal = hidden global [4 x i32] zeroinitializer, align 32
@main.alignedGlobal16 = hidden global [4 x i32] zeroinitializer, align 16