Function doNotOptimizeAway [src]

Force an evaluation of the expression; this tries to prevent the compiler from optimizing the computation away even if the result eventually gets discarded.

Prototype

pub fn doNotOptimizeAway(val: anytype) void

Example

test doNotOptimizeAway { comptime doNotOptimizeAway("test"); doNotOptimizeAway(null); doNotOptimizeAway(true); doNotOptimizeAway(0); doNotOptimizeAway(0.0); doNotOptimizeAway(@as(u1, 0)); doNotOptimizeAway(@as(u3, 0)); doNotOptimizeAway(@as(u8, 0)); doNotOptimizeAway(@as(u16, 0)); doNotOptimizeAway(@as(u32, 0)); doNotOptimizeAway(@as(u64, 0)); doNotOptimizeAway(@as(u128, 0)); doNotOptimizeAway(@as(u13, 0)); doNotOptimizeAway(@as(u37, 0)); doNotOptimizeAway(@as(u96, 0)); doNotOptimizeAway(@as(u200, 0)); doNotOptimizeAway(@as(f32, 0.0)); doNotOptimizeAway(@as(f64, 0.0)); doNotOptimizeAway([_]u8{0} ** 4); doNotOptimizeAway([_]u8{0} ** 100); doNotOptimizeAway(@as(std.builtin.Endian, .little)); }

Source

pub fn doNotOptimizeAway(val: anytype) void { if (@inComptime()) return; const max_gp_register_bits = @bitSizeOf(c_long); const t = @typeInfo(@TypeOf(val)); switch (t) { .void, .null, .comptime_int, .comptime_float => return, .@"enum" => doNotOptimizeAway(@intFromEnum(val)), .bool => doNotOptimizeAway(@intFromBool(val)), .int => { const bits = t.int.bits; if (bits <= max_gp_register_bits and builtin.zig_backend != .stage2_c) { const val2 = @as( std.meta.Int(t.int.signedness, @max(8, std.math.ceilPowerOfTwoAssert(u16, bits))), val, ); asm volatile ("" : : [val2] "r" (val2), ); } else doNotOptimizeAway(&val); }, .float => { if ((t.float.bits == 32 or t.float.bits == 64) and builtin.zig_backend != .stage2_c) { asm volatile ("" : : [val] "rm" (val), ); } else doNotOptimizeAway(&val); }, .pointer => { if (builtin.zig_backend == .stage2_c) { doNotOptimizeAwayC(val); } else { asm volatile ("" : : [val] "m" (val), : "memory" ); } }, .array => { if (t.array.len * @sizeOf(t.array.child) <= 64) { for (val) |v| doNotOptimizeAway(v); } else doNotOptimizeAway(&val); }, else => doNotOptimizeAway(&val), } }