global var init

This commit is contained in:
xushiwei
2024-04-21 00:22:39 +08:00
parent 358e18b9de
commit 8f31e4a6d3
7 changed files with 22 additions and 11 deletions

View File

@@ -1,7 +1,7 @@
; ModuleID = 'main'
source_filename = "main"
@"init$guard" = external global ptr
@"init$guard" = global ptr null
define void @init() {
_llgo_0:

View File

@@ -1,8 +1,8 @@
; ModuleID = 'main'
source_filename = "main"
@"init$guard" = external global ptr
@a = external global ptr
@"init$guard" = global ptr null
@a = global ptr null
define void @init() {
_llgo_0:

View File

@@ -53,6 +53,7 @@ func (p *context) compileGlobal(pkg llssa.Package, gbl *ssa.Global) llssa.Global
return g
}
g := pkg.NewVar(gbl.Name(), gbl.Type())
g.Init(p.prog.Null(g.Type))
p.glbs[gbl] = g
return g
}

View File

@@ -115,8 +115,8 @@ var a int
`, `; ModuleID = 'foo'
source_filename = "foo"
@"init$guard" = external global ptr
@a = external global ptr
@"init$guard" = global ptr null
@a = global ptr null
define void @init() {
_llgo_0:
@@ -142,7 +142,7 @@ func fn(a int, b float64) int {
`, `; ModuleID = 'foo'
source_filename = "foo"
@"init$guard" = external global ptr
@"init$guard" = global ptr null
define void @init() {
_llgo_0:

View File

@@ -46,11 +46,13 @@ type aGlobal struct {
// A Global is a named Value holding the address of a package-level
// variable.
//
// Pos() returns the position of the ast.ValueSpec.Names[*]
// identifier.
type Global = *aGlobal
// Init initializes the global variable with the given value.
func (g Global) Init(v Expr) {
g.impl.SetInitializer(v.impl)
}
// -----------------------------------------------------------------------------
// Function represents the parameters, results, and code of a function

View File

@@ -43,6 +43,10 @@ func llvmValues(vals []Expr) []llvm.Value {
// -----------------------------------------------------------------------------
func (p Program) Null(t Type) Expr {
return Expr{llvm.ConstNull(t.ll), t}
}
func (p Program) BoolVal(v bool) Expr {
t := p.Bool()
var bv uint64

View File

@@ -37,11 +37,15 @@ func assertPkg(t *testing.T, p Package, expected string) {
func TestVar(t *testing.T) {
prog := NewProgram(nil)
pkg := prog.NewPackage("bar", "foo/bar")
pkg.NewVar("a", types.Typ[types.Int])
a := pkg.NewVar("a", types.Typ[types.Int])
a.Init(prog.Val(100))
b := pkg.NewVar("b", types.Typ[types.Int])
b.Init(a.Expr)
assertPkg(t, pkg, `; ModuleID = 'foo/bar'
source_filename = "foo/bar"
@a = external global i64
@a = global i64 100
@b = global i64 @a
`)
}