Source file inline.ml

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
(* Js_of_ocaml compiler
 * http://www.ocsigen.org/js_of_ocaml/
 * Copyright (C) 2010 Jérôme Vouillon
 * Laboratoire PPS - CNRS Université Paris Diderot
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, with linking exception;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *)

open! Stdlib
open Code

let optimizable blocks pc _ =
  Code.traverse
    Code.fold_children
    (fun pc acc ->
      if not acc
      then acc
      else
        let b = Addr.Map.find pc blocks in
        match b with
        | { handler = Some _; _ } | { branch = Pushtrap _; _ } | { branch = Poptrap _; _ }
          ->
            false
        | _ ->
            List.for_all b.body ~f:(function
                | Let (_, Prim (Extern "caml_js_eval_string", _)) -> false
                | Let (_, Prim (Extern "debugger", _)) -> false
                | Let
                    ( _
                    , Prim
                        (Extern ("caml_js_var" | "caml_js_expr" | "caml_pure_js_expr"), _)
                    ) ->
                    (* TODO: we should smarter here and look the generated js *)
                    (* let's consider it this opmiziable *)
                    true
                | _ -> true))
    pc
    blocks
    true

let rec follow_branch_rec seen blocks = function
  | (pc, []) as k -> (
      let seen = Addr.Set.add pc seen in
      try
        match Addr.Map.find pc blocks with
        | { body = []; branch = Branch (pc, []); _ } when not (Addr.Set.mem pc seen) ->
            follow_branch_rec seen blocks (pc, [])
        | _ -> k
      with Not_found -> k)
  | k -> k

let follow_branch = follow_branch_rec Addr.Set.empty

let get_closures (_, blocks, _) =
  Addr.Map.fold
    (fun _ block closures ->
      List.fold_left block.body ~init:closures ~f:(fun closures i ->
          match i with
          | Let (x, Closure (l, cont)) ->
              let cont = follow_branch blocks cont in
              (* we can compute this once during the pass
                 as the property won't change with inlining *)
              let f_optimizable = optimizable blocks (fst cont) true in
              Var.Map.add x (l, cont, f_optimizable) closures
          | _ -> closures))
    blocks
    Var.Map.empty

(****)

let rewrite_block (pc', handler) pc blocks =
  let block = Addr.Map.find pc blocks in
  assert (Option.is_none block.handler);
  let block = { block with handler } in
  let block =
    match block.branch, pc' with
    | Return y, Some pc' -> { block with branch = Branch (pc', [ y ]) }
    | _ -> block
  in
  Addr.Map.add pc block blocks

let ( >> ) x f = f x

(* Skip try body *)
let fold_children blocks pc f accu =
  let block = Addr.Map.find pc blocks in
  match block.branch with
  | Return _ | Raise _ | Stop -> accu
  | Branch (pc', _) | Poptrap ((pc', _), _) -> f pc' accu
  | Pushtrap (_, _, (pc1, _), pcs) -> f pc1 (Addr.Set.fold f pcs accu)
  | Cond (_, _, (pc1, _), (pc2, _)) -> accu >> f pc1 >> f pc2
  | Switch (_, a1, a2) ->
      let accu = Array.fold_right a1 ~init:accu ~f:(fun (pc, _) accu -> f pc accu) in
      let accu = Array.fold_right a2 ~init:accu ~f:(fun (pc, _) accu -> f pc accu) in
      accu

let rewrite_closure blocks cont_pc clos_pc handler =
  Code.traverse fold_children (rewrite_block (cont_pc, handler)) clos_pc blocks blocks

(****)

(*
get new location
put continuation at new location
update closure body to return to this location
make current block continuation jump to closure body
*)

let rec find_mapping mapping x =
  match mapping with
  | [] -> x
  | ([], []) :: rest -> find_mapping rest x
  | (a :: _, b :: _) :: rest when Code.Var.compare a x = 0 -> find_mapping rest b
  | (_ :: ax, _ :: bx) :: rest -> find_mapping ((ax, bx) :: rest) x
  | ([], _ | _, []) :: _ -> assert false

