Files
llgo/cl/compile.go

941 lines
23 KiB
Go
Raw Normal View History

2023-12-10 11:24:08 +08:00
/*
2024-04-20 15:58:34 +08:00
* Copyright (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
2023-12-10 11:24:08 +08:00
*
* 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
2024-04-20 15:58:34 +08:00
import (
2024-04-20 17:31:49 +08:00
"fmt"
2024-04-22 15:09:08 +08:00
"go/ast"
2024-04-25 14:25:14 +08:00
"go/constant"
2024-04-22 21:16:43 +08:00
"go/token"
2024-04-22 20:09:23 +08:00
"go/types"
2024-04-21 16:04:05 +08:00
"log"
2024-04-21 17:54:51 +08:00
"os"
2024-04-20 15:58:34 +08:00
"sort"
"strings"
2024-04-20 15:58:34 +08:00
2024-06-05 15:08:05 +08:00
"github.com/goplus/llgo/cl/blocks"
"github.com/goplus/llgo/internal/typepatch"
2024-04-20 15:58:34 +08:00
"golang.org/x/tools/go/ssa"
llssa "github.com/goplus/llgo/ssa"
2024-04-20 15:58:34 +08:00
)
2024-04-21 16:04:05 +08:00
// -----------------------------------------------------------------------------
type dbgFlags = int
const (
DbgFlagInstruction dbgFlags = 1 << iota
2024-04-21 17:54:51 +08:00
DbgFlagGoSSA
2024-04-21 16:04:05 +08:00
2024-04-21 17:54:51 +08:00
DbgFlagAll = DbgFlagInstruction | DbgFlagGoSSA
2024-04-21 16:04:05 +08:00
)
var (
debugInstr bool
2024-04-21 17:54:51 +08:00
debugGoSSA bool
2024-04-21 16:04:05 +08:00
)
// SetDebug sets debug flags.
func SetDebug(dbgFlags dbgFlags) {
debugInstr = (dbgFlags & DbgFlagInstruction) != 0
2024-04-21 17:54:51 +08:00
debugGoSSA = (dbgFlags & DbgFlagGoSSA) != 0
}
// -----------------------------------------------------------------------------
2024-04-28 22:20:46 +08:00
type instrOrValue interface {
2024-04-20 17:31:49 +08:00
ssa.Instruction
ssa.Value
}
2024-04-29 09:51:32 +08:00
const (
2024-04-29 11:34:59 +08:00
PkgNormal = iota
PkgLLGo
2024-05-11 06:44:45 +08:00
PkgPyModule // py.<module>
2024-05-09 14:51:01 +08:00
PkgNoInit // noinit: a package that don't need to be initialized
PkgDeclOnly // decl: a package that only have declarations
PkgLinkIR // link llvm ir (.ll)
PkgLinkExtern // link external object (.a/.so/.dll/.dylib/etc.)
// PkgLinkBitCode // link bitcode (.bc)
2024-04-29 09:51:32 +08:00
)
type pkgInfo struct {
kind int
}
2024-06-28 15:14:30 +08:00
type none = struct{}
2024-04-20 15:58:34 +08:00
type context struct {
2024-04-22 20:09:23 +08:00
prog llssa.Program
pkg llssa.Package
fn llssa.Function
fset *token.FileSet
2024-04-25 21:44:23 +08:00
goProg *ssa.Program
2024-04-23 01:16:31 +08:00
goTyps *types.Package
2024-04-22 20:09:23 +08:00
goPkg *ssa.Package
2024-05-11 10:07:46 +08:00
pyMod string
link map[string]string // pkgPath.nameInPkg => linkname
skips map[string]none
2024-04-29 09:51:32 +08:00
loaded map[*types.Package]*pkgInfo // loaded packages
2024-04-25 14:25:14 +08:00
bvals map[ssa.Value]llssa.Expr // block values
vargs map[*ssa.Alloc][]llssa.Expr // varargs
patches Patches
2024-06-05 15:08:05 +08:00
blkInfos []blocks.Info
inits []func()
phis []func()
2024-06-16 21:32:11 +08:00
2024-06-18 18:23:16 +08:00
state pkgState
inCFunc bool
skipall bool
}
2024-06-18 18:23:16 +08:00
type pkgState byte
const (
pkgNormal pkgState = iota
pkgHasPatch
pkgInPatch
pkgFNoOldInit = 0x80 // flag if no initFnNameOld
2024-06-18 18:23:16 +08:00
)
func (p *context) inMain(instr ssa.Instruction) bool {
2024-06-18 18:23:16 +08:00
return p.fn.Name() == "main"
}
2024-04-25 21:44:23 +08:00
func (p *context) compileType(pkg llssa.Package, t *ssa.Type) {
tn := t.Object().(*types.TypeName)
2024-04-29 02:56:21 +08:00
if tn.IsAlias() { // don't need to compile alias type
return
}
2024-04-26 04:44:49 +08:00
tnName := tn.Name()
2024-04-25 21:44:23 +08:00
typ := tn.Type()
2024-04-27 07:47:10 +08:00
name := llssa.FullName(tn.Pkg(), tnName)
2024-04-26 04:44:49 +08:00
if ignoreName(name) {
return
}
2024-04-25 21:44:23 +08:00
if debugInstr {
log.Println("==> NewType", name, typ)
}
2024-04-26 00:31:02 +08:00
p.compileMethods(pkg, typ)
p.compileMethods(pkg, types.NewPointer(typ))
}
func (p *context) compileMethods(pkg llssa.Package, typ types.Type) {
2024-04-25 21:44:23 +08:00
prog := p.goProg
mthds := prog.MethodSets.MethodSet(typ)
for i, n := 0, mthds.Len(); i < n; i++ {
mthd := mthds.At(i)
2024-04-26 04:44:49 +08:00
if ssaMthd := prog.MethodValue(mthd); ssaMthd != nil {
p.compileFuncDecl(pkg, ssaMthd)
2024-04-26 04:44:49 +08:00
}
2024-04-25 21:44:23 +08:00
}
2024-04-20 15:58:34 +08:00
}
// Global variable.
2024-04-21 15:12:57 +08:00
func (p *context) compileGlobal(pkg llssa.Package, gbl *ssa.Global) {
2024-06-18 00:06:40 +08:00
typ := globalType(gbl)
name, vtype, define := p.varName(gbl.Pkg.Pkg, gbl)
2024-05-15 16:51:44 +08:00
if vtype == pyVar || ignoreName(name) || checkCgo(gbl.Name()) {
2024-04-26 04:44:49 +08:00
return
}
2024-04-21 16:04:05 +08:00
if debugInstr {
log.Println("==> NewVar", name, typ)
}
2024-05-05 12:11:51 +08:00
g := pkg.NewVar(name, typ, llssa.Background(vtype))
if define {
2024-06-14 09:57:23 +08:00
g.InitNil()
2024-05-01 21:18:28 +08:00
}
2024-04-20 15:58:34 +08:00
}
func makeClosureCtx(pkg *types.Package, vars []*ssa.FreeVar) *types.Var {
n := len(vars)
flds := make([]*types.Var, n)
for i, v := range vars {
flds[i] = types.NewField(token.NoPos, pkg, v.Name(), v.Type(), false)
}
t := types.NewPointer(types.NewStruct(flds, nil))
return types.NewParam(token.NoPos, pkg, "__llgo_ctx", t)
}
2024-05-07 10:16:03 +08:00
var (
argvTy = types.NewPointer(types.NewPointer(types.Typ[types.Int8]))
)
func (p *context) compileFuncDecl(pkg llssa.Package, f *ssa.Function) (llssa.Function, llssa.PyObjRef, int) {
2024-05-07 15:35:37 +08:00
pkgTypes, name, ftype := p.funcName(f, true)
if ftype != goFunc {
2024-05-14 19:38:30 +08:00
/*
if ftype == pyFunc {
// TODO(xsw): pyMod == ""
fnName := pysymPrefix + p.pyMod + "." + name
return nil, pkg.NewPyFunc(fnName, f.Signature, call), pyFunc
}
*/
2024-05-11 21:55:50 +08:00
return nil, nil, ignoredFunc
}
sig := f.Signature
state := p.state
isInit := (f.Name() == "init" && sig.Recv() == nil)
if isInit && state == pkgHasPatch {
name = initFnNameOfHasPatch(name)
// TODO(xsw): pkg.init$guard has been set, change ssa.If to ssa.Jump
2024-07-28 16:52:03 +08:00
block := f.Blocks[0].Instrs[1].(*ssa.If).Block()
block.Succs[0], block.Succs[1] = block.Succs[1], block.Succs[0]
}
fn := pkg.FuncOf(name)
if fn != nil && fn.HasBody() {
2024-05-11 21:55:50 +08:00
return fn, nil, goFunc
}
var hasCtx = len(f.FreeVars) > 0
if hasCtx {
2024-05-03 20:02:33 +08:00
if debugInstr {
log.Println("==> NewClosure", name, "type:", sig)
}
ctx := makeClosureCtx(pkgTypes, f.FreeVars)
sig = llssa.FuncAddCtx(ctx, sig)
2024-05-03 19:59:56 +08:00
} else {
2024-05-17 09:31:48 +08:00
if debugInstr {
log.Println("==> NewFunc", name, "type:", sig.Recv(), sig, "ftype:", ftype)
2024-05-03 19:59:56 +08:00
}
2024-05-03 16:00:31 +08:00
}
2024-08-04 09:54:34 +08:00
async := isAsyncFunc(f.Signature)
if fn == nil {
2024-05-07 10:16:03 +08:00
if name == "main" {
argc := types.NewParam(token.NoPos, pkgTypes, "", types.Typ[types.Int32])
argv := types.NewParam(token.NoPos, pkgTypes, "", argvTy)
params := types.NewTuple(argc, argv)
2024-05-17 09:31:48 +08:00
ret := types.NewParam(token.NoPos, pkgTypes, "", p.prog.CInt().RawType())
results := types.NewTuple(ret)
sig = types.NewSignatureType(nil, nil, nil, params, results, false)
2024-05-07 10:16:03 +08:00
}
2024-08-04 09:54:34 +08:00
fn = pkg.NewFuncEx(name, sig, llssa.Background(ftype), hasCtx, async)
}
2024-08-04 09:54:34 +08:00
nBlkOff := 0
if nblk := len(f.Blocks); nblk > 0 {
2024-08-05 16:42:51 +08:00
var entryBlk, allocBlk, cleanBlk, suspdBlk, trapBlk, beginBlk llssa.BasicBlock
2024-08-04 09:54:34 +08:00
if async {
2024-08-05 15:19:42 +08:00
nBlkOff = 5
2024-08-05 16:42:51 +08:00
entryBlk = fn.MakeBlock("entry")
allocBlk = fn.MakeBlock("alloc")
cleanBlk = fn.MakeBlock("clean")
suspdBlk = fn.MakeBlock("suspend")
trapBlk = fn.MakeBlock("trap")
2024-08-04 09:54:34 +08:00
}
2024-08-05 16:42:51 +08:00
fn.MakeBlocks(nblk) // to set fn.HasBody() = true
beginBlk = fn.Block(nBlkOff)
2024-06-18 17:33:37 +08:00
if f.Recover != nil { // set recover block
2024-08-05 12:37:34 +08:00
// TODO(lijie): fix this for async function because of the block offset increase
2024-08-04 09:54:34 +08:00
fn.SetRecover(fn.Block(f.Recover.Index + nBlkOff))
2024-06-18 17:33:37 +08:00
}
p.inits = append(p.inits, func() {
p.fn = fn
2024-06-18 18:23:16 +08:00
p.state = state // restore pkgState when compiling funcBody
defer func() {
p.fn = nil
}()
p.phis = nil
if debugGoSSA {
f.WriteTo(os.Stderr)
}
if debugInstr {
log.Println("==> FuncBody", name)
}
b := fn.NewBuilder()
2024-08-04 09:54:34 +08:00
b.SetBlockOffset(nBlkOff)
if async {
2024-08-05 16:42:51 +08:00
b.BeginAsync(fn, entryBlk, allocBlk, cleanBlk, suspdBlk, trapBlk, beginBlk)
2024-08-04 09:54:34 +08:00
}
p.bvals = make(map[ssa.Value]llssa.Expr)
2024-05-06 22:21:49 +08:00
off := make([]int, len(f.Blocks))
for i, block := range f.Blocks {
2024-05-06 22:21:49 +08:00
off[i] = p.compilePhis(b, block)
}
2024-06-05 15:08:05 +08:00
p.blkInfos = blocks.Infos(f.Blocks)
i := 0
for {
block := f.Blocks[i]
2024-05-12 18:42:45 +08:00
doMainInit := (i == 0 && name == "main")
2024-06-18 17:33:37 +08:00
doModInit := (i == 1 && isInit)
2024-05-12 18:42:45 +08:00
p.compileBlock(b, block, off[i], doMainInit, doModInit)
2024-06-05 15:08:05 +08:00
if i = p.blkInfos[i].Next; i < 0 {
break
}
}
for _, phi := range p.phis {
phi()
}
2024-06-02 21:54:51 +08:00
b.EndBuild()
})
for _, af := range f.AnonFuncs {
p.compileFuncDecl(pkg, af)
}
}
2024-05-11 21:55:50 +08:00
return fn, nil, goFunc
2024-04-20 17:31:49 +08:00
}
2024-04-20 15:58:34 +08:00
2024-05-12 18:42:45 +08:00
func (p *context) compileBlock(b llssa.Builder, block *ssa.BasicBlock, n int, doMainInit, doModInit bool) llssa.BasicBlock {
2024-05-11 11:33:35 +08:00
var last int
2024-05-12 18:42:45 +08:00
var pyModInit bool
2024-05-12 20:03:27 +08:00
var prog = p.prog
var pkg = p.pkg
2024-06-18 18:23:16 +08:00
var fn = p.fn
2024-05-12 18:42:45 +08:00
var instrs = block.Instrs[n:]
2024-08-04 09:54:34 +08:00
var ret = fn.Block(block.Index + b.BlockOffset())
2024-04-20 22:05:45 +08:00
b.SetBlock(ret)
2024-05-12 18:42:45 +08:00
if doModInit {
if pyModInit = p.pyMod != ""; pyModInit {
last = len(instrs) - 1
instrs = instrs[:last]
2024-07-28 11:29:22 +08:00
} else if p.state != pkgHasPatch {
// TODO(xsw): confirm pyMod don't need to call AfterInit
2024-07-28 11:29:22 +08:00
p.inits = append(p.inits, func() {
pkg.AfterInit(b, ret)
2024-07-28 11:29:22 +08:00
})
2024-05-13 00:41:42 +08:00
}
2024-05-12 18:42:45 +08:00
} else if doMainInit {
argc := pkg.NewVar("__llgo_argc", types.NewPointer(types.Typ[types.Int32]), llssa.InC)
argv := pkg.NewVar("__llgo_argv", types.NewPointer(argvTy), llssa.InC)
2024-06-14 09:57:23 +08:00
argc.InitNil()
argv.InitNil()
2024-05-12 18:42:45 +08:00
b.Store(argc.Expr, fn.Param(0))
b.Store(argv.Expr, fn.Param(1))
callRuntimeInit(b, pkg)
b.Call(pkg.FuncOf("main.init").Expr)
2024-05-11 11:33:35 +08:00
}
2024-06-18 18:23:16 +08:00
for i, instr := range instrs {
if i == 1 && doModInit && p.state == pkgInPatch { // in patch package but no pkgFNoOldInit
2024-06-18 18:23:16 +08:00
initFnNameOld := initFnNameOfHasPatch(p.fn.Name())
fnOld := pkg.NewFunc(initFnNameOld, llssa.NoArgsNoRet, llssa.InC)
b.Call(fnOld.Expr)
}
2024-04-20 17:31:49 +08:00
p.compileInstr(b, instr)
2024-04-20 15:58:34 +08:00
}
2024-05-11 11:33:35 +08:00
if pyModInit {
2024-05-12 18:42:45 +08:00
jump := block.Instrs[n+last].(*ssa.Jump)
2024-05-11 11:33:35 +08:00
jumpTo := p.jumpTo(jump)
modPath := p.pyMod
modName := pysymPrefix + modPath
modPtr := pkg.PyNewModVar(modName, true).Expr
2024-05-11 11:33:35 +08:00
mod := b.Load(modPtr)
cond := b.BinOp(token.NEQ, mod, prog.Nil(mod.Type))
newBlk := fn.MakeBlock("")
2024-05-11 11:33:35 +08:00
b.If(cond, jumpTo, newBlk)
2024-05-24 09:20:58 +08:00
b.SetBlockEx(newBlk, llssa.AtEnd, false)
b.Store(modPtr, b.PyImportMod(modPath))
2024-05-11 11:33:35 +08:00
b.Jump(jumpTo)
}
2024-04-20 22:05:45 +08:00
return ret
2024-04-20 15:58:34 +08:00
}
const (
RuntimeInit = llssa.PkgRuntime + ".init"
)
func callRuntimeInit(b llssa.Builder, pkg llssa.Package) {
2024-05-12 11:11:19 +08:00
fn := pkg.NewFunc(RuntimeInit, llssa.NoArgsNoRet, llssa.InC) // don't need to convert runtime.init
b.Call(fn.Expr)
}
2024-04-25 14:25:14 +08:00
func isAny(t types.Type) bool {
if t, ok := t.(*types.Interface); ok {
return t.Empty()
}
return false
}
func intVal(v ssa.Value) int64 {
if c, ok := v.(*ssa.Const); ok {
if iv, exact := constant.Int64Val(c.Value); exact {
return iv
}
}
panic("intVal: ssa.Value is not a const int")
}
2024-06-11 10:35:27 +08:00
func (p *context) isVArgs(v ssa.Value) (ret []llssa.Expr, ok bool) {
switch v := v.(type) {
case *ssa.Alloc:
2024-06-11 10:35:27 +08:00
ret, ok = p.vargs[v] // varargs: this is a varargs index
2024-04-25 14:25:14 +08:00
}
return
}
2024-04-28 10:29:06 +08:00
func (p *context) checkVArgs(v *ssa.Alloc, t *types.Pointer) bool {
2024-05-09 06:19:09 +08:00
if v.Comment == "varargs" { // this maybe a varargs allocation
2024-04-28 10:29:06 +08:00
if arr, ok := t.Elem().(*types.Array); ok {
2024-06-12 21:02:26 +08:00
if isAny(arr.Elem()) && isAllocVargs(p, v) {
2024-04-28 10:29:06 +08:00
p.vargs[v] = make([]llssa.Expr, arr.Len())
return true
2024-04-25 14:25:14 +08:00
}
}
}
return false
}
2024-06-12 21:02:26 +08:00
func isAllocVargs(ctx *context, v *ssa.Alloc) bool {
2024-05-09 06:19:09 +08:00
refs := *v.Referrers()
n := len(refs)
lastref := refs[n-1]
if i, ok := lastref.(*ssa.Slice); ok {
if refs = *i.Referrers(); len(refs) == 1 {
2024-06-11 10:35:27 +08:00
var call *ssa.CallCommon
switch ref := refs[0].(type) {
case *ssa.Call:
call = &ref.Call
case *ssa.Defer:
call = &ref.Call
case *ssa.Go:
call = &ref.Call
default:
return false
2024-05-09 06:19:09 +08:00
}
2024-06-11 10:35:27 +08:00
return ctx.funcKind(call.Value) == fnHasVArg
2024-05-09 06:19:09 +08:00
}
}
return false
}
func isPhi(i ssa.Instruction) bool {
_, ok := i.(*ssa.Phi)
return ok
}
2024-05-06 22:21:49 +08:00
func (p *context) compilePhis(b llssa.Builder, block *ssa.BasicBlock) int {
2024-06-13 13:51:36 +08:00
fn := p.fn
ret := fn.Block(block.Index)
2024-05-24 09:20:58 +08:00
b.SetBlockEx(ret, llssa.AtEnd, false)
2024-05-06 22:21:49 +08:00
if ninstr := len(block.Instrs); ninstr > 0 {
if isPhi(block.Instrs[0]) {
n := 1
2024-05-06 22:21:49 +08:00
for n < ninstr && isPhi(block.Instrs[n]) {
n++
}
rets := make([]llssa.Expr, n) // TODO(xsw): check to remove this
for i := 0; i < n; i++ {
2024-05-06 22:21:49 +08:00
iv := block.Instrs[i].(*ssa.Phi)
rets[i] = p.compilePhi(b, iv)
}
for i := 0; i < n; i++ {
2024-05-06 22:21:49 +08:00
iv := block.Instrs[i].(*ssa.Phi)
2024-05-26 14:58:26 +08:00
p.bvals[iv] = rets[i]
}
2024-05-06 22:21:49 +08:00
return n
}
}
2024-05-06 22:21:49 +08:00
return 0
}
func (p *context) compilePhi(b llssa.Builder, v *ssa.Phi) (ret llssa.Expr) {
2024-05-05 12:11:51 +08:00
phi := b.Phi(p.prog.Type(v.Type(), llssa.InGo))
ret = phi.Expr
p.phis = append(p.phis, func() {
preds := v.Block().Preds
bblks := make([]llssa.BasicBlock, len(preds))
for i, pred := range preds {
bblks[i] = p.fn.Block(pred.Index)
}
edges := v.Edges
2024-05-26 16:18:24 +08:00
phi.AddIncoming(b, bblks, func(i int, blk llssa.BasicBlock) llssa.Expr {
b.SetBlockEx(blk, llssa.BeforeLast, false)
return p.compileValue(b, edges[i])
})
})
return
}
2024-04-28 22:20:46 +08:00
func (p *context) compileInstrOrValue(b llssa.Builder, iv instrOrValue, asValue bool) (ret llssa.Expr) {
if asValue {
if v, ok := p.bvals[iv]; ok {
return v
}
log.Panicln("unreachable:", iv)
2024-04-20 22:16:28 +08:00
}
2024-04-20 17:31:49 +08:00
switch v := iv.(type) {
2024-04-20 23:15:10 +08:00
case *ssa.Call:
2024-05-31 12:01:11 +08:00
ret = p.call(b, llssa.Call, &v.Call)
2024-04-20 23:15:10 +08:00
case *ssa.BinOp:
x := p.compileValue(b, v.X)
y := p.compileValue(b, v.Y)
ret = b.BinOp(v.Op, x, y)
2024-04-20 17:31:49 +08:00
case *ssa.UnOp:
x := p.compileValue(b, v.X)
2024-07-02 20:12:12 +08:00
if v.Op == token.ARROW {
ret = b.Recv(x, v.CommaOk)
} else {
ret = b.UnOp(v.Op, x)
}
2024-04-26 00:31:02 +08:00
case *ssa.ChangeType:
t := v.Type()
x := p.compileValue(b, v.X)
2024-05-05 12:11:51 +08:00
ret = b.ChangeType(p.prog.Type(t, llssa.InGo), x)
2024-04-28 06:23:21 +08:00
case *ssa.Convert:
t := v.Type()
x := p.compileValue(b, v.X)
2024-05-05 12:11:51 +08:00
ret = b.Convert(p.prog.Type(t, llssa.InGo), x)
2024-04-27 07:47:10 +08:00
case *ssa.FieldAddr:
x := p.compileValue(b, v.X)
ret = b.FieldAddr(x, v.Field)
2024-05-01 07:26:51 +08:00
case *ssa.Alloc:
t := v.Type().(*types.Pointer)
2024-05-09 06:19:09 +08:00
if p.checkVArgs(v, t) { // varargs: this maybe a varargs allocation
2024-05-01 07:26:51 +08:00
return
}
2024-05-05 12:11:51 +08:00
elem := p.prog.Type(t.Elem(), llssa.InGo)
ret = b.Alloc(elem, v.Heap)
2024-04-21 15:12:57 +08:00
case *ssa.IndexAddr:
2024-04-25 14:25:14 +08:00
vx := v.X
if _, ok := p.isVArgs(vx); ok { // varargs: this is a varargs index
return
}
x := p.compileValue(b, vx)
2024-04-21 15:12:57 +08:00
idx := p.compileValue(b, v.Index)
ret = b.IndexAddr(x, idx)
2024-05-01 21:56:11 +08:00
case *ssa.Index:
x := p.compileValue(b, v.X)
idx := p.compileValue(b, v.Index)
2024-07-03 13:21:18 +08:00
ret = b.Index(x, idx, func() (addr llssa.Expr, zero bool) {
2024-07-02 21:14:36 +08:00
switch n := v.X.(type) {
2024-07-03 13:21:18 +08:00
case *ssa.Const:
zero = true
2024-07-02 21:14:36 +08:00
case *ssa.UnOp:
2024-07-03 13:21:18 +08:00
addr = p.compileValue(b, n.X)
2024-05-01 21:56:11 +08:00
}
2024-07-02 21:14:36 +08:00
return
2024-05-01 21:56:11 +08:00
})
2024-05-06 01:17:37 +08:00
case *ssa.Lookup:
x := p.compileValue(b, v.X)
idx := p.compileValue(b, v.Index)
ret = b.Lookup(x, idx, v.CommaOk)
2024-04-25 14:25:14 +08:00
case *ssa.Slice:
vx := v.X
if _, ok := p.isVArgs(vx); ok { // varargs: this is a varargs slice
return
}
2024-04-30 08:23:55 +08:00
var low, high, max llssa.Expr
x := p.compileValue(b, vx)
if v.Low != nil {
low = p.compileValue(b, v.Low)
}
if v.High != nil {
high = p.compileValue(b, v.High)
}
if v.Max != nil {
max = p.compileValue(b, v.Max)
}
ret = b.Slice(x, low, high, max)
2024-04-25 14:25:14 +08:00
case *ssa.MakeInterface:
2024-05-09 06:48:16 +08:00
if refs := *v.Referrers(); len(refs) == 1 {
switch ref := refs[0].(type) {
case *ssa.Store:
2024-05-09 06:48:16 +08:00
if va, ok := ref.Addr.(*ssa.IndexAddr); ok {
if _, ok = p.isVArgs(va.X); ok { // varargs: this is a varargs store
return
}
}
case *ssa.Call:
if fn, ok := ref.Call.Value.(*ssa.Function); ok {
if _, _, ftype := p.funcOf(fn); ftype == llgoFuncAddr { // llgo.funcAddr
return
}
}
2024-05-09 06:48:16 +08:00
}
}
2024-06-28 15:14:30 +08:00
prog := p.prog
t := prog.Type(v.Type(), llssa.InGo)
2024-04-27 20:45:55 +08:00
x := p.compileValue(b, v.X)
2024-05-09 06:48:16 +08:00
ret = b.MakeInterface(t, x)
2024-05-03 23:10:02 +08:00
case *ssa.MakeSlice:
2024-05-05 12:11:51 +08:00
t := p.prog.Type(v.Type(), llssa.InGo)
2024-05-03 23:10:02 +08:00
nLen := p.compileValue(b, v.Len)
2024-06-26 06:49:48 +08:00
nCap := p.compileValue(b, v.Cap)
2024-05-05 12:11:51 +08:00
ret = b.MakeSlice(t, nLen, nCap)
2024-05-03 23:10:02 +08:00
case *ssa.MakeMap:
var nReserve llssa.Expr
2024-05-05 12:11:51 +08:00
t := p.prog.Type(v.Type(), llssa.InGo)
2024-05-03 23:10:02 +08:00
if v.Reserve != nil {
nReserve = p.compileValue(b, v.Reserve)
}
2024-05-05 12:11:51 +08:00
ret = b.MakeMap(t, nReserve)
case *ssa.MakeClosure:
fn := p.compileValue(b, v.Fn)
bindings := p.compileValues(b, v.Bindings, 0)
ret = b.MakeClosure(fn, bindings)
2024-04-27 17:39:25 +08:00
case *ssa.TypeAssert:
x := p.compileValue(b, v.X)
2024-05-05 12:11:51 +08:00
t := p.prog.Type(v.AssertedType, llssa.InGo)
ret = b.TypeAssert(x, t, v.CommaOk)
2024-05-06 19:42:18 +08:00
case *ssa.Extract:
x := p.compileValue(b, v.Tuple)
ret = b.Extract(x, v.Index)
case *ssa.Range:
x := p.compileValue(b, v.X)
ret = b.Range(x)
case *ssa.Next:
2024-06-29 20:43:12 +08:00
var typ llssa.Type
if !v.IsString {
typ = p.prog.Type(v.Iter.(*ssa.Range).X.Type(), llssa.InGo)
}
iter := p.compileValue(b, v.Iter)
2024-06-29 20:43:12 +08:00
ret = b.Next(typ, iter, v.IsString)
2024-06-03 16:03:05 +08:00
case *ssa.ChangeInterface:
t := v.Type()
x := p.compileValue(b, v.X)
ret = b.ChangeInterface(p.prog.Type(t, llssa.InGo), x)
2024-06-11 10:23:00 +08:00
case *ssa.Field:
x := p.compileValue(b, v.X)
ret = b.Field(x, v.Field)
2024-07-02 20:12:12 +08:00
case *ssa.MakeChan:
t := v.Type()
size := p.compileValue(b, v.Size)
ret = b.MakeChan(p.prog.Type(t, llssa.InGo), size)
2024-07-07 06:22:46 +08:00
case *ssa.Select:
states := make([]*llssa.SelectState, len(v.States))
for i, s := range v.States {
states[i] = &llssa.SelectState{
Chan: p.compileValue(b, s.Chan),
Send: s.Dir == types.SendOnly,
}
if s.Send != nil {
states[i].Value = p.compileValue(b, s.Send)
}
}
ret = b.Select(states, v.Blocking)
2024-04-20 22:16:28 +08:00
default:
panic(fmt.Sprintf("compileInstrAndValue: unknown instr - %T\n", iv))
2024-04-20 17:31:49 +08:00
}
2024-04-20 23:15:10 +08:00
p.bvals[iv] = ret
2024-04-20 22:16:28 +08:00
return ret
2023-12-10 13:43:44 +08:00
}
2024-05-11 11:33:35 +08:00
func (p *context) jumpTo(v *ssa.Jump) llssa.BasicBlock {
fn := p.fn
succs := v.Block().Succs
return fn.Block(succs[0].Index)
}
2024-04-20 17:31:49 +08:00
func (p *context) compileInstr(b llssa.Builder, instr ssa.Instruction) {
2024-04-28 22:20:46 +08:00
if iv, ok := instr.(instrOrValue); ok {
p.compileInstrOrValue(b, iv, false)
2024-04-20 17:31:49 +08:00
return
}
switch v := instr.(type) {
2024-04-20 22:05:45 +08:00
case *ssa.Store:
2024-04-25 14:25:14 +08:00
va := v.Addr
if va, ok := va.(*ssa.IndexAddr); ok {
if args, ok := p.isVArgs(va.X); ok { // varargs: this is a varargs store
idx := intVal(va.Index)
val := v.Val
if vi, ok := val.(*ssa.MakeInterface); ok {
val = vi.X
}
args[idx] = p.compileValue(b, val)
return
}
}
ptr := p.compileValue(b, va)
2024-04-20 22:05:45 +08:00
val := p.compileValue(b, v.Val)
b.Store(ptr, val)
case *ssa.Jump:
2024-05-11 11:33:35 +08:00
jmpb := p.jumpTo(v)
2024-04-20 22:05:45 +08:00
b.Jump(jmpb)
case *ssa.Return:
var results []llssa.Expr
if n := len(v.Results); n > 0 {
results = make([]llssa.Expr, n)
for i, r := range v.Results {
results[i] = p.compileValue(b, r)
}
}
if p.inMain(instr) {
results = make([]llssa.Expr, 1)
2024-05-17 09:06:53 +08:00
results[0] = p.prog.IntVal(0, p.prog.CInt())
}
2024-08-04 09:54:34 +08:00
if b.Async() {
b.EndAsync()
} else {
b.Return(results...)
}
2024-04-20 17:31:49 +08:00
case *ssa.If:
2024-04-20 22:05:45 +08:00
fn := p.fn
cond := p.compileValue(b, v.Cond)
succs := v.Block().Succs
thenb := fn.Block(succs[0].Index)
elseb := fn.Block(succs[1].Index)
b.If(cond, thenb, elseb)
2024-05-01 07:26:51 +08:00
case *ssa.MapUpdate:
2024-05-01 07:37:38 +08:00
m := p.compileValue(b, v.Map)
key := p.compileValue(b, v.Key)
val := p.compileValue(b, v.Value)
b.MapUpdate(m, key, val)
2024-06-02 14:29:35 +08:00
case *ssa.Defer:
2024-06-05 15:08:05 +08:00
p.call(b, p.blkInfos[v.Block().Index].Kind, &v.Call)
2024-05-31 12:01:11 +08:00
case *ssa.Go:
p.call(b, llssa.Go, &v.Call)
2024-06-02 15:24:42 +08:00
case *ssa.RunDefers:
b.RunDefers()
case *ssa.Panic:
2024-05-26 14:58:26 +08:00
arg := p.compileValue(b, v.X)
b.Panic(arg)
2024-07-02 20:12:12 +08:00
case *ssa.Send:
ch := p.compileValue(b, v.Chan)
x := p.compileValue(b, v.X)
b.Send(ch, x)
2024-04-20 22:05:45 +08:00
default:
panic(fmt.Sprintf("compileInstr: unknown instr - %T\n", instr))
2024-04-20 17:31:49 +08:00
}
2023-12-10 13:43:44 +08:00
}
2024-05-12 23:08:44 +08:00
func (p *context) compileFunction(v *ssa.Function) (goFn llssa.Function, pyFn llssa.PyObjRef, kind int) {
// TODO(xsw) v.Pkg == nil: means auto generated function?
2024-05-06 18:30:53 +08:00
if v.Pkg == p.goPkg || v.Pkg == nil {
// function in this package
goFn, pyFn, kind = p.compileFuncDecl(p.pkg, v)
2024-05-11 21:55:50 +08:00
if kind != ignoredFunc {
return
}
2024-05-06 18:30:53 +08:00
}
return p.funcOf(v)
}
2024-04-20 22:16:28 +08:00
func (p *context) compileValue(b llssa.Builder, v ssa.Value) llssa.Expr {
2024-04-28 22:20:46 +08:00
if iv, ok := v.(instrOrValue); ok {
return p.compileInstrOrValue(b, iv, true)
2024-04-20 22:16:28 +08:00
}
switch v := v.(type) {
2024-04-20 23:15:10 +08:00
case *ssa.Parameter:
fn := v.Parent()
for idx, param := range fn.Params {
if param == v {
return p.fn.Param(idx)
}
}
case *ssa.Function:
2024-05-11 21:55:50 +08:00
aFn, pyFn, _ := p.compileFunction(v)
if aFn != nil {
return aFn.Expr
}
return pyFn.Expr
2024-04-20 22:16:28 +08:00
case *ssa.Global:
return p.varOf(b, v)
2024-04-20 22:16:28 +08:00
case *ssa.Const:
t := types.Default(v.Type())
2024-06-17 21:41:49 +08:00
bg := llssa.InGo
if p.inCFunc {
bg = llssa.InC
}
return b.Const(v.Value, p.prog.Type(t, bg))
case *ssa.FreeVar:
fn := v.Parent()
for idx, freeVar := range fn.FreeVars {
if freeVar == v {
return p.fn.FreeVar(b, idx)
}
}
2024-04-20 17:31:49 +08:00
}
2024-04-20 23:15:10 +08:00
panic(fmt.Sprintf("compileValue: unknown value - %T\n", v))
}
2024-04-21 17:54:51 +08:00
func (p *context) compileVArg(ret []llssa.Expr, b llssa.Builder, v ssa.Value) []llssa.Expr {
_ = b
switch v := v.(type) {
2024-04-25 14:25:14 +08:00
case *ssa.Slice: // varargs: this is a varargs slice
if args, ok := p.isVArgs(v.X); ok {
return append(ret, args...)
}
2024-04-21 17:54:51 +08:00
case *ssa.Const:
if v.Value == nil {
return ret
}
}
2024-04-25 14:25:14 +08:00
panic(fmt.Sprintf("compileVArg: unknown value - %T\n", v))
2024-04-21 17:54:51 +08:00
}
func (p *context) compileValues(b llssa.Builder, vals []ssa.Value, hasVArg int) []llssa.Expr {
n := len(vals) - hasVArg
ret := make([]llssa.Expr, n)
for i := 0; i < n; i++ {
2024-05-26 14:58:26 +08:00
ret[i] = p.compileValue(b, vals[i])
2024-04-21 17:54:51 +08:00
}
if hasVArg > 0 {
ret = p.compileVArg(ret, b, vals[n])
2024-04-20 23:15:10 +08:00
}
return ret
2023-12-10 13:43:44 +08:00
}
2024-04-20 17:31:49 +08:00
// -----------------------------------------------------------------------------
2023-12-10 13:43:44 +08:00
2024-06-28 15:14:30 +08:00
// Patch is a patch of some package.
type Patch struct {
Alt *ssa.Package
Types *types.Package
}
// Patches is patches of some packages.
2024-06-28 15:14:30 +08:00
type Patches = map[string]Patch
2024-04-20 17:31:49 +08:00
// NewPackage compiles a Go package to LLVM IR package.
2024-06-15 12:43:05 +08:00
func NewPackage(prog llssa.Program, pkg *ssa.Package, files []*ast.File) (ret llssa.Package, err error) {
return NewPackageEx(prog, nil, pkg, files)
2024-06-15 12:43:05 +08:00
}
2023-12-10 15:34:42 +08:00
// NewPackageEx compiles a Go package to LLVM IR package.
func NewPackageEx(prog llssa.Program, patches Patches, pkg *ssa.Package, files []*ast.File) (ret llssa.Package, err error) {
2024-04-25 21:44:23 +08:00
pkgProg := pkg.Prog
2024-04-20 17:31:49 +08:00
pkgTypes := pkg.Pkg
2024-06-28 15:14:30 +08:00
oldTypes := pkgTypes
2024-04-27 07:47:10 +08:00
pkgName, pkgPath := pkgTypes.Name(), llssa.PathOf(pkgTypes)
2024-06-28 15:14:30 +08:00
patch, hasPatch := patches[pkgPath]
if hasPatch {
2024-06-28 15:14:30 +08:00
pkgTypes = patch.Types
2024-06-17 03:52:05 +08:00
pkg.Pkg = pkgTypes
2024-06-28 15:14:30 +08:00
patch.Alt.Pkg = pkgTypes
}
if pkgPath == llssa.PkgRuntime {
prog.SetRuntime(pkgTypes)
}
2024-04-25 00:14:02 +08:00
ret = prog.NewPackage(pkgName, pkgPath)
2024-04-20 17:31:49 +08:00
ctx := &context{
prog: prog,
pkg: ret,
fset: pkgProg.Fset,
goProg: pkgProg,
goTyps: pkgTypes,
goPkg: pkg,
patches: patches,
link: make(map[string]string),
skips: make(map[string]none),
vargs: make(map[*ssa.Alloc][]llssa.Expr),
2024-04-29 09:51:32 +08:00
loaded: map[*types.Package]*pkgInfo{
2024-04-29 11:34:59 +08:00
types.Unsafe: {kind: PkgDeclOnly}, // TODO(xsw): PkgNoInit or PkgDeclOnly?
2024-04-29 09:51:32 +08:00
},
2024-04-20 17:31:49 +08:00
}
2024-05-11 10:07:46 +08:00
ctx.initPyModule()
2024-04-25 00:14:02 +08:00
ctx.initFiles(pkgPath, files)
2024-07-01 19:05:12 +08:00
ret.SetPatch(ctx.patchType)
ret.SetResolveLinkname(ctx.resolveLinkname)
2024-06-15 12:43:05 +08:00
if hasPatch {
skips := ctx.skips
2024-06-28 15:14:30 +08:00
typepatch.Merge(pkgTypes, oldTypes, skips, ctx.skipall)
ctx.skips = nil
2024-06-18 18:23:16 +08:00
ctx.state = pkgInPatch
if _, ok := skips["init"]; ok || ctx.skipall {
ctx.state |= pkgFNoOldInit
}
2024-06-28 15:14:30 +08:00
processPkg(ctx, ret, patch.Alt)
2024-06-18 18:23:16 +08:00
ctx.state = pkgHasPatch
ctx.skips = skips
2024-06-15 12:43:05 +08:00
}
2024-06-16 21:32:11 +08:00
if !ctx.skipall {
processPkg(ctx, ret, pkg)
}
for len(ctx.inits) > 0 {
inits := ctx.inits
ctx.inits = nil
for _, ini := range inits {
ini()
}
}
2024-06-15 12:43:05 +08:00
return
}
2024-06-18 18:23:16 +08:00
func initFnNameOfHasPatch(name string) string {
return name + "$hasPatch"
2024-06-18 17:33:37 +08:00
}
2024-06-15 12:43:05 +08:00
func processPkg(ctx *context, ret llssa.Package, pkg *ssa.Package) {
type namedMember struct {
name string
val ssa.Member
}
members := make([]*namedMember, 0, len(pkg.Members))
skips := ctx.skips
2024-06-15 12:43:05 +08:00
for name, v := range pkg.Members {
if _, ok := skips[name]; !ok {
members = append(members, &namedMember{name, v})
}
2024-06-15 12:43:05 +08:00
}
sort.Slice(members, func(i, j int) bool {
return members[i].name < members[j].name
})
2023-12-10 15:34:42 +08:00
for _, m := range members {
member := m.val
switch member := member.(type) {
case *ssa.Function:
2024-05-07 15:35:37 +08:00
if member.TypeParams() != nil || member.TypeArgs() != nil {
// TODO(xsw): don't compile generic functions
2023-12-10 15:34:42 +08:00
// Do not try to build generic (non-instantiated) functions.
continue
}
ctx.compileFuncDecl(ret, member)
2023-12-10 15:34:42 +08:00
case *ssa.Type:
2024-04-20 17:31:49 +08:00
ctx.compileType(ret, member)
2023-12-10 15:34:42 +08:00
case *ssa.Global:
2024-04-20 17:31:49 +08:00
ctx.compileGlobal(ret, member)
2023-12-10 15:34:42 +08:00
}
}
2023-12-11 00:37:09 +08:00
}
2024-06-18 00:06:40 +08:00
func globalType(gbl *ssa.Global) types.Type {
t := gbl.Type()
if t, ok := t.(*types.Named); ok {
o := t.Obj()
if pkg := o.Pkg(); typepatch.IsPatched(pkg) {
2024-06-28 15:14:30 +08:00
if patch := gbl.Pkg.Pkg.Scope().Lookup(o.Name()); patch != nil {
return patch.Type()
}
2024-06-18 00:06:40 +08:00
}
}
return t
}
2024-06-30 11:53:12 +08:00
func (p *context) patchType(typ types.Type) types.Type {
if t, ok := typ.(*types.Named); ok {
2024-06-28 15:14:30 +08:00
o := t.Obj()
if pkg := o.Pkg(); typepatch.IsPatched(pkg) {
2024-06-30 11:53:12 +08:00
if patch, ok := p.patches[pkg.Path()]; ok {
2024-06-28 15:14:30 +08:00
if obj := patch.Types.Scope().Lookup(o.Name()); obj != nil {
2024-06-30 11:53:12 +08:00
return p.prog.Type(obj.Type(), llssa.InGo).RawType()
2024-06-28 15:14:30 +08:00
}
}
}
}
2024-06-30 11:53:12 +08:00
return typ
2024-06-28 15:14:30 +08:00
}
func (p *context) resolveLinkname(name string) string {
if link, ok := p.link[name]; ok {
prefix, ltarget, _ := strings.Cut(link, ".")
if prefix != "C" {
panic("resolveLinkname: invalid link: " + link)
}
return ltarget
}
return name
}
2024-04-20 17:31:49 +08:00
// -----------------------------------------------------------------------------