Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/no-late-inline.internal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Inline functions of other modules in one phase, the alias pass, and no longer again while compiling to JavaScript. A call through an alias, such as `add` from `let {add} = module(List)`, is now compiled as a call.
74 changes: 46 additions & 28 deletions compiler/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,8 @@ Typedtree translation in `compiler/typing/translcore.ml` and

`lam_pass_*.ml` and the other `lam_*.ml` modules
: Analyze and transform Lambda. [`lam_compile_main.ml`](lam_compile_main.ml)
coordinates the backend pass sequence; read it before inserting or
reordering a pass.

The sequence is hand-unrolled rather than iterated to a fixed point. Only
`simplify_alias` reads the statistics, and a fresh `collect_info` runs
immediately before each of its three rounds. `simplify_lets` and `sroa`
compute what they need themselves. Each `-debug-ir` dump is named after the
pass whose output it holds.

| # | pass | statistics |
|---|---|---|
| 1 | `collapse_var_aliases` | |
| 2 | `deep_flatten` | |
| 3 | `simplify_exits` | |
| 4 | `simplify_alias` | reads a snapshot taken just before |
| 5 | `deep_flatten` | |
| 6 | `simplify_alias` | reads a snapshot taken just before |
| 7 | `deep_flatten` | |
| 8 | `simplify_exits` | |
| 9 | `simplify_alias` | reads a snapshot taken just before |
| 10 | `simplify_lets` | own occurrence count |
| 11 | `sroa` | own field-use classification |
| 12 | `simplify_exits` | |
| 13 | `guard_raises` | |

A snapshot is fresh when its pass starts, but `simplify_alias` also mutates
the table as it rewrites, so entries can describe an earlier version of the
term by the time the pass finishes.
coordinates the backend pass sequence; read it and the Lambda pipeline
below before inserting or reordering a pass.

[`lam_compile.ml`](lam_compile.ml)
: Lowers Lambda to JavaScript IR. Primitive-specific and FFI lowering is split
Expand All @@ -54,6 +28,50 @@ Typedtree translation in `compiler/typing/translcore.ml` and
The driver's [`js_implementation.ml`](../driver/js_implementation.ml) runs a
source file through all compiler layers.

## Lambda pipeline

`lam_compile_main.ml` runs the passes in a fixed order. The sequence is
hand-unrolled rather than iterated to a fixed point. Each `-debug-ir` dump
is named after the pass whose output it holds.

| # | pass | what it does here |
|---|---|---|
| 1 | `collapse_var_aliases` | removes `let x = y` |
| 2 | `deep_flatten` | lifts nested lets, replaces a tuple that is only read field by field with its fields |
| 3 | `simplify_exits` | drops unused static exits, inlines those used once |
| 4 | `collect_info` + `simplify_alias` | first inlining round |
| 5 | `deep_flatten` | normalizes the inlined code |
| 6 | `collect_info` + `simplify_alias` | second round |
| 7 | `deep_flatten`, `simplify_exits` | normalize again |
| 8 | `collect_info` + `simplify_alias` | third round |
| 9 | `simplify_lets` | removes and inlines lets by their uses |
| 10 | `sroa` | turns local refs and mutable records into variables |
| 11 | `simplify_exits` | |
| 12 | `guard_raises` | |

`simplify_alias` inlines functions and uses what `collect_info` recorded
about each variable: what it is bound to, such as a function, a `Some` or a
block. An inlined body brings new bindings and new known values, so a
later round can resolve more. The facts are collected again before each
round, because the round before rewrote the term and the old entries can
name variables that are gone. The pass also updates the table as it
rewrites, so by its end some entries describe an earlier term.
`deep_flatten` and `simplify_exits` between rounds bring the inlined code
back to the shape the next round expects. `simplify_lets` and `sroa`
compute what they need themselves.

There is one cross-module inlining phase: `simplify_alias` inlines a full
call of another module's `@inline` function or functor, whose body that
module stored in its `.cmj`. A call it leaves alone is compiled as a call.
Inlining at the JavaScript level (`js_pass_tailcall_inline.ml`) is a
separate step for local functions.

`sroa` runs last because it is the only pass that creates `Lassign`. Every
pass before it relies on there being none, so a variable keeps the value it
is bound to. With `-check-lam`, `Lam_check.check` checks this after every
pass before `sroa`. A body another module stores was optimized by its own
`sroa`, so a body that assigns a variable is not stored (warning 113).

## Changing a representation

