desug.ml 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. open Printf
  2. open Types
  3. open Util
  4. let rec var_init = function
  5. (* Move global initialisations to __init function *)
  6. | Program (decls, ann) ->
  7. let decls = flatten_blocks (List.map var_init decls) in
  8. let rec trav assigns = function
  9. | [] -> (assigns, [])
  10. | (Assign _ as hd) :: tl
  11. | (Allocate _ as hd) :: tl -> trav (assigns @ [hd]) tl
  12. | hd :: tl ->
  13. let (assigns, decls) = trav assigns tl in
  14. (assigns, (hd :: decls))
  15. in
  16. let (assigns, decls) = trav [] decls in (
  17. match assigns with
  18. | [] -> Program (decls, ann)
  19. | assigns ->
  20. let init_func = FunDef (true, Void, "__init", [], Block assigns, []) in
  21. Program (init_func :: decls, ann)
  22. )
  23. (* Global variable initialisation:
  24. * Add an assign statement and the Program node will remove it later on *)
  25. | GlobalDef (export, ctype, name, Some init, ann) ->
  26. Block [GlobalDef (export, ctype, name, None, ann);
  27. Assign (name, None, init, ann)]
  28. (* Global array definition:
  29. * - Create a new global variable for each dimension and initialise it to
  30. * the given expression
  31. * - create __allocate statement in __init *)
  32. | GlobalDef (export, Array (ctype, dims), name, None, ann) as dec ->
  33. let rec create_dimvars i = function
  34. | [] -> []
  35. | hd :: tl ->
  36. let dimname = name ^ "$" ^ string_of_int i in
  37. let var = Var (dimname, None, ann) in
  38. var :: (create_dimvars (i + 1) tl)
  39. in
  40. let dimvars = create_dimvars 1 dims in
  41. let create_globaldef dim = function
  42. | Var (dimname, None, ann) ->
  43. var_init (GlobalDef (export, Int, dimname, Some dim, ann))
  44. | _ -> raise InvalidNode
  45. in
  46. let vardecs = List.map2 create_globaldef dims dimvars in
  47. let alloc = [Allocate (dec, dimvars, ann)] in
  48. Block (vardecs @
  49. [GlobalDef (export, Array (ctype, dimvars), name, None, ann)] @
  50. alloc)
  51. (* Split local variable initialisations in declaration and assignment *)
  52. | FunDef (export, ret_type, name, params, body, ann) ->
  53. let inits = ref [] in
  54. let rec extract_inits = function
  55. (* Translate scalar array initialisation to ArrayScalar node,
  56. * for easy replacement later on *)
  57. | VarDec (Array _ as vtype, name, Some (Const _ as v), ann) ->
  58. let init = Some (ArrayInit (ArrayScalar v, vtype)) in
  59. extract_inits (VarDec (vtype, name, init, ann))
  60. (* Wrap ArrayConst in ArrayInit to pass dimensions *)
  61. | VarDec (Array _ as vtype, name, Some (ArrayConst _ as v), ann) ->
  62. let init = Some (ArrayInit (v, vtype)) in
  63. extract_inits (VarDec (vtype, name, init, ann))
  64. | VarDec (ctype, name, init, ann) as dec ->
  65. (* array definition: create __allocate statement *)
  66. let alloc = match ctype with
  67. | Array (_, dims) -> [Allocate (dec, dims, ann)]
  68. | _ -> []
  69. in
  70. (* initialisation: create assign statement *)
  71. let add = match init with
  72. | Some value -> alloc @ [Assign (name, None, value, ann)]
  73. | None -> alloc
  74. in
  75. inits := !inits @ add;
  76. VarDec (ctype, name, None, ann)
  77. | node -> transform_children extract_inits node
  78. in
  79. let rec place_inits = function
  80. (* initialisations need to be placed after local functions *)
  81. | (LocalFuns _ as hd) :: tl -> hd :: !inits @ tl
  82. | hd :: tl -> hd :: (place_inits tl)
  83. | [] -> []
  84. in
  85. let params = flatten_blocks (List.map var_init params) in
  86. let body = flatten_blocks (place_inits (block_body (extract_inits body))) in
  87. FunDef (export, ret_type, name, params, Block body, ann)
  88. | node -> transform_children var_init node
  89. let rec replace_var var replacement node =
  90. let trav = (replace_var var replacement) in
  91. match node with
  92. | Var (name, None, ann) when name = var ->
  93. Var (replacement, None, ann)
  94. | For (counter, start, stop, step, body, ann) when counter = var ->
  95. For (replacement, trav start, trav stop, trav step, trav body, ann)
  96. | node ->
  97. transform_children trav node
  98. let for_to_while node =
  99. let rec traverse new_vars = function
  100. | FunDef (export, ret_type, name, params, body, ann) ->
  101. let new_vars = ref [] in
  102. let body = traverse new_vars body in
  103. let create_vardec name = VarDec (Int, name, None, []) in
  104. let new_vardecs = List.map create_vardec !new_vars in
  105. let _body = new_vardecs @ (flatten_blocks (block_body body)) in
  106. FunDef (export, ret_type, name, params, Block _body, ann)
  107. (* Transform for-loops to while-loops *)
  108. | For (counter, start, stop, step, body, ann) ->
  109. let _i = fresh_var counter in
  110. let _stop = fresh_const "stop" in
  111. let _step = fresh_const "step" in
  112. new_vars := !new_vars @ [_i; _stop; _step];
  113. let vi = Var (_i, None, []) in
  114. let vstop = Var (_stop, None, annof stop) in
  115. let vstep = Var (_step, None, annof step) in
  116. let cond = Cond (
  117. Binop (Gt, vstep, Const (IntVal 0, []), []),
  118. Binop (Lt, vi, vstop, []),
  119. Binop (Gt, vi, vstop, []),
  120. []
  121. ) in
  122. Block [
  123. Assign (_i, None, start, annof start);
  124. Assign (_stop, None, stop, annof stop);
  125. Assign (_step, None, step, annof step);
  126. traverse new_vars (While (cond, (Block (
  127. block_body (replace_var counter _i body) @
  128. [Assign (_i, None, Binop (Add, vi, vstep, []), [])]
  129. )), ann));
  130. ]
  131. (* DISABLED, while-loops are explicittly supported by the assembly phase
  132. (* Transform while-loops to do-while loops in if-statements *)
  133. | While (cond, body, ann) ->
  134. let cond = traverse new_vars cond in
  135. let body = traverse new_vars body in
  136. Block [If (cond, Block [DoWhile (cond, body, ann)], ann)]
  137. *)
  138. | node -> transform_children (traverse new_vars) node
  139. in
  140. traverse (ref []) node
  141. let rec array_init = function
  142. (* Transform scalar assignment into nested for-loops *)
  143. | Assign (name, None, ArrayInit (ArrayScalar value, Array (_, dims)), ann) ->
  144. let rec add_loop indices = function
  145. | [] ->
  146. Assign (name, Some indices, value, ann)
  147. | dim :: rest ->
  148. let counter = fresh_var "i" in
  149. let body = Block [add_loop (indices @ [Var (counter, None, [])]) rest] in
  150. For (counter, Const (IntVal 0, []), dim, Const (IntVal 1, []), body, [])
  151. in
  152. add_loop [] dims
  153. (* Transform array constant inisialisation into separate assign statements
  154. * for all entries in the constant array *)
  155. (* TODO: only allow when array dimensions are constant? *)
  156. | Assign (name, None, ArrayInit (ArrayConst _ as value, Array (_, dims)), ann) ->
  157. let ndims = list_size dims in
  158. let rec make_assigns depth i indices = function
  159. | [] -> []
  160. | hd :: tl ->
  161. let assigns = traverse depth (i :: indices) hd in
  162. make_assigns depth (i + 1) indices tl @ assigns
  163. and traverse depth indices = function
  164. | ArrayConst (values, _) ->
  165. make_assigns (depth + 1) 0 indices values
  166. | value when depth = ndims ->
  167. let indices = List.map (fun i -> Const (IntVal i, [])) indices in
  168. [Assign (name, Some (List.rev indices), value, ann)]
  169. | node ->
  170. let msg = sprintf
  171. "dimension mismatch: expected %d nesting levels, got %d"
  172. ndims depth
  173. in
  174. raise (NodeError (node, msg))
  175. in
  176. Block (List.rev (traverse 0 [] value))
  177. | node -> transform_children array_init node
  178. (* Generate new variables for array dimensions in function bodies, to avoid
  179. * re-evalutation after array dimension reduction. For example:
  180. *
  181. * int dims = 0;
  182. *
  183. * int dim() {
  184. * dims = dims 1; // Side effect => dims() should be called once
  185. * return 10;
  186. * }
  187. *
  188. * void foo() {
  189. * int[10, dim()] arr;
  190. * arr[0, 1] = 1;
  191. * }
  192. *
  193. * After dimension reduction, this would become:
  194. * void foo() {
  195. * int[] arr;
  196. * arr = allocate(10, dim());
  197. * arr[1 * dim() + 0] = 1;
  198. * }
  199. *
  200. * This behaviour is of course incorrect. To avoid dim() from being evaluated
  201. * twice, the snippet above is transformed into (note the $$ which will help
  202. * later during constant propagation):
  203. * void foo() {
  204. * int a$dim$$1 = 10;
  205. * int a$dim$$2 = dim();
  206. * int[a$dim$$1, a$dim$$2] arr;
  207. * arr[1, 2] = 1;
  208. * }
  209. *
  210. * ... which then becomes:
  211. * void foo() {
  212. * int a$dim$$1;
  213. * int a$dim$$2;
  214. * int[a$dim$$1, a$dim$$2] arr;
  215. * a$dim$1 = 10;
  216. * a$dim$2 = dim();
  217. * arr = __allocate(a$dim$1 * a$dim$2);
  218. * arr[1 * a$dim$2 * 0] = 1;
  219. * }
  220. * *)
  221. let rec array_dims = function
  222. | VarDec (Array (ctype, dims), name, init, ann) ->
  223. let make_dimname i _ = name ^ "$dim$$" ^ string_of_int (i + 1) in
  224. let dimnames = mapi make_dimname dims in
  225. let make_dimvar d n = Var (n, None, annof d) in
  226. let dimvars = List.map2 make_dimvar dims dimnames in
  227. let make_dimdec dimname dim = VarDec (Int, dimname, Some dim, []) in
  228. let dimdecs = List.map2 make_dimdec dimnames dims in
  229. Block (dimdecs @ [VarDec (Array (ctype, dimvars), name, init, ann)])
  230. | node -> transform_children array_dims node
  231. let rec phase input =
  232. log_line 1 "- Desugaring";
  233. match input with
  234. | Ast node ->
  235. Ast (for_to_while (array_init (var_init (array_dims node))))
  236. | _ -> raise (InvalidInput "desugar")