let simple blocks cont mapping =
  let map_var mapping x =
    let x' = find_mapping mapping x in
    if Var.equal x x' then raise Not_found else x'
  in
  let map_prim_arg mapping = function
    | Pc c -> Pc c
    | Pv x -> Pv (map_var mapping x)
  in
  let rec follow (pc, args) (instr : [ `Empty | `Ok of 'a ]) mapping =
    let b = Addr.Map.find pc blocks in
    let mapping = (b.params, args) :: mapping in
    let instr : [ `Empty | `Ok of 'a | `Fail ] =
      match b.body, instr with
      | [], _ -> (instr :> [ `Empty | `Ok of 'a | `Fail ])
      | [ Let (y, exp) ], `Empty -> `Ok (y, exp)
      | _, _ -> `Fail
    in
    match instr, b.branch with
    | `Fail, _ -> `Fail
    | `Empty, Return ret -> `Alias (map_var mapping ret)
    | `Ok (x, exp), Return ret when Code.Var.compare x (find_mapping mapping ret) = 0 -> (
        match exp with
        | Const _ -> `Exp exp
        | Constant (Float _ | Int64 _ | Int _ | IString _) -> `Exp exp
        | Apply (f, args, true) ->
            `Exp (Apply (map_var mapping f, List.map args ~f:(map_var mapping), true))
        | Prim (prim, args) -> `Exp (Prim (prim, List.map args ~f:(map_prim_arg mapping)))
        | Block (tag, args, aon) ->
            `Exp (Block (tag, Array.map args ~f:(map_var mapping), aon))
        | Field (x, i) -> `Exp (Field (map_var mapping x, i))
        | Closure _ -> `Fail
        | Constant _ -> `Fail
        | Apply _ -> `Fail)
    | ((`Empty | `Ok _) as instr), Branch cont -> follow cont instr mapping
    | (`Empty | `Ok _), _ -> `Fail
  in
  try follow cont `Empty mapping with Not_found -> `Fail

let rec args_equal xs ys =
  match xs, ys with
  | [], [] -> true
  | x :: xs, Pv y :: ys -> Code.Var.compare x y = 0 && args_equal xs ys
  | _ -> false

let inline closures live_vars outer_optimizable pc (blocks, free_pc) =
  let block = Addr.Map.find pc blocks in
  let body, (branch, blocks, free_pc) =
    List.fold_right
      block.body
      ~init:([], (block.branch, blocks, free_pc))
      ~f:(fun i (rem, state) ->
        match i with
        | Let (x, Apply (f, args, true)) when Var.Map.mem f closures -> (
            let branch, blocks, free_pc = state in
            let params, clos_cont, f_optimizable = Var.Map.find f closures in
            match simple blocks clos_cont [ params, args ] with
            | `Alias arg -> (
                match rem, branch with
                | [], Return y when Var.compare x y = 0 ->
                    [], (Return arg, blocks, free_pc)
                | _ ->
                    let blocks =
                      Addr.Map.add
                        free_pc
                        { params = [ x ]; handler = block.handler; body = rem; branch }
                        blocks
                    in
                    [], (Branch (free_pc, [ arg ]), blocks, free_pc + 1))
            | `Exp exp -> Let (x, exp) :: rem, state
            | `Fail ->
                if live_vars.(Var.idx f) = 1 && Bool.equal outer_optimizable f_optimizable
                   (* inlining the code of an optimizable function could make
                 this code unoptimized. (wrt to Jit compilers)
                 At the moment, V8 doesn't optimize function containing try..catch.
                 We disable inlining if the inner and outer functions don't have
                 the same "contain_try_catch" property *)
                then
                  let blocks, cont_pc =
                    match rem, branch with
                    | [], Return y when Var.compare x y = 0 ->
                        (* We do not need a continuation block for tail calls *)
                        blocks, None
                    | _ ->
                        ( Addr.Map.add
                            free_pc
                            { params = [ x ]
                            ; handler = block.handler
                            ; body = rem
                            ; branch
                            }
                            blocks
                        , Some free_pc )
                  in
                  let blocks =
                    rewrite_closure blocks cont_pc (fst clos_cont) block.handler
                  in
                  (* We do not really need this intermediate block.  It
                   just avoid the need to find which function parameters
                   are used in the function body. *)
                  let blocks =
                    Addr.Map.add
                      (free_pc + 1)
                      { params
                      ; handler = block.handler
                      ; body = []
                      ; branch = Branch clos_cont
                      }
                      blocks
                  in
                  [], (Branch (free_pc + 1, args), blocks, free_pc + 2)
                else
                  (* Format.eprintf "Do not inline because inner:%b outer:%b@." f_has_handler outer_has_handler; *)
                  i :: rem, state)
        | Let (x, Closure (l, (pc, []))) -> (
            let block = Addr.Map.find pc blocks in
            match block with
            | { body = [ Let (y, Prim (Extern prim, args)) ]
              ; branch = Return y'
              ; handler = None
              ; params = []
              } ->
                let len = List.length l in
                if Code.Var.compare y y' = 0
                   && Primitive.has_arity prim len
                   && args_equal l args
                then
                  Let (x, Prim (Extern "%closure", [ Pc (IString prim) ])) :: rem, state
                else i :: rem, state
            | _ -> i :: rem, state)
        | _ -> i :: rem, state)
  in
  Addr.Map.add pc { block with body; branch } blocks, free_pc

(****)

let times = Debug.find "times"

let f ((pc, blocks, free_pc) as p) live_vars =
  Code.invariant p;
  let t = Timer.make () in
  let closures = get_closures p in
  let blocks, free_pc =
    Code.fold_closures
      p
      (fun name _ (pc, _) (blocks, free_pc) ->
        let outer_optimizable =
          match name with
          | None -> optimizable blocks pc true
          | Some x ->
              let _, _, b = Var.Map.find x closures in
              b
        in
        Code.traverse
          Code.fold_children
          (inline closures live_vars outer_optimizable)
          pc
          blocks
          (blocks, free_pc))
      (blocks, free_pc)
  in
  if times () then Format.eprintf "  inlining: %a@." Timer.print t;
  let p = pc, blocks, free_pc in
  Code.invariant p;
  p