Files
llgo/cl/compile.go

1197 lines
30 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
2025-04-03 15:52:18 +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"
2025-04-03 15:52:18 +08:00
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
debugGoSSA bool
enableCallTracing bool
enableDbg bool
enableDbgSyms bool
disableInline 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
}
func EnableDebug(b bool) {
enableDbg = b
}
func EnableDbgSyms(b bool) {
enableDbgSyms = b
2024-09-13 20:23:56 +08:00
}
2025-02-10 22:28:25 +08:00
func EnableTrace(b bool) {
enableCallTracing = b
2025-02-10 22:28:25 +08:00
}
2024-04-21 17:54:51 +08:00
// -----------------------------------------------------------------------------
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 {
2025-10-15 13:36:52 +08:00
prog llssa.Program
pkg llssa.Package
fn llssa.Function
fset *token.FileSet
goProg *ssa.Program
goTyps *types.Package
goPkg *ssa.Package
pyMod string
skips map[string]none
loaded map[*types.Package]*pkgInfo // loaded packages
bvals map[ssa.Value]llssa.Expr // block values
vargs map[*ssa.Alloc][]llssa.Expr // varargs
paramDIVars map[*types.Var]llssa.DIVar
patches Patches
2024-06-05 15:08:05 +08:00
blkInfos []blocks.Info
2024-08-08 21:36:18 +08:00
inits []func()
phis []func()
initAfter func()
2024-06-16 21:32:11 +08:00
2024-06-18 18:23:16 +08:00
state pkgState
inCFunc bool
skipall bool
cgoCalled bool
cgoArgs []llssa.Expr
cgoRet llssa.Expr
cgoSymbols []string
}
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
)
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-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) {
typ := p.patchType(gbl.Type())
name, vtype, define := p.varName(gbl.Pkg.Pkg, gbl)
2025-01-16 21:55:25 +08:00
if vtype == pyVar {
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-11-26 22:34:19 +08:00
func isCgoExternSymbol(f *ssa.Function) bool {
2024-11-24 22:45:25 +08:00
name := f.Name()
return isCgoCfunc(name) || isCgoCmacro(name)
}
2025-01-11 16:47:23 +08:00
func isCgoCfpvar(name string) bool {
return strings.HasPrefix(name, "_Cfpvar_")
}
2024-11-24 22:45:25 +08:00
func isCgoCfunc(name string) bool {
return strings.HasPrefix(name, "_Cfunc_")
}
func isCgoCmacro(name string) bool {
return strings.HasPrefix(name, "_Cmacro_")
}
2024-11-26 22:34:19 +08:00
func isCgoVar(name string) bool {
return strings.HasPrefix(name, "__cgo_")
}
func (p *context) compileFuncDecl(pkg llssa.Package, f *ssa.Function) (llssa.Function, llssa.PyObjRef, int) {
2025-06-23 21:14:26 +08:00
pkgTypes, name, ftype := p.funcName(f)
if ftype != goFunc {
2024-05-11 21:55:50 +08:00
return nil, nil, ignoredFunc
}
2025-07-03 20:48:51 +08:00
sig := p.patchType(f.Signature).(*types.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
}
if fn == nil {
2024-08-09 22:23:48 +08:00
fn = pkg.NewFuncEx(name, sig, llssa.Background(ftype), hasCtx, f.Origin() != nil)
if disableInline {
2024-09-29 16:20:41 +08:00
fn.Inline(llssa.NoInline)
}
}
// set compiled to check generic function global instantiation
pkg.Prog.SetFuncCompiled(name)
2024-11-26 22:34:19 +08:00
isCgo := isCgoExternSymbol(f)
if nblk := len(f.Blocks); nblk > 0 {
p.cgoCalled = false
p.cgoArgs = nil
2024-11-24 22:45:25 +08:00
if isCgo {
fn.MakeBlocks(1)
} else {
fn.MakeBlocks(nblk) // to set fn.HasBody() = true
}
2024-06-18 17:33:37 +08:00
if f.Recover != nil { // set recover block
fn.SetRecover(fn.Block(f.Recover.Index))
}
2025-10-15 13:36:52 +08:00
dbgEnabled := enableDbg && (f == nil || f.Origin() == nil)
dbgSymsEnabled := enableDbgSyms && (f == nil || f.Origin() == nil)
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
2025-10-15 13:36:52 +08:00
if dbgSymsEnabled {
p.paramDIVars = make(map[*types.Var]llssa.DIVar)
} else {
p.paramDIVars = nil
}
if debugGoSSA {
f.WriteTo(os.Stderr)
}
if debugInstr {
log.Println("==> FuncBody", name)
}
b := fn.NewBuilder()
2025-10-15 13:36:52 +08:00
if dbgEnabled {
2024-09-24 18:16:11 +08:00
pos := p.goProg.Fset.Position(f.Pos())
bodyPos := p.getFuncBodyPos(f)
b.DebugFunction(fn, pos, bodyPos)
2024-09-13 17:15:36 +08:00
}
p.bvals = make(map[ssa.Value]llssa.Expr)
2024-05-06 22:21:49 +08:00
off := make([]int, len(f.Blocks))
2024-11-24 22:45:25 +08:00
if isCgo {
p.cgoArgs = make([]llssa.Expr, len(f.Params))
for i, param := range f.Params {
p.cgoArgs[i] = p.compileValue(b, param)
}
} else {
for i, block := range f.Blocks {
off[i] = p.compilePhis(b, block)
}
2024-05-06 22:21:49 +08:00
}
2024-06-05 15:08:05 +08:00
p.blkInfos = blocks.Infos(f.Blocks)
i := 0
for {
block := f.Blocks[i]
2024-06-18 17:33:37 +08:00
doModInit := (i == 1 && isInit)
p.compileBlock(b, block, off[i], doModInit)
2024-11-24 22:45:25 +08:00
if isCgo {
// just process first block for performance
break
}
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-09-24 18:16:11 +08:00
func (p *context) getFuncBodyPos(f *ssa.Function) token.Position {
if f.Object() != nil {
if fn, ok := f.Object().(*types.Func); ok && fn.Scope() != nil {
return p.goProg.Fset.Position(fn.Scope().Pos())
}
2024-09-24 18:16:11 +08:00
}
return p.goProg.Fset.Position(f.Pos())
}
2024-09-29 16:20:41 +08:00
func isGlobal(v *types.Var) bool {
// TODO(lijie): better implementation
return strings.HasPrefix(v.Parent().String(), "package ")
}
2024-09-24 18:16:11 +08:00
func (p *context) debugRef(b llssa.Builder, v *ssa.DebugRef) {
2025-10-15 13:36:52 +08:00
if !enableDbgSyms || v.Parent().Origin() != nil {
return
}
2024-09-24 18:16:11 +08:00
object := v.Object()
variable, ok := object.(*types.Var)
if !ok {
// Not a local variable.
return
}
if variable.IsField() {
// skip *ssa.FieldAddr
return
}
2024-09-29 16:20:41 +08:00
if isGlobal(variable) {
// avoid generate local variable debug info of global variable in function
return
}
2024-09-24 18:16:11 +08:00
pos := p.goProg.Fset.Position(v.Pos())
value := p.compileValue(b, v.X)
fn := v.Parent()
dbgVar := p.getLocalVariable(b, fn, variable)
2024-09-29 16:20:41 +08:00
scope := variable.Parent()
diScope := b.DIScope(p.fn, scope)
2024-09-24 18:16:11 +08:00
if v.IsAddr {
// *ssa.Alloc
2024-09-29 16:20:41 +08:00
b.DIDeclare(variable, value, dbgVar, diScope, pos, b.Func.Block(v.Block().Index))
2024-09-24 18:16:11 +08:00
} else {
2024-09-29 16:20:41 +08:00
b.DIValue(variable, value, dbgVar, diScope, pos, b.Func.Block(v.Block().Index))
2024-09-24 18:16:11 +08:00
}
}
2024-09-10 11:04:32 +08:00
func (p *context) debugParams(b llssa.Builder, f *ssa.Function) {
2025-10-15 13:36:52 +08:00
if !enableDbgSyms || f.Origin() != nil {
return
}
2024-09-14 10:36:17 +08:00
for i, param := range f.Params {
2024-09-24 18:16:11 +08:00
variable := param.Object().(*types.Var)
2024-09-10 11:04:32 +08:00
pos := p.goProg.Fset.Position(param.Pos())
v := p.compileValue(b, param)
ty := param.Type()
2024-09-14 10:36:17 +08:00
argNo := i + 1
2024-11-25 11:17:06 +08:00
div := b.DIVarParam(p.fn, pos, param.Name(), p.type_(ty, llssa.InGo), argNo)
2025-10-15 13:36:52 +08:00
if p.paramDIVars != nil {
p.paramDIVars[variable] = div
}
2024-09-27 20:08:45 +08:00
b.DIParam(variable, v, div, p.fn, pos, p.fn.Block(0))
2024-09-10 11:04:32 +08:00
}
}
func (p *context) compileBlock(b llssa.Builder, block *ssa.BasicBlock, n int, 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-06-18 18:23:16 +08:00
var ret = fn.Block(block.Index)
2024-04-20 22:05:45 +08:00
b.SetBlock(ret)
if block.Index == 0 && enableCallTracing && !strings.HasPrefix(fn.Name(), "github.com/goplus/llgo/runtime/internal/runtime.Print") {
2025-02-10 22:28:25 +08:00
b.Printf("call " + fn.Name() + "\n\x00")
}
// place here to avoid wrong current-block
2025-10-15 13:36:52 +08:00
if enableDbgSyms && block.Parent().Origin() == nil && block.Index == 0 {
p.debugParams(b, block.Parent())
}
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-08-08 21:36:18 +08:00
p.initAfter = func() {
pkg.AfterInit(b, ret)
2024-08-08 21:36:18 +08:00
}
2024-05-13 00:41:42 +08:00
}
2024-05-11 11:33:35 +08:00
}
2024-11-24 22:45:25 +08:00
fnName := block.Parent().Name()
cgoReturned := false
2024-11-24 22:45:25 +08:00
isCgoCfunc := isCgoCfunc(fnName)
isCgoCmacro := isCgoCmacro(fnName)
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-11-24 22:45:25 +08:00
if isCgoCfunc || isCgoCmacro {
switch instr := instr.(type) {
case *ssa.Alloc:
// return value allocation
p.compileInstr(b, instr)
case *ssa.UnOp:
// load cgo function pointer
2024-11-24 22:45:25 +08:00
varName := instr.X.Name()
if instr.Op == token.MUL && strings.HasPrefix(varName, "_cgo_") {
p.cgoSymbols = append(p.cgoSymbols, varName)
p.compileInstr(b, instr)
}
case *ssa.Call:
2024-11-24 22:45:25 +08:00
if isCgoCmacro {
p.cgoRet = p.compileValue(b, instr.Call.Args[0])
p.cgoCalled = true
} else {
// call c function
p.compileInstr(b, instr)
p.cgoCalled = true
}
case *ssa.Return:
// return cgo function result
2024-11-24 22:45:25 +08:00
if isCgoCmacro {
ty := p.type_(instr.Results[0].Type(), llssa.InGo)
p.cgoRet.Type = p.prog.Pointer(ty)
p.cgoRet = b.Load(p.cgoRet)
}
2024-11-24 22:45:25 +08:00
b.Return(p.cgoRet)
cgoReturned = true
}
} else {
p.compileInstr(b, instr)
}
}
// is cgo cfunc but not return yet, some funcs has multiple blocks
2024-11-24 22:45:25 +08:00
if (isCgoCfunc || isCgoCmacro) && !cgoReturned {
if !p.cgoCalled {
panic("cgo cfunc not called")
}
for _, block := range block.Parent().Blocks {
for _, instr := range block.Instrs {
2024-11-24 22:45:25 +08:00
if _, ok := instr.(*ssa.Return); ok {
b.Return(p.cgoRet)
goto end
}
}
}
2024-04-20 15:58:34 +08:00
}
end:
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))
2024-06-18 18:23:16 +08:00
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"
)
2024-04-25 14:25:14 +08:00
func isAny(t types.Type) bool {
2025-01-08 14:56:10 +08:00
if t, ok := t.Underlying().(*types.Interface); ok {
2024-04-25 14:25:14 +08:00
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
}
2025-09-09 13:20:01 +08:00
if call.IsInvoke() {
return llssa.HasNameValist(call.Signature())
}
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-11-25 11:17:06 +08:00
phi := b.Phi(p.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-11-25 11:17:06 +08:00
ret = b.ChangeType(p.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-11-25 11:17:06 +08:00
ret = b.Convert(p.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-11-25 11:17:06 +08:00
elem := p.type_(t.Elem(), llssa.InGo)
2024-05-05 12:11:51 +08:00
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)
2025-02-03 20:13:57 +08:00
ret.Type = b.Prog.Type(v.Type(), llssa.InGo)
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-11-25 11:17:06 +08:00
t := p.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-11-25 11:17:06 +08:00
t := p.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-11-25 11:17:06 +08:00
t := p.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-11-25 11:17:06 +08:00
t := p.type_(v.AssertedType, llssa.InGo)
2024-05-05 12:11:51 +08:00
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 {
2024-11-25 11:17:06 +08:00
typ = p.type_(v.Iter.(*ssa.Range).X.Type(), llssa.InGo)
2024-06-29 20:43:12 +08:00
}
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)
2024-11-25 11:17:06 +08:00
ret = b.ChangeInterface(p.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)
2024-11-25 11:17:06 +08:00
ret = b.MakeChan(p.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-08-09 08:53:39 +08:00
case *ssa.SliceToArrayPointer:
2024-11-25 11:17:06 +08:00
t := p.type_(v.Type(), llssa.InGo)
2024-08-09 08:53:39 +08:00
x := p.compileValue(b, v.X)
ret = b.SliceToArrayPointer(x, t)
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-09-29 16:20:41 +08:00
func (p *context) getDebugLocScope(v *ssa.Function, pos token.Pos) *types.Scope {
if v.Object() == nil {
return nil
}
funcScope := v.Object().(*types.Func).Scope()
if funcScope == nil {
return nil
}
2024-09-29 16:20:41 +08:00
return funcScope.Innermost(pos)
}
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
}
2025-10-15 13:36:52 +08:00
if enableDbg && instr.Parent().Origin() == nil {
2024-09-29 16:20:41 +08:00
scope := p.getDebugLocScope(instr.Parent(), instr.Pos())
if scope != nil {
diScope := b.DIScope(p.fn, scope)
pos := p.fset.Position(instr.Pos())
b.DISetCurrentDebugLocation(diScope, pos)
}
}
2024-04-20 17:31:49 +08:00
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)
}
}
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-09-10 11:04:32 +08:00
case *ssa.DebugRef:
2025-10-15 13:36:52 +08:00
if enableDbgSyms && v.Parent().Origin() == nil {
2024-09-24 18:16:11 +08:00
p.debugRef(b, v)
2024-09-14 17:38:56 +08:00
}
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-09-10 11:04:32 +08:00
func (p *context) getLocalVariable(b llssa.Builder, fn *ssa.Function, v *types.Var) llssa.DIVar {
2025-10-15 13:36:52 +08:00
if p.paramDIVars != nil {
if div, ok := p.paramDIVars[v]; ok {
return div
}
}
2024-09-10 11:04:32 +08:00
pos := p.fset.Position(v.Pos())
2024-11-25 11:17:06 +08:00
t := p.type_(v.Type(), llssa.InGo)
2024-09-10 11:04:32 +08:00
for i, param := range fn.Params {
if param.Object().(*types.Var) == v {
2024-09-14 10:36:17 +08:00
argNo := i + 1
2025-10-15 13:36:52 +08:00
div := b.DIVarParam(p.fn, pos, v.Name(), t, argNo)
if p.paramDIVars != nil {
p.paramDIVars[v] = div
}
return div
2024-09-10 11:04:32 +08:00
}
}
2024-09-29 16:20:41 +08:00
scope := b.DIScope(p.fn, v.Parent())
return b.DIVarAuto(scope, pos, v.Name(), t)
2024-09-10 11:04:32 +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 b.Param(idx)
2024-04-20 23:15:10 +08:00
}
}
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:
2024-11-26 22:34:19 +08:00
varName := v.Name()
2024-09-18 22:05:41 +08:00
val := p.varOf(b, v)
2024-11-26 22:34:19 +08:00
if isCgoVar(varName) {
p.cgoSymbols = append(p.cgoSymbols, val.Name())
2024-11-26 22:34:19 +08:00
}
if enableDbgSyms {
2024-09-18 22:05:41 +08:00
pos := p.fset.Position(v.Pos())
b.DIGlobal(val, v.Name(), pos)
}
return val
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
}
2024-11-25 11:17:06 +08:00
return b.Const(v.Value, p.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
}
case *ssa.Parameter:
2025-09-09 13:20:01 +08:00
if llssa.HasNameValist(v.Parent().Signature) {
return ret
}
2024-04-21 17:54:51 +08:00
}
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) {
ret, _, err = NewPackageEx(prog, nil, pkg, files)
return
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, externs []string, 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)
if enableDbg {
ret.InitDebug(pkgName, pkgPath, pkgProg.Fset)
2024-09-13 17:15:36 +08:00
}
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,
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
},
cgoSymbols: make([]string, 0, 128),
2024-04-20 17:31:49 +08:00
}
2024-05-11 10:07:46 +08:00
ctx.initPyModule()
2025-06-23 22:01:42 +08:00
ctx.initFiles(pkgPath, files, pkgName == "C")
2024-11-25 11:17:06 +08:00
ctx.prog.SetPatch(ctx.patchType)
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-08-08 21:36:18 +08:00
if fn := ctx.initAfter; fn != nil {
ctx.initAfter = nil
fn()
}
externs = ctx.cgoSymbols
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:
2025-01-11 16:47:23 +08:00
if !isCgoVar(member.Name()) {
ctx.compileGlobal(ret, member)
}
2023-12-10 15:34:42 +08:00
}
}
// check instantiate named in RuntimeTypes
var typs []*types.Named
for _, T := range pkg.Prog.RuntimeTypes() {
if typ, ok := T.(*types.Named); ok && typ.TypeArgs() != nil && typ.Obj().Pkg() == pkg.Pkg {
typs = append(typs, typ)
}
}
sort.Slice(typs, func(i, j int) bool {
2025-02-01 13:30:33 +08:00
return typs[i].String() < typs[j].String()
})
for _, typ := range typs {
ctx.compileMethods(ret, typ)
ctx.compileMethods(ret, types.NewPointer(typ))
}
2023-12-11 00:37:09 +08:00
}
2024-11-25 11:17:06 +08:00
func (p *context) type_(typ types.Type, bg llssa.Background) llssa.Type {
return p.prog.Type(p.patchType(typ), bg)
}
2025-07-03 20:48:51 +08:00
func (p *context) patchType(typ types.Type) (r types.Type) {
r, _ = p._patchType(typ)
return
}
func (p *context) _patchType(typ types.Type) (types.Type, bool) {
switch typ := typ.(type) {
case *types.Pointer:
2025-07-03 20:48:51 +08:00
if t, ok := p._patchType(typ.Elem()); ok {
return types.NewPointer(t), true
}
case *types.Named:
o := typ.Obj()
2024-06-28 15:14:30 +08:00
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 {
2025-07-03 20:48:51 +08:00
raw := p.prog.Type(instantiate(obj.Type(), typ), llssa.InGo).RawType()
return raw, typ != raw
2024-06-28 15:14:30 +08:00
}
}
}
2025-07-03 20:48:51 +08:00
case *types.Tuple:
var patched bool
vars := make([]*types.Var, typ.Len())
for i := 0; i < typ.Len(); i++ {
v := typ.At(i)
if t, ok := p._patchType(v.Type()); ok {
vars[i] = types.NewVar(v.Pos(), v.Pkg(), v.Name(), t)
patched = true
} else {
vars[i] = v
}
}
if patched {
return types.NewTuple(vars...), true
}
case *types.Signature:
params, ok1 := p._patchType(typ.Params())
results, ok2 := p._patchType(typ.Results())
if ok1 || ok2 {
return types.NewSignature(typ.Recv(), params.(*types.Tuple), results.(*types.Tuple), typ.Variadic()), true
}
2024-06-28 15:14:30 +08:00
}
2025-07-03 20:48:51 +08:00
return typ, false
2024-06-28 15:14:30 +08:00
}
2024-10-30 21:02:08 +08:00
func instantiate(orig types.Type, t *types.Named) (typ types.Type) {
typ, _ = llssa.Instantiate(orig, t)
return
}
func (p *context) resolveLinkname(name string) string {
if link, ok := p.prog.Linkname(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
// -----------------------------------------------------------------------------