| 1 | module List = ListLabels |
| 2 | |
| 3 | module Temp = Tiger_temp |
| 4 | module T = Tiger_tree |
| 5 | |
| 6 | type access = |
| 7 | | InFrame of {offset_from_frame_pointer : int} |
| 8 | | InReg of {register : Temp.Temp.t} |
| 9 | |
| 10 | type t = |
| 11 | (* p.136 Frame.t is a data structure holding: |
| 12 | * - the locations of all the formals |
| 13 | * - instructions required to implement the "view shift" |
| 14 | * - the number of locals allocated so far |
| 15 | * - the `label` at which the function's machine code is to begin (see p.140) |
| 16 | * *) |
| 17 | { name : Temp.Label.t |
| 18 | ; formals : access list |
| 19 | ; locals_count : int |
| 20 | ; instructions : unit (* TODO: instructions for view shift *) |
| 21 | } |
| 22 | |
| 23 | let pointer = Temp.Temp.gen () |
| 24 | |
| 25 | let word_size_bits = 32 |
| 26 | let word_size_bytes = word_size_bits / 8 |
| 27 | let word_size = word_size_bytes |
| 28 | |
| 29 | let name {name; _} = |
| 30 | name |
| 31 | |
| 32 | let formals {formals; _} = |
| 33 | formals |
| 34 | |
| 35 | let alloc offset_from_frame_pointer ~escapes = |
| 36 | if escapes then |
| 37 | InFrame {offset_from_frame_pointer} |
| 38 | else |
| 39 | InReg {register = Temp.Temp.gen ()} |
| 40 | |
| 41 | let alloc_local _ ~escapes = |
| 42 | (* FIXME: offset_from_frame_pointer. With neither mutation nor new frame? *) |
| 43 | let offset_from_frame_pointer = 0 in |
| 44 | alloc offset_from_frame_pointer ~escapes |
| 45 | |
| 46 | let make ~name ~formals = |
| 47 | (* p.136: For each formal parameter, "newFrame" must calculate two things: |
| 48 | * - How the parameter will be seen from inside the function |
| 49 | * (in a register, or in a frame location); |
| 50 | * - What instructions must be produced to implement the "view shift" |
| 51 | * *) |
| 52 | let formals, locals_count = |
| 53 | (* TODO: What should offset increment be? Word? *) |
| 54 | List.fold_left formals ~init:([], 0) ~f:(fun (formals, offset) escapes -> |
| 55 | ((alloc offset ~escapes) :: formals, succ offset) |
| 56 | ) |
| 57 | in |
| 58 | { name |
| 59 | ; formals |
| 60 | ; locals_count |
| 61 | ; instructions = () (* TODO: instructions for view shift *) |
| 62 | } |
| 63 | |
| 64 | (*failwith ("NOT IMPLEMENTED: " ^ __MODULE__ ^ ".exp")*) |
| 65 | |
| 66 | let exp ~access ~pointer = |
| 67 | match access with |
| 68 | | InReg {register} -> |
| 69 | T.TEMP register |
| 70 | | InFrame {offset_from_frame_pointer} -> |
| 71 | T.MEM (T.BINOP (T.PLUS, pointer, T.CONST offset_from_frame_pointer)) |