Source file optimizations.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
open Catala_utils
open Definitions
type ('a, 'b, 'm) optimizations_ctx = { decl_ctx : decl_ctx }
let binder_vars_used_at_most_once
(binder :
( ('a dcalc_lcalc, 'a dcalc_lcalc, 'm) base_gexpr,
('a dcalc_lcalc, 'm) gexpr )
Bindlib.mbinder) : bool =
(not (Array.exists Fun.id (Bindlib.mbinder_occurs binder)))
||
let vars, body = Bindlib.unmbind binder in
let rec vars_count (e : ('a dcalc_lcalc, 'm) gexpr) : int array =
match e with
| EVar v, _ ->
Array.map (fun vi -> if Bindlib.eq_vars v vi then 1 else 0) vars
| e ->
Expr.shallow_fold
(fun e' acc -> Array.map2 (fun x y -> x + y) (vars_count e') acc)
e
(Array.make (Array.length vars) 0)
in
not (Array.exists (fun c -> c > 1) (vars_count body))
let simplified_apply f args tys =
match f, args with
| _, [(EAbs { tys = (TClosureEnv, _) :: _; _ }, _)] ->
EApp { f; args; tys }
| _, args when List.exists (fun e -> not (Expr.is_pure e)) args ->
EApp { f; args; tys }
| (EAbs { binder; _ }, _), _
when binder_vars_used_at_most_once binder
|| List.for_all
(function (EVar _ | ELit _), _ -> true | _ -> false)
args ->
Mark.remove (Bindlib.msubst binder (List.map fst args |> Array.of_list))
| _ -> EApp { f; args; tys }
let literal_bool = function
| ELit (LBool b), _
| EAppOp { op = Log _, _; args = [(ELit (LBool b), _)]; _ }, _ ->
Some b
| _ -> None
let simplified_ifthenelse cond etrue efalse m =
if Expr.equal etrue efalse then Mark.remove etrue
else
match literal_bool etrue, literal_bool efalse with
| Some true, Some false -> Mark.remove cond
| Some false, Some true ->
EAppOp
{
op = Not, Expr.mark_pos m;
tys = [TLit TBool, Expr.mark_pos m];
args = [cond];
}
| Some true, Some true | Some false, Some false -> Mark.remove etrue
| _ -> (
match literal_bool cond with
| Some true -> Mark.remove etrue
| Some false -> Mark.remove efalse
| None -> EIfThenElse { cond; etrue; efalse })
let simplified_match enum_name match_arg cases mark =
let max_duplicate_inlining_size = 3 in
let allow_duplicate_inlining_cases =
EnumConstructor.Map.fold
(fun cons f acc ->
if Expr.size f <= max_duplicate_inlining_size then
EnumConstructor.Set.add cons acc
else acc)
cases EnumConstructor.Set.empty
in
let app_cases cons e =
simplified_apply
(EnumConstructor.Map.find cons cases)
[e]
[Expr.maybe_ty (Mark.get e)]
in
let ret_ty = Expr.maybe_ty mark in
let rec aux seen_constrs = function
| EInj { cons; e; _ }, m ->
if EnumConstructor.Set.mem cons seen_constrs then raise Exit;
let seen_constrs =
if EnumConstructor.Set.mem cons allow_duplicate_inlining_cases then
seen_constrs
else EnumConstructor.Set.add cons seen_constrs
in
seen_constrs, (app_cases cons e, Expr.with_ty m ret_ty)
| EMatch ({ cases; _ } as ematch), m ->
let seen_constrs, cases =
EnumConstructor.Map.fold
(fun cons case (seen_constrs, acc) ->
match case with
| EAbs ({ binder; _ } as eabs), m ->
let vars, body = Bindlib.unmbind binder in
let seen_constrs, body = aux seen_constrs body in
let binder = Bindlib.unbox (Expr.bind vars (Expr.rebox body)) in
let m =
Expr.map_ty
(function
| TArrow (args, _), pos -> TArrow (args, ret_ty), pos
| (TVar _, _) as t -> t
| _ -> assert false)
m
in
( seen_constrs,
EnumConstructor.Map.add cons (EAbs { eabs with binder }, m) acc
)
| _ -> assert false)
cases
(seen_constrs, EnumConstructor.Map.empty)
in
seen_constrs, (EMatch { ematch with cases }, Expr.with_ty m ret_ty)
| EIfThenElse { cond; etrue; efalse }, m ->
let seen_constrs, etrue = aux seen_constrs etrue in
let seen_constrs, efalse = aux seen_constrs efalse in
let mark = Expr.with_ty m ret_ty in
seen_constrs, (simplified_ifthenelse cond etrue efalse mark, mark)
| _ -> raise Exit
in
try
let _seen_contrs, e = aux EnumConstructor.Set.empty match_arg in
Mark.remove e
with Exit ->
EMatch { e = match_arg; cases; name = enum_name }
let rec optimize_expr :
type a b.
(a, b, 'm) optimizations_ctx ->
(a dcalc_lcalc, 'm) gexpr ->
(a dcalc_lcalc, 'm) boxed_gexpr =
fun ctx e ->
let e = Expr.map ~f:(optimize_expr ctx) ~op:Fun.id e in
let mark = Mark.get e in
let reduce (e : (a dcalc_lcalc, 'm) gexpr) =
match Mark.remove e with
| EAppOp { op = Not, _; args = [(ELit (LBool b), _)]; _ } ->
ELit (LBool (not b))
| EAppOp { op = Or, _; args = [(ELit (LBool b), _); (e, _)]; _ }
| EAppOp { op = Or, _; args = [(e, _); (ELit (LBool b), _)]; _ } ->
if b then ELit (LBool true) else e
| EAppOp { op = And, _; args = [(ELit (LBool b), _); (e, _)]; _ }
| EAppOp { op = And, _; args = [(e, _); (ELit (LBool b), _)]; _ } ->
if b then e else ELit (LBool false)
| EMatch { name; e; cases } -> simplified_match name e cases mark
| EApp { f; args; tys } -> simplified_apply f args tys
| EStructAccess { name; field; e = EStruct { name = name1; fields }, _ }
when StructName.equal name name1 ->
Mark.remove (StructField.Map.find field fields)
| EErrorOnEmpty (EPureDefault (e, _), _) -> e
| EDefault { excepts; just; cons } -> (
let excepts =
List.filter (fun except -> Mark.remove except <> EEmpty) excepts
in
let value_except_count =
List.fold_left
(fun nb except -> if Expr.is_value except then nb + 1 else nb)
0 excepts
in
if value_except_count > 1 then
let (_ : _ gexpr) =
Interpreter.evaluate_expr ctx.decl_ctx Global.En
e
in
assert false
else
match excepts, just with
| [(EDefault { excepts = []; just = ELit (LBool true), _; cons }, _)], _
->
Mark.remove cons
| [], cond -> simplified_ifthenelse cond cons (EEmpty, mark) mark
| ( [except],
( ( ELit (LBool false)
| EAppOp { op = Log _, _; args = [(ELit (LBool false), _)]; _ } ),
_ ) ) ->
Mark.remove except
| excepts, just -> EDefault { excepts; just; cons })
| EIfThenElse { cond; etrue; efalse } ->
simplified_ifthenelse cond etrue efalse mark
| EAppOp { op = Op.Fold, _; args = [_f; init; (EArray [], _)]; _ } ->
Mark.remove init
| EAppOp
{
op = (Map, _) as op;
args =
[
f1;
( EAppOp
{
op = Map, _;
args = [f2; ls];
tys = [_; ((TArray xty, _) as lsty)];
},
m2 );
];
tys = [_; (TArray yty, _)];
} ->
let fg =
let v =
Var.make
(match f2 with
| EAbs { binder; _ }, _ -> (Bindlib.mbinder_names binder).(0)
| _ -> "x")
in
let mty m =
Expr.map_ty (function TArray ty, _ -> ty | _, pos -> Type.any pos) m
in
let x = Expr.evar v (mty (Mark.get ls)) in
Expr.make_ghost_abs [v]
(Expr.eapp ~f:(Expr.box f1)
~args:[Expr.eapp ~f:(Expr.box f2) ~args:[x] ~tys:[xty] (mty m2)]
~tys:[yty] (mty mark))
[xty] (Expr.pos e)
in
let fg = optimize_expr ctx (Expr.unbox fg) in
let mapl =
Expr.eappop ~op
~args:[fg; Expr.box ls]
~tys:[Expr.maybe_ty (Mark.get fg); lsty]
mark
in
Mark.remove (Expr.unbox mapl)
| EAppOp
{
op = Map, _;
args =
[
f1;
( EAppOp
{
op = (Map2, _) as op;
args = [f2; ls1; ls2];
tys =
[
_;
((TArray x1ty, _) as ls1ty);
((TArray x2ty, _) as ls2ty);
];
},
m2 );
];
tys = [_; (TArray yty, _)];
} ->
let fg =
let v1, v2 =
match f2 with
| EAbs { binder; _ }, _ ->
let names = Bindlib.mbinder_names binder in
Var.make names.(0), Var.make names.(1)
| _ -> Var.make "x", Var.make "y"
in
let mty m =
Expr.map_ty (function TArray ty, _ -> ty | _, pos -> Type.any pos) m
in
let x1 = Expr.evar v1 (mty (Mark.get ls1)) in
let x2 = Expr.evar v2 (mty (Mark.get ls2)) in
Expr.make_ghost_abs [v1; v2]
(Expr.eapp ~f:(Expr.box f1)
~args:
[
Expr.eapp ~f:(Expr.box f2) ~args:[x1; x2] ~tys:[x1ty; x2ty]
(mty m2);
]
~tys:[yty] (mty mark))
[x1ty; x2ty] (Expr.pos e)
in
let fg = optimize_expr ctx (Expr.unbox fg) in
let mapl =
Expr.eappop ~op
~args:[fg; Expr.box ls1; Expr.box ls2]
~tys:[Expr.maybe_ty (Mark.get fg); ls1ty; ls2ty]
mark
in
Mark.remove (Expr.unbox mapl)
| EAppOp
{
op = Op.Fold, _;
args = [f; init; (EArray [e'], _)];
tys = [_; tinit; (TArray tx, _)];
} ->
EApp { f; args = [init; e']; tys = [tinit; tx] }
| ETuple ((ETupleAccess { e; index = 0; _ }, _) :: el)
when List.for_all Fun.id
(List.mapi
(fun i -> function
| ETupleAccess { e = en; index; _ }, _ ->
index = i + 1 && Expr.equal en e
| _ -> false)
el) ->
Mark.remove e
| e -> e
in
Expr.Box.app1 e reduce mark
let optimize_expr :
'm.
decl_ctx -> ('a dcalc_lcalc, 'm) gexpr -> ('a dcalc_lcalc, 'm) boxed_gexpr
=
fun (decl_ctx : decl_ctx) (e : ('a dcalc_lcalc, 'm) gexpr) ->
optimize_expr { decl_ctx } e
let optimize_program (p : 'm program) : 'm program =
Program.map_exprs ~f:(optimize_expr p.decl_ctx) ~varf:(fun v -> v) p
let test_iota_reduction_1 () =
let x = Var.make "x" in
let enumT = EnumName.fresh [] ("t", Pos.void) in
let consA = EnumConstructor.fresh ("A", Pos.void) in
let consB = EnumConstructor.fresh ("B", Pos.void) in
let consC = EnumConstructor.fresh ("C", Pos.void) in
let consD = EnumConstructor.fresh ("D", Pos.void) in
let nomark = Untyped { pos = Pos.void } in
let injA = Expr.einj ~e:(Expr.evar x nomark) ~cons:consA ~name:enumT nomark in
let injC = Expr.einj ~e:(Expr.evar x nomark) ~cons:consC ~name:enumT nomark in
let injD = Expr.einj ~e:(Expr.evar x nomark) ~cons:consD ~name:enumT nomark in
let cases : ('a, 't) boxed_gexpr EnumConstructor.Map.t =
EnumConstructor.Map.of_list
[
( consA,
Expr.eabs_ghost (Expr.bind [| x |] injC) [Type.any Pos.void] nomark );
( consB,
Expr.eabs_ghost (Expr.bind [| x |] injD) [Type.any Pos.void] nomark );
]
in
let matchA = Expr.ematch ~e:injA ~name:enumT ~cases nomark in
Alcotest.(check string)
"same string"
begin[@ocamlformat "disable"]
"before=match (A x) with\n\
\ | A x → C x\n\
\ | B x → D x\n\
after=C x"
end
(Format.asprintf "before=%a\nafter=%a" Expr.format (Expr.unbox matchA)
Expr.format
(Expr.unbox (optimize_expr Program.empty_ctx (Expr.unbox matchA))))
let cases_of_list l : ('a, 't) boxed_gexpr EnumConstructor.Map.t =
EnumConstructor.Map.of_list
@@ ListLabels.map l ~f:(fun (cons, f) ->
let var = Var.make "x" in
( cons,
Expr.eabs_ghost
(Expr.bind [| var |] (f var))
[Type.any Pos.void]
(Untyped { pos = Pos.void }) ))
let test_iota_reduction_2 () =
let enumT = EnumName.fresh [] ("t", Pos.void) in
let consA = EnumConstructor.fresh ("A", Pos.void) in
let consB = EnumConstructor.fresh ("B", Pos.void) in
let consC = EnumConstructor.fresh ("C", Pos.void) in
let consD = EnumConstructor.fresh ("D", Pos.void) in
let nomark = Untyped { pos = Pos.void } in
let num n = Expr.elit (LInt (Catala_runtime.integer_of_int n)) nomark in
let injAe e = Expr.einj ~e ~cons:consA ~name:enumT nomark in
let injBe e = Expr.einj ~e ~cons:consB ~name:enumT nomark in
let injCe e = Expr.einj ~e ~cons:consC ~name:enumT nomark in
let injDe e = Expr.einj ~e ~cons:consD ~name:enumT nomark in
let injB x = injBe (Expr.evar x nomark) in
let injC x = injCe (Expr.evar x nomark) in
let injD x = injDe (Expr.evar x nomark) in
let matchA =
Expr.ematch
~e:
(Expr.ematch ~e:(num 1) ~name:enumT
~cases:
(cases_of_list
[
(consB, fun x -> injBe (injB x));
(consA, fun _x -> injAe (num 20));
])
nomark)
~name:enumT
~cases:(cases_of_list [consA, injC; consB, injD])
nomark
in
Alcotest.(check string)
"same string "
begin[@ocamlformat "disable"]
"before=match (match 1 with\n\
\ | A x → A 20\n\
\ | B x → B (B x)) with\n\
\ | A x → C x\n\
\ | B x → D x\n\
after=match 1 with\n\
\ | A x → C 20\n\
\ | B x → D (B x)\n"
end
(Format.asprintf "before=@[%a@]@.after=%a@." Expr.format (Expr.unbox matchA)
Expr.format
(Expr.unbox (optimize_expr Program.empty_ctx (Expr.unbox matchA))))