daml/compiler/daml-lf-tools
Martin Huschenbett d75afebb8a
damlc: Avoid immediately invoked closures (#6274)
* damlc: Avoid immediately invoked closures

We add rules to the simplifier which rewrite expressions of the form
```
(\x1 ... xn -> E) A1 ... An
```
into
```
let x1 = A1 in ... let xn = An in E
```
provided that `xi` is not free in `Aj` for any `i < j`.

In cases where `E` is _not_ a lambda, this rewriting is beneficial
since it removes a costly closure allocation and the immediate entering
of the closure. If `E` is a closure itself, this rewriting is not
detrimental since the only difference it makes is that the values for
`A1, ..., An` end up in the list of captured variables rather than in
the list of already applied variables.

Even though users might not write expressions like the one we're
simplifying here themselves, various desugarings produce them
nevertheless. A common pattern is to define multiple auxiliary
functions that a only used once in a where cluase. For instance, with
the help these new rewriting rules the function
```haskell
f: Int -> Int -> Int
f x y = g (h x) y
  where
    g x y = x+y
    h x = 2*x
```
gets translated to
```
def f : Int64 -> Int64 -> Int64 =
  \(x : Int64) (y : Int64).
    let x2 : Int64 =
          let x2 : Int64 = x
          in MUL_INT64 2 x2
        y2 : Int64 = y
    in ADD_INT64 x2 y2
```
Without the simplification, `g` and `h` would each allocate a closure:
```
def f : Int64 -> Int64 -> Int64 =
  \(x : Int64) (y : Int64).
    (\(x2 : Int64) (y2 : Int64). ADD_INT64 x2 y2)
      ((\(x2 : Int64). MUL_INT64 2 x2) x)
      y
```

The `collect-authority` benchmarck is sped up by 1.03x by this change.
This is not a huge improvement but the change is simple enough to
merge it nevertheless.

CHANGELOG_BEGIN
CHANGELOG_END

* Let code speak not comments

CHANGELOG_BEGIN
CHANGELOG_END

* Improve explanations

CHANGELOG_BEGIN
CHANGELOG_END
2020-06-09 18:07:33 +00:00
..
src/DA/Daml/LF damlc: Avoid immediately invoked closures (#6274) 2020-06-09 18:07:33 +00:00
BUILD.bazel replace DAML Authors with DA in copyright headers (#5228) 2020-03-27 01:26:10 +01:00