package wax-lib

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file recover_loops.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
open Wax_lang
open Ast

(* Recover the high-level [while] loop from the [loop] shape that
   [Ast_utils.lower_while] produces (and that compilers emit for the
   corresponding source):

     'L: loop { if C { B; br 'L; } }     ⇒  'L?: while C { B }      (leading test)

   so decompiled WAT/WASM (and round-tripped Wax loops) read as the high-level
   form rather than a bare [loop] with an explicit back-edge. A trailing-test
   [loop { B; br_if 'L C; }] has no leading-test [while] equivalent, so it is
   left as a bare [loop].

   The synthesised loop label is kept on the recovered loop only when the body
   still branches to it after the back-edge is removed (a "continue"); otherwise
   it is dropped and the label-less form re-lowers to a fresh synthetic label.
   The reference test is exhaustive and conservative — erring toward keeping the
   label is safe, dropping a still-referenced one would dangle — so a missed
   constructor is a compile error, not silently wrong output.

   Folding is the exact inverse of the lowering, so re-lowering reproduces the
   original [loop] byte-for-byte and the rewrite always preserves runtime
   semantics. Meant to run on {!From_wasm.module_} output, after
   {!Recover_dispatch.module_} and before {!Sink_let.module_} (which would
   otherwise sink locals into the loop body and hide the shape). *)

let is_void (t : functype) = t.params = [||] && t.results = [||]

(* Whether any branch within [i] targets the label [name] — a "continue" to a
   recovered loop, which forces the label to be kept. *)
let rec refs_instr name (i : location instr) : bool =
  match i.desc with
  | Br (l, e) -> String.equal l.desc name || refs_opt name e
  | Br_if (l, e) -> String.equal l.desc name || refs_instr name e
  | Br_table (ls, e) ->
      List.exists (fun l -> String.equal l.Annot.desc name) ls
      || refs_instr name e
  | On (e, _) -> refs_instr name e
  | Br_on_null (l, e) | Br_on_non_null (l, e) ->
      String.equal l.desc name || refs_instr name e
  | Br_on_cast (l, _, e) | Br_on_cast_fail (l, _, e) ->
      String.equal l.desc name || refs_instr name e
  | Br_on_cast_desc_eq (l, _, e, d) | Br_on_cast_desc_eq_fail (l, _, e, d) ->
      String.equal l.desc name || refs_instr name e || refs_instr name d
  | Dispatch { index; cases; default; arms } ->
      String.equal default.desc name
      || List.exists (fun l -> String.equal l.Annot.desc name) cases
      || refs_instr name index
      || List.exists
           (fun (_, (b : (_ instr list, _) Ast.annotated)) ->
             refs_instrs name b.desc)
           arms
  | Match { scrutinee; arms; default } ->
      refs_instr name scrutinee
      || List.exists
           (fun (_, (b : (_ instr list, _) Ast.annotated)) ->
             refs_instrs name b.desc)
           arms
      || refs_instrs name default.desc
  | Block { block; _ } | Loop { block; _ } | TryTable { block; _ } ->
      refs_instrs name block.desc
  | While { cond; step; block; _ } ->
      refs_instr name cond || refs_opt name step || refs_instrs name block.desc
  | If { cond; if_block; else_block; _ } -> (
      refs_instr name cond
      || refs_instrs name if_block.desc
      ||
      match else_block with
      | Some b -> refs_instrs name b.desc
      | None -> false)
  | Try { block; catches; catch_all; _ } -> (
      refs_instrs name block.desc
      || List.exists (fun (_, b) -> refs_instrs name b.Annot.desc) catches
      ||
      match catch_all with
      | Some b -> refs_instrs name b.desc
      | None -> false)
  | TryCatch { block; arms; _ } ->
      refs_instrs name block.desc
      || List.exists (fun a -> refs_instrs name a.arm_body.desc) arms
  | If_annotation { then_body; else_body; _ } -> (
      refs_instrs name then_body.desc
      ||
      match else_body with
      | Some b -> refs_instrs name b.desc
      | None -> false)
  | Set (_, _, e)
  | Tee (_, e)
  | Labelled (_, e)
  | Cast (e, _)
  | Test (e, _)
  | NonNull e
  | StructGet (e, _)
  | GetDescriptor e
  | StructDefaultDesc e
  | ArrayDefault (_, e)
  | UnOp (_, e)
  | ThrowRef e
  | ContNew (_, e) ->
      refs_instr name e
  | Call (a, l) | TailCall (a, l) -> refs_instr name a || refs_instrs name l
  | Struct (_, fs) -> List.exists (fun (_, e) -> refs_opt name e) fs
  | StructDesc (d, fs) ->
      refs_instr name d || List.exists (fun (_, e) -> refs_opt name e) fs
  | CastDesc (a, _, b)
  | StructSet (a, _, b)
  | Array (_, a, b)
  | ArraySegment (_, _, a, b)
  | ArrayGet (a, b)
  | BinOp (_, a, b) ->
      refs_instr name a || refs_instr name b
  | ArraySet (a, b, c) | Select (a, b, c) ->
      refs_instr name a || refs_instr name b || refs_instr name c
  | ArrayFixed (_, l)
  | ContBind (_, _, l)
  | Suspend (_, l)
  | Resume (_, _, l)
  | ResumeThrow (_, _, _, l)
  | ResumeThrowRef (_, _, l)
  | Switch (_, _, l)
  | Throw (_, l)
  | Sequence l ->
      refs_instrs name l
  | Let (_, e) | Return e -> refs_opt name e
  | Unreachable | Nop | Hole | Null | Get _ | Path _ | Char _ | String _ | Int _
  | Float _ | StructDefault _ ->
      false

and refs_instrs name l =
  match l with [] -> false | i :: r -> refs_instr name i || refs_instrs name r

and refs_opt name = function Some x -> refs_instr name x | None -> false

let refs_list = refs_instrs

(* Whether the (already-rewritten) body of void loop [l] still references [l]
   after dropping its back-edge, with [cond] the loop's recovered test. *)
let keep_label l cond body =
  if refs_list l.Annot.desc body || refs_instr l.desc cond then Some l else None

(* Whether [i] reads the variable [name] (a [Get]). Conservative: unlisted forms
   report [false], which only makes the induction-step heuristic in [fold_loop]
   fire less often, never wrongly. *)
let rec reads_var name (i : location instr) : bool =
  match i.desc with
  | Get id -> String.equal id.desc name
  | BinOp (_, a, b) | ArrayGet (a, b) -> reads_var name a || reads_var name b
  | UnOp (_, e)
  | Cast (e, _)
  | Test (e, _)
  | NonNull e
  | StructGet (e, _)
  | GetDescriptor e
  | On (e, _) ->
      reads_var name e
  | Select (a, b, c) -> reads_var name a || reads_var name b || reads_var name c
  | Call (f, args) | TailCall (f, args) ->
      reads_var name f || reads_var_list name args
  | Tee (id, e) -> String.equal id.desc name || reads_var name e
  | Set (id, _, e) -> String.equal id.desc name || reads_var name e
  | Block { block; _ } | Loop { block; _ } -> reads_var_list name block.desc
  | If { cond; if_block; else_block; _ } -> (
      reads_var name cond
      || reads_var_list name if_block.desc
      ||
      match else_block with
      | Some b -> reads_var_list name b.desc
      | None -> false)
  | _ -> false

and reads_var_list name l =
  match l with
  | [] -> false
  | i :: r -> reads_var name i || reads_var_list name r

(* Fold an already-rewritten void [loop] labelled [l] into a [while] when its
   body is the leading-test shape, else leave it a [loop]. *)
let fold_loop l typ (block : (_ Ast.instr list, _) Ast.annotated) =
  match block.desc with
  (* Leading test: the body is a single label-less void [if] with no else whose
     own body ends in the back-edge. *)
  | [
   {
     desc = If { label = None; typ = it; cond; if_block; else_block = None };
     _;
   };
  ]
    when is_void it -> (
      match List.rev if_block.desc with
      | { desc = Br (bl, None); _ } :: rev_body
        when String.equal bl.desc l.Annot.desc -> (
          let body = List.rev rev_body in
          match body with
          (* Continue-expression shape (see [Ast_utils.lower_while]): the body is
             a labelled block (the continue target) whose own body branches to it,
             followed by the step, then the loop back-edge. Recover it as
             [while 'blk cond : (step) { inner }]. *)
          | [
           { desc = Block { label = Some blk; typ = bt; block = inner }; _ };
           step;
          ]
            when is_void bt
                 && (not (String.equal blk.desc l.desc))
                 && refs_list blk.desc inner.desc ->
              While { label = Some blk; cond; step = Some step; block = inner }
          | _ -> (
              let label = keep_label l cond body in
              (* Readability recovery: with no continue (label dropped, so
                 re-lowering is byte-identical), present a trailing
                 induction-variable update — an assignment to a variable the
                 condition reads — as a continue-expression, so index-and-stride
                 loops read as [while i <s n : (i += 1) { … }]. Kept conservative:
                 at least one other body statement must remain. *)
              match (label, List.rev body) with
              | ( None,
                  ({ desc = Set (x, _, _); _ } as step) :: (_ :: _ as rev_rest)
                )
                when reads_var x.desc cond ->
                  While
                    {
                      label = None;
                      cond;
                      step = Some step;
                      block = { block with desc = List.rev rev_rest };
                    }
              | _ ->
                  While
                    {
                      label;
                      cond;
                      step = None;
                      block = { block with desc = body };
                    }))
      | _ -> Loop { label = Some l; typ; block })
  | _ -> Loop { label = Some l; typ; block }

let rec rewrite_instr (i : location instr) : location instr =
  let d = rewrite_desc i.desc in
  if d == i.desc then i else { i with desc = d }

and rewrite_list l = Ast_utils.smart_map rewrite_instr l

and rewrite_desc (desc : location instr_desc) : location instr_desc =
  match desc with
  | Loop { label = Some l; typ; block } when is_void typ ->
      fold_loop l typ { block with desc = rewrite_list block.desc }
  | d ->
      (* structural, share-preserving; the loop recovery is the case above *)
      Ast_utils.map_desc ~instr:rewrite_instr ~block:rewrite_list d

let rec field_desc (f : location modulefield) =
  let map_fields =
    List.map (fun (a : (location modulefield, location) Ast.annotated) ->
        { a with desc = field_desc a.desc })
  in
  match f with
  | Func ({ body = label, instrs; _ } as r) ->
      Func { r with body = (label, rewrite_list instrs) }
  | Conditional ({ then_fields; else_fields; _ } as r) ->
      Conditional
        {
          r with
          then_fields = { then_fields with desc = map_fields then_fields.desc };
          else_fields =
            Option.map
              (fun (b :
                     ( (location modulefield, location) Ast.annotated list,
                       location )
                     Ast.annotated) -> { b with desc = map_fields b.desc })
              else_fields;
        }
  | ( Type _ | Module_annotation _ | Import _ | Import_group _ | Global _
    | Tag _ | Memory _ | Data _ | Table _ | Elem _ ) as f ->
      f

let module_ (m : location module_) : location module_ =
  List.map
    (fun (a : (location modulefield, location) Ast.annotated) ->
      { a with desc = field_desc a.desc })
    m