Skip to content

perf(wave): branchless Q15 clamp + hoisted row indexing + __restrict__ (refs #3073 §4) #3094

Closed

Description

@zackees

Scope from #3073 §4.

Two micro-optimizations in the 2D inner update loop (src/fl/math/wave/wave_simulation_real.cpp.hpp ~lines 278–288):

1. Branchless Q15 clamp

Current:

if (f > 32767) f = 32767;
else if (f < -32768) f = -32768;

Compiles to 2 compares + branches on AVR / Cortex-M0 (no cmov). fl::clamp typically lowers branchlessly on Cortex-M4+ (ssat or min/max sequences):

next[index] = static_cast<i16>(fl::clamp(f, -32768, 32767));

If §3 (#TBD) lands first, the half-duplex lo value can be hoisted into the same clamp expression:

const i32 lo = mHalfDuplex ? 0 : -32768;  // hoisted
next[index] = static_cast<i16>(fl::clamp(f, lo, 32767));

2. Hoist row arithmetic + __restrict__

Currently int index = j * stride + i; recomputes j * stride for every i in the inner loop. The optimizer should hoist this but often doesn't with fl::size (size_t) plus non-restricted aliasing on curr/next.

Explicit hoist + restrict makes the dependency clear:

for (fl::size j = 1; j <= height; ++j) {
    const i32 row = j * stride;
    const i16* __restrict__ row_curr  = curr + row;
    const i16* __restrict__ row_above = curr + row - stride;
    const i16* __restrict__ row_below = curr + row + stride;
    i16*       __restrict__ row_next  = next + row;
    for (fl::size i = 1; i <= width; ++i) {
        const i32 c = row_curr[i];
        i32 lap = row_curr[i+1] + row_curr[i-1]
                + row_above[i] + row_below[i]
                - (c << 2);
        // ... rest of inner body unchanged
    }
}

Acceptance

  • bash test fl_math_wave_wave_simulation_real --cpp passes.
  • Generated assembly on -O2 shows the multiply lifted to the outer loop (verify with objdump -d or godbolt).

Relation

Bundle with §3 (#TBD — half-duplex fold-in); both touch the same inner loop body and the bundled diff is easier to review.

Refs: #3073 §4.

Activity

  1. zackees commented on Jun 15, 2026

    @zackees
    MemberAuthor

    Parent meta: #3098. Bundle with #3093 (§3 half-duplex fold-in) — same inner loop body.

  2. added a commit that references this issue on Jun 15, 2026
    b22674e
  3. moved this from Triage to Done in FastLED Trackeron Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions