-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodegen.fs
52 lines (46 loc) · 1.63 KB
/
Codegen.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
module Codegen
open LLVMSharp
open Parser
open System.Collections.Generic
let context = LLVMContextRef.Global
let themodule = context.CreateModuleWithName "module"
let builder = context.CreateBuilder()
let name_values = Dictionary<_, _>()
let rec codegen expr =
let (!) = codegen
let (!!) = List.map codegen >> List.toArray
match expr with
| Expr.Number f -> LLVMValueRef.CreateConstReal(context.DoubleType, f)
| Variable n -> name_values.[n]
| Binop((op, _), rhs, lhs) ->
match op with
| "+" -> builder.BuildFAdd(!lhs, !rhs)
| "-" -> builder.BuildFSub(!lhs, !rhs)
| "*" -> builder.BuildFMul(!lhs, !rhs)
| "<" ->
let bool = builder.BuildFCmp(LLVMRealPredicate.LLVMRealULT, !lhs, !rhs)
builder.BuildUIToFP(bool, context.DoubleType)
| _ -> failwithf "Invalid operator %O" op
| Call(callee, args) -> builder.BuildCall(!callee, !! args)
| Func(name, param, body) ->
let func =
let typ = [| for p in param -> context.DoubleType |]
let ty = LLVMTypeRef.CreateFunction(context.DoubleType, typ)
themodule.AddFunction(name, ty)
name_values.[name] <- func
for i, p in List.indexed param do name_values.[p] <- func.GetParam (uint32 i)
let bb = func.AppendBasicBlock "entry"
builder.PositionAtEnd bb
let _ = builder.BuildRet (! body)
func
| Extern(name, param) ->
let func =
let typ = [| for p in param -> context.DoubleType |]
let ty = LLVMTypeRef.CreateFunction(context.DoubleType, typ)
themodule.AddFunction(name, ty)
name_values.[name] <- func
func
let dump_ir expr =
let value = codegen expr
value.Dump()
printfn ""