assemble.ml 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. open Printf
  2. open Types
  3. open Util
  4. open Stringify
  5. let comline comment = InlineComment (EmptyLine, comment)
  6. let assemble program =
  7. let labcounter = ref 0 in
  8. let genlabel suffix =
  9. labcounter := !labcounter + 1;
  10. string_of_int !labcounter ^ "_" ^ suffix
  11. in
  12. let consts = Hashtbl.create 20 in
  13. let rec trav node =
  14. let rec trav_all = function
  15. | [] -> []
  16. | hd :: tl -> trav hd @ (trav_all tl)
  17. in
  18. let rec traverse_localfuns = function
  19. | LocalFuns body -> List.concat (List.map trav body)
  20. | Block body -> List.concat (List.map traverse_localfuns body)
  21. | _ -> []
  22. in
  23. match node with
  24. (* Global *)
  25. | Program (decls, _) ->
  26. trav_all decls
  27. | GlobalDef (_, ctype, name, _, _) ->
  28. [Comment (sprintf "global var \"%s\" at index %d" name (indexof node));
  29. Global ctype]
  30. | FunDec (ret_type, name, params, _) ->
  31. [Comment (sprintf "extern fun \"%s\" at index %d" name (indexof node));
  32. Import (name, ret_type, List.map typeof params)]
  33. | FunDef (export, ret_type, name, params, body, _) ->
  34. let label = labelof node in
  35. (if export then
  36. let param_types = List.map typeof params in
  37. [Export (name, ret_type, param_types, label)]
  38. else []) @
  39. [
  40. Comment (sprintf "fun \"%s\" with %d local vars" label (indexof node));
  41. Label label;
  42. RtnEnter (indexof node);
  43. ] @
  44. (trav body) @
  45. (match ret_type with Void -> [Ret Void] | _ -> []) @
  46. [EmptyLine] @
  47. (traverse_localfuns body)
  48. | VarDec (_, name, _, _) ->
  49. [comline (sprintf "local var \"%s\" at index %d" name (indexof node))]
  50. | DimDec (name, _, _) ->
  51. [comline (sprintf "local dim \"%s\" at index %d" name (indexof node))]
  52. | LocalFuns _ -> []
  53. | Block body | VarDecs body -> trav_all body
  54. (* Statements *)
  55. | VarLet (dec, None, value, _) ->
  56. let store = match (depthof dec, depthof node) with
  57. | (0, _) -> Store (typeof dec, Glob, indexof dec)
  58. | (a, b) when a = b -> Store (typeof dec, Current, indexof dec)
  59. | (a, b) -> Store (typeof dec, Rel (b - a), indexof dec)
  60. in
  61. trav value @ [InlineComment (store, node2str node)]
  62. | Return (value, _) ->
  63. trav value @ [InlineComment (Ret (typeof value), node2str node)]
  64. | If (cond, body, _) ->
  65. let endlabel = genlabel "end" in
  66. (trav cond) @
  67. [Branch (false, endlabel);
  68. comline ("if (" ^ (node2str cond) ^ ") {")] @
  69. (trav body) @
  70. [comline "}";
  71. Label endlabel]
  72. | IfElse (cond, true_body, false_body, _) ->
  73. let elselabel = genlabel "else" in
  74. let endlabel = genlabel "end" in
  75. (trav cond) @
  76. [Branch (false, elselabel);
  77. comline ("if (" ^ (node2str cond) ^ ") {")] @
  78. (trav true_body) @
  79. [Jump endlabel;
  80. comline "} else {";
  81. Label elselabel] @
  82. (trav false_body) @
  83. [comline "}";
  84. Label endlabel]
  85. | While (cond, body, _) ->
  86. let startlabel = genlabel "while" in
  87. let endlabel = genlabel "end" in
  88. let com = ("while (" ^ (node2str cond) ^ ") {") in
  89. [Label startlabel] @
  90. (trav cond) @
  91. [InlineComment (Branch (false, endlabel), com)] @
  92. (trav body) @
  93. [Jump startlabel;
  94. Label endlabel;
  95. comline "}"]
  96. | DoWhile (cond, body, _) ->
  97. let startlabel = genlabel "dowhile" in
  98. let com = ("} while (" ^ (node2str cond) ^ ");") in
  99. [comline "do {";
  100. Label startlabel] @
  101. (trav body) @
  102. (trav cond) @
  103. [InlineComment (Branch (true, startlabel), com)]
  104. (* Expression statement pops the disregarded expression value from the
  105. * stack, if any *)
  106. | Expr value ->
  107. let pop = match typeof value with
  108. | Void -> [comline (node2str node)]
  109. | ctype -> [InlineComment (Pop ctype, node2str node)]
  110. in
  111. (trav value) @ pop
  112. (* Expressions *)
  113. (* Immediate values are handled here, and not in the peephole optimizer,
  114. * for convenience: the indices in the constant table would be altered,
  115. * so entries cannot be removed. By this early detection (also during
  116. * index analysis), they are not added in the first place *)
  117. | Const (value, _) when is_immediate_const value ->
  118. [InlineComment (LoadImm value, node2str node)]
  119. | Const (value, _) ->
  120. Hashtbl.replace consts value (indexof node);
  121. let load = LoadConst (typeof node, indexof node) in
  122. [InlineComment (load, node2str node)]
  123. | VarUse (dec, None, _) ->
  124. let load = match (depthof dec, depthof node) with
  125. | (0, _) -> Load (typeof dec, Glob, indexof dec)
  126. | (a, b) when a = b -> Load (typeof dec, Current, indexof dec)
  127. | (a, b) -> Load (typeof dec, Rel (b - a), indexof dec)
  128. in
  129. [InlineComment (load, node2str node)]
  130. | Monop (op, value, _) ->
  131. (trav value) @
  132. [InlineComment (Op (op, typeof value), op2str op)]
  133. | Binop (op, left, right, _) ->
  134. (trav left) @
  135. (trav right) @
  136. [InlineComment (Op (op, typeof left), op2str op)]
  137. | TypeCast (ctype, value, _) ->
  138. let vtype = typeof value in
  139. (match (ctype, vtype) with
  140. | (Float, Int) | (Int, Float) -> ()
  141. | _ ->
  142. let msg = sprintf
  143. "invalid typecast: %s -> %s"
  144. (type2str vtype) (type2str ctype)
  145. in raise (NodeError (node, msg))
  146. );
  147. trav value @ [Convert (vtype, ctype)]
  148. (* Function calls *)
  149. | FunUse (dec, args, _) ->
  150. let init = match (depthof dec, depthof node) with
  151. | (0, _) -> RtnInit Glob
  152. | (a, b) when a = b -> RtnInit Current
  153. | (a, b) when a = b + 1 -> RtnInit Local
  154. | (a, b) -> RtnInit (Rel (b - a))
  155. in
  156. let jmp = match dec with
  157. | FunDec _ -> RtnJmp (ExternFun (indexof dec))
  158. | FunDef _ -> RtnJmp (LocalFun (List.length args, labelof dec))
  159. | _ -> raise InvalidNode
  160. in
  161. init :: (trav_all args) @ [jmp]
  162. | Arg value -> trav value
  163. (* Conditional expression (short-circuit evaluation) *)
  164. (* <cond>
  165. * branch_f else
  166. * <true_expr>
  167. * jump end
  168. * else:
  169. * <false_expr>
  170. * end:
  171. *)
  172. | Cond (cond, texp, fexp, _) ->
  173. let elselabel = genlabel "false_expr" in
  174. let endlabel = genlabel "end" in
  175. (trav cond) @
  176. [Branch (false, elselabel)] @
  177. (trav texp) @
  178. [Jump (endlabel);
  179. Label (elselabel)] @
  180. (trav fexp) @
  181. [InlineComment (Label (endlabel), node2str node)]
  182. (* Arrays *)
  183. | Allocate (dec, dims, _) ->
  184. let store = match (depthof dec, depthof node) with
  185. | (0, _) -> Store (typeof dec, Glob, indexof dec)
  186. | (a, b) when a = b -> Store (typeof dec, Current, indexof dec)
  187. | _ -> raise InvalidNode
  188. in
  189. trav_all dims @
  190. [NewArray (basetypeof dec, List.length dims);
  191. InlineComment (store, node2str node)]
  192. | VarUse (dec, Some dims, _) ->
  193. let load = match (depthof dec, depthof node) with
  194. | (0, _) -> Load (typeof dec, Glob, indexof dec)
  195. | (a, b) when a = b -> Load (typeof dec, Current, indexof dec)
  196. | (a, b) -> Load (typeof dec, Rel (b - a), indexof dec)
  197. in
  198. (trav_all (List.rev dims)) @ (* push dimensions *)
  199. [InlineComment (load, nameof dec)] @ (* push array reference *)
  200. [InlineComment (LoadArray (basetypeof dec), node2str node)]
  201. | VarLet (dec, Some dims, value, _) ->
  202. let load = match (depthof dec, depthof node) with
  203. | (0, _) -> Load (typeof dec, Glob, indexof dec)
  204. | (a, b) when a = b -> Load (typeof dec, Current, indexof dec)
  205. | (a, b) -> Load (typeof dec, Rel (b - a), indexof dec)
  206. in
  207. (trav value) @ (* push value *)
  208. (trav_all dims) @ (* push dimensions *)
  209. [InlineComment (load, nameof dec)] @ (* push array reference *)
  210. [InlineComment (StoreArray (basetypeof dec), node2str node)]
  211. | _ -> [Comment ("FIXME: " ^ Stringify.node2str node)]
  212. (*| _ -> raise InvalidNode*)
  213. in
  214. let instrs = trav program in
  215. (* Sort aggregated constants and add definitions
  216. * If possible, this should be rewritten in the future because it's a little
  217. * cumbersome right now... *)
  218. let pairs = ref [] in
  219. let add_pair value index =
  220. let com = sprintf "index %d" index in
  221. pairs := (InlineComment (ConstDef value, com), index) :: !pairs;
  222. in
  223. Hashtbl.iter add_pair consts;
  224. let cmp (_, i) (_, j) = compare i j in
  225. let sorted_pairs = List.sort cmp !pairs in
  226. let const_defs = List.map (fun (d, _) -> d) sorted_pairs in
  227. instrs @ const_defs
  228. let phase = function
  229. | Ast node -> Assembly (assemble node)
  230. | _ -> raise (InvalidInput "assembly")