assemble.ml 9.2 KB

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