Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions builder/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,11 @@ func Build(pkgName, outpath, tmpdir string, config *compileopts.Config) (BuildRe
if err != nil {
return err
}
if strings.HasPrefix(config.Triple(), "wasm") {
if err := compiler.ValidateWasmFunctionParameters(mod); err != nil {
Comment thread
jakebailey marked this conversation as resolved.
return err
}
}

// Make sure stack sizes are loaded from a separate section so they can be
// modified after linking.
Expand Down
46 changes: 17 additions & 29 deletions compiler/calls.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,6 @@ func (b *builder) createInvoke(fnType llvm.Type, fn llvm.Value, args []llvm.Valu
return b.createCall(fnType, fn, args, name)
}

// Expand an argument type to a list that can be used in a function call
// parameter list.
func (c *compilerContext) expandFormalParamType(t llvm.Type, name string, goType types.Type) []paramInfo {
if c.isIndirectAggregate(t) {
return []paramInfo{{
llvmType: c.dataPtrType,
name: name,
elemSize: c.targetData.TypeAllocSize(t),
flags: paramIsGoParam | paramIsReadonly | paramIsIndirect,
}}
}
return c.expandDirectFormalParamType(t, name, goType)
}

func (c *compilerContext) expandDirectFormalParamType(t llvm.Type, name string, goType types.Type) []paramInfo {
switch t.TypeKind() {
case llvm.StructTypeKind:
Expand All @@ -130,34 +116,36 @@ func (c *compilerContext) expandDirectFormalParamType(t llvm.Type, name string,
return []paramInfo{c.getParamInfo(t, name, goType)}
}

func (c *compilerContext) storedParamType(t llvm.Type, exported bool) llvm.Type {
if c.isIndirectParam(t, exported) {
func (c *compilerContext) storedParamType(t llvm.Type) llvm.Type {
if c.isIndirectAggregate(t) {
return c.dataPtrType
}
return t
}

func (c *compilerContext) isIndirectParam(t llvm.Type, exported bool) bool {
return !exported && c.isIndirectAggregate(t)
}

func (b *builder) appendStoredValueTypes(valueTypes []llvm.Type, values []ssa.Value, exported bool) []llvm.Type {
for _, value := range values {
valueTypes = append(valueTypes, b.storedParamType(b.getLLVMType(value.Type()), exported))
func (b *builder) appendStoredParamTypes(valueTypes []llvm.Type, params []functionABIParam) []llvm.Type {
for _, param := range params {
if param.indirect {
valueTypes = append(valueTypes, b.dataPtrType)
} else {
valueTypes = append(valueTypes, param.llvmType)
}
}
return valueTypes
}

func (b *builder) appendStoredParamTypes(valueTypes []llvm.Type, params []*types.Var, exported bool) []llvm.Type {
for _, param := range params {
valueTypes = append(valueTypes, b.storedParamType(b.getLLVMType(param.Type()), exported))
func (b *builder) getCallArguments(values []ssa.Value, params []functionABIParam) []llvm.Value {
args := make([]llvm.Value, len(values))
for i, value := range values {
args[i] = b.getCallArgument(value, params[i].indirect)
}
return valueTypes
return args
}

func (b *builder) prependIndirectResult(sig *types.Signature, exported bool, params []llvm.Value, name string) []llvm.Value {
if resultType, indirect := b.hasIndirectResult(sig); !exported && indirect {
return append([]llvm.Value{b.createIndirectStorage(resultType, name)}, params...)
abi := b.getFunctionABI(sig, exported)
if abi.indirectResult {
return append([]llvm.Value{b.createIndirectStorage(abi.resultType, name)}, params...)
}
return params
}
Expand Down
41 changes: 21 additions & 20 deletions compiler/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ type compilerContext struct {
program *ssa.Program
diagnostics []error
functionInfos map[*ssa.Function]functionInfo
functionABIs map[functionABIKey]functionABI
astComments map[string]*ast.CommentGroup
embedGlobals map[string][]*loader.EmbedFile
pkg *types.Package
Expand All @@ -107,6 +108,7 @@ func newCompilerContext(moduleName string, machine llvm.TargetMachine, config *C
machine: machine,
targetData: machine.CreateTargetData(),
functionInfos: map[*ssa.Function]functionInfo{},
functionABIs: map[functionABIKey]functionABI{},
astComments: map[string]*ast.CommentGroup{},
}

Expand Down Expand Up @@ -1284,27 +1286,23 @@ func (b *builder) createFunctionStart(intrinsic bool) {
}

// Load function parameters
abi := b.getFunctionABI(b.fn.Signature, b.info.exported)
llvmParamIndex := 0
if _, indirectResult := b.hasIndirectResult(b.fn.Signature); indirectResult && !b.info.exported {
if abi.indirectResult {
b.indirectReturn = b.llvmFn.Param(llvmParamIndex)
b.indirectReturn.SetName("return")
llvmParamIndex++
}
for _, param := range b.fn.Params {
llvmType := b.getLLVMType(param.Type())
if b.isIndirectParam(llvmType, b.info.exported) {
for i, param := range b.fn.Params {
llvmType := abi.params[i].llvmType
if abi.params[i].indirect {
llvmParam := b.llvmFn.Param(llvmParamIndex)
llvmParam.SetName(param.Name())
b.indirectValues[param] = llvmParam
llvmParamIndex++
continue
}
var paramInfos []paramInfo
if b.info.exported {
paramInfos = b.expandDirectFormalParamType(llvmType, param.Name(), param.Type())
} else {
paramInfos = b.expandFormalParamType(llvmType, param.Name(), param.Type())
}
paramInfos := b.expandDirectFormalParamType(llvmType, param.Name(), param.Type())
fields := make([]llvm.Value, 0, 1)
for _, info := range paramInfos {
param := b.llvmFn.Param(llvmParamIndex)
Expand Down Expand Up @@ -1444,8 +1442,9 @@ func (b *builder) createFunction() {
for _, phi := range b.phis {
block := phi.ssa.Block()
for i, edge := range phi.ssa.Edges {
llvmVal := b.getCallArgument(edge, false)
llvmBlock := b.blockInfo[block.Preds[i].Index].exit
b.SetInsertPointBefore(llvmBlock.LastInstruction())
llvmVal := b.getCallArgument(edge, b.isIndirectAggregate(b.getLLVMType(edge.Type())))
phi.llvm.AddIncoming([]llvm.Value{llvmVal}, []llvm.BasicBlock{llvmBlock})
}
}
Expand Down Expand Up @@ -1676,9 +1675,8 @@ func (b *builder) getValuePointer(value ssa.Value) llvm.Value {
return ptr
}

func (b *builder) getCallArgument(value ssa.Value, exported bool) llvm.Value {
paramType := b.getLLVMType(value.Type())
if b.isIndirectParam(paramType, exported) {
func (b *builder) getCallArgument(value ssa.Value, indirect bool) llvm.Value {
if indirect {
return b.getValuePointer(value)
}
return b.getValue(value, getPos(value))
Expand Down Expand Up @@ -2323,18 +2321,21 @@ func (b *builder) createFunctionCall(instr *ssa.CallCommon) (llvm.Value, error)
b.createNilCheck(instr.Value, callee, "fpcall")
}

var params []llvm.Value
for _, param := range instr.Args {
params = append(params, b.getCallArgument(param, exported))
abi := b.getFunctionABI(instr.Signature(), exported)
paramOffset := 0
if instr.IsInvoke() {
abi = b.getInterfaceFunctionABI(instr.Signature())
paramOffset = 1
}
params := b.getCallArguments(instr.Args, abi.params[paramOffset:])
if instr.IsInvoke() {
params = append([]llvm.Value{invokeReceiver}, params...)
params = append(params, invokeTypecode)
}

if !exported {
if resultType, indirectResult := b.hasIndirectResult(instr.Signature()); indirectResult {
result := b.createIndirectStorage(resultType, "call.result")
if abi.indirectResult {
result := b.createIndirectStorage(abi.resultType, "call.result")
params = append([]llvm.Value{result}, params...)
params = append(params, context)
b.createInvoke(calleeType, callee, params, "")
Expand Down Expand Up @@ -2715,7 +2716,7 @@ func (b *builder) createExpr(expr ssa.Value) (llvm.Value, error) {
return b.createMapIteratorNext(rangeVal, llvmRangeVal, it), nil
}
case *ssa.Phi:
phiType := b.storedParamType(b.getLLVMType(expr.Type()), false)
phiType := b.storedParamType(b.getLLVMType(expr.Type()))
phi := b.CreatePHI(phiType, "")
b.phis = append(b.phis, phiNode{expr, phi})
return phi, nil
Expand Down
144 changes: 144 additions & 0 deletions compiler/compiler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,147 @@ func TestOptimizedLargeAggregateABI(t *testing.T) {
}
}

func TestAggregateFunctionABI(t *testing.T) {
for _, target := range []string{"wasm", "cortex-m-qemu"} {
t.Run(target, func(t *testing.T) {
options := &compileopts.Options{Target: target}
if target != "wasm" {
options.Scheduler = "tasks"
}
mod, errs := testCompilePackage(t, options, "aggregate-abi.go")
if len(errs) != 0 {
for _, err := range errs {
t.Error(err)
}
return
}
defer mod.Dispose()

passOptions := llvm.NewPassBuilderOptions()
defer passOptions.Dispose()
if err := mod.RunPasses("default<O2>", llvm.TargetMachine{}, passOptions); err != nil {
t.Fatal(err)
}
if err := llvm.VerifyModule(mod, llvm.ReturnStatusAction); err != nil {
t.Fatal(err)
}

checkFunctionParamABI(t, mod, "main.readDirectAggregates", false, false)
checkFunctionParamABI(t, mod, "main.readLimitAggregates", false, false)
checkFunctionParamABI(t, mod, "main.readBoundaryAggregates", true, false)
checkFunctionParamABI(t, mod, "main.readAggregates", true, false)
checkFunctionParamABI(t, mod, "main.readSingleAggregate", false)
checkFunctionParamABI(t, mod, "main.readThreeAggregates", true, false, false)
checkFunctionParamABI(t, mod, "main.readResultBudget", false, true)
checkFunctionParamABI(t, mod, "readAggregateExport", false)
if target == "wasm" {
if err := ValidateWasmFunctionParameters(mod); err != nil {
t.Error(err)
}
}
})
}
}

func checkFunctionParamABI(t *testing.T, mod llvm.Module, name string, indirect ...bool) {
t.Helper()
fn := mod.NamedFunction(name)
if fn.IsNil() {
t.Fatalf("missing function %s", name)
}
paramTypes := fn.GlobalValueType().ParamTypes()
for i, wantIndirect := range indirect {
gotIndirect := paramTypes[i].TypeKind() == llvm.PointerTypeKind
if gotIndirect != wantIndirect {
t.Errorf("%s parameter %d indirect=%t, want %t", name, i, gotIndirect, wantIndirect)
}
}
}

func TestAggregateExportedInterfaceABI(t *testing.T) {
options := &compileopts.Options{Target: "wasm"}
mod, errs := testCompilePackage(t, options, "aggregate-export-abi.go")
defer mod.Dispose()

for _, err := range errs {
t.Error(err)
}

var markedWrappers int
for fn := mod.FirstFunction(); !fn.IsNil(); fn = llvm.NextFunction(fn) {
if attr := fn.GetStringAttributeAtIndex(-1, "tinygo-interface-abi-error"); !attr.IsNil() {
markedWrappers++
}
}
if markedWrappers != 1 {
t.Errorf("found %d exported interface ABI markers, want 1", markedWrappers)
}
if err := ValidateWasmFunctionParameters(mod); err == nil {
t.Error("missing oversized WebAssembly signature error")
}
}

func TestValidateWasmFunctionParameters(t *testing.T) {
for _, test := range []struct {
name string
params int
resultFields int
declaration bool
used bool
wantError bool
}{
{"at limit", 999, 2, false, false, false},
{"hidden result over limit", 1000, 2, false, false, true},
{"single result at limit", 1000, 1, false, false, false},
{"empty result at limit", 1000, 0, false, false, false},
{"unused declaration", 1001, 0, true, false, false},
{"used declaration", 1001, 0, true, true, true},
} {
t.Run(test.name, func(t *testing.T) {
ctx := llvm.NewContext()
defer ctx.Dispose()
mod := ctx.NewModule("test")
defer mod.Dispose()
builder := ctx.NewBuilder()
defer builder.Dispose()

paramTypes := make([]llvm.Type, test.params)
for i := range paramTypes {
paramTypes[i] = ctx.Int32Type()
}
resultFields := make([]llvm.Type, test.resultFields)
for i := range resultFields {
resultFields[i] = ctx.Int32Type()
}
resultType := ctx.StructType(resultFields, false)
fnType := llvm.FunctionType(resultType, paramTypes, false)
fn := llvm.AddFunction(mod, "test", fnType)
if test.declaration {
if test.used {
caller := llvm.AddFunction(mod, "caller", llvm.FunctionType(ctx.VoidType(), nil, false))
block := ctx.AddBasicBlock(caller, "entry")
builder.SetInsertPointAtEnd(block)
args := make([]llvm.Value, len(paramTypes))
for i, paramType := range paramTypes {
args[i] = llvm.Undef(paramType)
}
builder.CreateCall(fnType, fn, args, "")
builder.CreateRetVoid()
}
} else {
block := ctx.AddBasicBlock(fn, "entry")
builder.SetInsertPointAtEnd(block)
builder.CreateRet(llvm.Undef(resultType))
}

err := ValidateWasmFunctionParameters(mod)
if (err != nil) != test.wantError {
t.Errorf("ValidateWasmFunctionParameters() error = %v, wantError = %t", err, test.wantError)
}
})
}
}

// normalizeIR canonicalizes LLVM-version-specific IR spellings for comparison
// and when regenerating golden files.
func normalizeIR(s string) string {
Expand Down Expand Up @@ -280,6 +421,9 @@ func filterIrrelevantIRLines(lines []string) []string {
if strings.HasPrefix(line, "source_filename = ") {
continue
}
if strings.HasPrefix(line, "@tinygo.indirect-abi = ") {
continue
}
if llvmVersion < 15 && strings.HasPrefix(line, "target datalayout = ") {
// The datalayout string may vary betewen LLVM versions.
// Right now test outputs are for LLVM 15 and higher.
Expand Down
Loading
Loading