`Lambda.t` is private: every term is built through the constructors in
Expand Down
44 changes: 8 additions & 36 deletions compiler/backend/lam_compile.ml
Original file line number Diff line number Diff line change
Expand Up @@ -577,43 +577,15 @@ let compile output_prefix =
and compile_external_field_apply (appinfo : Lambda.lambda_apply)
(module_id : Ident.t) (field_name : string)
(lambda_cxt : Lam_compile_context.t) : Js_output.t =
let ident_info =
Lam_compile_env.query_external_id_info module_id field_name
(* A call that the alias pass did not inline is compiled as a call *)
let args_code, args = compile_arguments lambda_cxt appinfo.ap_args in
let fn = E.ml_var_dot module_id field_name in
let expression =
E.call ~info:(call_info_of_apply lambda_cxt.meta appinfo) fn args
in
let ap_args = appinfo.ap_args in
match ident_info.persistent_closed_lambda with
| Some (Lfunction ({params; body; _} as lfunction))
when List.compare_lengths params ap_args = 0
&& Lambda.lfunction_can_be_inlined lfunction ->
(* TODO: serialize it when exporting to save compile time *)
let _, param_map =
Lam_closure.is_closed_with_map Set_ident.empty params body
in
let inlined =
Lam_beta_reduce.propagate_beta_reduce_with_map lambda_cxt.meta param_map
params body ap_args
in
(* The inlined body comes from another module, so the variables it
assigns are not in [meta.assignable] yet. *)
let meta =
{
lambda_cxt.meta with
assignable =
Set_ident.union lambda_cxt.meta.assignable
(Lambda_traverse.assigned_variables inlined);
}
in
compile_lambda {lambda_cxt with meta} inlined
| _ ->
let args_code, args = compile_arguments lambda_cxt ap_args in

let fn = E.ml_var_dot module_id ident_info.name in
let expression =
E.call ~info:(call_info_of_apply lambda_cxt.meta appinfo) fn args
in
let expression = with_source_loc appinfo.ap_loc expression in
Js_output.output_of_block_and_expression lambda_cxt.continuation args_code
expression
let expression = with_source_loc appinfo.ap_loc expression in
Js_output.output_of_block_and_expression lambda_cxt.continuation args_code
expression
(*
The second return value holds declarations, such as [dummy_obj]
placeholders, that are emitted before the bindings
Expand Down
5 changes: 2 additions & 3 deletions compiler/backend/lam_pass_remove_alias.ml
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,8 @@ let simplify_alias (meta : Lam_stats.t) (lam : Lambda.t) : Lambda.t =
and functors store one, and every full call of it is inlined *)
when List.compare_lengths params args = 0
&& Lambda.lfunction_can_be_inlined lfunction ->
(* Like the inlining in [Lam_compile]: an argument without side
effects that the body reads once takes the parameter's place,
instead of a binding of its own *)
(* An argument without side effects that the body reads once takes
the parameter's place, instead of a binding of its own *)
let _, param_map =
Lam_closure.is_closed_with_map Set_ident.empty params body
in
Expand Down
4 changes: 2 additions & 2 deletions tests/compiler_tests/src/hello_res.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ let a = b - 1 | 0;

console.log("hello, res");

Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}});
Stdlib_List.add(/* [] */0, Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}}));

Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}});
Stdlib_List.add(/* [] */0, Stdlib_List.length({hd: 1, tl: {hd: 2, tl: {hd: 3, tl: /* [] */0}}}));

console.log(3);

Expand Down
62 changes: 62 additions & 0 deletions tests/compiler_tests/src/inline_late_alias_lib.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Generated by ReScript, PLEASE EDIT WITH CARE

import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs";

function id(x) {
return x;
}

let c = id(3);

function apply(x, f) {
return f(x);
}

function apply2(p, v, g) {
return g(v, p);
}

function unwrapG(x, o) {
if (o !== undefined) {
return [
Primitive_option.valFromOption(o),
x
];
}
}

function weird(p, o, f) {
f();
if (o !== undefined) {
return o + p | 0;
} else {
return p;
}
}

function weirdT(p, t, f) {
f();
return t[0] + p | 0;
}

function weirdG(p, o, f) {
f();
if (o !== undefined) {
return [
Primitive_option.valFromOption(o),
p
];
}
}

export {
id,
c,
apply,
apply2,
unwrapG,
weird,
weirdT,
weirdG,
}
/* c Not a pure module */
44 changes: 44 additions & 0 deletions tests/compiler_tests/src/inline_late_alias_lib.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Inlined by inline_late_alias_test.res. Each call there passes a parameter of
// the caller.
@inline(never) let id = x => x

let c = id(3)

@inline
let apply = (x, f) => f(x)

@inline
let apply2 = (p: int, v, g) => g(v, p)

@inline
let unwrapG = (x: int, o: option<'a>) =>
switch o {
| Some(v) => Some((v, x))
| None => None
}

// [f] may assign the variable the option or the tuple was made from.
@inline
let weird = (p: int, o: option<int>, f) => {
f()
switch o {
| Some(v) => v + p
| None => p
}
}

@inline
let weirdT = (p: int, t: (int, int), f) => {
f()
let (a, _) = t
a + p
}

@inline
let weirdG = (p: int, o: option<'a>, f) => {
f()
switch o {
| Some(v) => Some((v, p))
| None => None
}
}
Loading
Loading