# SIR Optimization Pipeline

This page describes the current pipeline conservatively: what is clearly implemented, what route a workload tends to take, and where the sharp edges still are.

## High-level picture

There are two different optimization routes that often get conflated:

- compiler-side inline SIMD for qualifying small static arrays
- SIR lowering and backend dispatch for tensor or graph workloads

Conceptually:

```text
source code
  -> HIR
  -> either small-array inline SIMD
  -> or SIR graph lowering
  -> backend selection
  -> LLVM IR / target code
```

Both routes are expected to follow the same SIMD/SIMT execution contract.
The canonical contract definition is:

- [SIMD/SIMT Unified Execution Contract](simd-simt-contract.md)

## Route 1: inline SIMD for small arrays

The compiler has a dedicated `simd_small` path for qualifying fixed-size arrays.

The current backend threshold is explicit:

- maximum 64 bytes total
- maximum 64 elements
- element count must be a power of two

That threshold is implemented in `crates/vex-sir/src/codegen/backends/simd/inline.rs` and mirrored by the small-array codegen helpers in `crates/vex-compiler/src/codegen_hir/expr/simd_small`.

Typical examples on this path are:

- element-wise arithmetic on `[T; N]`
- vector comparisons on `[T; N]`
- reductions such as `<+` and `>?|` on small arrays

Example:

```vex
fn sum8(x: [i32; 8]): i32 {
    return <+ x
}
```

On this path, the likely evidence in emitted LLVM is:

- `<N x T>` vector values
- `insertelement` chains for tiny literals
- `llvm.vector.reduce.*` intrinsics for reductions

The same operation family can be routed to SIMT kernels via SIR when shapes are dynamic or graph-oriented.

## Route 2: SIR for tensor and graph code

When code is written around `graph fn`, `Tensor<T>`, or other graph-shaped tensor operations, the compiler lowers into SIR first and then chooses a backend based on shapes and supported node families.

This route is the right mental model for:

- dynamic tensors
- graph compute
- gather and scatter families
- backend dispatch between CPU SIMD and GPU-style paths

Backend choice is implementation detail. Correctness is checked at the SIR contract level.

## Static and dynamic shape routing

The internal contract distinguishes between static and dynamic shapes:

- static tensors like `Tensor<f32, 4>` carry fixed shape information
- dynamic tensors like `Tensor<f32>` lower to `%VexDynTensor { ptr, i64 }`
- `Span<T>` lowers as a non-owning `%VexSlice { ptr, i64 }`

These are compiler-internal host layouts, not public foreign ABI declarations.
Target width/alignment and ownership still apply. That distinction matters: A dynamic tensor owns storage and participates in drop behavior, while a span is a borrowed view.

## Important coercion boundary

One of the easy mistakes is assuming every tensor-like value is interchangeable because the layouts look similar.

They are not.

The compiler has an explicit safety guard to avoid silently fabricating an owning dynamic tensor from a stack-aliased vector value. Conversions into `Tensor<T>` must go through the proper owned path.

In practical terms:

- `Span<T> -> Tensor<T>` is an owned materialization
- `Tensor<T> -> Span<T>` is an owner-bound borrowed view
- `Tensor<T, N> -> Span<T>` uses scoped addressable storage and cannot escape
- `Tensor<T>` and `Span<T>` are not just two names for the same thing
- bugs at generic call boundaries have historically shown up exactly here

## Unified Silicon IR (SIR) Operator Reference

The following catalog describes internal SIR operation families. It is not a complete source-syntax or backend-support guarantee: source lowering, dtype/shape validation, generation and runtime execution are separate boundaries. Scalar and floating-point mappings also differ.

### Arithmetic and Shape Nodes

SIR distinguishes element-wise maps from reductions, reshapes/permutations,
gathers/scatters and matrix operations. Element-wise arithmetic has lane-local
data dependencies; a reduction combines many lanes; matrix multiplication
requires compatible ranks and a matching inner dimension. These differences
affect fusion and scheduling even when source expressions look similarly short.

For executable source spellings, use the [SIMD operator guide](simd-operations.md)
and [operator reference](../advanced/operators-reference.md). Internal enum
variants such as `Fma`, `Atan2` or `Transpose` do not establish a public bare
function, Unicode operator, or method with the same name.

### Numeric Lowering

A backend selects operations according to signedness and element type.
Integer division is not always `sdiv`; unsigned operands need unsigned
semantics. A floating-point min/max lowering must define NaN and signed-zero
behavior. Rotations and carry-less multiplication may use intrinsics or
expanded instruction sequences depending on target capabilities.

An SIR `Fma` is a three-input operation. A two-operand source token does not
supply an implicit third operand. Similarly, a vector `Select` chooses between
computed lane values; it does not provide scalar branch short-circuiting for
unsafe reads or division by zero in the unused lane expression.

### Reduction and Mask Nodes

Canonical source reductions use `<+`, `<*`, `<?|`, `>?|`, `<&` and `<|>`.
The emitter determines the legal accumulation strategy for the selected dtype
and backend. A reduction intrinsic in LLVM is not proof of one hardware
instruction or bitwise parity with another accumulation order.

Masks have scalar queries (`any`, `all`, `countBits`, `firstSet`, `toBitmask`)
and mask-valued operations such as boolean algebra. `fromBitmask` constructs a
mask; it does not return a scalar. Fixed masks and runtime masks can have
different internal representations, while the documented logical lane order
must remain consistent. See [Tensor and Mask](tensor-mask.md) for
ownership and [SIMD/SIMT](simd-simt-contract.md) for transport details.

## Backend Operator Support Matrix

Support is checked per operation, dtype, shape and capability. A table marking
all element-wise math, reductions or matrix operations “Full” across every
backend would hide those boundaries. Use the
[backend implementation map](../../architecture/sir-backends-reference.md) and
[SIMD/SIMT contract](simd-simt-contract.md) to identify the selected
route, then validate the concrete workload. Shader generation, driver
acceptance and correct execution are separate results.


## Performance Routing & FLOP Weights

Dispatch policy estimates work and transfer cost using operation weights,
shape information and runtime capabilities. These weights are relative model
inputs, not measured cycles or floating-point throughput. Exceeding a threshold
does not bypass graph-support or executor checks and does not guarantee GPU
execution. Constants differ across implementation paths and can change between
compiler builds. See [GPU dispatch](../gpu/index.md#runtime-deferred-dispatch) for
how to validate the actual route.

---

## See also

- [SIMD and Auto-Vectorization](index.md)
- [Tensor and Mask Types](tensor-mask.md)
- [GPU Programming](../gpu/index.md)
