Skip to content

[Feature] Optimize logical operators for non-expression arguments #277

@MaxGraey

Description

@MaxGraey

Not sure is this optimization logic should be part of binaryen, because it can optimize simple low-level operations. Let me describe what I mean. Suppose we have a logical operation on two variables (not expressions), then we could easily optimize such an operation to a bitwise operations:

export function nonOptimal1(a: u32, b: u32): bool {
  return (a || b) ? true : false;
}

export function nonOptimal2(a: u32, b: u32): bool {
  return <bool>(a || b);
}

export function optimal(a: u32, b: u32): bool {
  return <bool>(a | b);
}

Output for nonOptimal1 (-O3):

(func $main/nonOptimal1 (export "nonOptimal1") (type $t0) (param $p0 i32) (param $p1 i32) (result i32)
    get_local $p0
    i32.eqz
    if $I0
      get_local $p1
      set_local $p0
    end
    get_local $p0
    if $I1 (result i32)
      i32.const 1
    else
      i32.const 0
    end
    tee_local $p0)

Output for optimal (-O3):

(func $main/optimal (export "optimal") (type $t0) (param $p0 i32) (param $p1 i32) (result i32)
    get_local $p0
    get_local $p1
    i32.or
    i32.const 0
    i32.ne)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions