silk.core.hint.
Facts and branch weights that guide the optimizer without changing what a program computes.
When to use#
Use these functions in measured hot code: a state machine whose rare branches slow its common path, or a check the optimizer cannot prove redundant. Ordinary code needs none of them.
Details#
likely and unlikely return their condition unchanged and only weigh the branch that tests
it, as C's __builtin_expect does. assume and unreachable are unsafe: they state a fact
the caller proves, the optimizer removes checks and paths that contradict it, and a false fact is
undefined behavior. Static evaluation runs likely and unlikely as their condition.
Examples#
Weigh a rare branch and drop a check the caller proved#
import silk.core.hint
import silk.num.u32
fn scaled(value: u32, shift: u32) -> u32 {
if hint.unlikely(value == 0) {
return 1
}
// The callers pass a shift below 32, so the shift needs no range check.
unsafe { hint.assume(shift < 32) }
return u32.shiftLeft(value, shift)
}
pub fn main() -> i32 {
if scaled(3, 2) != 12 || scaled(0, 5) != 1 {
return 1
}
return 0
}Import as hint with import silk.core.hint as hint.
Public declarations: 4.
likely#
pub fn likely(condition: bool) -> boolReturns condition and weighs the branch that tests it as usually taken.
Details#
The result is always condition. The optimizer lays out the true path as the fall-through
path and moves the false path out of the way.
unlikely#
pub fn unlikely(condition: bool) -> boolReturns condition and weighs the branch that tests it as rarely taken.
Details#
The result is always condition. The optimizer lays out the false path as the fall-through
path and moves the true path out of the way.
assume#
pub unsafe fn assume(condition: bool) -> ()States that condition holds, so the optimizer can remove checks that it makes redundant.
Details#
In an optimized build the call emits no code. Later checks that condition decides, such as a
bounds check or a shift count test, fold away.
Gotchas#
The caller must prove condition. When it is false, the behavior is undefined, and a build may
skip a check that would have trapped.
unreachable#
pub unsafe fn unreachable() -> neverMarks a point that execution never reaches.
Details#
The optimizer treats every path that leads here as dead and removes it, along with the tests that select it.
Gotchas#
The caller must prove that no execution reaches the call. Reaching it is undefined behavior,
not a trap. Use Intrinsic.trap for a point that stops the program when reached.
Category: Core.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.