Skip to content

Allow for linktime conditional branching #4997

Closed
@tanishiking

Description

@tanishiking

Part of #4991

Motivation

The motivation behind this feature was to allow switching the implementation based on whether the target is Wasm running in the browser (WasmJS) or a standalone Wasm application. For example, with regular expressions, WasmJS could reuse the JavaScript Regex implementation, while a standalone Wasm application would use a pure-Scala Regex implementation.

While the original motivation is from Wasm use cases, the feature itself is self-contained and can be used for optimization purposes in the JavaScript backend as well.

How to

The main idea is to introducing the new IR node LInkTimeIf like:

To put into writing something we discussed offline at some point: I believe the easiest and cleanest way to do this is with a new IR node that would look like

case class LinkTimeIf(cond: LinkTimeCondition, thenp: Tree, elsep: Tree) extends Tree

Then, our 3 main link-time passes process it as follows:

  • the Analyzer, for the reachability analysis, deals with it during the Infos builder. Since the Infos builder walks the IR trees to build Infos, it can resolve the LinkTimeCondition and only recurse in the appropriate branch
  • the OptimizerCore would trivially replace the LinkTimeIf with either thenp or elsep, allowing further optimizations
  • the backends would do the same, if any LinkTimeIf survives until then (normally, only if the optimizer is disabled)

The precise nature of LinkTimeCondition remains to be determined, but it would fairly limited. Definitely not a full Tree.

Originally posted by @sjrd in #4991 (comment)

Where the LinkTimeCondition should be like same as scala-native's LinktimeCondition

How to: frontend

  • Introduce @LinkTime (or @resolvedAtLinktime like SN) annotation, only the annotated values (functions?) can be used as part of LinkTimeCondition
  • if expression will be translated to LinkTimeIf instead of If, when the condition is only composed of @LinkTime annotated value, Literals, and BinaryOps.

For example, the if will be translated to LinkTimeIf because the condition is composed of @LinkTime annotated booleans + BinaryOp. (if it's mixed with the runtime-value, we should fail linking).

@LinkTime
def foo: Boolean = ...
@LinkTime
def bar: Boolean = ...

if (foo && bar) { ... }

Metadata

Metadata

Labels

languageAffects language semantics.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions