diff --git a/asm/amd64/codegen.go b/asm/amd64/codegen.go index a7bc120..fd4285e 100644 --- a/asm/amd64/codegen.go +++ b/asm/amd64/codegen.go @@ -41,7 +41,7 @@ func CgProgram(prog *ttir.Program) *Program { return &newProgram } -func cgFunction(f ttir.Function) Function { +func cgFunction(f *ttir.Function) Function { newInstructions := []Instruction{} for _, inst := range f.Instructions { diff --git a/asm/qbe/qbe.go b/asm/qbe/qbe.go index 9e3d1e0..084df54 100644 --- a/asm/qbe/qbe.go +++ b/asm/qbe/qbe.go @@ -19,6 +19,28 @@ func emitf(w io.Writer, format string, args ...any) error { } func Emit(output io.Writer, input *ttir.Program) error { + if input.MainFunction.HasReturnValue { + emitf(output, ` +export function $_start() { +@start + %%result =l call $main() + call $syscall1(l 60, l %%result) + hlt +} + `, + ) + } else { + emitf(output, ` +export function $_start() { +@start + call $main() + call $syscall1(l 60, l 0) + hlt +} +`, + ) + } + for _, f := range input.Functions { err := emitFunction(output, f) if err != nil { @@ -28,7 +50,7 @@ func Emit(output io.Writer, input *ttir.Program) error { return nil } -func emitFunction(w io.Writer, f ttir.Function) error { +func emitFunction(w io.Writer, f *ttir.Function) error { emitf(w, "export function ") if f.HasReturnValue { if err := emitf(w, "l "); err != nil { diff --git a/test.tt b/test.tt index 516ad28..04f1db5 100644 --- a/test.tt +++ b/test.tt @@ -1,6 +1,3 @@ fn main() = { - 5 <= 4; - 5 < 4; - 5 >= 4; - 5 > 4; + 3 }; diff --git a/ttir/emit.go b/ttir/emit.go index 336353e..5d8990c 100644 --- a/ttir/emit.go +++ b/ttir/emit.go @@ -15,27 +15,35 @@ func temp() string { } func EmitProgram(program *tast.Program) *Program { - functions := make([]Function, 0) + functions := make([]*Function, 0) + var mainFunction *Function for _, decl := range program.Declarations { switch decl := decl.(type) { case *tast.FunctionDeclaration: - functions = append(functions, *emitFunction(decl)) + f := emitFunction(decl) + functions = append(functions, f) + if f.Name == "main" { + mainFunction = f + } } } return &Program{ - Functions: functions, + Functions: functions, + MainFunction: mainFunction, } } func emitFunction(function *tast.FunctionDeclaration) *Function { value, instructions := emitExpression(function.Body) instructions = append(instructions, &Ret{Op: value}) - return &Function{ + f := &Function{ Name: function.Name, Instructions: instructions, HasReturnValue: !function.ReturnType.IsSameType(types.Unit), } + + return f } func emitExpression(expr tast.Expression) (Operand, []Instruction) { diff --git a/ttir/ttir.go b/ttir/ttir.go index b93356f..65a3a43 100644 --- a/ttir/ttir.go +++ b/ttir/ttir.go @@ -8,7 +8,8 @@ import ( ) type Program struct { - Functions []Function + Functions []*Function + MainFunction *Function } func (p *Program) String() string {