optBarrier
On this page

optBarrier()

Function in Builtins

An optimization barrier on one f32 value, the shader equivalent of C's volatile.

import { optBarrier } from 'typeshade'

The signature, the description and the examples come from the compiler's own source at commit 26de7be8.

Syntax

const optBarrier: (v: ReadonlyNode<"f32"> | number) => Node<"f32">

Parameters

v ReadonlyNode<'f32'> | number

Return value

Node<'f32'>

Description

An optimization barrier on one f32 value, the shader equivalent of C’s volatile. It is the value-level counterpart of FuncDecl.opaque, which protects a whole function and is therefore never inlined.

optBarrier(x) equals x bit for bit, on both targets and in the CPU evaluation. What it adds is that no optimizer may look through it: it is emitted as an f32 to u32 to f32 round-trip (bitcastU32 then bitcastF32), and the integer domain is not subject to float reassociation, distribution or contraction. Two instructions, both targets, no extension.

What it defeats: this library’s own constant folding and algebraic simplification, which match literal operands only, so a wrapped term stops matching every rewrite they have; and a driver’s float reassociation or contraction across the barrier.

What it does not fix: it is a compiler barrier and has no effect on the hardware. It cannot make a lossy f32 multiply correctly rounded, and on Apple GPUs no float-domain barrier has been shown sufficient for an emulated-double multiply; the integer flavour that recommendFp64Flavor selects exists for that case. Use it to pin one value an optimizer would otherwise be free to rewrite: a Kahan compensation term, a split constant, an error-free-transform residual. Wrapping every operation buys nothing.

Examples

Example

import { fn, Let, optBarrier, f32T } from 'typeshade'
// Kahan compensation: `(sum + y) - sum - y` is algebraically zero, which is exactly
// what a reassociating compiler is licensed to delete.
const compensation = fn('kahan_c', { sum: f32T, y: f32T }, ({ sum, y }) => {
const t = Let(sum.add(y))
return optBarrier(t.sub(sum)).sub(y)
})

See also

Source

src/core/ir/node.ts, line 1967, at commit 26de7be8

Edit this page Report a problem