Example #1
0
func main() {
	flag.Parse()

	if flag.NArg() < 1 {
		println("USAGE: brainfuck <program file>")
		return
	}

	codeFile := flag.Arg(0)
	source, err := os.Open(codeFile)
	if err != nil {
		panic(err)
	}
	defer source.Close()

	parser := new(Parser)
	parser.Source = bufio.NewReader(source)

	println("Parsing...")
	if err := parser.Parse(); err != nil {
		panic(err)
	}

	println("Building...")
	bundle, err := parser.BuildBundle()
	if err != nil {
		panic(err)
	}

	println("Generating code...")
	mod := ir.NewModule("mod")
	builder := ir.NewBuilder()

	mainFnType := ir.NewFunctionType([]ir.Type{}, ir.NewIntType(32), false)
	mainFn := mod.AddFunction("main", mainFnType)

	entry := mainFn.AddBlockAtStart("entry")
	builder.SetInsertAtBlockStart(entry)

	bundle.Codegen(builder)

	_ = x86.NewTarget(platform.Linux)
}
Example #2
0
func makeMod() *ir.Module {
	mod := ir.NewModule("mod")
	builder := ir.NewBuilder()

	/*ity := ir.NewIntType(32)

	mainFnType := ir.NewFunctionType([]ir.Type{ity}, ity, false)

	mainFn := mod.AddFunction("main", mainFnType)
	mainFn.Parameters()[0].SetName("thing")


	exFnType := ir.NewFunctionType([]ir.Type{ity}, ity, false)
	exFn := mod.AddFunction("ex", exFnType)
	exEntryblock := exFn.AddBlockAtEnd("entry")
	builder.SetInsertAtBlockEnd(exEntryblock)
	add := builder.CreateAdd("test", exFn.Parameters()[0], ir.NewIntLit(ity, 9))
	sub := builder.CreateSub("sub", add, ir.NewIntLit(ity, 3))
	mul := builder.CreateMul("mul", sub, ir.NewIntLit(ity, 3))
	rem := builder.CreateURem("rem", mul, ir.NewIntLit(ity, 4))

	exNextBlock := exFn.AddBlockAtEnd("next")
	builder.CreateBr(exNextBlock)
	builder.SetInsertAtBlockStart(exNextBlock)

	builder.CreateRet(rem)

	entryBlock := mainFn.AddBlockAtEnd("entry")
	builder.SetInsertAtBlockEnd(entryBlock)
	call := builder.CreateCall("call", exFn, ir.NewIntLit(ity, 1))
	builder.CreateRet(call)*/

	retType := ir.NewIntType(32)

	mainFnType := ir.NewFunctionType([]ir.Type{ir.NewIntType(32)}, retType, false)
	mainFn := mod.AddFunction("main", mainFnType)

	entry := mainFn.AddBlockAtStart("entry")
	builder.SetInsertAtBlockStart(entry)
	//builder.CreateRet(ir.NewIntLit(ir.NewIntType(1), 1))

	trueBlock := mainFn.AddBlockAtEnd("true")
	falseBlock := mainFn.AddBlockAtEnd("false")

	icmp := builder.CreateICmp("icmp", ir.IntSLT, ir.NewIntLit(ir.NewIntType(32), 10), ir.NewIntLit(ir.NewIntType(32), 10))

	builder.CreateBrif(icmp, trueBlock, falseBlock)

	builder.SetInsertAtBlockStart(trueBlock)
	builder.CreateRet(ir.NewIntLit(retType, 20))

	builder.SetInsertAtBlockStart(falseBlock)
	builder.CreateRet(ir.NewIntLit(retType, 10))

	fmt.Print(mod.String())
	err := mod.Validate()
	if err != nil {
		fmt.Println("\n\nError:", err)
		os.Exit(1)
	}

	return mod
}