Learn verified native integer idioms from C and tune offline policies

Add modular Ziran C/native assembly comparison and SIGPROF reports for the
six kernels, three widget scenarios and hello. Use closed differential-tested
multiply idioms, compact IMUL immediates and bounded scalar leaf inlining.

Extend ziran learn with offline rule verification and deterministic policy
selection joined to current-format corpus identities. Builds use a reviewed
versioned source table; benchmarks keep recording off. Identical artifacts
share timing evidence, so the initial calibration retains the baseline policy.

Local validation: 281/281 tests and bootstrap passed; the subsequent stable
constructor checkpoint passed all compiler tests and bootstrap. Its two site
receipt failures were resolved and both retained site tests passed in a
separate final run. Preserve all raw timings, exclusions and source-epoch
limitations in bench/results. Remaining loop/widget work stays with its lanes.
This commit is contained in:
waozi committed 2026-11-16 16:56:03 -03:00
1 parent e991274a2e
commit 36e6caf964
51 files changed
+22287 -71

No files matched your search

+5 -5
View File
@@ -220,7 +220,7 @@ obj = $(patsubst %.c,$(BUILD_DIR)/obj/%.o,$(1))
# bootstrap compiler opens no bundle and has none.
ENGINE_C := $(BUILD_DIR)/compiler-runtime
ENGINE_MODULES := binary math utf8 vec compiler_lowered_ir compiler_lowered_verify \
compiler_lowered_proven compiler_exec_serial compiler_exec_debug compiler_exec_link compiler_exec compiler_opt
compiler_lowered_proven compiler_exec_serial compiler_exec_debug compiler_exec_link compiler_exec compiler_opt compiler_opt_inline compiler_learning compiler_learning_policy
# The Wasm lowering of revision-28 ZX (cmd/zx2wasm/zx_wasm_lower.c) reads
# the program through the same engine, under the same names.
# The native loader's per-architecture veneers are zir_host_native_<arch>.c.
@@ -483,10 +483,10 @@ $(BIN_DIR):
PACKAGE_C := $(BUILD_DIR)/package-c
PACKAGE_SOURCES := cmd/package_artifact.zi cmd/package.zi cmd/package_entry.zi cmd/package_process.zi cmd/package_script.zi cmd/package_bundle_run.zi cmd/diagnostics.zi \
cmd/package_add.zi cmd/package_guide.zi \
cmd/package_capabilities.zi cmd/package_features.zi cmd/package_explain.zi cmd/package_learn.zi cmd/package_common.zi cmd/compiler_target.zi \
cmd/package_capabilities.zi cmd/package_features.zi cmd/package_explain.zi cmd/package_learn.zi cmd/package_learn_teacher.zi cmd/package_learn_tuning.zi cmd/compiler_learning_tuning.zi cmd/compiler_bundle.zi cmd/compiler_lowered_ir.zi std/sort.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_fixture.zi cmd/package_common.zi cmd/compiler_target.zi \
cmd/package_manifest.zi cmd/package_source.zi cmd/package_lock.zi cmd/package_map.zi cmd/package_options.zi cmd/package_compile_commands.zi cmd/package_template.zi \
std/byte_text_linux.zi std/c_string.zi std/file_linux.zi std/number_text.zi \
std/json_scan.zi std/json_quote.zi std/json_bytes.zi std/simd.zi std/date_time_linux.zi std/date_time_types.zi \
std/byte_text_linux.zi std/c_string.zi std/file_linux.zi std/number_text.zi std/process_run_linux.zi \
std/json_scan.zi std/json_quote.zi std/json_bytes.zi std/json_document.zi std/float_text.zi std/text_tools.zi std/simd.zi std/date_time_linux.zi std/date_time_types.zi \
std/toml_document.zi std/utf8.zi std/text.zi std/vec.zi VERSION
# Generated files are listed when the ziran recipe expands, after generation.
PACKAGE_OBJECTS = $(patsubst $(PACKAGE_C)/%.c,$(BUILD_DIR)/obj/package-c/%.o,$(wildcard $(PACKAGE_C)/*.c))
@@ -714,7 +714,7 @@ $(PROOF_C)/.generated: cmd/compiler_proof.zi cmd/compiler_ir.zi cmd/compiler_ser
-o $(PROOF_C) cmd/compiler_proof.zi
touch $@
$(ENGINE_C)/.generated: cmd/compiler_runtime.zi cmd/compiler_exec_link.zi cmd/compiler_exec_debug.zi cmd/compiler_exec.zi cmd/compiler_opt.zi \
$(ENGINE_C)/.generated: cmd/compiler_runtime.zi cmd/compiler_exec_link.zi cmd/compiler_exec_debug.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_inline.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi \
cmd/compiler_exec_serial.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_lowered_ir.zi \
cmd/compiler_bundle.zi $(BOOTSTRAP_BIN)
env -u DISPLAY -u WAYLAND_DISPLAY $(BOOTSTRAP_BIN) --no-main --root cmd \
+2 -2
View File
@@ -6,7 +6,7 @@ ASSEMBLY_MACHINE_SOURCES := cmd/compiler_target.zi cmd/compiler_machine_image.zi
cmd/compiler_aarch64.zi cmd/compiler_armv7.zi \
cmd/compiler_arm_bytes.zi \
cmd/compiler_machine_elf.zi cmd/compiler_machine_pe.zi cmd/compiler_machine_pipeline.zi cmd/compiler_native_cache.zi
ASSEMBLY_SOURCES := cmd/compiler_bundle.zi cmd/compiler_lowered_ir.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_zir_lower.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_debug.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi $(ASSEMBLY_MACHINE_SOURCES)
ASSEMBLY_SOURCES := cmd/compiler_bundle.zi cmd/compiler_lowered_ir.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_zir_lower.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_debug.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_inline.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi $(ASSEMBLY_MACHINE_SOURCES)
ifneq ($(BOOTSTRAP),1)
ifeq ($(NATIVE_HOST_ENABLED),1)
@@ -60,7 +60,7 @@ $(BUILD_DIR)/obj/assembly-core.o: assembly.mk $(ASSEMBLY_C)/.generated $(BUILD_D
ASSEMBLY_NATIVE_MODULES := compiler_abi compiler_machine_image \
compiler_machine_ir compiler_machine_verify \
compiler_machine_aggregate compiler_machine_fields compiler_machine_select compiler_machine_lower compiler_machine_verify_allocated compiler_regalloc \
compiler_target compiler_x86_bytes compiler_x86_64 compiler_x86_runtime compiler_aarch64 compiler_armv7 \
compiler_target compiler_learning compiler_learning_policy compiler_x86_bytes compiler_x86_64 compiler_x86_runtime compiler_aarch64 compiler_armv7 \
compiler_x86_win64 compiler_x86_host compiler_x86_image \
compiler_arm_bytes \
compiler_machine_elf compiler_machine_pe \
+5 -3
View File
@@ -42,8 +42,8 @@ BENCH_ENVIRONMENT: [9]string = .["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DB
"SESSION_MANAGER", "XDG_SESSION_ID", "XDG_SESSION_TYPE", "ZIRAN_PROFILE", "ZIRAN_LEARN=off"];
// Files in bench/ that a registered benchmark builds or imports.
SUPPORT_FILES: [7]string = .["bench.zi", "benchmark_statistics.zi", "codec_kernels.py", "json_document.zi",
"math_sqrt.zi", "native_cache_fixture.zi", "wasm_tier.zi"];
SUPPORT_FILES: [10]string = .["bench.zi", "benchmark_statistics.zi", "codec_kernels.py", "json_document.zi",
"math_sqrt.zi", "native_cache_fixture.zi", "wasm_tier.zi", "c_teacher_assembly.zi", "c_teacher_profile.zi", "c_teacher_rules.zi"];
Add :: (list: *Vec(Benchmark), name: string, file: string, runner: Runner, place: Place, summary: string) {
unused VecPush(list.*, Benchmark.{.name = name, .file = file, .runner = runner, .place = place, .summary = summary})
@@ -59,6 +59,8 @@ Registry :: () -> Vec(Benchmark) {
Add(*list, "bundle-assets", "bench/bundle_assets.py", .Python, .Host, "checked resource loading with real bundles")
Add(*list, "bundle-instances", "bench/bundle_instances.py", .Python, .Host, "bundle loading and fresh-instance costs")
Add(*list, "compiler-build", "bench/compiler_build.zi", .Ziran, .Host, "full native compiler rebuild")
Add(*list, "c-teacher", "bench/c_teacher.zi", .Ziran, .Host, "generated C versus native assembly and SIGPROF")
Add(*list, "c-teacher-tune", "bench/c_teacher_tuning.zi", .Ziran, .Host, "offline leaf policies against generated C")
Add(*list, "compiler-kernels", "bench/compiler_kernel_benchmarks.sh", .Shell, .Host, "timed compiler and codec kernels")
Add(*list, "compiler-scaling", "bench/compiler_scaling.py", .Python, .Host, "module graphs and generic specialization")
Add(*list, "cpu-features", "bench/cpu_features.py", .Python, .Host, "CPU-selected assembly against fallbacks")
@@ -85,7 +87,7 @@ Registry :: () -> Vec(Benchmark) {
Add(*list, "vm-execution", "bench/vm_execution.py", .Python, .Host, "verified engine execution")
Add(*list, "vm-native", "bench/vm_native.py", .Python, .Host, "engine workloads against generated C and Go")
Add(*list, "vm-startup", "bench/vm_startup.py", .Python, .Host, "checked loading and engine preparation")
Add(*list, "wasm-tier", "bench/wasm_tier.py", .Python, .Host, "native and Wasm against the engine and C")
Add(*list, "wasm-tier", "bench/wasm_tier.py", .Python, .Host, "native/Wasm kernels; --standard adds independent C/Go references")
Add(*list, "zx-compare", "bench/zx_compare.zi", .Ziran, .Host, "ZX runtime comparison cohorts")
Add(*list, "zx-compare-devices", "bench/zx_compare.py", .Python, .Device, "ZX comparison on Alpha or a USB phone")
Add(*list, "zx-engine", "bench/zx_engine.zi", .Ziran, .Host, "instruction engine against the C target")
+407
View File
@@ -0,0 +1,407 @@
// Compare generated C with the native pipeline using identical checked input.
// Run only through bench/bench.zi; all compilation and sampling shares its
// learning-off environment and the caller's build-queue reservation.
#import "c_teacher_assembly"
#import "c_teacher_profile"
#import "c_teacher_rules"
#import "std/byte_text_linux"
#import "std/environment_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/json_document"
#import "std/number_text"
#import "std/process_run_linux"
#import "std/text_tools"
using Vectors :: #import "std/vec"
#scope_file
Case :: struct { name: string; bundle: string; cdir: string; symbol: string; header: string; expected: s32; printing: bool; checksum: string }
Finding :: struct { workload: string; compiler: string; name: string; native: TeacherMetrics; teacher: TeacherMetrics; samples: s64; total: s64; score: s64 }
Join :: (a: string, b: string) -> string { parts := string.[a, b]; return TextDetach(TextJoin(parts[:], "")) }
Number :: (n: s64) -> string { bytes: [32]u8; return Join("", FormatInteger(n, bytes[:])) }
Field :: (d: *JsonDocument, node: s32, key: string) -> string { return TextDetach(JsonString(d, JsonMember(d, node, key))) }
Integer :: (d: *JsonDocument, node: s32, key: string) -> s64 { n, ok := JsonInteger(d, JsonMember(d, node, key)); return ifx ok then n else -1 }
Capture :: (args: []string) -> (text: string, code: s32) {
run: ProcessRun
options: ProcessOptions = .{arguments = args, capture_output = true, merge_error = true}
if !RunProcess(options, *run) { return "could not start child", 127 }
return TextDetach(BuilderFinish(run.output)), run.code
}
Require :: (args: []string) -> bool {
text, code := Capture(args)
if code != 0 { print("command failed (%): %\n%\n", code, TextJoin(args, " "), text); return false }
return true
}
Sources :: (directory: string, suffix: string, files: *Vec(string)) {
names: Vec(string)
if !ListDirectory(directory, *names) { return }
for name: names {
path := TextDetach(JoinPath(directory, name))
if IsDirectory(path) { Sources(path, suffix, files) }
else if TextHasSuffix(path, suffix) { unused VecPush(files.*, path) }
}
}
Hash :: (path: string) -> string {
command := string.["sha256sum", path]
text, code := Capture(command[:])
return ifx code == 0 && text.count >= 64 then text[:64] else "unavailable"
}
Clang :: () -> string {
candidates := string.["clang", "clang-22", "clang-21", "clang-20", "clang-19", "clang-18", "clang-17"]
for candidate: candidates {
command := string.[candidate, "--version"]
version, code := Capture(command[:])
if code == 0 { return candidate }
}
return ""
}
Metrics :: (m: TeacherMetrics) -> string {
values := s64.[m.instructions, m.loop_instructions, m.back_edges, m.stack_reads, m.stack_writes,
m.memory, m.indexed, m.branches, m.forward_branches, m.calls, m.vectors, m.multiplies, m.divides, m.shifts, m.loop_constants]
parts: Vec(string)
for value: values { unused VecPush(parts, Number(value)) }
return TextDetach(TextJoin(VecSlice(parts, 0, parts.count), "/"))
}
Patterns :: (n: TeacherMetrics, c: TeacherMetrics) -> string {
patterns: Vec(string)
if n.stack_reads + n.stack_writes > c.stack_reads + c.stack_writes { unused VecPush(patterns, "stack traffic (regalloc/aggregate lane)") }
if n.branches > c.branches { unused VecPush(patterns, "branch layout/loop rotation (SSA lane)") }
if n.calls > c.calls { unused VecPush(patterns, "calls/inlining candidates") }
if n.multiplies + n.divides > c.multiplies + c.divides { unused VecPush(patterns, "strength reduction candidates") }
if n.loop_constants > c.loop_constants { unused VecPush(patterns, "loop constants/LICM candidates") }
if c.vectors > n.vectors { unused VecPush(patterns, "vector idioms (inspect scalar SSE uses)") }
if n.memory > c.memory { unused VecPush(patterns, "memory/address folding candidates") }
return TextDetach(TextJoin(VecSlice(patterns, 0, patterns.count), "; "))
}
SaveProfile :: (path: string, profile: *TeacherProfile, digest: string) -> bool {
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
JsonSet(*document, root, "artifact_sha256", JsonNewStringCopy(*document, digest))
JsonSet(*document, root, "samples", JsonNewInteger(*document, profile.total))
JsonSet(*document, root, "runs", JsonNewInteger(*document, profile.runs))
ips := JsonNewArray(*document)
JsonSet(*document, root, "ips", ips)
for sample: profile.samples {
ip := JsonNewObject(*document)
JsonSet(*document, ip, "address", JsonNewInteger(*document, cast(s64)sample.address))
JsonSet(*document, ip, "count", JsonNewInteger(*document, sample.count))
unused JsonAppend(*document, ips, ip)
}
return WriteEntireFile(path, TextDetach(JsonWrite(*document, root, JsonPythonStyle(2))))
}
Append :: (text: *Vec(u8), value: string) { BuilderAppend(text.*, value) }
Line :: (text: *Vec(u8), value: string) { Append(text, value); Append(text, "\n") }
Row :: (text: *Vec(u8), cells: []string) {
Append(text, "| "); Append(text, TextDetach(TextJoin(cells, " | "))); Line(text, " |")
}
LoopSummary :: (code: []TeacherInstruction, begin: s64, end: s64, base: s64, profile: *TeacherProfile) -> string {
loops := TeacherLoops(code, begin, end)
best: TeacherLoop
best_samples: s64 = -1
for loop: loops {
samples: s64
for sample: profile.samples {
if sample.address >= cast(u64)(base + loop.begin) && sample.address <= cast(u64)(base + loop.end) { samples += sample.count }
}
if samples > best_samples || samples == best_samples && loop.instructions > best.instructions {
best = loop; best_samples = samples
}
}
if best_samples < 0 { return "none" }
parts := string.[Number(best.begin), "..", Number(best.end), ": ", Number(best.instructions), " instructions, ", Number(best_samples), " samples"]
return TextDetach(TextJoin(parts[:], ""))
}
Bindings :: (arguments: *Vec(string)) -> bool {
text, found := ReadEntireFile("build/site-library-targets/sources/widget_benchmarks.json")
document: JsonDocument
defer JsonReset(*document)
if !found || !JsonRead(*document, text) { return false }
bindings := JsonMember(*document, document.root, "bindings")
if JsonKindOf(*document, bindings) != .Array { return false }
for index: cast(s32)0..JsonCount(*document, bindings) - 1 {
binding := TeacherIRBinding(JsonString(*document, JsonElement(*document, bindings, index)))
if binding == "" { return false }
unused VecPush(arguments.*, "--bind")
unused VecPush(arguments.*, binding)
}
return true
}
// Reuse the scenario harness's checked IR, including its ordinary library
// bindings, rather than teaching this tool anything about widget internals.
GenerateC :: (item: Case, directory: string) -> bool {
if item.name == "Hello" { return true }
arguments: Vec(string)
root := ifx item.header == "wasm_tier.h" then "bench" else "build/site-library-targets/ir"
module := ifx item.header == "wasm_tier.h" then "wasm_tier" else "widget_benchmarks"
entry := ifx item.header == "wasm_tier.h" then item.name else Join(item.name, "Case")
flags := string.["build/bin/zi2c", "--no-main", "--root", root, "--module-path", "std", "--entry",
Join(module, Join(":", entry)), "-o", directory]
for flag: flags { unused VecPush(arguments, flag) }
if root == "bench" { unused VecPush(arguments, "bench/wasm_tier.zi") }
else {
if !Bindings(*arguments) { return false }
Sources(root, ".zir", *arguments)
}
return Require(VecSlice(arguments, 0, arguments.count))
}
Compare :: (item: Case, compiler: string, work: string, report: *Vec(u8), findings: *Vec(Finding)) -> bool {
directory := TextDetach(JoinPath(work, item.name))
if !CreateDirectories(directory) { return false }
generated := TextDetach(JoinPath(directory, "c"))
if !GenerateC(item, generated) { return false }
cdir := ifx item.name == "Hello" then item.cdir else generated
native := TextDetach(JoinPath(directory, "native"))
mapfile := TextDetach(JoinPath(directory, "native.map.json"))
native_command := string.["build/bin/zx2native", "-o", native, item.bundle]
map_command := string.["build/bin/zx2native", "--emit", "map", "-o", mapfile, item.bundle]
if !Require(native_command[:]) || !Require(map_command[:]) { return false }
maptext, read := ReadEntireFile(mapfile)
map: JsonDocument
defer JsonReset(*map)
if !read || !JsonRead(*map, maptext) { return false }
identity := JsonMember(*map, map.root, "identity")
if Field(*map, identity, "digest") != Hash(native) { print("native map identity mismatch for %\n", item.name); return false }
image := JsonMember(*map, map.root, "image")
offset := Integer(*map, image, "text_file_offset")
size := Integer(*map, image, "text_size")
base := Integer(*map, image, "text_virtual_address")
raw := TextDetach(JoinPath(directory, "text.bin"))
extract_command := string.["dd", Join("if=", native), Join("of=", raw), "bs=65536", "iflag=skip_bytes,count_bytes",
Join("skip=", Number(offset)), Join("count=", Number(size)), "status=none"]
if offset < 0 || size <= 0 || !Require(extract_command[:]) { return false }
native_dump := string.["objdump", "-D", "-b", "binary", "-m", "i386:x86-64", "-M", "intel", "--no-show-raw-insn", raw]
ntext, ncode := Capture(native_dump[:])
if ncode != 0 { return false }
unused WriteEntireFile(JoinPath(directory, "native.asm"), ntext)
executable := TextDetach(JoinPath(directory, compiler))
arguments: Vec(string)
flags := string.[compiler, "-O2", "-std=c11"]
for flag: flags { unused VecPush(arguments, flag) }
matrix_flags := string.["-DMATRIX_NATIVE", Join("-I", cdir),
Join("-DMATRIX_HEADER=\"", Join(item.header, "\"")), Join("-DMATRIX_ENTRY=", item.symbol)]
if item.header != "" { for flag: matrix_flags { unused VecPush(arguments, flag) } }
if item.header != "" { unused VecPush(arguments, "bench/site_target_host.c") }
if item.printing { unused VecPush(arguments, "-DMATRIX_VOID") }
Sources(cdir, ".c", *arguments)
link_flags := string.["-lm", "-o", executable]
for flag: link_flags { unused VecPush(arguments, flag) }
if !Require(VecSlice(arguments, 0, arguments.count)) { return false }
parity_command := string.[executable, "-", item.checksum, "3"]
parity, parity_code := Capture(parity_command[:])
if parity_code != 0 { print("C checksum parity failed for %/%: %\n", item.name, compiler, parity); return false }
unused WriteEntireFile(JoinPath(directory, Join(compiler, ".parity.json")), parity)
c_dump := string.["objdump", "-d", "-M", "intel", "--no-show-raw-insn", executable]
ctext, ccode := Capture(c_dump[:])
if ccode != 0 { return false }
unused WriteEntireFile(JoinPath(directory, Join(compiler, ".asm")), ctext)
// Sampling is diagnostic, never a benchmark timing. Short programs may
// yield no ticks; report unknown instead of inventing a time share.
profile := TeacherSampleProgram(native, item.expected)
if !profile.valid { print("sampling failed for %\n", item.name); return false }
if !SaveProfile(JoinPath(directory, Join(compiler, ".profile.json")), *profile, Hash(native)) { return false }
Line(report, Join("\n## ", Join(item.name, Join(" / ", compiler))))
Line(report, Join("Native SHA-256: ", Hash(native)))
Line(report, Join("C SHA-256: ", Hash(executable)))
Line(report, Join("ZX SHA-256: ", Hash(item.bundle)))
version_command := string.[compiler, "--version"]
compiler_version, version_code := Capture(version_command[:])
version_end := TextFind(compiler_version, "\n")
if version_end >= 0 { compiler_version = compiler_version[:version_end] }
Line(report, Join("Compiler: ", compiler_version))
Line(report, Join("SIGPROF samples/runs: ", Join(Number(profile.total), Join("/", Number(profile.runs)))))
Line(report, "\n| Function | Native metrics | C metrics | Samples | Native loop with most samples (text offsets) |\n| --- | --- | --- | ---: | --- |")
ninst := TeacherInstructions(ntext)
cinst := TeacherInstructions(ctext)
symbol_command := string.["nm", "-S", "-n", "--defined-only", executable]
symbol_text, symbol_code := Capture(symbol_command[:])
if symbol_code != 0 { return false }
symbols := TeacherSizedSymbols(symbol_text)
proposals: JsonDocument
defer JsonReset(*proposals)
proposal_root := JsonNewObject(*proposals)
JsonSet(*proposals, proposal_root, "schema_version", JsonNewInteger(*proposals, 1))
JsonSet(*proposals, proposal_root, "native_sha256", JsonNewStringCopy(*proposals, Hash(native)))
JsonSet(*proposals, proposal_root, "zx_sha256", JsonNewStringCopy(*proposals, Hash(item.bundle)))
JsonSet(*proposals, proposal_root, "c_sha256", JsonNewStringCopy(*proposals, Hash(executable)))
JsonSet(*proposals, proposal_root, "compiler", JsonNewStringCopy(*proposals, compiler_version))
proposal_rules := JsonNewArray(*proposals)
JsonSet(*proposals, proposal_root, "candidates", proposal_rules)
functions := JsonMember(*map, map.root, "functions")
for index: cast(s32)0..JsonCount(*map, functions) - 1 {
function := JsonElement(*map, functions, index)
begin := Integer(*map, function, "begin")
end := Integer(*map, function, "end")
if begin < 0 || end <= begin { continue }
name := Field(*map, function, "name")
module := Field(*map, function, "module")
mangled := Join(module, Join("_", name))
found := false
cbegin: s64
cend: s64
cmetrics: TeacherMetrics
for symbol: symbols {
if symbol.name == mangled || name != "main" && symbol.name == name {
cmetrics = TeacherMeasure(VecSlice(cinst, 0, cinst.count), symbol.begin, symbol.end)
cbegin = symbol.begin; cend = symbol.end
found = true; break
}
}
native_metrics := TeacherMeasure(VecSlice(ninst, 0, ninst.count), begin, end)
samples: s64
for sample: profile.samples {
if sample.address >= cast(u64)(base + begin) && sample.address < cast(u64)(base + end) { samples += sample.count }
}
cname := ifx found then Metrics(cmetrics) else "absent (inline/dead/renamed unknown)"
cells := string.[mangled, Metrics(native_metrics), cname, Number(samples),
LoopSummary(VecSlice(ninst, 0, ninst.count), begin, end, base, *profile)]
Row(report, cells[:])
if found {
rules := TeacherMineRewrites(VecSlice(ninst, 0, ninst.count), begin, end,
VecSlice(cinst, 0, cinst.count), cbegin, cend)
for rule: rules {
proposal := JsonNewObject(*proposals)
JsonSet(*proposals, proposal, "rule", JsonNewStringCopy(*proposals, "x86-multiply-constant"))
JsonSet(*proposals, proposal, "function", JsonNewStringCopy(*proposals, mangled))
JsonSet(*proposals, proposal, "factor", JsonNewInteger(*proposals, rule.factor))
JsonSet(*proposals, proposal, "native", JsonNewStringCopy(*proposals, rule.native))
JsonSet(*proposals, proposal, "teacher", JsonNewStringCopy(*proposals, rule.teacher))
JsonSet(*proposals, proposal, "precondition", JsonNewStringCopy(*proposals, "integer-modulo-width; flags-dead; no-memory"))
JsonSet(*proposals, proposal, "verified", JsonNewBool(*proposals, false))
unused JsonAppend(*proposals, proposal_rules, proposal)
}
}
if found && native_metrics.instructions > cmetrics.instructions {
delta := native_metrics.instructions - cmetrics.instructions
// Ranking is a proxy, not estimated cycles. Weight excess code by
// observed function samples; unsampled functions rank last.
score := ifx profile.total > 0 then samples * 100000 * delta / (native_metrics.instructions * profile.total) else 0
unused VecPush(findings.*, Finding.{workload = item.name, compiler = compiler, name = mangled,
native = native_metrics, teacher = cmetrics, samples = samples, total = profile.total, score = score})
}
}
return WriteEntireFile(JoinPath(directory, Join(compiler, ".candidates.json")),
TextDetach(JsonWrite(*proposals, proposal_root, JsonPythonStyle(2))))
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
output := "bench/results/c-teacher-omega.md"
if argc == 3 && TextFromCString(argv[1]) == "--output" { output = TextFromCString(argv[2]) }
else if argc != 1 { print("c_teacher.zi [--output REPORT.md]\nPrepare wasm-tier and library-targets through bench/bench.zi first.\n"); return 2 }
work := "build/c-teacher"
if !CreateDirectories(work) { return 1 }
cases: Vec(Case)
kernel_names := string.["Sieve", "Records", "Hash", "Vectors", "Calls", "Printing"]
for name: kernel_names {
wrapper_path := Join("build/wasm-tier/native_", Join(name, ".zi"))
wrapper, found := ReadEntireFile(wrapper_path)
if !found { print("prepare wasm-tier first: missing %\n", wrapper_path); return 1 }
wrapper = TextDetach(TextReplace(wrapper, "0..31", "0..1023"))
checksum_at := TextFind(wrapper, "checksum != ")
result := "0"
if checksum_at >= 0 {
at := checksum_at + 12
end := TextFind(wrapper, " {", at)
checksum, ok := TextInteger(wrapper[at:end])
if !ok { return 1 }
result = Number(checksum / 32)
wrapper = TextDetach(TextReplace(wrapper, Join("checksum != ", Number(checksum)), Join("checksum != ", Number(checksum * 32))))
}
teacher_source := TextDetach(JoinPath(work, Join("teacher_", Join(name, ".zi"))))
bundle := TextDetach(JoinPath(work, Join(name, ".zx")))
if !WriteEntireFile(teacher_source, wrapper) { return 1 }
build_command := string.["build/bin/zi2zx", "--root", work, "--module-path", "bench", "--module-path", "std",
"--entry", Join("teacher_", Join(name, ":main")), "-o", bundle, teacher_source]
if !Require(build_command[:]) { return 1 }
unused VecPush(cases, Case.{name = name, bundle = bundle,
cdir = "build/wasm-tier/c", symbol = Join("wasm_tier_", name), header = "wasm_tier.h", expected = 42, printing = name == "Printing", checksum = result})
}
widget_cases := string.["Button", "Text", "Input"]
widget_ids := string.["button", "text", "input"]
for index: 0..2 {
folder := Join("build/site-library-targets/", widget_ids[index])
module := Join("teacher_", widget_cases[index])
source := TextDetach(JoinPath(work, Join(module, ".zi")))
bundle := TextDetach(JoinPath(work, Join(module, ".zx")))
body := string.["Widget :: #import \"widget_benchmarks\";\n#program_export\nmain :: () -> s32 {\n",
" for iteration: 0..2047 { if Widget.", widget_cases[index], "Case() != 0 { return 1 } }\n return 0\n}\n"]
if !WriteEntireFile(source, TextDetach(TextJoin(body[:], ""))) { return 1 }
command: Vec(string)
flags := string.["build/bin/zi2zx", "--root", work, "--module-path", "build/site-library-targets/ir", "--module-path", "std",
"--entry", Join(module, ":main"), "-o", bundle]
for flag: flags { unused VecPush(command, flag) }
if !Bindings(*command) { return 1 }
unused VecPush(command, source)
Sources("build/site-library-targets/ir", ".zir", *command)
if !Require(VecSlice(command, 0, command.count)) { return 1 }
unused VecPush(cases, Case.{name = widget_cases[index], bundle = bundle,
cdir = Join(folder, "/c"), symbol = Join(widget_cases[index], "Case"), header = "widget_benchmarks.h", checksum = "0"})
}
hello_bundle := string.["build/bin/zi2zx", "--root", "examples", "--module-path", "std", "--entry", "hello:main", "-o", "build/c-teacher/hello.zx", "examples/hello.zi"]
hello_c := string.["build/bin/zi2c", "--root", "examples", "--module-path", "std", "-o", "build/c-teacher/hello-c", "examples/hello.zi"]
if !Require(hello_bundle[:]) || !Require(hello_c[:]) { return 1 }
unused VecPush(cases, Case.{name = "Hello", bundle = "build/c-teacher/hello.zx", cdir = "build/c-teacher/hello-c",
symbol = "hello_main", header = "hello.h", printing = true, checksum = "0"})
report: Vec(u8)
revision_command := string.["git", "rev-parse", "HEAD"]
revision, code := Capture(revision_command[:])
Line(*report, "# C teacher: native assembly comparison")
Line(*report, Join("\nBase revision: ", TextTrim(revision)))
host_command := string.["hostname"]
host, host_code := Capture(host_command[:])
if host_code != 0 { return 1 }
Line(*report, Join("Host: ", TextTrim(host)))
tool_names := string.["build/bin/zi2c", "build/bin/zi2zx", "build/bin/zx2native"]
tool_hashes: Vec(string)
for tool: tool_names {
digest := Hash(tool)
unused VecPush(tool_hashes, digest)
Line(*report, Join(tool, Join(" SHA-256: ", digest)))
}
Line(*report, "Learning off. Generated C compiled with -O2; native compiled from verified ZX. Function extents come from the native map; C symbols match module_name or exported name exactly. Absent symbols are not evidence of inlining. Metrics: instructions/loop-union/back-edges/stack-reads/stack-writes/memory/indexed/branches/forward-branches/calls/vector-register-uses/mul/div/shifts/loop-immediate-or-PC-relative candidates. Stack traffic includes locals and saves. Vector-register uses include scalar floating point. Loop constants are LICM candidates, not proven invariants. Back edges describe loop bodies, not execution frequency. SIGPROF uses a 1ms CPU timer, at most 30 runs; zero samples means unknown time share. Sampling includes process startup and runtime. Ranking weights relative instruction excess by observed function samples; it predicts neither cycles nor speedup.")
findings: Vec(Finding)
clang := Clang()
failures: s64
for item: cases {
if !Compare(item, "cc", work, *report, *findings) {
Line(*report, Join("\nINCOMPLETE: comparison failed for ", item.name))
failures += 1
continue
}
if clang != "" && !Compare(item, clang, work, *report, *findings) {
Line(*report, Join("\nINCOMPLETE: clang comparison failed for ", item.name))
failures += 1
}
}
ranked: Vec(u8)
Line(*ranked, "\n## Ranked C wins\n\n| Workload/compiler/function | Weighted excess | Function samples/total (estimated CPU share) | Patterns to inspect | Native | C |\n| --- | ---: | ---: | --- | --- | --- |")
for index: 1..findings.count - 1 {
at := index
while at > 0 && findings[at].score > findings[at - 1].score {
swap := findings[at]; findings[at] = findings[at - 1]; findings[at - 1] = swap; at -= 1
}
}
for finding: findings {
identity := string.[finding.workload, finding.compiler, finding.name]
share := ifx finding.total > 0 then Join(Number(finding.samples * 100 / finding.total), "%") else "unknown"
cells := string.[TextDetach(TextJoin(identity[:], "/")), Number(finding.score),
Join(Number(finding.samples), Join("/", Join(Number(finding.total), Join(" ", share)))),
Patterns(finding.native, finding.teacher), Metrics(finding.native), Metrics(finding.teacher)]
Row(*ranked, cells[:])
}
Append(*report, TextDetach(BuilderFinish(ranked)))
for index: 0..tool_names.count - 1 {
if Hash(tool_names[index]) != tool_hashes[index] {
Line(*report, Join("INCOMPLETE: compiler changed during comparison: ", tool_names[index]))
failures += 1
}
}
if !WriteEntireFile(output, TextDetach(BuilderFinish(report))) { return 1 }
print("C teacher: % workloads, % ranked function comparisons, % failed; %\n", cases.count, findings.count, failures, output)
return ifx failures == 0 then 0 else 1
}
+194
View File
@@ -0,0 +1,194 @@
// Structural observations, never equivalence proofs. Addresses are normalized
// by the caller: ELF virtual addresses for C, text-relative addresses for ZX.
#import "std/text_tools"
#import "std/byte_text_linux"
using Vectors :: #import "std/vec"
TeacherInstruction :: struct {
address: s64
mnemonic: string
operands: string
}
TeacherFunction :: struct {
name: string
begin: s64
end: s64
}
TeacherLoop :: struct { begin: s64; end: s64; instructions: s64 }
// Checked IR export uses the leaf module name. Apply the same mapping to
// each qualified side of a manifest binding; retain the function spelling.
TeacherIRBinding :: (binding: string) -> string {
sides := TextSplit(binding, "=")
flattened: Vec(string)
for side: sides {
colon := TextFind(side, ":")
if colon < 0 { return "" }
slash := TextFindLast(side[:colon], "/")
unused VecPush(flattened, side[slash + 1:])
}
if flattened.count != 2 { return "" }
return TextDetach(TextJoin(VecSlice(flattened, 0, flattened.count), "="))
}
TeacherMetrics :: struct {
instructions: s64
loop_instructions: s64
back_edges: s64
stack_reads: s64
stack_writes: s64
memory: s64
indexed: s64
branches: s64
forward_branches: s64
calls: s64
vectors: s64
multiplies: s64
divides: s64
shifts: s64
loop_constants: s64
}
TeacherHex :: (text: string) -> (value: s64, valid: bool) {
if TextHasPrefix(text, "0x") { text = text[2:] }
value: s64
digits: s64
for byte: text {
digit: s64 = -1
if byte >= 48 && byte <= 57 { digit = cast(s64)byte - 48 }
if byte >= 97 && byte <= 102 { digit = cast(s64)byte - 87 }
if byte >= 65 && byte <= 70 { digit = cast(s64)byte - 55 }
if digit < 0 || value > 576460752303423487 { return 0, false }
value = value * 16 + digit
digits += 1
}
return value, digits > 0
}
// objdump --no-show-raw-insn -M intel. Ignore symbol headings, data and
// diagnostic lines; never count a wrapped instruction byte line as code.
TeacherInstructions :: (text: string) -> Vec(TeacherInstruction) {
result: Vec(TeacherInstruction)
lines := TextLines(text)
for raw: lines {
line := TextTrim(raw)
colon := TextFind(line, ":")
if colon <= 0 { continue }
address, valid := TeacherHex(line[:colon])
if !valid { continue }
body := TextTrim(line[colon + 1:])
at: s64
while at < body.count && !TextIsSpace(body[at]) { at += 1 }
if at == 0 { continue }
mnemonic := body[:at]
if mnemonic == "(bad)" || mnemonic[0] == 46 { continue }
unused VecPush(result, TeacherInstruction.{address = address, mnemonic = mnemonic,
operands = TextTrim(body[at:])})
}
return result
}
TeacherSymbols :: (text: string) -> Vec(TeacherFunction) {
result: Vec(TeacherFunction)
lines := TextLines(text)
for raw: lines {
line := TextTrim(raw)
left := TextFind(line, " <")
right := TextFind(line, ">:")
if left <= 0 || right <= left { continue }
address, valid := TeacherHex(line[:left])
if !valid { continue }
if result.count > 0 { result[result.count - 1].end = address }
unused VecPush(result, TeacherFunction.{name = line[left + 2:right], begin = address, end = 9223372036854775807})
}
return result
}
// nm -S -n --defined-only gives real symbol sizes, excluding alignment
// padding and adjacent functions. Zero-sized/untyped symbols stay unmatched.
TeacherSizedSymbols :: (text: string) -> Vec(TeacherFunction) {
result: Vec(TeacherFunction)
lines := TextLines(text)
for line: lines {
pieces := TextSplit(TextTrim(line), " ")
fields: Vec(string)
for piece: pieces { if piece != "" { unused VecPush(fields, piece) } }
if fields.count != 4 || fields[2] != "T" && fields[2] != "t" { continue }
address, address_ok := TeacherHex(fields[0])
size, size_ok := TeacherHex(fields[1])
if !address_ok || !size_ok || size <= 0 || size > 9223372036854775807 - address { continue }
unused VecPush(result, TeacherFunction.{name = fields[3], begin = address, end = address + size})
}
return result
}
TeacherBranch :: (instruction: TeacherInstruction) -> bool {
return TextHasPrefix(instruction.mnemonic, "j") || instruction.mnemonic == "loop"
}
TeacherTarget :: (instruction: TeacherInstruction) -> (address: s64, valid: bool) {
at: s64
while at < instruction.operands.count && !TextIsSpace(instruction.operands[at]) { at += 1 }
return TeacherHex(instruction.operands[:at])
}
TeacherLoops :: (code: []TeacherInstruction, begin: s64, end: s64) -> Vec(TeacherLoop) {
result: Vec(TeacherLoop)
for instruction: code {
if instruction.address < begin || instruction.address >= end || !TeacherBranch(instruction) { continue }
target, valid := TeacherTarget(instruction)
if !valid || target < begin || target > instruction.address { continue }
count: s64
for member: code { if member.address >= target && member.address <= instruction.address { count += 1 } }
unused VecPush(result, TeacherLoop.{begin = target, end = instruction.address, instructions = count})
}
return result
}
TeacherMeasure :: (code: []TeacherInstruction, begin: s64, end: s64) -> TeacherMetrics {
result: TeacherMetrics
// Count the union of loop intervals; nested loops must not inflate the
// static instruction count. Back edges are candidates, not hotness data.
loops := TeacherLoops(code, begin, end)
result.back_edges = loops.count
for instruction: code {
if instruction.address < begin || instruction.address >= end { continue }
result.instructions += 1
loop := false
for candidate: loops {
if instruction.address >= candidate.begin && instruction.address <= candidate.end { loop = true }
}
if loop { result.loop_instructions += 1 }
operands := instruction.operands
memory := TextContains(operands, "[")
if memory {
result.memory += 1
if TextContains(operands, "*") || TextContains(operands, "+r") || TextContains(operands, "+e") { result.indexed += 1 }
// Stack references include locals, saved registers and spills.
// They cannot be identified as allocator spills from assembly alone.
if TextContains(operands, "[rsp") || TextContains(operands, "[rbp") {
comma := TextFind(operands, ",")
bracket := TextFind(operands, "[")
if comma >= 0 && bracket < comma && instruction.mnemonic != "cmp" && instruction.mnemonic != "test" && instruction.mnemonic != "lea" {
result.stack_writes += 1
} else if instruction.mnemonic != "lea" { result.stack_reads += 1 }
}
}
if TeacherBranch(instruction) {
result.branches += 1
target, valid := TeacherTarget(instruction)
if valid && target > instruction.address { result.forward_branches += 1 }
}
if instruction.mnemonic == "call" { result.calls += 1 }
if TextContains(operands, "xmm") || TextContains(operands, "ymm") || TextContains(operands, "zmm") { result.vectors += 1 }
if instruction.mnemonic == "imul" || instruction.mnemonic == "mul" { result.multiplies += 1 }
if instruction.mnemonic == "idiv" || instruction.mnemonic == "div" { result.divides += 1 }
if instruction.mnemonic == "shl" || instruction.mnemonic == "shr" || instruction.mnemonic == "sar" { result.shifts += 1 }
if loop && (TextContains(operands, ",0x") || instruction.mnemonic == "lea" && TextContains(operands, "[rip")) {
result.loop_constants += 1
}
}
return result
}
+132
View File
@@ -0,0 +1,132 @@
// SIGPROF sampling of a private child, Linux x86-64. Install ITIMER_PROF at
// exec's first stop, restore its instruction and registers, and then sample
// unchanged code. No signal handler or runtime is added to the measured ELF.
#import "std/c_string"
using Vectors :: #import "std/vec"
#scope_file
libc_teacher :: #system_library "libc";
Ptrace :: (request: s64, pid: s32, address: u64, data: u64) -> s64 #foreign libc_teacher "ptrace";
Fork :: () -> s32 #foreign libc_teacher "fork";
Exec :: (path: *u8, arguments: **u8) -> s32 #foreign libc_teacher "execv";
Exit :: (code: s32) -> void #foreign libc_teacher "_exit";
WaitPid :: (pid: s32, status: *s32, options: s32) -> s32 #foreign libc_teacher "waitpid";
Kill :: (pid: s32, number: s32) -> s32 #foreign libc_teacher "kill";
Open :: (path: *u8, flags: s32) -> s32 #foreign libc_teacher "open";
Dup :: (from: s32, to: s32) -> s32 #foreign libc_teacher "dup2";
Close :: (fd: s32) -> s32 #foreign libc_teacher "close";
Errno :: () -> *s32 #foreign libc_teacher "__errno_location";
Registers :: struct { words: [27]u64 }
Wait :: (pid: s32, status: *s32) -> bool {
while true {
if WaitPid(pid, status, 0) == pid { return true }
if Errno()[0] != 4 { return false }
}
}
Trace :: (request: s64, pid: s32, address: u64, data: u64) -> bool {
error := Errno()
error[0] = 0
result := Ptrace(request, pid, address, data)
return result != -1 || Errno()[0] == 0
}
#scope_export
TeacherSample :: struct { address: u64; count: s64 }
TeacherProfile :: struct {
samples: Vec(TeacherSample)
total: s64
runs: s64
valid: bool
exit_code: s32
}
TeacherSampleRun :: (path: string, profile: *TeacherProfile) -> bool {
cpath: [4096]u8
sink: [16]u8
if !CopyCString(path, cpath[:]) || !CopyCString("/dev/null", sink[:]) { return false }
arguments: [2]*u8 = .[*cpath[0], null]
pid := Fork()
if pid < 0 { return false }
if pid == 0 {
fd := Open(*sink[0], 1)
if fd < 0 { Exit(120); return false }
unused Dup(fd, 1); unused Dup(fd, 2); unused Close(fd)
if !Trace(0, 0, 0, 0) { Exit(121); return false }
unused Exec(*cpath[0], *arguments[0])
Exit(122)
return false
}
reaped := false
status: s32
defer {
if !reaped {
// Confirm this PID is still our unreaped child before signaling.
pending := WaitPid(pid, *status, 1)
if pending == 0 || pending == pid && (status & 255) == 127 {
unused Kill(pid, 9)
unused Wait(pid, *status)
}
}
}
if !Wait(pid, *status) { return false }
if (status & 255) != 127 { reaped = true; return false }
// EXITKILL ensures a stopped child cannot outlive a failed tracer.
if !Trace(16896, pid, 0, 1048576) { return false }
saved: Registers
if !Trace(12, pid, 0, cast(u64)*saved) { return false }
ip := saved.words[16]
error := Errno()
error[0] = 0
original := Ptrace(1, pid, ip, 0)
if original == -1 && Errno()[0] != 0 { return false }
// syscall is two bytes; single-step it with setitimer(ITIMER_PROF).
patched := (cast(u64)original & ~cast(u64)65535) | 1295
if !Trace(4, pid, ip, patched) { return false }
timer := saved.words[19] - 128
values: [4]u64 = .[0, 1000, 0, 1000]
for index: 0..3 { if !Trace(5, pid, timer + cast(u64)index * 8, values[index]) { return false } }
registers := saved
registers.words[10] = 38
registers.words[14] = 2
registers.words[13] = timer
registers.words[12] = 0
if !Trace(13, pid, 0, cast(u64)*registers) || !Trace(9, pid, 0, 0) || !Wait(pid, *status) { return false }
if (status & 255) != 127 || !Trace(12, pid, 0, cast(u64)*registers) || registers.words[10] != 0 { return false }
if !Trace(4, pid, ip, cast(u64)original) || !Trace(13, pid, 0, cast(u64)*saved) || !Trace(7, pid, 0, 0) { return false }
while Wait(pid, *status) {
if (status & 127) == 0 {
reaped = true
profile.exit_code = (status >> 8) & 255
profile.runs += 1
return true
}
if (status & 255) != 127 { reaped = true; return false }
signal_number := (status >> 8) & 255
if signal_number == 27 {
if !Trace(12, pid, 0, cast(u64)*registers) { return false }
address := registers.words[16]
found := false
for index: 0..profile.samples.count - 1 {
if profile.samples[index].address == address { profile.samples[index].count += 1; found = true; break }
}
if !found { unused VecPush(profile.samples, TeacherSample.{address = address, count = 1}) }
profile.total += 1
signal_number = 0
}
if !Trace(7, pid, 0, cast(u64)signal_number) { return false }
}
return false
}
TeacherSampleProgram :: (path: string, expected: s32) -> TeacherProfile {
profile: TeacherProfile
valid := true
for run: 0..29 {
if !TeacherSampleRun(path, *profile) || profile.exit_code != expected { valid = false; break }
if profile.total >= 150 { break }
}
profile.valid = valid
return profile
}
+59
View File
@@ -0,0 +1,59 @@
// Mine candidates only. Matching two assembly idioms proves nothing about
// program equivalence; the learning verifier must certify their semantics.
#import "c_teacher_assembly"
#import "std/text_tools"
using Vectors :: #import "std/vec"
TeacherRewrite :: struct { factor: s64; native: string; teacher: string }
TeacherLeaFactor :: (operands: string) -> s64 {
left := TextFind(operands, "[")
right := TextFind(operands, "]")
if left < 0 || right < left { return 0 }
body := operands[left + 1:right]
plus := TextFind(body, "+")
if plus <= 0 { return 0 }
base := body[:plus]
index := body[plus + 1:]
star := TextFind(index, "*")
if star < 0 { return ifx base == index then 2 else 0 }
if index[:star] != base { return 0 }
scale, valid := TeacherHex(index[star + 1:])
if !valid || scale != 1 && scale != 2 && scale != 4 && scale != 8 { return 0 }
return 1 + scale
}
TeacherIdiomFactor :: (instruction: TeacherInstruction) -> s64 {
if instruction.mnemonic == "lea" { return TeacherLeaFactor(instruction.operands) }
parts := TextSplit(instruction.operands, ",")
if parts.count != 2 { return 0 }
if instruction.mnemonic == "add" && TextTrim(parts[0]) == TextTrim(parts[1]) { return 2 }
if instruction.mnemonic != "shl" && instruction.mnemonic != "sal" { return 0 }
shift, valid := TeacherHex(TextTrim(parts[1]))
if !valid || shift < 1 || shift > 30 { return 0 }
return cast(s64)(cast(u64)1 << cast(u64)shift)
}
TeacherMineRewrites :: (native: []TeacherInstruction, begin: s64, end: s64,
teacher: []TeacherInstruction, cbegin: s64, cend: s64) -> Vec(TeacherRewrite) {
result: Vec(TeacherRewrite)
for instruction: native {
if instruction.address < begin || instruction.address >= end || instruction.mnemonic != "imul" { continue }
operands := TextSplit(instruction.operands, ",")
if operands.count != 3 { continue }
factor, valid := TeacherHex(TextTrim(operands[2]))
if !valid || factor < 2 { continue }
duplicate := false
for rule: result { if rule.factor == factor { duplicate = true; break } }
if duplicate { continue }
for candidate: teacher {
if candidate.address < cbegin || candidate.address >= cend || TeacherIdiomFactor(candidate) != factor { continue }
n := string.[instruction.mnemonic, " ", instruction.operands]
c := string.[candidate.mnemonic, " ", candidate.operands]
unused VecPush(result, TeacherRewrite.{factor = factor,
native = TextDetach(TextJoin(n[:], "")), teacher = TextDetach(TextJoin(c[:], ""))})
break
}
}
return result
}
+220
View File
@@ -0,0 +1,220 @@
// Offline calibration of the bounded leaf pass. Run through bench/bench.zi.
// Uses the teacher's long, checksum-checking kernel wrappers and generated C.
#import, file "../cmd/compiler_exec_link.zi";
#import, file "../cmd/compiler_opt.zi";
#import, file "../cmd/compiler_lowered_ir.zi";
#import, file "../cmd/compiler_bundle.zi";
#import, file "../cmd/compiler_learning.zi";
#import "std/byte_text_linux"
#import "std/environment_linux"
#import "std/file"
#import "std/file_tree_linux"
#import "std/json_document"
#import "std/number_text"
#import "std/process_run_linux"
#import "std/text_tools"
#import "std/timer_linux"
#import "std/vec"
#scope_file
Join :: (a: string, b: string) -> string { parts := string.[a, b]; return TextDetach(TextJoin(parts[:], "")) }
Number :: (n: s64) -> string { digits: [32]u8; return Join("", FormatInteger(n, digits[:])) }
Capture :: (arguments: []string) -> (text: string, code: s32) {
run: ProcessRun
options := ProcessOptions.{arguments = arguments, capture_output = true, merge_error = true}
if !RunProcess(options, *run) { return "cannot start child", 127 }
return TextDetach(BuilderFinish(run.output)), run.code
}
Require :: (arguments: []string) -> bool {
text, code := Capture(arguments)
if code != 0 { print("calibration failed (%): %\n%\n", code, TextJoin(arguments, " "), text); return false }
return true
}
Digest :: (path: string) -> string {
command := string.["sha256sum", "--", path]
text, code := Capture(command[:])
return ifx code == 0 && text.count >= 64 then text[:64] else ""
}
TextField :: (document: *JsonDocument, root: s32, key: string, value: string) {
JsonSet(document, root, key, JsonNewStringCopy(document, value))
}
Policy :: (document: *JsonDocument, row: s32, leaf: s32) {
policy := JsonNewObject(document)
JsonSet(document, row, "policy", policy)
JsonSet(document, policy, "leaf_operations", JsonNewInteger(document, leaf))
JsonSet(document, policy, "unroll_factor", JsonNewInteger(document, 1))
JsonSet(document, policy, "block_layout", JsonNewInteger(document, 1))
JsonSet(document, policy, "allocation", JsonNewInteger(document, 0))
}
// Clone/verify and vary only the leaf pass. The canonical input has already
// passed the ordinary optimizer; running other passes again would confound it.
Variant :: (source: string, output: string, leaf: s32) -> bool {
bytes, found := ReadEntireFile(source)
if !found { return false }
decoded: ZxExecOwner
defer ZxExecReadFree(*decoded)
if ZxExecRead(*decoded, bytes, LirDefaultLimits()).problem != .None || decoded.assets != 0 { return false }
if ZxExecReadProgram(*decoded).checks { return false }
optimized: LirOptOwner
defer LirOptFree(*optimized)
options := LirOptOptions.{maximum_rounds = 1, inline_leaf_operations = leaf}
result := LirOptBuild(*optimized, ZxExecReadProgram(*decoded), LirDefaultLimits(), options)
if result.problem != .None { return false }
program := LirOptProgram(*optimized)
assets: [0]Asset
empty: []u8
measured := ZxExecWrite(program, assets[:], empty, TextView(decoded.interface[:]))
if measured.problem != .None { return false }
encoded: Vec(u8)
defer VecFree(encoded)
if !VecResize(encoded, measured.size) { return false }
written := ZxExecWrite(program, assets[:], encoded[:], TextView(decoded.interface[:]))
if written.problem != .None || written.size != measured.size { return false }
print("leaf=% inlined_calls=% source=%\n", leaf, result.counters.inline_leaf.instructions, source)
return WriteEntireFile(output, TextView(encoded[:]))
}
Time :: (executable: string) -> s64 {
command := string.[executable]
options := ProcessOptions.{arguments = command[:], output_path = "/dev/null", error_path = "/dev/null"}
run: ProcessRun
start := MonotonicNanoseconds()
if !RunProcess(options, *run) || run.code != 42 { return -1 }
return MonotonicNanoseconds() - start
}
Record :: (corpus: string, bundle: string, elf: string, original: string, compiler: string) -> string {
format := Join("zx", Join(Number(ExecutableVersionNumber()), Join("-lir", Number(LirVersion))))
zx_digest := Digest(bundle)
native_digest := Digest(elf)
relative := Join(format, Join("/", Join(zx_digest, Join("/x86_64-", native_digest))))
stem := Join(corpus, Join("/", relative))
folder := PathParent(stem)
if !CreateDirectories(folder) { return "" }
copy_zx := string.["cp", "--", bundle, Join(folder, "/program.zx")]
copy_elf := string.["cp", "--", elf, Join(stem, ".elf")]
map := string.["build/bin/zx2native", "--emit", "map", "-o", Join(stem, ".map.json"), bundle]
if !Require(copy_zx[:]) || !Require(copy_elf[:]) || !Require(map[:]) { return "" }
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
TextField(*document, root, "format", format)
TextField(*document, root, "target", "x86_64")
TextField(*document, root, "platform", "linux")
TextField(*document, root, "zx2native_sha256", compiler)
TextField(*document, root, "input_sha256", original)
TextField(*document, root, "producer", "c-teacher-tune")
if !WriteEntireFile(Join(stem, ".record.json"), JsonWrite(*document, root, JsonCompactStyle())) { return "" }
return Join(relative, ".record.json")
}
Epoch :: (work: string) -> string {
// Hash the source inventory too: exact tool identities alone cannot detect
// edits awaiting a rebuild. Include untracked learning modules explicitly.
command := string.["git", "ls-files", "cmd", "std", "Makefile", "assembly.mk", "bench"]
inventory, code := Capture(command[:])
if code != 0 { return "" }
paths := TextLines(inventory)
defer VecFree(paths)
text: Vec(u8)
for path: paths {
if path == "" || TextHasPrefix(path, "bench/results/") { continue }
hash := Digest(path)
if hash.count != 64 { VecFree(text); return "" }
BuilderAppend(text, path); BuilderAppend(text, hash)
}
extra := string.["build/bin/zi2c", "build/bin/zi2zx", "build/bin/zx2native",
"cmd/compiler_opt_inline.zi", "cmd/compiler_learning.zi", "cmd/compiler_learning_policy.zi",
"cmd/compiler_learning_table.zi", "bench/c_teacher_tuning.zi"]
for path: extra {
hash := Digest(path)
if hash.count != 64 { VecFree(text); return "" }
BuilderAppend(text, path); BuilderAppend(text, hash)
}
receipt := Join(work, "/source-epoch")
return ifx WriteEntireFile(receipt, BuilderFinish(text)) then Digest(receipt) else ""
}
#scope_export
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
output: string; corpus: string
if argc != 5 { print("usage: c-teacher-tune --output FILE --corpus DIR\n"); return 1 }
for index: cast(s32)1..argc - 1 {
value := TextFromCString(argv[index])
if value == "--output" && index + 1 < argc { output = TextFromCString(argv[index + 1]) }
if value == "--corpus" && index + 1 < argc { corpus = TextFromCString(argv[index + 1]) }
}
if output == "" || corpus == "" || EnvironmentText("ZIRAN_LEARN") != "off" { return 1 }
policy := LearningTuningChoice()
if policy.leaf_operations != 0 || policy.block_layout != 1 {
print("calibration needs the baseline leaf/layout table and freshly prepared teacher inputs\n"); return 1
}
work := "build/c-teacher/tuning"
if !CreateDirectories(work) || !CreateDirectories(corpus) { return 1 }
epoch := Epoch(work)
compiler := Digest("build/bin/zx2native")
host := string.["hostname"]
hostname, host_code := Capture(host[:])
if epoch.count != 64 || compiler.count != 64 || host_code != 0 { return 1 }
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
JsonSet(*document, root, "schema_version", JsonNewInteger(*document, 1))
JsonSet(*document, root, "checks", JsonNewBool(*document, false))
TextField(*document, root, "target", "x86_64-linux")
TextField(*document, root, "learning", "off")
TextField(*document, root, "host", TextTrim(hostname))
TextField(*document, root, "source_epoch_sha256", epoch)
TextField(*document, root, "method", "paired process wall time; 1024 checksum-checked kernel calls; includes startup; 11 samples")
rows := JsonNewArray(*document)
JsonSet(*document, root, "measurements", rows)
names := string.["Sieve", "Records", "Hash", "Vectors", "Calls", "Printing"]
for name: names {
folder := Join(work, Join("/", name))
if !CreateDirectories(folder) { return 1 }
original := Join("build/c-teacher/", Join(name, ".zx"))
source := Join("build/c-teacher/teacher_", Join(name, ".zi"))
reference_folder := Join(folder, "/c")
reference := Join(reference_folder, Join("/teacher_", name))
c := string.["env", "CFLAGS=-O2", "build/bin/zi2c", "--exe", "--root", "build/c-teacher", "--module-path", "bench", "--module-path", "std",
"--entry", Join("teacher_", Join(name, ":main")), "-o", reference_folder, source]
if !Require(c[:]) { return 1 }
for leaf: cast(s32)0..cast(s32)1 {
bundle := Join(folder, Join("/policy-", Join(Number(leaf), ".zx")))
native := Join(folder, Join("/policy-", Number(leaf)))
if !Variant(original, bundle, leaf) { return 1 }
encode := string.["build/bin/zx2native", "-o", native, bundle]
if !Require(encode[:]) { return 1 }
record := Record(corpus, bundle, native, Digest(original), compiler)
if record == "" || Time(native) <= 0 || Time(reference) <= 0 { return 1 }
row := JsonNewObject(*document)
unused JsonAppend(*document, rows, row)
TextField(*document, row, "workload", name)
TextField(*document, row, "input_sha256", Digest(original))
TextField(*document, row, "zx_sha256", Digest(bundle))
TextField(*document, row, "native_sha256", Digest(native))
TextField(*document, row, "compiler_sha256", compiler)
TextField(*document, row, "corpus_record", record)
TextField(*document, row, "checksum", "42"); TextField(*document, row, "c_checksum", "42")
file := OpenRead(native)
if !file.valid { return 1 }
JsonSet(*document, row, "code_bytes", JsonNewInteger(*document, FileSize(file)))
CloseFile(file)
Policy(*document, row, leaf)
ns := JsonNewArray(*document); cs := JsonNewArray(*document)
JsonSet(*document, row, "native_ns", ns); JsonSet(*document, row, "c_ns", cs)
for sample: 0..10 {
// Alternate native/reference order to reduce drift bias.
n: s64; ctime: s64
if sample % 2 == 0 { n = Time(native); ctime = Time(reference) }
else { ctime = Time(reference); n = Time(native) }
if n <= 0 || ctime <= 0 { return 1 }
unused JsonAppend(*document, ns, JsonNewInteger(*document, n))
unused JsonAppend(*document, cs, JsonNewInteger(*document, ctime))
}
}
}
if Epoch(work) != epoch || Digest("build/bin/zx2native") != compiler { print("compiler/source changed; calibration rejected\n"); return 1 }
if !WriteEntireFile(output, JsonWrite(*document, root, JsonPythonStyle(2))) { return 1 }
print("Saved measured leaf policies: %, corpus %\n", output, corpus)
return 0
}
@@ -0,0 +1,117 @@
{
"schema_version": 1,
"native_sha256": "9978ae84253c8a66826459bd18f3379aa9b73784caf6e1942727fc5bffbfe82e",
"zx_sha256": "5c47cb8218aeed347661abe511c183dca5e1278e852b5791595e3dcbe7f4b75e",
"c_sha256": "c77c158bdc0e61b8c246fb0fb2efd8e62a5f537c6e0ef7fc7e573b897bd6d311",
"compiler": "cc (Debian 14.2.0-19) 14.2.0",
"candidates": [
{
"rule": "x86-multiply-constant",
"function": "tree_input_SecondaryPointerSample",
"factor": 3,
"native": "imul r11,rax,0x3",
"teacher": "lea rdx,[rax+rax*2]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "tree_TreeRead",
"factor": 65536,
"native": "imul r11,rcx,0x10000",
"teacher": "shl r8,0x10",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "cursor_CursorHoverFrameStart",
"factor": 16,
"native": "imul r11,rax,0x10",
"teacher": "shl rdx,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "paint_queue_SnapshotTextJoin",
"factor": 512,
"native": "imul r11,rdi,0x200",
"teacher": "shl rax,0x9",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "tree_TreeStoreLabel",
"factor": 65536,
"native": "imul r11,r9,0x10000",
"teacher": "shl rdx,0x10",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "contextmenu_Draw",
"factor": 16,
"native": "imul r11,rax,0x10",
"teacher": "shl rbx,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "cursor_CursorHoverFrameCommit",
"factor": 16,
"native": "imul r11,rax,0x10",
"teacher": "shl rax,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_icon_behavior_PaintSvgIcon",
"factor": 5,
"native": "imul r11,r14,0x5",
"teacher": "lea rdx,[r12+r12*4]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_icon_behavior_SvgIconTexture",
"factor": 5,
"native": "imul r11,rcx,0x5",
"teacher": "lea rcx,[rcx+rcx*4]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_icon_behavior_SvgIconCells",
"factor": 5,
"native": "imul r11,rcx,0x5",
"teacher": "lea rsi,[rcx+rcx*4]",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_shape_ShapeCoverEdges",
"factor": 16,
"native": "imul r11,rcx,0x10",
"teacher": "shl r12,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
},
{
"rule": "x86-multiply-constant",
"function": "svg_shape_ShapeAddEdge",
"factor": 16,
"native": "imul r11,rdx,0x10",
"teacher": "shl rdx,0x4",
"precondition": "integer-modulo-width; flags-dead; no-memory",
"verified": false
}
]
}
@@ -0,0 +1,78 @@
{
"started_unix": 1794856923,
"revision": "42dc1b0f41489e8affae19815a52aa3a875ff0d9",
"commands": [
{
"command": [
"make",
"-j1",
"check"
],
"code": 0
},
{
"command": [
"make",
"-j1",
"check-bootstrap"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"wasm-tier",
"--samples",
"11",
"--label",
"c-teacher-final",
"--output",
"bench/results/c-teacher-omega-final.json"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"library-targets",
"--project",
"/mnt/storage/Projects/kryonlabs/kryon",
"--manifest",
"/mnt/storage/Projects/kryonlabs/kryon/tests/widget_benchmarks.json",
"--samples",
"11"
],
"code": 0
},
{
"command": [
"build/bin/ziran",
"run",
"--target=c",
"bench/bench.zi",
"--",
"c-teacher",
"--output",
"bench/results/c-teacher-omega-2026-11-16-final.md"
],
"code": 0
}
],
"changed": [
"cmd/compiler_machine_aggregate.zi",
"tests/machine_place_cases.zi"
],
"finished_unix": 1794857182,
"complete": false,
"source_files": 1056,
"start_epoch_sha256": "d1189e0d940d29b38732e3f6ba42344977b296d1369f10cf5c663f9671082574",
"end_epoch_sha256": "76ce23f6965ad9660265dd485aaf17fee1e3a52457918f76f8b191efcf10fdde"
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
{
"schema_version": 1,
"host": "omega",
"learning": "off",
"checks": "manual-safety default; test-specific assertions retained",
"github_ci": "not checked",
"local_tests": [
{
"receipt": "16151a4867e2fa478e3d0afde52731aaa7a0",
"revision": "42dc1b0f41489e8affae19815a52aa3a875ff0d9",
"suite": "make -j1 check",
"code": 0,
"passed": 281,
"total": 281,
"bootstrap_code": 0,
"source_guard": "two concurrent constructor files changed; compiler binaries unchanged"
},
{
"receipt": "34159fa4c599897ee55a627d0b74327deffa",
"suite": "constructor canonical build, check and check-bootstrap",
"build_code": 0,
"bootstrap_code": 0,
"passed": 279,
"total": 281,
"source_guard": "3409 guarded inputs and seven compiler identities unchanged",
"failed": [
"site_pages.sh: missing targets receipt",
"site_targets.sh: Publish one measured host"
]
},
{
"receipt": "8382856e6704249164010f4a322be36d05e9",
"revision": "efefbb1f40dacbd00972b41126bc26ef5349463e",
"command": "env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off HARMONY_BUILD_LOCAL=1 build-queue -- sh -c 'sh tests/site_pages.sh build/bin/ziran && sh tests/site_targets.sh build/bin/ziran'",
"code": 0,
"result": "Both prior publication-data failures resolved; pages, matrices, hashes, samples and independent artifact oracles passed."
}
],
"learning_verification": {
"receipt": "d001bab87cfb730312d572c86d3128929bc9",
"differential_output_lines": 70210,
"retained_zx_parity": "passed"
},
"offline_calibration": {
"receipt": "e5cffefb436f30c04174e17009bdec81bc1a",
"c_optimization": "-O2",
"deterministic_training_repeat": "byte-identical",
"selected_policy": 1,
"leaf_operations": 0,
"same_artifacts": "Both leaf settings produce identical artifacts for all six kernels."
}
}
@@ -0,0 +1,9 @@
{
"schema_version": 1,
"compiler_identity": "d55316e60ab0235601d973b6f8486b4afd56bfb67a91960eccef58bd0f855b34",
"evidence_sha256": "2f53cf40a46149669ee62d3efe39e5fb676b8a629be93fdea7183c78695ccee7",
"fixture_sha256": "4b7385ea2655619107c8356699dc898c908b726dbd5b10d236bc39bbed207062",
"parity_list_sha256": "cdf4b85dba5869f940f5a28a6d0e39a58d2179d41e6c4bedfce6798bf793fd47",
"table_sha256": "6dc93292225b19dff574d79d2e41f43a79f6664dab8e5e0bf76d186746272b4c",
"verified": true
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,207 @@
{
"schema": 1,
"started_unix": 1794851103,
"start": {
"Makefile": "05f3a05a07580c113c3c2e41e122fb2fda564fdbab2406c0daafe3558f0d9919",
"assembly.mk": "35cc7ad2f0897895f8aa498e4cbd6660a4981fe068eb0944897469e4fa5014ba",
"bench/bench.zi": "e725a1f50a8ddb30ba19c5e3e1165a98ba7df0ce2836fa4d7d7e42e51fabbec1",
"bench/c_teacher.zi": "0f302d034bd0abb7a94a04c1052b51d4b147390ae854b43fa5beda3e64ba4ce0",
"bench/c_teacher_assembly.zi": "af71355d406f4a0fae62c90ff7774b3c09af01ceeab8ce96bff366f4ec6ffb2f",
"bench/c_teacher_profile.zi": "8bf97b7a800bb9ae617a1d04eb1877aa419632ff725541b8d57a9eb064b771c7",
"bench/c_teacher_rules.zi": "c8bd719f89b63c69eb68f6e5104893614e42f490997ef7ca56907d715898b2cc",
"bench/wasm_tier.zi": "0e6bdffd2b7dd8b7f6df7b3665393a17d1b840e4b48bb4b88d110d27b84dde91",
"build/bin/zi2c": "549a9b9f3600255c4b8af83947661f92ec8db8a97d80d26392b1674a8bc59f27",
"build/bin/zi2zx": "582853558ec22e178d5e8f4f802802b2c81ffc2607b6e258259bc59dbae00520",
"build/bin/ziran": "5597a16f7fc6cfb32c9e1ac4bdccbda176ca402620e641944f099b270b40988b",
"build/bin/zx2native": "fc7dd7c5f4409c68a26b634888085d39b7fa0592398119bbed7bdb09a9f4867d",
"build/bin/zx2wasm": "9de465c0be09ae7c03d0f4a10ff5ce88c3a4ec473cf7a9a5662a93acd0090637",
"build/libziran.a": "e7c22c683f3711b8f0d2d8203a2ab234d29d2457940296abb552ed20960a721e",
"cmd/compiler_aarch64.zi": "6e6290525bd8ffcd58f5c38c191e7b39090d7af2b5cf1aeabcfc99b676928a75",
"cmd/compiler_abi.zi": "2563e498e4a09e7ff41eb330c1055167ec92828758c5873ab551221214119399",
"cmd/compiler_arm_bytes.zi": "ff30a43a4b0729f0690102b9b1870d8584fe604baf8f659a37edb3c958095552",
"cmd/compiler_armv7.zi": "1e1364169f7b4b679e9db6d8d1e0be0efbc9955d37b1de1f931de1f8a9d0c0fe",
"cmd/compiler_backend_cache.zi": "5a76c6cc76373475ef3f3a9f858abae7970e4fd21f06128749574518d2b47903",
"cmd/compiler_backend_process.zi": "db1452d9aa71a3cfc3b7e1b709ea285e73d52fbcd392a9587a4da3603f836817",
"cmd/compiler_bundle.zi": "b2442aba7e10a91d8ef422f3ae9d42aa3a82873e26d23bf0aefd116819419a92",
"cmd/compiler_declaration.zi": "4b243127fbda612bb75399d35a0e5a62b926b06cd21668ecf4967b0fb44a683b",
"cmd/compiler_enum.zi": "3bb33881dd63ef654f3f3b7b2d0201a82df84e50fbb04f3ebf3f748aeac63214",
"cmd/compiler_exec.zi": "4c7a89ec2854db68ed159b95132177e526e42108c6a120160ebf1e40d431644c",
"cmd/compiler_exec_debug.zi": "aa1b2141fd720cb6541e7b729ffbd0e3f2af15d207ea6ec4367fe51f8f040284",
"cmd/compiler_exec_link.zi": "81643c45850d1651b54589f38746254828e41884c9dc703036af9e84b955dc6d",
"cmd/compiler_exec_serial.zi": "f7057b91f1371862c5f95a6da507ef5ab87564cd8183c8e275b158e93aef21d0",
"cmd/compiler_expression.zi": "ae9ae5bef1606eb6146bd0b44ccbab9a98e18455c76d3feee24e0f1fb28b7e02",
"cmd/compiler_ir.zi": "541000ea6b99130911da25e05e5318f69d4689bf830668a7f2d7a2dd781da946",
"cmd/compiler_law.zi": "ea7a848dbfce6244bd5f576ba2d4808ab4a7439eb488f734ac488d7bc52aba06",
"cmd/compiler_learning_policy.zi": "0664cdd8661832eedfd7bacb4edc53dc72effd4549ef3bc9b3d7d1638c659e57",
"cmd/compiler_link.zi": "34303bb84496bf662f3e1e10ecda6dcbf9d8190c2bbec8d9e21c5d94c04cce02",
"cmd/compiler_lowered_ir.zi": "8ec004a5862e1511edca0de5c9b02f552a53992c3c791a53e909385f318987a4",
"cmd/compiler_lowered_proven.zi": "75f4ea7dc721078b982bb7b3d156ab1c63d4f3b0fe6dfe78cbbd2fc5a7bca7aa",
"cmd/compiler_lowered_verify.zi": "f7051f16f19c4d2ba90e3147285c9f193280bc2d11bdc46117e0185b282ccd8c",
"cmd/compiler_machine_aggregate.zi": "16d5e7ed5f3cfe04ad400edae311caaca4c4e4cee9a5e033f92acbb0b6a075ce",
"cmd/compiler_machine_elf.zi": "4b3388d402a74dd06077bb9de6295fd9af080dde9e7b57d77bb9c9a17c7e1982",
"cmd/compiler_machine_fields.zi": "9f3e21befa992755ae86695bea8245c26aa6530146e8f9adc38c79ec02d8daed",
"cmd/compiler_machine_image.zi": "a9adc6b4e330f4366120719a8fd054ba5721cc7d21c4ab37c4e90ca4af0ad6a6",
"cmd/compiler_machine_ir.zi": "66597bf7c70717f51897af8f705a70912c2e9b6c6eab7a59229dead32cd9a8b1",
"cmd/compiler_machine_lower.zi": "927ecd665617665a7fb0137a2d54f92a79d4e81587ec9ce37f9465e246aa73a9",
"cmd/compiler_machine_pe.zi": "282b2bbf3e9984f605bd5f9c7e78f17434198a065693f6fcdbf5b99dc20de5ea",
"cmd/compiler_machine_pipeline.zi": "873bdd8fb8dde2e9110beb40f538b251cd9ffa3b99c585c43ce99ee046f7b138",
"cmd/compiler_machine_select.zi": "086467c928a6ad77f60388ebe6f65406fd51df8fc595734affca3c9f6ab1bf56",
"cmd/compiler_machine_verify.zi": "e8cf207237a2316649171b95196493b225fad3a4bb0e34864060215ba7901a26",
"cmd/compiler_machine_verify_allocated.zi": "39d018331ce8b54d3d835d77b44200d248a0b36c15af7d39d9ca46158361a69b",
"cmd/compiler_native_cache.zi": "0035b3d5549ca11a77cdf90267bbde11c59443abfaf8e1e9ee3a95e82b2fb290",
"cmd/compiler_native_names.zi": "785afd249f662ccee7618a8047f3a7e4912301802c60a6056b87dbd2d744adde",
"cmd/compiler_opt.zi": "05189b0d37431433cb92c6d3ba8ef93e1c43b20b21a80ef9ae0614c0c1663173",
"cmd/compiler_opt_rotate.zi": "1e0de077d2bb2cd0dd82844eec3b02af76caa23b0e139e4e9dfee4bac68639b8",
"cmd/compiler_opt_ssa.zi": "d48ffcab34672abb811f62e1ec4c6ece48796ca915aa88f737a64ac3a06ba6e0",
"cmd/compiler_parse.zi": "faeff7c000d4dedf9c6172aa7fe191f8051d6d161fef3301871e6d2456476c50",
"cmd/compiler_proof.zi": "b750025110bbf98bd481225d35893503d636167b05c5f8f676d14f1b21c4045a",
"cmd/compiler_proof_kernel.zi": "ef6ef0e45033d412e69f665d0adab88cf7b8447e6b7d2380285256bf8b560657",
"cmd/compiler_regalloc.zi": "c685aa88b55f3818815f647827108b4a430ede7eb23dc068832a843cf7a1ce05",
"cmd/compiler_runtime.zi": "76a03293273f596114419c57ae2d7d90bcbb3601f53ca3bea2aa493fa7c45333",
"cmd/compiler_runtime_emit.zi": "75cac74ccd128c798b138cc8debf12bfe32a73374a59ed38c2da544a5ea5e8c0",
"cmd/compiler_scan.zi": "7a5543ff4d2a948662a73799cef24d5493f6d8f2c00bc8e9c79966bc3e08ebf6",
"cmd/compiler_services.zi": "44e86142a49ca50c93d2ee4549a62d5d910039a26bed8edba9eee6e32ad100c8",
"cmd/compiler_source.zi": "b72e15ebf7db2ca8701443be8665b521550e6365278d0451972b13012749f6a1",
"cmd/compiler_statement.zi": "9cab342dfca003629336188001161db10da1bfffb81c4a72762c7ac825014147",
"cmd/compiler_target.zi": "45aa88ad0735e0728084e298d3384f58dde43552205713eb21ba45a4efdf6996",
"cmd/compiler_text.zi": "6c984ceb501cf4910f1f188a8a194724e1153b2ccf64425d183572c48b3b521b",
"cmd/compiler_type.zi": "c855d452c68ef1143c0b2c0bb5e8124b0c2eb98194357ea20459290099664392",
"cmd/compiler_x86_64.zi": "46f5507aeed0ccb72d1db423f8ad9b5e421d3f5d56e334d0adb0a95aedd1a7b5",
"cmd/compiler_x86_bytes.zi": "e657e4757e6e44f58bdf3c797de83ef4ec9d29cf9cdfb9945e38b5af8ba6add5",
"cmd/compiler_x86_host.zi": "62790138a13faee1421e7ed381d049b31681cdd0215ea23fed86205554f99fab",
"cmd/compiler_x86_image.zi": "002266f04f7ef848df21c7561f42ddffbc23f80fc990a1f9100bdeef8c41dace",
"cmd/compiler_x86_runtime.zi": "c1a5a8cf1a1979052b1e367670a297e68fe772aaf7b0be4cf3bd9a5aa743ff95",
"cmd/compiler_x86_win64.zi": "56579376dde03d3fae4c14a52db835eb30ee9f3ed034bd057af87c8389a011e7",
"cmd/compiler_zir_lower.zi": "5a256120bf827f1973e07db313abc5ebe233bfac27c4bb8b2a1f8ebce8fde83a",
"cmd/diagnostics.zi": "bab7e536840cbfd0bf376586f79dd2aaeced3d7ead8e993f32a916a2a00a2efd",
"cmd/edit.zi": "0b7754a51bfdb9f977502033fc8d0d37e338199c6303b72c6f56068b735a3c1d",
"cmd/format.zi": "1d3a98b9f2bcb8bb4397addbaa79c482a248a4a1c90a65469a43baf3093df49e",
"cmd/format_source.zi": "dab11397691519e67cbf1b6d28a1c56511ab6e9f1a8173495895c301964d2166",
"cmd/package.zi": "d5d7c5943018b0dde1f2e7bea6cc748d00329aa1b3ae09c1dfaf6050b40164e2",
"cmd/package_add.zi": "73d66ff9c67140ec2ea027aa9c6de35c116c0387863c83cd250bf98146cd391c",
"cmd/package_artifact.zi": "4233d6388cd50e361a4bd1dd9cb7406ae8c118466ea07c05e3c971cca7f50c1a",
"cmd/package_bundle_run.zi": "f6e7d9812e441bc7e5c5e11a14c821a31144b18ef49726e5c81ed81e5f9b7a75",
"cmd/package_capabilities.zi": "5d02a368970770d83a2743904c11f96d554fcfed54ef626c120b02b0699b9547",
"cmd/package_common.zi": "d9a532f872397a1d85af3fa9c0e6880c84a4fdd08414d81c42eb092e11a4eaa6",
"cmd/package_compile_commands.zi": "3c89799708f97fb2cb7df2addaa79cab488bfd6cdfb981fa7400911a39f30651",
"cmd/package_entry.zi": "e38f333965caa5a04333ec4bf5049e9c4c8fbec11dc21a564caca9b0128c8457",
"cmd/package_explain.zi": "a66faa839eab24613009572eb26c29103b83f27ead407a5082545cf6821fd51d",
"cmd/package_features.zi": "1558d4bbe5a8bad6980cd0a36618e86af8172ff18ae56563e61991f4bc0cb780",
"cmd/package_guide.zi": "4f37a7e919d9724f422bb0bc31f16cb00f53dd15faefe0951ca2004e80957f66",
"cmd/package_learn.zi": "00a9b8f0cd272cc80cff0fb902424abc2116ba6e2b155e4e54a29918a05fc148",
"cmd/package_lock.zi": "e7ec127c0d5c67062d1bc7bde60fea6c731589ebdfdfa5c49a9a22723e500527",
"cmd/package_manifest.zi": "7c3e09a31e2c6fee8f24332c488d7e47919d231e6807b8ff1a3977f0b19712af",
"cmd/package_map.zi": "f5237bf7644c72fc8fd8215dbea21c11ea5902fab55c94793161e18c922f5662",
"cmd/package_options.zi": "2bbe79bfb722160835c982d467039a503d654177f45ef927af53b9443d4f64f1",
"cmd/package_process.zi": "cacac81d35ccfaeceb65a320844b9d6b067a46dcd9e88310fa1a9e0f42d8abce",
"cmd/package_script.zi": "a424b568ca6c9c7d6c6e000df3fe64768d21d8f3551c5885b1d2920f79099f43",
"cmd/package_source.zi": "d85372881205f92f9e26b3afd1e9f401d324af3958a57af66f6aafec5c98c02a",
"cmd/package_template.zi": "04c681f5b549ed446d0e085f7b2f2aea16dbb0433de774974a80884f09707682",
"cmd/transport.zi": "4b18fa172dc12b15dedabdcfdd2d2dba257b48edccadd08c1ff76cff8977f8af",
"scripts/site_library_targets.py": "09eab054f7b4236ba6db4e0b62fd423d068805636cb3fb9fc9ad9f704390cedf"
},
"command": "env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off ZIRAN_BENCH_HOST=omega build-queue -- build/bin/ziran run --target=c bench/bench.zi -- c-teacher --output bench/results/c-teacher-omega-2026-11-16-stage2.md",
"finished_unix": 1794851136,
"end": {
"Makefile": "05f3a05a07580c113c3c2e41e122fb2fda564fdbab2406c0daafe3558f0d9919",
"assembly.mk": "35cc7ad2f0897895f8aa498e4cbd6660a4981fe068eb0944897469e4fa5014ba",
"bench/bench.zi": "e725a1f50a8ddb30ba19c5e3e1165a98ba7df0ce2836fa4d7d7e42e51fabbec1",
"bench/c_teacher.zi": "0f302d034bd0abb7a94a04c1052b51d4b147390ae854b43fa5beda3e64ba4ce0",
"bench/c_teacher_assembly.zi": "af71355d406f4a0fae62c90ff7774b3c09af01ceeab8ce96bff366f4ec6ffb2f",
"bench/c_teacher_profile.zi": "8bf97b7a800bb9ae617a1d04eb1877aa419632ff725541b8d57a9eb064b771c7",
"bench/c_teacher_rules.zi": "c8bd719f89b63c69eb68f6e5104893614e42f490997ef7ca56907d715898b2cc",
"bench/wasm_tier.zi": "0e6bdffd2b7dd8b7f6df7b3665393a17d1b840e4b48bb4b88d110d27b84dde91",
"build/bin/zi2c": "549a9b9f3600255c4b8af83947661f92ec8db8a97d80d26392b1674a8bc59f27",
"build/bin/zi2zx": "582853558ec22e178d5e8f4f802802b2c81ffc2607b6e258259bc59dbae00520",
"build/bin/ziran": "5597a16f7fc6cfb32c9e1ac4bdccbda176ca402620e641944f099b270b40988b",
"build/bin/zx2native": "fc7dd7c5f4409c68a26b634888085d39b7fa0592398119bbed7bdb09a9f4867d",
"build/bin/zx2wasm": "9de465c0be09ae7c03d0f4a10ff5ce88c3a4ec473cf7a9a5662a93acd0090637",
"build/libziran.a": "e7c22c683f3711b8f0d2d8203a2ab234d29d2457940296abb552ed20960a721e",
"cmd/compiler_aarch64.zi": "6e6290525bd8ffcd58f5c38c191e7b39090d7af2b5cf1aeabcfc99b676928a75",
"cmd/compiler_abi.zi": "2563e498e4a09e7ff41eb330c1055167ec92828758c5873ab551221214119399",
"cmd/compiler_arm_bytes.zi": "ff30a43a4b0729f0690102b9b1870d8584fe604baf8f659a37edb3c958095552",
"cmd/compiler_armv7.zi": "1e1364169f7b4b679e9db6d8d1e0be0efbc9955d37b1de1f931de1f8a9d0c0fe",
"cmd/compiler_backend_cache.zi": "5a76c6cc76373475ef3f3a9f858abae7970e4fd21f06128749574518d2b47903",
"cmd/compiler_backend_process.zi": "db1452d9aa71a3cfc3b7e1b709ea285e73d52fbcd392a9587a4da3603f836817",
"cmd/compiler_bundle.zi": "b2442aba7e10a91d8ef422f3ae9d42aa3a82873e26d23bf0aefd116819419a92",
"cmd/compiler_declaration.zi": "4b243127fbda612bb75399d35a0e5a62b926b06cd21668ecf4967b0fb44a683b",
"cmd/compiler_enum.zi": "3bb33881dd63ef654f3f3b7b2d0201a82df84e50fbb04f3ebf3f748aeac63214",
"cmd/compiler_exec.zi": "4c7a89ec2854db68ed159b95132177e526e42108c6a120160ebf1e40d431644c",
"cmd/compiler_exec_debug.zi": "aa1b2141fd720cb6541e7b729ffbd0e3f2af15d207ea6ec4367fe51f8f040284",
"cmd/compiler_exec_link.zi": "81643c45850d1651b54589f38746254828e41884c9dc703036af9e84b955dc6d",
"cmd/compiler_exec_serial.zi": "f7057b91f1371862c5f95a6da507ef5ab87564cd8183c8e275b158e93aef21d0",
"cmd/compiler_expression.zi": "ae9ae5bef1606eb6146bd0b44ccbab9a98e18455c76d3feee24e0f1fb28b7e02",
"cmd/compiler_ir.zi": "541000ea6b99130911da25e05e5318f69d4689bf830668a7f2d7a2dd781da946",
"cmd/compiler_law.zi": "ea7a848dbfce6244bd5f576ba2d4808ab4a7439eb488f734ac488d7bc52aba06",
"cmd/compiler_learning_policy.zi": "0664cdd8661832eedfd7bacb4edc53dc72effd4549ef3bc9b3d7d1638c659e57",
"cmd/compiler_link.zi": "34303bb84496bf662f3e1e10ecda6dcbf9d8190c2bbec8d9e21c5d94c04cce02",
"cmd/compiler_lowered_ir.zi": "8ec004a5862e1511edca0de5c9b02f552a53992c3c791a53e909385f318987a4",
"cmd/compiler_lowered_proven.zi": "75f4ea7dc721078b982bb7b3d156ab1c63d4f3b0fe6dfe78cbbd2fc5a7bca7aa",
"cmd/compiler_lowered_verify.zi": "f7051f16f19c4d2ba90e3147285c9f193280bc2d11bdc46117e0185b282ccd8c",
"cmd/compiler_machine_aggregate.zi": "16d5e7ed5f3cfe04ad400edae311caaca4c4e4cee9a5e033f92acbb0b6a075ce",
"cmd/compiler_machine_elf.zi": "4b3388d402a74dd06077bb9de6295fd9af080dde9e7b57d77bb9c9a17c7e1982",
"cmd/compiler_machine_fields.zi": "9f3e21befa992755ae86695bea8245c26aa6530146e8f9adc38c79ec02d8daed",
"cmd/compiler_machine_image.zi": "a9adc6b4e330f4366120719a8fd054ba5721cc7d21c4ab37c4e90ca4af0ad6a6",
"cmd/compiler_machine_ir.zi": "66597bf7c70717f51897af8f705a70912c2e9b6c6eab7a59229dead32cd9a8b1",
"cmd/compiler_machine_lower.zi": "927ecd665617665a7fb0137a2d54f92a79d4e81587ec9ce37f9465e246aa73a9",
"cmd/compiler_machine_pe.zi": "282b2bbf3e9984f605bd5f9c7e78f17434198a065693f6fcdbf5b99dc20de5ea",
"cmd/compiler_machine_pipeline.zi": "873bdd8fb8dde2e9110beb40f538b251cd9ffa3b99c585c43ce99ee046f7b138",
"cmd/compiler_machine_select.zi": "086467c928a6ad77f60388ebe6f65406fd51df8fc595734affca3c9f6ab1bf56",
"cmd/compiler_machine_verify.zi": "e8cf207237a2316649171b95196493b225fad3a4bb0e34864060215ba7901a26",
"cmd/compiler_machine_verify_allocated.zi": "39d018331ce8b54d3d835d77b44200d248a0b36c15af7d39d9ca46158361a69b",
"cmd/compiler_native_cache.zi": "0035b3d5549ca11a77cdf90267bbde11c59443abfaf8e1e9ee3a95e82b2fb290",
"cmd/compiler_native_names.zi": "785afd249f662ccee7618a8047f3a7e4912301802c60a6056b87dbd2d744adde",
"cmd/compiler_opt.zi": "05189b0d37431433cb92c6d3ba8ef93e1c43b20b21a80ef9ae0614c0c1663173",
"cmd/compiler_opt_rotate.zi": "1e0de077d2bb2cd0dd82844eec3b02af76caa23b0e139e4e9dfee4bac68639b8",
"cmd/compiler_opt_ssa.zi": "d48ffcab34672abb811f62e1ec4c6ece48796ca915aa88f737a64ac3a06ba6e0",
"cmd/compiler_parse.zi": "faeff7c000d4dedf9c6172aa7fe191f8051d6d161fef3301871e6d2456476c50",
"cmd/compiler_proof.zi": "b750025110bbf98bd481225d35893503d636167b05c5f8f676d14f1b21c4045a",
"cmd/compiler_proof_kernel.zi": "ef6ef0e45033d412e69f665d0adab88cf7b8447e6b7d2380285256bf8b560657",
"cmd/compiler_regalloc.zi": "c685aa88b55f3818815f647827108b4a430ede7eb23dc068832a843cf7a1ce05",
"cmd/compiler_runtime.zi": "76a03293273f596114419c57ae2d7d90bcbb3601f53ca3bea2aa493fa7c45333",
"cmd/compiler_runtime_emit.zi": "75cac74ccd128c798b138cc8debf12bfe32a73374a59ed38c2da544a5ea5e8c0",
"cmd/compiler_scan.zi": "7a5543ff4d2a948662a73799cef24d5493f6d8f2c00bc8e9c79966bc3e08ebf6",
"cmd/compiler_services.zi": "44e86142a49ca50c93d2ee4549a62d5d910039a26bed8edba9eee6e32ad100c8",
"cmd/compiler_source.zi": "b72e15ebf7db2ca8701443be8665b521550e6365278d0451972b13012749f6a1",
"cmd/compiler_statement.zi": "9cab342dfca003629336188001161db10da1bfffb81c4a72762c7ac825014147",
"cmd/compiler_target.zi": "45aa88ad0735e0728084e298d3384f58dde43552205713eb21ba45a4efdf6996",
"cmd/compiler_text.zi": "6c984ceb501cf4910f1f188a8a194724e1153b2ccf64425d183572c48b3b521b",
"cmd/compiler_type.zi": "c855d452c68ef1143c0b2c0bb5e8124b0c2eb98194357ea20459290099664392",
"cmd/compiler_x86_64.zi": "46f5507aeed0ccb72d1db423f8ad9b5e421d3f5d56e334d0adb0a95aedd1a7b5",
"cmd/compiler_x86_bytes.zi": "e657e4757e6e44f58bdf3c797de83ef4ec9d29cf9cdfb9945e38b5af8ba6add5",
"cmd/compiler_x86_host.zi": "62790138a13faee1421e7ed381d049b31681cdd0215ea23fed86205554f99fab",
"cmd/compiler_x86_image.zi": "002266f04f7ef848df21c7561f42ddffbc23f80fc990a1f9100bdeef8c41dace",
"cmd/compiler_x86_runtime.zi": "c1a5a8cf1a1979052b1e367670a297e68fe772aaf7b0be4cf3bd9a5aa743ff95",
"cmd/compiler_x86_win64.zi": "56579376dde03d3fae4c14a52db835eb30ee9f3ed034bd057af87c8389a011e7",
"cmd/compiler_zir_lower.zi": "5a256120bf827f1973e07db313abc5ebe233bfac27c4bb8b2a1f8ebce8fde83a",
"cmd/diagnostics.zi": "bab7e536840cbfd0bf376586f79dd2aaeced3d7ead8e993f32a916a2a00a2efd",
"cmd/edit.zi": "0b7754a51bfdb9f977502033fc8d0d37e338199c6303b72c6f56068b735a3c1d",
"cmd/format.zi": "1d3a98b9f2bcb8bb4397addbaa79c482a248a4a1c90a65469a43baf3093df49e",
"cmd/format_source.zi": "dab11397691519e67cbf1b6d28a1c56511ab6e9f1a8173495895c301964d2166",
"cmd/package.zi": "d5d7c5943018b0dde1f2e7bea6cc748d00329aa1b3ae09c1dfaf6050b40164e2",
"cmd/package_add.zi": "73d66ff9c67140ec2ea027aa9c6de35c116c0387863c83cd250bf98146cd391c",
"cmd/package_artifact.zi": "4233d6388cd50e361a4bd1dd9cb7406ae8c118466ea07c05e3c971cca7f50c1a",
"cmd/package_bundle_run.zi": "f6e7d9812e441bc7e5c5e11a14c821a31144b18ef49726e5c81ed81e5f9b7a75",
"cmd/package_capabilities.zi": "5d02a368970770d83a2743904c11f96d554fcfed54ef626c120b02b0699b9547",
"cmd/package_common.zi": "d9a532f872397a1d85af3fa9c0e6880c84a4fdd08414d81c42eb092e11a4eaa6",
"cmd/package_compile_commands.zi": "3c89799708f97fb2cb7df2addaa79cab488bfd6cdfb981fa7400911a39f30651",
"cmd/package_entry.zi": "e38f333965caa5a04333ec4bf5049e9c4c8fbec11dc21a564caca9b0128c8457",
"cmd/package_explain.zi": "a66faa839eab24613009572eb26c29103b83f27ead407a5082545cf6821fd51d",
"cmd/package_features.zi": "1558d4bbe5a8bad6980cd0a36618e86af8172ff18ae56563e61991f4bc0cb780",
"cmd/package_guide.zi": "4f37a7e919d9724f422bb0bc31f16cb00f53dd15faefe0951ca2004e80957f66",
"cmd/package_learn.zi": "00a9b8f0cd272cc80cff0fb902424abc2116ba6e2b155e4e54a29918a05fc148",
"cmd/package_lock.zi": "e7ec127c0d5c67062d1bc7bde60fea6c731589ebdfdfa5c49a9a22723e500527",
"cmd/package_manifest.zi": "7c3e09a31e2c6fee8f24332c488d7e47919d231e6807b8ff1a3977f0b19712af",
"cmd/package_map.zi": "f5237bf7644c72fc8fd8215dbea21c11ea5902fab55c94793161e18c922f5662",
"cmd/package_options.zi": "2bbe79bfb722160835c982d467039a503d654177f45ef927af53b9443d4f64f1",
"cmd/package_process.zi": "cacac81d35ccfaeceb65a320844b9d6b067a46dcd9e88310fa1a9e0f42d8abce",
"cmd/package_script.zi": "a424b568ca6c9c7d6c6e000df3fe64768d21d8f3551c5885b1d2920f79099f43",
"cmd/package_source.zi": "d85372881205f92f9e26b3afd1e9f401d324af3958a57af66f6aafec5c98c02a",
"cmd/package_template.zi": "04c681f5b549ed446d0e085f7b2f2aea16dbb0433de774974a80884f09707682",
"cmd/transport.zi": "4b18fa172dc12b15dedabdcfdd2d2dba257b48edccadd08c1ff76cff8977f8af",
"scripts/site_library_targets.py": "09eab054f7b4236ba6db4e0b62fd423d068805636cb3fb9fc9ad9f704390cedf"
},
"changed": [],
"exit_code": 0,
"complete": true
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,160 @@
# C teacher: Omega findings and validation
The final comparison covers Sieve, Records, Hash, Vectors, Calls, Printing,
Button, Text, Input and hello against GCC 14.2 and Clang 19.1.7 at `-O2`.
All ten workloads completed: 1,539 ranked function comparisons and zero failed
workloads. The compiler binaries remained unchanged throughout the run.
See [the final ranked report](c-teacher-omega-2026-11-16-final.md).
These measurements ran on physical Omega under the task's original explicit
host instruction. The parent's later instruction moves all future benchmarks
to physical Alpha, serialized through its build queue; builds and local tests
remain on Omega. No Alpha result is claimed here.
| Rank against GCC | Function | Native / C instructions | Sampled function CPU share | Main findings / owner |
| --- | --- | ---: | ---: | --- |
| 1 | Records | 407 / 70 | 73 / 73 | 4 stack reads and 260 writes versus zero; aggregate/regalloc and SSA lanes |
| 2 | Sieve | 90 / 34 | 120 / 120 | 22 branches versus six; surrounding loop layout and address folding |
| 3 | Hash | 62 / 26 | 149 / 149 | 18 branches versus two; loop layout and invariant candidates |
| 4 | Vectors | 149 / 101 | 133 / 153 | stack traffic, value induction, scalar reduction and loop structure |
The earlier [stable stage-two report](c-teacher-omega-2026-11-16-stage2.md)
counted 929 native Records instructions, 260 stack reads and 520 writes;
the integrated aggregate work reduced these static counts to 407, 4 and 260.
That work belongs to its owning lane. The teacher's report measures the
resulting assembly; it does not establish a causal runtime speedup.
Static back-edge envelopes contain branches and cold paths, so their size is
not an executed instruction count per iteration. In Sieve, the sampled native
envelope spans 40 static instructions, but its marking loop at text offsets
`0x1ce..0x1dc` executes four instructions: byte store, add induction value,
compare and branch. GCC's corresponding loop also executes four. The remaining
Sieve gap is in its surrounding loops, including a separate load/compare where
C uses a memory compare, joins, trampolines and repeated values.
Vectors has more direct gaps. The capacity-available native push path executes
28 instructions, with five stack reloads, five stack writes and one element
store; GCC executes 17 with no stack traffic and one element store. Native
recomputes the element value with multiply, while GCC carries it with add.
The native reduction executes eight instructions per element, including an
accumulator stack reload/write. GCC uses five per two elements with a 16-byte
load and packed addition, with an end pointer computed outside the loop.
These are manually followed paths in the exact disassemblies named by the
report, not counts inferred from its back-edge union.
The loop lane received these concrete paths and now owns LICM, induction and
strength reduction alongside SSA and rotation. The records lane owns vector
push and aggregate/allocation work; the vectorizer lane owns SIMD reduction.
Widget/host findings went to the widget
lane. Startup samples sometimes rank `SessionIndex` and theme creation highly;
these do not replace warm scenario measurements. Missing C symbols remain
unknown inlining/dead-code/name information. Stack operands include locals and
saved registers, vector-register uses include scalar floating point, loop
constants are candidates rather than proven invariants, and zero timer samples
remain unknown. Weighted instruction excess predicts neither cycles nor speedup.
This lane implemented shorter immediate-IMUL encoding, value-only LEA/shift
selection when flags are dead, and a bounded, separately tested integer leaf
inliner. An immediate in `[-128,127]` uses the one-byte immediate encoding,
saving three bytes per matching instruction. Positive scaled-add factors use
LEA; in-place powers of two use a shift after verification. No runtime speedup
is attributed to these changes by the measurements below.
`ziran learn verify` checks closed mined multiply proposals using 34 factors,
17 boundary inputs plus 2,048 deterministic random inputs, eight signed and
unsigned widths, exact C/native output agreement (70,210 lines), then the
retained ZX parity suite. Unknown semantics or any disagreement leave the
existing table unchanged. Repeated verification generated the same table.
See the [candidate evidence](c-teacher-omega-2026-11-16-candidates.json) and
[base-table verification certificate](c-teacher-omega-2026-11-16-rules-verification.json).
`ziran learn train` joins timing observations to current-format corpus records
by input, ZX, native ELF, map and compiler identities. It requires equal
checksums, learning off, manual safety, one host and one source epoch. It keeps
integer raw timings and symmetric inclusive-quartile 1.5×IQR exclusions,
compares complete workload cohorts and breaks ties by size then policy ID.
Identical ELF artifacts share one timing experiment so noise cannot select a
policy. Unsupported unroll/allocation strategies are rejected.
The real six-kernel calibration compared leaf thresholds zero and one against
C compiled at `-O2`, with eleven paired samples per observation. All six emitted
identical native artifacts and had zero eligible one-operation leaf calls.
The selected table therefore keeps leaf inlining off, block layout on, unroll
one and allocation zero. The [raw calibration](c-teacher-omega-2026-11-16-tuning.json)
and [deterministic selection receipt](c-teacher-omega-2026-11-16-tuning-selection.json)
retain all samples, exclusions and the final table digest. Training twice
produced byte-identical source. The rule certificate covers the base table;
the selection receipt binds the policy-only update to the final table.
Ordinary compilation reads only that checked-in, versioned Ziran table: no
corpus, clock or online training. Recording remains on by default outside
benchmarks; `ZIRAN_LEARN=off` disables it.
Kernel times below are microseconds per call, with eleven samples, learning off
and symmetric 1.5×IQR filtering. Five of six initial/stage-one native artifact
digests were identical, so those timing differences cannot be attributed to an
optimization. The final run includes other lanes' compiler changes and a busy
host (load average about 36); native samples also amortize one process startup
across 32 calls. These are observations, not isolated teacher speedups.
| Kernel | Initial native | Stage-one native | Final native | Initial C | Final C |
| --- | ---: | ---: | ---: | ---: | ---: |
| Sieve | 71.173 | 26.469 | 27.606 | 15.677 | 11.398 |
| Records | 46.891 | 20.442 | 19.234 | 12.972 | 9.290 |
| Hash | 31.488 | 35.585 | 33.365 | 25.037 | 22.550 |
| Vectors | 34.826 | 34.875 | 41.559 | 16.930 | 13.331 |
| Calls | 8.112 | 9.050 | 7.678 | 5.157 | 5.285 |
| Printing | 9.054 | 8.827 | 5.967 | 8.003 | 4.347 |
Raw values, exclusions and identities remain in the
[initial](c-teacher-omega-before.json),
[stage-one](c-teacher-omega-stage1-after.json) and
[final kernel receipts](c-teacher-omega-final.json).
The final warm native widget results below exercise public layout, interaction
and paint-command generation; every batch verifies its result. They exclude
pixel rasterization, system fonts and OS I/O. The earlier receipt from the
widget lane uses an older compiler and is contextual evidence, not a controlled
before/after experiment for this lane.
| Widget | Earlier native µs | Final native µs | Final C µs | Final Go µs |
| --- | ---: | ---: | ---: | ---: |
| Button | 612.345 | 3.696 | 1.966 | 3.165 |
| Text | 478.862 | 4.392 | 2.140 | 2.503 |
| Input | 791.135 | 5.543 | 2.765 | 4.885 |
See [the widget lane's earlier receipt](widget-omega-2026-11-16-after.json) and
[the final warm-widget receipt](c-teacher-omega-2026-11-16-widgets-final.json).
The gap to C and Go remains open.
Exact final commands, all through `build-queue` with learning and displays off:
```sh
make -j1 check
make -j1 check-bootstrap
build/bin/ziran run --target=c bench/bench.zi -- wasm-tier --samples 11 --label c-teacher-final --output bench/results/c-teacher-omega-final.json
build/bin/ziran run --target=c bench/bench.zi -- library-targets --project /mnt/storage/Projects/kryonlabs/kryon --manifest /mnt/storage/Projects/kryonlabs/kryon/tests/widget_benchmarks.json --samples 11
build/bin/ziran run --target=c bench/bench.zi -- c-teacher --output bench/results/c-teacher-omega-2026-11-16-final.md
```
All five commands returned zero: 281/281 local tests, bootstrap passing, six
kernels, three widgets and the ten-workload teacher report. The broader source
guard detected concurrent changes to `cmd/compiler_machine_aggregate.zi` and
`tests/machine_place_cases.zi`, so the combined
[validation receipt](c-teacher-omega-2026-11-16-final-validation.json) correctly
records `complete: false`. Compiler binaries were unchanged, but this run does
not validate that lane's newest constructor source; its next canonical
checkpoint owns that validation. The earlier stage-two guard covered 97 inputs
with no changes. No GitHub CI result or installation is claimed.
A subsequent canonical constructor checkpoint rebuilt successfully, passed
bootstrap and held all 3,409 guarded source/map inputs plus seven compiler
fingerprints unchanged. Its full suite passed 279/281: only `site_targets`
("Publish one measured host") and `site_pages` (a missing targets receipt)
failed. Those publication-data failures were resolved by the targets lane's
completed cohort and successful retained site tests. No compiler or constructor
test failed. A separate final site-test repeat records the integration verdict.
Final retained site repeat passed with exit zero:
`env -u DISPLAY -u WAYLAND_DISPLAY ZIRAN_LEARN=off HARMONY_BUILD_LOCAL=1 build-queue -- sh -c 'sh tests/site_pages.sh build/bin/ziran && sh tests/site_targets.sh build/bin/ziran'`.
The [integration receipt](c-teacher-omega-2026-11-16-integration-validation.json)
keeps the earlier full-suite and later canonical/rerun results distinct.
@@ -0,0 +1,171 @@
{
"schema_version": 1,
"selected_policy": 1,
"measurements_sha256": "33dd0c8bc432d50c22f02c3b21245a85ea59c0cbe3c8bc06563ebc165c3876c7",
"table_sha256": "a4cae8ab1d24b99da61655f0e9f75a4590a0a32ab4c4bffafcbc2c2ede9acb96",
"method": "symmetric inclusive-quartile 1.5 IQR; equal artifacts share lowest-policy timings; ties by bytes then policy ID",
"observations": [
{
"workload": "Sieve",
"native_sha256": "81468f46fa5939aeec5abd2c18b72fb884295ee84ea0190e788663fed0d10ae9",
"native_ns": {
"median_twice": 39545946,
"excluded_indices": []
},
"c_ns": {
"median_twice": 24655152,
"excluded_indices": [
4,
8
]
}
},
{
"workload": "Sieve",
"native_sha256": "81468f46fa5939aeec5abd2c18b72fb884295ee84ea0190e788663fed0d10ae9",
"native_ns": {
"median_twice": 39633286,
"excluded_indices": [
5
]
},
"c_ns": {
"median_twice": 25287510,
"excluded_indices": []
}
},
{
"workload": "Records",
"native_sha256": "6653d136d7d21aaafb92a9255befdf5d125e49adebec03b7965a551c76753db8",
"native_ns": {
"median_twice": 30094488,
"excluded_indices": []
},
"c_ns": {
"median_twice": 19479634,
"excluded_indices": []
}
},
{
"workload": "Records",
"native_sha256": "6653d136d7d21aaafb92a9255befdf5d125e49adebec03b7965a551c76753db8",
"native_ns": {
"median_twice": 29809390,
"excluded_indices": []
},
"c_ns": {
"median_twice": 19531824,
"excluded_indices": [
9
]
}
},
{
"workload": "Hash",
"native_sha256": "4875728741b927cad36d216942e1dc4bfeb809d2d05daf6ad7539f792b89798c",
"native_ns": {
"median_twice": 47833720,
"excluded_indices": [
3
]
},
"c_ns": {
"median_twice": 48473046,
"excluded_indices": []
}
},
{
"workload": "Hash",
"native_sha256": "4875728741b927cad36d216942e1dc4bfeb809d2d05daf6ad7539f792b89798c",
"native_ns": {
"median_twice": 48218448,
"excluded_indices": []
},
"c_ns": {
"median_twice": 48523308,
"excluded_indices": []
}
},
{
"workload": "Vectors",
"native_sha256": "533cfc39d0908267889f1c8501bfe4cb4d3f850aa08cbaaf69c17104b6b3a1a6",
"native_ns": {
"median_twice": 58869962,
"excluded_indices": [
1
]
},
"c_ns": {
"median_twice": 28103656,
"excluded_indices": [
6,
7
]
}
},
{
"workload": "Vectors",
"native_sha256": "533cfc39d0908267889f1c8501bfe4cb4d3f850aa08cbaaf69c17104b6b3a1a6",
"native_ns": {
"median_twice": 56032874,
"excluded_indices": []
},
"c_ns": {
"median_twice": 28565534,
"excluded_indices": []
}
},
{
"workload": "Calls",
"native_sha256": "c5a6038ad354524756fc02ba8750c8bee956f625548574f176e01eda8d9a88b9",
"native_ns": {
"median_twice": 413148,
"excluded_indices": [
2
]
},
"c_ns": {
"median_twice": 12276466,
"excluded_indices": []
}
},
{
"workload": "Calls",
"native_sha256": "c5a6038ad354524756fc02ba8750c8bee956f625548574f176e01eda8d9a88b9",
"native_ns": {
"median_twice": 391418,
"excluded_indices": []
},
"c_ns": {
"median_twice": 12022737,
"excluded_indices": [
8
]
}
},
{
"workload": "Printing",
"native_sha256": "99f953bd85ed52e718ff319f8e0bcf118b3257dba3a5949bc12020526d3aff4b",
"native_ns": {
"median_twice": 3686464,
"excluded_indices": []
},
"c_ns": {
"median_twice": 10149236,
"excluded_indices": []
}
},
{
"workload": "Printing",
"native_sha256": "99f953bd85ed52e718ff319f8e0bcf118b3257dba3a5949bc12020526d3aff4b",
"native_ns": {
"median_twice": 3805102,
"excluded_indices": []
},
"c_ns": {
"median_twice": 10331054,
"excluded_indices": []
}
}
]
}
@@ -0,0 +1,527 @@
{
"schema_version": 1,
"checks": false,
"target": "x86_64-linux",
"learning": "off",
"host": "omega",
"source_epoch_sha256": "ecb2dd640a110ffc21c0e655cb8f0fb65cdc98e74adf0b73bfad4fd221a8d1cd",
"method": "paired process wall time; 1024 checksum-checked kernel calls; includes startup; 11 samples",
"measurements": [
{
"workload": "Sieve",
"input_sha256": "f1fccf1c68dab477a2d0e35a94d9fda6ed8c9873d34deb24c4de73e88f22d92e",
"zx_sha256": "f1fccf1c68dab477a2d0e35a94d9fda6ed8c9873d34deb24c4de73e88f22d92e",
"native_sha256": "81468f46fa5939aeec5abd2c18b72fb884295ee84ea0190e788663fed0d10ae9",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/f1fccf1c68dab477a2d0e35a94d9fda6ed8c9873d34deb24c4de73e88f22d92e/x86_64-81468f46fa5939aeec5abd2c18b72fb884295ee84ea0190e788663fed0d10ae9.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 928,
"policy": {
"leaf_operations": 0,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
20867869,
18254550,
22190842,
25413449,
17126374,
17709972,
19211226,
19772973,
22190052,
22695430,
18717818
],
"c_ns": [
12485855,
12297866,
12327576,
11976347,
14679756,
11797518,
11769858,
12596135,
13603501,
12638594,
12624895
]
},
{
"workload": "Sieve",
"input_sha256": "f1fccf1c68dab477a2d0e35a94d9fda6ed8c9873d34deb24c4de73e88f22d92e",
"zx_sha256": "f1fccf1c68dab477a2d0e35a94d9fda6ed8c9873d34deb24c4de73e88f22d92e",
"native_sha256": "81468f46fa5939aeec5abd2c18b72fb884295ee84ea0190e788663fed0d10ae9",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/f1fccf1c68dab477a2d0e35a94d9fda6ed8c9873d34deb24c4de73e88f22d92e/x86_64-81468f46fa5939aeec5abd2c18b72fb884295ee84ea0190e788663fed0d10ae9.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 928,
"policy": {
"leaf_operations": 1,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
20999377,
19884662,
17851882,
22994789,
20456060,
24408072,
18467699,
18384260,
21003638,
19748624,
19605413
],
"c_ns": [
12486225,
12191667,
12878123,
13559331,
12835844,
12029308,
12814034,
12440965,
13339812,
11879617,
12643755
]
},
{
"workload": "Records",
"input_sha256": "4dc39f678013ae78a3783b0dc2cf95aa0cd66f3c79ed5b88250f42f8d9d3ea45",
"zx_sha256": "4dc39f678013ae78a3783b0dc2cf95aa0cd66f3c79ed5b88250f42f8d9d3ea45",
"native_sha256": "6653d136d7d21aaafb92a9255befdf5d125e49adebec03b7965a551c76753db8",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/4dc39f678013ae78a3783b0dc2cf95aa0cd66f3c79ed5b88250f42f8d9d3ea45/x86_64-6653d136d7d21aaafb92a9255befdf5d125e49adebec03b7965a551c76753db8.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 2816,
"policy": {
"leaf_operations": 0,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
14462317,
16515978,
13225751,
14065619,
15305102,
15092884,
15731771,
14513127,
16387748,
13496971,
15047244
],
"c_ns": [
10074795,
10539854,
9831067,
9739817,
9375789,
9834007,
10387754,
8980270,
9317879,
9488338,
9608837
]
},
{
"workload": "Records",
"input_sha256": "4dc39f678013ae78a3783b0dc2cf95aa0cd66f3c79ed5b88250f42f8d9d3ea45",
"zx_sha256": "4dc39f678013ae78a3783b0dc2cf95aa0cd66f3c79ed5b88250f42f8d9d3ea45",
"native_sha256": "6653d136d7d21aaafb92a9255befdf5d125e49adebec03b7965a551c76753db8",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/4dc39f678013ae78a3783b0dc2cf95aa0cd66f3c79ed5b88250f42f8d9d3ea45/x86_64-6653d136d7d21aaafb92a9255befdf5d125e49adebec03b7965a551c76753db8.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 2816,
"policy": {
"leaf_operations": 1,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
16420928,
15917500,
15161824,
16250438,
14737855,
13867479,
14299717,
13939998,
17311484,
14904695,
13922058
],
"c_ns": [
10043136,
9910006,
9412558,
9941177,
10889212,
9621818,
9339349,
9021011,
10286935,
12788914,
9532118
]
},
{
"workload": "Hash",
"input_sha256": "41e6991d1c84b4fec12fe82b4ad9275c6394ed284ae862572e2ee2ea7f65f4b2",
"zx_sha256": "41e6991d1c84b4fec12fe82b4ad9275c6394ed284ae862572e2ee2ea7f65f4b2",
"native_sha256": "4875728741b927cad36d216942e1dc4bfeb809d2d05daf6ad7539f792b89798c",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/41e6991d1c84b4fec12fe82b4ad9275c6394ed284ae862572e2ee2ea7f65f4b2/x86_64-4875728741b927cad36d216942e1dc4bfeb809d2d05daf6ad7539f792b89798c.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 704,
"policy": {
"leaf_operations": 0,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
23778495,
24370513,
24052204,
25592958,
23571896,
24515242,
24071235,
23719886,
23781516,
24465373,
23692396
],
"c_ns": [
23859285,
24482703,
23914385,
24310353,
23914565,
24805761,
24741011,
24269803,
24236523,
23927435,
23590197
]
},
{
"workload": "Hash",
"input_sha256": "41e6991d1c84b4fec12fe82b4ad9275c6394ed284ae862572e2ee2ea7f65f4b2",
"zx_sha256": "41e6991d1c84b4fec12fe82b4ad9275c6394ed284ae862572e2ee2ea7f65f4b2",
"native_sha256": "4875728741b927cad36d216942e1dc4bfeb809d2d05daf6ad7539f792b89798c",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/41e6991d1c84b4fec12fe82b4ad9275c6394ed284ae862572e2ee2ea7f65f4b2/x86_64-4875728741b927cad36d216942e1dc4bfeb809d2d05daf6ad7539f792b89798c.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 704,
"policy": {
"leaf_operations": 1,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
23691446,
23581766,
24109224,
24533572,
23658496,
24126864,
24617702,
23831145,
24376133,
25027880,
24066295
],
"c_ns": [
23864855,
24728732,
23749216,
23839975,
24261654,
24777631,
23927775,
24275583,
25036220,
25237799,
23623006
]
},
{
"workload": "Vectors",
"input_sha256": "541c0b8413f48e82b2b148136f15a8f226ee7f9e6b4a82413f0df09fc64630d2",
"zx_sha256": "541c0b8413f48e82b2b148136f15a8f226ee7f9e6b4a82413f0df09fc64630d2",
"native_sha256": "533cfc39d0908267889f1c8501bfe4cb4d3f850aa08cbaaf69c17104b6b3a1a6",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/541c0b8413f48e82b2b148136f15a8f226ee7f9e6b4a82413f0df09fc64630d2/x86_64-533cfc39d0908267889f1c8501bfe4cb4d3f850aa08cbaaf69c17104b6b3a1a6.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 1792,
"policy": {
"leaf_operations": 0,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
29929688,
33329353,
28847073,
31372233,
28824763,
29442571,
28753763,
30010728,
27477479,
29427391,
29534601
],
"c_ns": [
13348252,
13889649,
13295732,
14243767,
14127988,
14051828,
15859901,
15669851,
13824970,
14743255,
14409756
]
},
{
"workload": "Vectors",
"input_sha256": "541c0b8413f48e82b2b148136f15a8f226ee7f9e6b4a82413f0df09fc64630d2",
"zx_sha256": "541c0b8413f48e82b2b148136f15a8f226ee7f9e6b4a82413f0df09fc64630d2",
"native_sha256": "533cfc39d0908267889f1c8501bfe4cb4d3f850aa08cbaaf69c17104b6b3a1a6",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/541c0b8413f48e82b2b148136f15a8f226ee7f9e6b4a82413f0df09fc64630d2/x86_64-533cfc39d0908267889f1c8501bfe4cb4d3f850aa08cbaaf69c17104b6b3a1a6.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 1792,
"policy": {
"leaf_operations": 1,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
29218002,
28792154,
25840686,
24514012,
28731574,
25602317,
26241535,
29797079,
28016437,
27044931,
31460342
],
"c_ns": [
15497072,
15546411,
14649856,
14115088,
13444071,
13510161,
13438841,
12655644,
14282767,
14376077,
14370237
]
},
{
"workload": "Calls",
"input_sha256": "b55d21c3a286aa61d33a3f7eab3eca09121875b0c839f806192bb1c6c9ef011f",
"zx_sha256": "b55d21c3a286aa61d33a3f7eab3eca09121875b0c839f806192bb1c6c9ef011f",
"native_sha256": "c5a6038ad354524756fc02ba8750c8bee956f625548574f176e01eda8d9a88b9",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/b55d21c3a286aa61d33a3f7eab3eca09121875b0c839f806192bb1c6c9ef011f/x86_64-c5a6038ad354524756fc02ba8750c8bee956f625548574f176e01eda8d9a88b9.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 448,
"policy": {
"leaf_operations": 0,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
203649,
181800,
275028,
219999,
196589,
188029,
155009,
215059,
210679,
221669,
209499
],
"c_ns": [
6215543,
6238912,
5602646,
6426082,
6138233,
5903684,
5623696,
5917704,
6224322,
6235133,
6008554
]
},
{
"workload": "Calls",
"input_sha256": "b55d21c3a286aa61d33a3f7eab3eca09121875b0c839f806192bb1c6c9ef011f",
"zx_sha256": "b55d21c3a286aa61d33a3f7eab3eca09121875b0c839f806192bb1c6c9ef011f",
"native_sha256": "c5a6038ad354524756fc02ba8750c8bee956f625548574f176e01eda8d9a88b9",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/b55d21c3a286aa61d33a3f7eab3eca09121875b0c839f806192bb1c6c9ef011f/x86_64-c5a6038ad354524756fc02ba8750c8bee956f625548574f176e01eda8d9a88b9.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 448,
"policy": {
"leaf_operations": 1,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
223699,
195709,
161219,
184239,
184749,
241108,
197600,
163969,
205879,
244499,
182000
],
"c_ns": [
5986924,
5953174,
6022574,
6396762,
6234373,
5954164,
6000163,
6023344,
6723341,
5937463,
6306132
]
},
{
"workload": "Printing",
"input_sha256": "b10e5d3d72ba8ccea623fd45c8fbceb20787a7d8bccd47512eb7bbef246d8d9a",
"zx_sha256": "b10e5d3d72ba8ccea623fd45c8fbceb20787a7d8bccd47512eb7bbef246d8d9a",
"native_sha256": "99f953bd85ed52e718ff319f8e0bcf118b3257dba3a5949bc12020526d3aff4b",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/b10e5d3d72ba8ccea623fd45c8fbceb20787a7d8bccd47512eb7bbef246d8d9a/x86_64-99f953bd85ed52e718ff319f8e0bcf118b3257dba3a5949bc12020526d3aff4b.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 1088,
"policy": {
"leaf_operations": 0,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
1843232,
1887841,
1876532,
1743973,
1724652,
1751162,
1934542,
2020811,
1699852,
1936131,
1773913
],
"c_ns": [
5074618,
5024658,
4710789,
4770989,
5551996,
4928228,
4798509,
5886204,
5865335,
5853474,
5301256
]
},
{
"workload": "Printing",
"input_sha256": "b10e5d3d72ba8ccea623fd45c8fbceb20787a7d8bccd47512eb7bbef246d8d9a",
"zx_sha256": "b10e5d3d72ba8ccea623fd45c8fbceb20787a7d8bccd47512eb7bbef246d8d9a",
"native_sha256": "99f953bd85ed52e718ff319f8e0bcf118b3257dba3a5949bc12020526d3aff4b",
"compiler_sha256": "786d749f18e22326435e450341e67ccd563c007656245c5cfcdfa16bb17f24c2",
"corpus_record": "zx28-lir4/b10e5d3d72ba8ccea623fd45c8fbceb20787a7d8bccd47512eb7bbef246d8d9a/x86_64-99f953bd85ed52e718ff319f8e0bcf118b3257dba3a5949bc12020526d3aff4b.record.json",
"checksum": "42",
"c_checksum": "42",
"code_bytes": 1088,
"policy": {
"leaf_operations": 1,
"unroll_factor": 1,
"block_layout": 1,
"allocation": 0
},
"native_ns": [
1769923,
1774792,
2139061,
1765763,
1902551,
1812652,
1932871,
2031621,
1974651,
1787052,
2312930
],
"c_ns": [
4933298,
5210677,
5165527,
4956148,
4950259,
4955699,
5620876,
5906544,
5761195,
5169107,
4775529
]
}
]
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+22
View File
@@ -0,0 +1,22 @@
// Ordinary compilation consults this checked-in table only. No corpus,
// settings, files, clock or online search participates in code generation.
#import "compiler_learning_policy"
#import "compiler_learning_table"
LearningTableValid :: () -> bool {
return LearningTableVersion == LearningPolicyVersion && LearningVerifierVersion == 1 &&
LearningTableTarget == "x86_64" && LearningTableEvidence.count == 64 && LearningTableFixture.count == 64
}
LearningRuleEnabled :: (rule: LearningRule) -> bool {
if !LearningTableValid() { return false }
return rule == .MultiplyPower && LearningMultiplyPower == 1 || rule == .MultiplyScaledAdd && LearningMultiplyScaledAdd == 1
}
LearningTuningChoice :: () -> LearningTuning {
baseline := LearningTuning.{unroll_factor = 1, block_layout = 1}
if !LearningTableValid() { return baseline }
selected := LearningTuning.{leaf_operations = LearningLeafOperations, unroll_factor = LearningUnrollFactor,
block_layout = LearningBlockLayout, allocation = LearningAllocation}
return ifx LearningTuningValid(selected) then selected else baseline
}
+60
View File
@@ -0,0 +1,60 @@
// Generate runtime-input parity cases for the closed rewrite vocabulary.
// Constants remain literal in each branch so the native instruction selector
// actually exercises the immediate-multiply rule being certified.
#import "std/number_text"
#import "std/text_tools"
using Vectors :: #import "std/vec"
LearningFixtureFactor :: (index: s64) -> s64 {
if index < 30 { return cast(s64)(cast(u64)1 << cast(u64)(index + 1)) }
if index == 30 { return 2 }
if index == 31 { return 3 }
if index == 32 { return 5 }
return 9
}
LearningFixtureSource :: () -> string {
source: Vec(u8)
BuilderAppend(source, "Emit :: (x: u64, factor: s64) {\n")
for index: 0..33 {
digits: [32]u8
literal := FormatInteger(LearningFixtureFactor(index), digits[:])
BuilderAppend(source, " if factor == "); BuilderAppend(source, literal)
BuilderAppend(source, " { print(\"% % % % % % % %\\n\", ")
types := string.["u64", "s64", "u32", "s32", "u16", "s16", "u8", "s8"]
for type_index: 0..7 {
if type_index > 0 { BuilderAppend(source, ", ") }
type := types[type_index]
BuilderAppend(source, "cast("); BuilderAppend(source, type)
BuilderAppend(source, ")(cast("); BuilderAppend(source, type)
BuilderAppend(source, ")x * cast("); BuilderAppend(source, type)
BuilderAppend(source, ")"); BuilderAppend(source, literal); BuilderAppend(source, ")")
}
BuilderAppend(source, "); return }\n")
}
BuilderAppend(source, "}\nmain :: () -> s32 {\n factors := s64.[")
for index: 0..33 {
if index > 0 { BuilderAppend(source, ", ") }
digits: [32]u8
BuilderAppend(source, FormatInteger(LearningFixtureFactor(index), digits[:]))
}
BuilderAppend(source, #string FIXTURE
]
edges := u64.[0, 1, 127, 128, 255, 256, 32767, 32768, 65535, 65536,
2147483647, 2147483648, 4294967295, 4294967296, 9223372036854775807,
9223372036854775808, 18446744073709551615]
for factor: factors {
for value: edges { Emit(value, factor) }
random: u64 = 521288629
for iteration: 0..2047 {
random = random ^ (random << 13)
random = random ^ (random >> 7)
random = random ^ (random << 17)
Emit(random, factor)
}
}
return 0
}
FIXTURE)
return TextDetach(BuilderFinish(source))
}
+69
View File
@@ -0,0 +1,69 @@
// Closed semantic vocabulary for the offline learner. A mined sequence may
// propose one of these rules; it cannot supply executable optimizer code.
LearningPolicyVersion :: 1
LearningRule :: enum s32 { None; MultiplyPower; MultiplyScaledAdd }
LearningTuning :: struct {
leaf_operations: s32
unroll_factor: s32
block_layout: s32
allocation: s32
}
LearningRuleForFactor :: (factor: s64) -> LearningRule {
if factor == 2 || factor == 3 || factor == 5 || factor == 9 { return .MultiplyScaledAdd }
if factor < 2 || factor > 1073741824 { return .None }
bits := cast(u64)factor
return ifx (bits & (bits - 1)) == 0 then .MultiplyPower else .None
}
// Only implemented choices are legal. New policies need a consumer and
// parity coverage before widening this domain.
LearningTuningValid :: (policy: LearningTuning) -> bool {
return policy.leaf_operations >= 0 && policy.leaf_operations <= 1 &&
policy.unroll_factor == 1 && policy.block_layout >= 0 && policy.block_layout <= 1 && policy.allocation == 0
}
LearningRewriteValue :: (rule: LearningRule, value: u64, factor: s64) -> u64 {
if rule == .MultiplyScaledAdd {
if factor == 2 { return value + value }
if factor == 3 { return value + (value << 1) }
if factor == 5 { return value + (value << 2) }
if factor == 9 { return value + (value << 3) }
}
if rule == .MultiplyPower {
power := cast(u64)factor
shift: u64
while power > 1 { power = power >> 1; shift += 1 }
return value << shift
}
return value
}
// A deterministic preflight, additional to C/native differential execution.
// Test every supported parameter, not just the factors the teacher observed.
LearningCheckFamily :: (rule: LearningRule) -> bool {
if rule != .MultiplyPower && rule != .MultiplyScaledAdd { return false }
edges := u64.[0, 1, 127, 128, 255, 256, 32767, 32768, 65535, 65536,
2147483647, 2147483648, 4294967295, 4294967296, 9223372036854775807,
9223372036854775808, 18446744073709551615]
for index: 0..33 {
factor: s64
if index < 30 { factor = cast(s64)(cast(u64)1 << cast(u64)(index + 1)) }
else if index == 30 { factor = 2 }
else if index == 31 { factor = 3 }
else if index == 32 { factor = 5 }
else { factor = 9 }
if LearningRuleForFactor(factor) != rule { continue }
random: u64 = 521288629
for trial: 0..2064 {
random = random ^ (random << 13)
random = random ^ (random >> 7)
random = random ^ (random << 17)
value := ifx trial < edges.count then edges[trial] else random
expected := value * cast(u64)factor
actual := LearningRewriteValue(rule, value, factor)
if actual != expected { return false }
}
}
return true
}
+14
View File
@@ -0,0 +1,14 @@
// Generated by ziran learn verify; review and check in before use.
// Preconditions: integer modulo width, dead flags, no memory effects.
LearningTableVersion :: 1
LearningVerifierVersion :: 1
LearningTableTarget :: "x86_64"
LearningTableEvidence :: "2f53cf40a46149669ee62d3efe39e5fb676b8a629be93fdea7183c78695ccee7"
LearningTableFixture :: "4b7385ea2655619107c8356699dc898c908b726dbd5b10d236bc39bbed207062"
LearningMultiplyPower :: 1
LearningMultiplyScaledAdd :: 1
LearningLeafOperations :: 0
LearningUnrollFactor :: 1
LearningBlockLayout :: 1
LearningAllocation :: 0
LearningTuningEvidence :: "33dd0c8bc432d50c22f02c3b21245a85ea59c0cbe3c8bc06563ebc165c3876c7"
+139
View File
@@ -0,0 +1,139 @@
// Deterministic offline policy scoring. Times are integer nanoseconds, joined
// by the caller to verified corpus artifacts before they reach this module.
#import "compiler_learning_policy"
#import "std/sort"
using Vectors :: #import "std/vec"
LearningSamples :: struct { valid: bool; median_twice: s64; excluded: Vec(s64) }
LearningObservation :: struct {
workload: string
input: string
artifact: string
host: string
source_epoch: string
policy: LearningTuning
bytes: s64
native_ns: []s64
c_ns: []s64
}
LearningSelection :: struct { valid: bool; policy: LearningTuning; score: float64; bytes: s64 }
// Inclusive interpolated quartiles, symmetric 1.5 IQR fences. Quartiles are
// scaled by four, fences by eight, so no floating-point rounding changes the
// excluded indices. Keep the caller's raw ordering untouched.
LearningAnalyze :: (samples: []s64) -> LearningSamples {
result: LearningSamples
if samples.count < 11 || samples.count > 4096 { return .{} }
sorted: Vec(s64)
defer VecFree(sorted)
for sample: samples {
if sample <= 0 || sample > 1000000000000 { return .{} }
if !VecPush(sorted, sample) { return .{} }
}
Sort(VecSlice(sorted, 0, sorted.count))
first := sorted.count - 1
third := first * 3
q1 := sorted[first / 4] * (4 - first % 4) + sorted[(first + 3) / 4] * (first % 4)
q3 := sorted[third / 4] * (4 - third % 4) + sorted[(third + 3) / 4] * (third % 4)
lower := 2 * q1 - 3 * (q3 - q1)
upper := 2 * q3 + 3 * (q3 - q1)
for index: 0..samples.count - 1 {
if samples[index] * 8 < lower || samples[index] * 8 > upper {
if !VecPush(result.excluded, index) { VecFree(result.excluded); return .{} }
}
}
kept: Vec(s64)
defer VecFree(kept)
for sample: sorted {
if sample * 8 >= lower && sample * 8 <= upper {
if !VecPush(kept, sample) { VecFree(result.excluded); return .{} }
}
}
if kept.count < 3 { VecFree(result.excluded); return .{} }
result.median_twice = kept[(kept.count - 1) / 2] + kept[kept.count / 2]
result.valid = true
return result
}
LearningPolicyId :: (policy: LearningTuning) -> s32 {
return ifx LearningTuningValid(policy) then policy.leaf_operations * 2 + policy.block_layout else -1
}
// Compare policies over exactly the same workload set. Sort workload names so
// summation and tie breaking never depend on receipt/corpus traversal order.
LearningSelect :: (observations: []LearningObservation) -> LearningSelection {
result: LearningSelection
if observations.count == 0 || observations.count > 1024 { return .{} }
workloads: Vec(string)
defer VecFree(workloads)
for observation: observations {
if observation.workload.count == 0 || observation.input.count != 64 || observation.host.count == 0 ||
observation.source_epoch.count != 64 || observation.bytes <= 0 || LearningPolicyId(observation.policy) < 0 {
return .{}
}
if observation.host != observations[0].host || observation.source_epoch != observations[0].source_epoch { return .{} }
for other: observations {
if other.workload == observation.workload && other.input != observation.input { return .{} }
}
native := LearningAnalyze(observation.native_ns)
c := LearningAnalyze(observation.c_ns)
valid := native.valid && c.valid
VecFree(native.excluded); VecFree(c.excluded)
if !valid { return .{} }
found := false
for workload: workloads { if workload == observation.workload { found = true; break } }
if !found && !VecPush(workloads, observation.workload) { return .{} }
}
SortText(VecSlice(workloads, 0, workloads.count))
for policy_id: cast(s32)0..cast(s32)3 {
score: float64
bytes: s64
complete := true
for workload: workloads {
at: s64 = -1
reference: s64 = -1
for index: 0..observations.count - 1 {
observation := observations[index]
if observation.workload != workload { continue }
if reference < 0 { reference = index }
if LearningPolicyId(observation.policy) == policy_id {
if at >= 0 { return .{} }
at = index
}
}
if at < 0 { complete = false; break }
row := observations[at]
baseline := observations[reference]
if row.input != baseline.input || row.host != baseline.host || row.source_epoch != baseline.source_epoch {
return .{}
}
// One common host and compiler source epoch for the whole search.
if row.host != observations[0].host || row.source_epoch != observations[0].source_epoch { return .{} }
// Equal emitted bytes are one experiment, regardless of policy.
// Reuse the lowest policy's timing pair so repeated measurements
// of identical code cannot manufacture a tuning win from noise.
timing_index := at
if row.artifact.count == 64 {
for index: 0..observations.count - 1 {
other := observations[index]
if other.workload == row.workload && other.artifact == row.artifact &&
LearningPolicyId(other.policy) < LearningPolicyId(observations[timing_index].policy) { timing_index = index }
}
}
native := LearningAnalyze(observations[timing_index].native_ns)
c := LearningAnalyze(observations[timing_index].c_ns)
defer VecFree(native.excluded)
defer VecFree(c.excluded)
if !native.valid || !c.valid || row.bytes > 9223372036854775807 - bytes { return .{} }
score += cast(float64)native.median_twice / cast(float64)c.median_twice
bytes += row.bytes
}
if !complete { continue }
if !result.valid || score < result.score || score == result.score &&
(bytes < result.bytes || bytes == result.bytes && policy_id < LearningPolicyId(result.policy)) {
result = .{valid = true, policy = .{leaf_operations = policy_id / 2,
block_layout = policy_id % 2, unroll_factor = 1}, score = score, bytes = bytes}
}
}
return result
}
+2 -1
View File
@@ -1,6 +1,7 @@
using Lir :: #import "compiler_lowered_ir"
using Machine :: #import "compiler_machine_ir"
using Vectors :: #import "std/vec"
#import "compiler_learning"
// Instruction-selection facts for one LIR function on x86-64, planned before
// machine lowering so integer code compares, branches and computes the way a
@@ -372,7 +373,7 @@ MachineSelectPlanBuild :: (plan: *MachineSelectPlan, program: LirProgram, functi
for at: cast(s64)0..function.blocks.count - 1 {
plan.dead[at] = plan.threaded[at] > 0 && plan.threaded[at] == plan.incoming[at]
}
Layout(plan, function, enabled)
Layout(plan, function, enabled && LearningTuningChoice().block_layout == 1)
return .None
}
+16 -2
View File
@@ -2,6 +2,8 @@ using IR :: #import "compiler_lowered_ir"
using Verify :: #import "compiler_lowered_verify"
using Codec :: #import "compiler_exec_serial"
using Vectors :: #import "std/vec"
using Inline :: #import "compiler_opt_inline"
#import "compiler_learning"
LirOptProblem :: enum s32 {
None; Owner; Options; VerifyInput; VerifyPass; Limit; Allocation; Codec
@@ -24,6 +26,7 @@ LirOptCounters :: struct {
dead: LirOptPassCounters
cfg: LirOptPassCounters
compact: LirOptPassCounters
inline_leaf: LirOptPassCounters
input_functions: s64
input_blocks: s64
input_values: s64
@@ -40,6 +43,7 @@ LirOptOptions :: struct {
eliminate_dead: bool
simplify_cfg: bool
maximum_rounds: s32
inline_leaf_operations: s32
}
LirOptOwner :: struct {
@@ -1857,7 +1861,7 @@ Result :: (state: OptState) -> LirOptResult {
#scope_export
LirOptDefaultOptions :: () -> LirOptOptions {
return .{fold_constants = true, propagate_copies = true, eliminate_dead = true,
simplify_cfg = true, maximum_rounds = 8}
simplify_cfg = true, maximum_rounds = 8, inline_leaf_operations = LearningTuningChoice().leaf_operations}
}
LirOptFree :: (owner: *LirOptOwner) {
@@ -1883,7 +1887,8 @@ LirOptBuild :: (owner: *LirOptOwner, program: LirProgram, limits: LirLimits,
state.problem = .Limit
return Result(state)
}
if options.maximum_rounds < 1 || options.maximum_rounds > 64 {
if options.maximum_rounds < 1 || options.maximum_rounds > 64 ||
options.inline_leaf_operations < 0 || options.inline_leaf_operations > 1 {
LirOptFree(owner)
state.problem = .Options
return Result(state)
@@ -1904,6 +1909,15 @@ LirOptBuild :: (owner: *LirOptOwner, program: LirProgram, limits: LirLimits,
}
owner.valid = false
owner.program = .{version = LirVersion, entry = LirNoId}
if options.inline_leaf_operations > 0 {
inlined := LirInlineLeaves(LirReadProgram(*owner.storage), options.inline_leaf_operations, state.remaining)
if !Spend(*state, inlined.work) || inlined.limited {
unused Fail(*state, .Limit); LirOptFree(owner); return Result(state)
}
state.counters.inline_leaf.runs += 1
state.counters.inline_leaf.instructions += inlined.calls
if !VerifyPass(*state, LirReadProgram(*owner.storage), limits) { LirOptFree(owner); return Result(state) }
}
ScratchReset(*state)
if options.fold_constants && !FoldPass(*state, owner, limits, options) {
LirOptFree(owner)
+87
View File
@@ -0,0 +1,87 @@
// Bounded scalar leaf inlining. Reuse the call's operand storage; no new values,
// blocks or allocations are needed. General CFG inlining belongs in a separate
// pass with its own growth budget.
using IR :: #import "compiler_lowered_ir"
LirInlineResult :: struct { work: s64; calls: s64; limited: bool }
#scope_file
Scalar :: (program: LirProgram, type: s32) -> bool {
return type >= 0 && type < program.types.count &&
(program.types[type].kind == .Integer || program.types[type].kind == .Bool)
}
Operation :: (op: LirOp) -> bool {
return op == .Add || op == .Subtract || op == .Multiply || op == .Negate ||
op == .BitAnd || op == .BitOr || op == .BitXor || op == .BitNot ||
op == .Equal || op == .NotEqual || op == .Less || op == .LessEqual ||
op == .Greater || op == .GreaterEqual || op == .Convert || op == .Bitcast
}
Parameter :: (parameters: []s32, value: s32) -> s64 {
for at: 0..parameters.count - 1 { if parameters[at] == value { return at } }
return -1
}
Leaf :: (program: LirProgram, call: LirInstruction) -> (instruction: LirInstruction, valid: bool) {
if call.result < 0 || call.symbol < 0 || call.symbol >= program.functions.count { return .{}, false }
function := program.functions[call.symbol]
if function.external || function.variadic || function.calling != .Portable ||
function.blocks.count != 1 || function.entry != 0 || !Scalar(program, function.result) { return .{}, false }
block := function.blocks[0]
if block.instructions.count != 2 || block.parameters.count != call.operands.count { return .{}, false }
operation := block.instructions[0]
terminal := block.instructions[1]
if !Operation(operation.op) || operation.effect != 0 || operation.operands.count > 2 ||
operation.operands.count > call.operands.count || terminal.op != .Return ||
terminal.operands.count != 1 || terminal.operands[0] != operation.result { return .{}, false }
for value: operation.operands {
if Parameter(block.parameters, value) < 0 || !Scalar(program, function.values[value]) { return .{}, false }
}
return operation, true
}
#scope_export
// PROGRAM must have passed LirVerify. On budget exhaustion the caller discards
// its private clone, as for every other optimizer pass.
LirInlineLeaves :: (program: LirProgram, maximum_operations: s32, budget: s64) -> LirInlineResult {
result: LirInlineResult
if maximum_operations != 1 { return result }
for function: program.functions {
for block: function.blocks {
for at: 0..block.instructions.count - 1 {
if result.work >= budget { result.limited = true; return result }
result.work += 1
call := block.instructions[at]
if call.op != .Call { continue }
cost := cast(s64)call.operands.count * 3 + 1
if cost > budget - result.work { result.limited = true; return result }
result.work += cost
operation, valid := Leaf(program, call)
if !valid { continue }
callee := program.functions[call.symbol]
mapped: [2]s32
for operand: 0..operation.operands.count - 1 {
parameter := Parameter(callee.blocks[0].parameters, operation.operands[operand])
mapped[operand] = call.operands[parameter]
}
for operand: 0..operation.operands.count - 1 { call.operands[operand] = mapped[operand] }
call.operands = call.operands[:operation.operands.count]
call.op = operation.op
call.immediate = operation.immediate
call.symbol = operation.symbol
call.alignment = operation.alignment
call.checked = operation.checked
call.effect = 0
block.instructions[at] = call
result.calls += 1
}
effect: s32
for at: 0..block.instructions.count - 1 {
if result.work >= budget { result.limited = true; return result }
result.work += 1
if LirEffectful(block.instructions[at].op) {
effect += 1; block.instructions[at].effect = effect
} else { block.instructions[at].effect = 0 }
}
}
}
return result
}
+1 -1
View File
@@ -603,7 +603,7 @@ Binary :: (state: *State, opcode: MachineOpcode) -> bool {
if type.kind == .Bool && !logical || type.kind == .Function { return Fail(state, .Unsupported, OperandId(state, 0)) }
value := cast(s64)immediate.immediate
if opcode == .IntegerMultiply {
if constant { X86MultiplyImmediate(*state.writer, destination, destination, value) }
if constant { X86MultiplyValue(*state.writer, destination, destination, value) }
else { X86Multiply(*state.writer, destination, right) }
} else {
code: u32 = X86Add
+38
View File
@@ -2,6 +2,8 @@
// (no output buffer) or writes into a buffer sized by a previous measure. Both
// modes run the same calls, so measured and written sizes agree exactly; no
// instruction's length depends on a displacement value.
#import "compiler_learning"
#import "compiler_learning_policy"
X86Rax :: 0
X86Rcx :: 1
@@ -203,10 +205,46 @@ X86Multiply :: (writer: *X86Writer, destination: s32, source: s32) {
}
X86MultiplyImmediate :: (writer: *X86Writer, destination: s32, source: s32, value: s64) {
// Both forms sign-extend the immediate to 64 bits and set identical
// flags. Keep the full imm32 form when sign extension would differ.
if X86Fits8(value) {
X86Encode(writer, 0, true, 107, 1, destination, X86Direct(source), trailing = 1)
X86Little(writer, cast(u64)value, 1)
return
}
X86Encode(writer, 0, true, 105, 1, destination, X86Direct(source), trailing = 4)
X86Signed32(writer, value)
}
// Integer value multiplication with dead flags. Machine integer arithmetic
// normalizes the result after this operation; no carry/overflow flag escapes
// it. Keep this separate from the flag-preserving IMUL encoder above.
X86MultiplyValue :: (writer: *X86Writer, destination: s32, source: s32, value: s64) {
if value == 1 {
if destination != source { X86Move(writer, destination, source) }
return
}
rule := LearningRuleForFactor(value)
if LearningRuleEnabled(rule) && rule == .MultiplyScaledAdd && source != X86Rsp {
shift: s32
if value == 3 { shift = 1 }
if value == 5 { shift = 2 }
if value == 9 { shift = 3 }
X86Lea(writer, destination, X86Indexed(source, source, 0, shift))
return
}
if LearningRuleEnabled(rule) && rule == .MultiplyPower && destination == source {
power := cast(u64)value
if (power & (power - 1)) == 0 {
shift: s32
while power > 1 { power = power >> 1; shift += 1 }
X86ShiftImmediate(writer, 4, destination, shift)
return
}
}
X86MultiplyImmediate(writer, destination, source, value)
}
// F7 group: 2 not, 3 neg, 6 div, 7 idiv.
X86Group3 :: (writer: *X86Writer, extension: s32, register: s32) {
X86Encode(writer, 0, true, 247, 1, extension, X86Direct(register))
+1 -1
View File
@@ -846,7 +846,7 @@ PackageMain :: (launcher: string, arguments: []string) -> s32 {
if command == "features" { return Features(arguments[1:]) }
if command == "capabilities" { return Capabilities(arguments[1:]) }
if command == "explain" { return Explain(arguments[1:]) }
if command == "learn" { return Learn(arguments[1:]) }
if command == "learn" { return Learn(arguments[1:], launcher) }
if command == "add" { return Add(launcher, arguments[1:]) }
separator: s32 = PkgAfterSeparator(arguments)
script_flags: []string = arguments[0:ScriptArgumentEnd(arguments)]
+10 -6
View File
@@ -5,6 +5,8 @@
#import "json_quote"
Clock :: #import "date_time_linux"
CompilerVersion :: #import "version"
#import "package_learn_teacher"
#import "package_learn_tuning"
// `ziran learn on|off|status`: a corpus of the programs this machine builds to
// native code, kept as training data for improving Ziran's machine code.
@@ -33,7 +35,7 @@ CompilerVersion :: #import "version"
// before/after pairs. Benchmark receipts name artifacts by the same digests.
#scope_file
LEARN_USAGE :: "usage: ziran learn on [--limit-mb N] | ziran learn off | ziran learn status";
LEARN_USAGE :: "usage: ziran learn on [--limit-mb N] | off | status | verify --candidates FILE --repo DIR --output FILE | train --measurements FILE --table FILE --verification FILE --output FILE";
LEARN_DEFAULT_LIMIT_MB :: 1024;
LEARN_MAX_FILE :: 16777216;
LEARN_MAX_TOOL :: 268435456;
@@ -205,16 +207,16 @@ LearnField :: (name: string, value: string) -> string {
// One JSON line naming what made a record. Empty when a tool cannot be read.
LearnRecordText :: (tool_directory: string, format: string, target: string,
source: string, entry: string) -> string {
source: string, entry: string, input: string) -> string {
native := LearnToolDigest(tool_directory, "zx2native")
portable := LearnToolDigest(tool_directory, "zi2zx")
if native.count == 0 || portable.count == 0 { return "" }
path := PkgCanonical(source)
if path.count == 0 { path = source }
fields: [8]string = .[LearnField("format", format), LearnField("target", target),
fields: [9]string = .[LearnField("format", format), LearnField("target", target),
LearnField("platform", "linux"), LearnField("ziran", CompilerVersion.Version),
LearnField("zx2native_sha256", native), LearnField("zi2zx_sha256", portable),
LearnField("source", path), LearnField("entry", entry)]
LearnField("source", path), LearnField("entry", entry), LearnField("input_sha256", input)]
text := ""
for field: fields {
if field.count == 0 { return "" }
@@ -242,7 +244,7 @@ LearnStore :: (tool_directory: string, program: string, elf: string, target: str
if PathExists(record) { return .Present }
stored := LearnStoredBytes(directory)
if stored >= settings.limit_mb * MEGABYTE { return .Full }
record_text := LearnRecordText(tool_directory, format, target, source, entry)
record_text := LearnRecordText(tool_directory, format, target, source, entry, zx_digest)
if record_text.count == 0 { return .Failed }
if !PkgMkdirs(folder) { return .Failed }
added: s64 = 0
@@ -383,9 +385,11 @@ LearnStatus :: () -> s32 {
#scope_export
LearnUsage :: () -> string { return PkgJoin(LEARN_USAGE, "\n") }
Learn :: (arguments: []string) -> s32 {
Learn :: (arguments: []string, launcher: string = "") -> s32 {
if arguments.count == 0 { return PkgFail(LEARN_USAGE) }
action := arguments[0]
if action == "verify" { return LearnTeacher(arguments, launcher) }
if action == "train" { return LearnTune(arguments, LearnDirectory()) }
if action == "status" {
if arguments.count != 1 { return PkgFail(LEARN_USAGE) }
return LearnStatus()
+159
View File
@@ -0,0 +1,159 @@
// Offline promotion of C-teacher proposals. The input is evidence, never code:
// only closed, independently tested rule families can enter the source table.
#import "package_common"
#import "compiler_learning_policy"
#import "compiler_learning_fixture"
#import "std/json_document"
#import "std/process_run_linux"
#import "std/text_tools"
#import "std/vec"
#scope_file
USAGE :: "usage: ziran learn verify --candidates FILE --repo DIR --output FILE";
Field :: (document: *JsonDocument, node: s32, name: string) -> string {
return TextDetach(JsonString(document, JsonMember(document, node, name)))
}
DigestFile :: (path: string) -> string {
file := PkgReadLimited(path, 268435456)
return ifx file.valid then PkgDigest(file.text) else ""
}
Identity :: (tools: string) -> string {
names := string.["ziran", "zi2c", "zi2zx", "zx2native"]
text: Vec(u8)
for name: names {
digest := DigestFile(PkgJoin3(tools, "/", name))
if digest.count != 64 { return "" }
BuilderAppend(text, digest)
}
return PkgDigest(BuilderFinish(text))
}
Run :: (arguments: []string, repo: string) -> PkgProcessResult {
names := string.["ZIRAN_LEARN", "DISPLAY", "WAYLAND_DISPLAY"]
values := string.["off", "", ""]
return PkgCaptureEnv(arguments, repo, names[:], values[:])
}
Succeeded :: (arguments: []string, repo: string) -> bool {
result := Run(arguments, repo)
if result.code == 0 { return true }
PkgPrint(PkgJoin3("learning verification failed: ", result.text, "\n"), true)
return false
}
RunFixture :: (executable: string, repo: string, output: string) -> bool {
command := string.["build-queue", "--", executable]
environment := string.["ZIRAN_LEARN=off", "DISPLAY", "WAYLAND_DISPLAY"]
options := ProcessOptions.{arguments = command[:], directory = repo,
environment = environment[:], output_path = output, merge_error = true}
run: ProcessRun
return RunProcess(options, *run) && run.code == 0
}
// Canonical order and fixed text make output independent of proposal ordering,
// wall time, corpus traversal, environment and the location of this checkout.
LearnTeacherTable :: (power: bool, scaled: bool, evidence: string, fixture: string) -> string {
parts := string.["// Generated by ziran learn verify; review and check in before use.\n",
"// Preconditions: integer modulo width, dead flags, no memory effects.\n",
"LearningTableVersion :: 1\nLearningVerifierVersion :: 1\nLearningTableTarget :: \"x86_64\"\n",
PkgJoin3("LearningTableEvidence :: \"", evidence, "\"\n"),
PkgJoin3("LearningTableFixture :: \"", fixture, "\"\n"),
PkgJoin3("LearningMultiplyPower :: ", ifx power then "1" else "0", "\n"),
PkgJoin3("LearningMultiplyScaledAdd :: ", ifx scaled then "1" else "0", "\n"),
"LearningLeafOperations :: 0\nLearningUnrollFactor :: 1\nLearningBlockLayout :: 1\nLearningAllocation :: 0\n"]
return TextDetach(TextJoin(parts[:], ""))
}
#scope_export
LearnTeacher :: (arguments: []string, launcher: string) -> s32 {
candidates: string; repo: string; output: string
index: s64 = 1
while index < cast(s64)arguments.count {
if index + 1 >= cast(s64)arguments.count { return PkgFail(USAGE) }
flag := arguments[index]; value := arguments[index + 1]
if flag == "--candidates" && candidates.count == 0 { candidates = value }
else if flag == "--repo" && repo.count == 0 { repo = value }
else if flag == "--output" && output.count == 0 { output = value }
else { return PkgFail(USAGE) }
index += 2
}
if candidates.count == 0 || repo.count == 0 || output.count == 0 { return PkgFail(USAGE) }
read := PkgReadLimited(candidates, 16777216)
document: JsonDocument
defer JsonReset(*document)
if !read.valid || !JsonRead(*document, read.text) { return PkgFail("cannot read teacher proposals") }
version, valid := JsonInteger(*document, JsonMember(*document, document.root, "schema_version"))
if !valid || version != 1 { return PkgFail("unsupported teacher proposal schema") }
artifact_keys := string.["native_sha256", "zx_sha256", "c_sha256"]
for key: artifact_keys {
digest := Field(*document, document.root, key)
if digest.count != 64 { return PkgFail("proposal lacks artifact identity") }
for byte: digest { if !(byte >= 48 && byte <= 57 || byte >= 97 && byte <= 102) { return PkgFail("invalid artifact digest") } }
}
proposals := JsonMember(*document, document.root, "candidates")
if JsonKindOf(*document, proposals) != .Array || JsonCount(*document, proposals) == 0 { return PkgFail("no teacher proposals") }
power: bool; scaled: bool
node := JsonFirst(*document, proposals)
while node >= 0 {
factor, known := JsonInteger(*document, JsonMember(*document, node, "factor"))
rule := LearningRuleForFactor(factor)
if !known || rule == .None || Field(*document, node, "rule") != "x86-multiply-constant" ||
Field(*document, node, "precondition") != "integer-modulo-width; flags-dead; no-memory" ||
Field(*document, node, "native").count == 0 || Field(*document, node, "teacher").count == 0 {
return PkgFail("unsupported rewrite or precondition; table unchanged")
}
if rule == .MultiplyPower { power = true } else { scaled = true }
node = JsonNext(*document, node)
}
if power && !LearningCheckFamily(.MultiplyPower) || scaled && !LearningCheckFamily(.MultiplyScaledAdd) {
return PkgFail("rewrite semantic preflight disagrees; table unchanged")
}
tools := PkgLauncherDirectory(launcher)
identity := Identity(tools)
if identity.count == 0 { return PkgFail("cannot identify verifier tools") }
work := PkgJoin(repo, "/build/learn-teacher")
if !PkgMkdirs(work) { return PkgFail("cannot create teacher verification directory") }
source := LearningFixtureSource()
fixture := PkgJoin(work, "/teacher_fixture.zi")
reference_directory := PkgJoin(work, "/reference")
reference := PkgJoin(reference_directory, "/teacher_fixture")
native := PkgJoin(work, "/native")
zx := PkgJoin(work, "/fixture.zx")
std := PkgJoin(repo, "/std")
if !PkgWriteAtomic(fixture, source) { return PkgFail("cannot write parity fixture") }
c_command := string.["build-queue", "--", PkgJoin(tools, "/zi2c"), "--exe", "--entry", "teacher_fixture:main", "--root", work,
"--module-path", std, "-o", reference_directory, fixture]
zx_command := string.["build-queue", "--", PkgJoin(tools, "/zi2zx"), "--root", work,
"--module-path", std, "--entry", "teacher_fixture:main", "-o", zx, fixture]
native_command := string.["build-queue", "--", PkgJoin(tools, "/zx2native"), "-o", native, zx]
if !Succeeded(c_command[:], repo) || !Succeeded(zx_command[:], repo) || !Succeeded(native_command[:], repo) { return 1 }
c_output := PkgJoin(work, "/reference.stdout")
native_output := PkgJoin(work, "/native.stdout")
if !RunFixture(reference, repo, c_output) || !RunFixture(native, repo, native_output) {
return PkgFail("C/native differential fixture failed; table unchanged")
}
expected := PkgReadLimited(c_output, 16777216)
actual := PkgReadLimited(native_output, 16777216)
lines: s64
for byte: expected.text { if byte == 10 { lines += 1 } }
if !expected.valid || !actual.valid || lines != 70210 || expected.text != actual.text {
return PkgFail("C/native disagreement; table unchanged")
}
parity := string.["build-queue", "--", "make", "-j1", "check", "CHECK_FILTER=zx_lowered_parity"]
if !Succeeded(parity[:], repo) { return 1 }
if Identity(tools) != identity { return PkgFail("verifier compiler changed; table unchanged") }
table := LearnTeacherTable(power, scaled, PkgDigest(read.text), PkgDigest(source))
certificate: JsonDocument
defer JsonReset(*certificate)
root := JsonNewObject(*certificate)
JsonSet(*certificate, root, "schema_version", JsonNewInteger(*certificate, 1))
JsonSet(*certificate, root, "compiler_identity", JsonNewStringCopy(*certificate, identity))
JsonSet(*certificate, root, "evidence_sha256", JsonNewStringCopy(*certificate, PkgDigest(read.text)))
JsonSet(*certificate, root, "fixture_sha256", JsonNewStringCopy(*certificate, PkgDigest(source)))
JsonSet(*certificate, root, "parity_list_sha256", JsonNewStringCopy(*certificate, DigestFile(PkgJoin(repo, "/tests/zx_parity_list.zi"))))
JsonSet(*certificate, root, "table_sha256", JsonNewStringCopy(*certificate, PkgDigest(table)))
JsonSet(*certificate, root, "verified", JsonNewBool(*certificate, true))
if !PkgWriteAtomic(PkgJoin(output, ".verification.json"), TextDetach(JsonWrite(*certificate, root, JsonPythonStyle(2)))) {
return PkgFail("cannot save verification certificate; table unchanged")
}
if !PkgWriteAtomic(output, table) { return PkgFail("cannot save verified source table") }
PkgPrint("Verified teacher rules: 34 factors, 17 boundary and 2048 random inputs at eight widths, plus retained parity fixtures. Review and check in the deterministic table before rebuilding.\n", false)
return 0
}
+254
View File
@@ -0,0 +1,254 @@
// Offline policy selection from measured, checksum-verified corpus artifacts.
#import "package_common"
#import "compiler_learning_policy"
#import "compiler_learning_tuning"
using Bundle :: #import "compiler_bundle"
using IR :: #import "compiler_lowered_ir"
#import "std/json_document"
#import "std/file_linux"
#import "std/number_text"
#import "std/text_tools"
#import "std/vec"
#scope_file
USAGE :: "usage: ziran learn train --measurements FILE --table FILE --verification FILE --output FILE";
Field :: (document: *JsonDocument, node: s32, name: string) -> string {
return TextDetach(JsonString(document, JsonMember(document, node, name)))
}
Integer :: (document: *JsonDocument, node: s32, name: string) -> s64 {
value, valid := JsonInteger(document, JsonMember(document, node, name))
return ifx valid then value else -1
}
Number :: (value: s64) -> string { digits: [32]u8; return PkgJoin("", FormatInteger(value, digits[:])) }
Digest :: (path: string) -> string {
arguments := string.["sha256sum", "--", path]
result := PkgCapture(arguments[:], "")
return ifx result.code == 0 && result.text.count >= 64 then result.text[:64] else ""
}
Relative :: (path: string) -> bool {
if path.count == 0 || path[0] == cast(u8)47 { return false }
parts := TextSplit(path, "/")
defer VecFree(parts)
for part: parts { if part == "." || part == ".." || part.count == 0 { return false } }
return true
}
FileBytes :: (path: string) -> s64 {
file := OpenRead(path)
if !file.valid { return -1 }
size := FileSize(file)
CloseFile(file)
return size
}
// Corpus records identify artifacts through their names, rather than mutable
// source paths. Validate the current format, exact native compiler, ZX and ELF
// digests, and the map's complete-ELF identity before accepting a timing row.
Artifact :: (row: s32, document: *JsonDocument, corpus: string) -> bool {
relative := Field(document, row, "corpus_record")
suffix := ".record.json"
if !Relative(relative) || !TextHasSuffix(relative, suffix) { return false }
path := PkgJoin3(corpus, "/", relative)
record := PkgReadLimited(path, 8192)
metadata: JsonDocument
defer JsonReset(*metadata)
if !record.valid || !JsonRead(*metadata, record.text) { return false }
format := PkgJoin3("zx", Number(ExecutableVersionNumber()), PkgJoin("-lir", Number(LirVersion)))
if Field(*metadata, metadata.root, "format") != format ||
Field(*metadata, metadata.root, "target") != "x86_64" ||
Field(*metadata, metadata.root, "platform") != "linux" ||
Field(*metadata, metadata.root, "input_sha256").count != 64 ||
Field(*metadata, metadata.root, "input_sha256") != Field(document, row, "input_sha256") ||
Field(*metadata, metadata.root, "zx2native_sha256") != Field(document, row, "compiler_sha256") { return false }
stem := path[:path.count - suffix.count]
elf := PkgJoin(stem, ".elf")
parent := TextFindLast(path, "/")
if parent < 0 { return false }
zx := PkgJoin(path[:parent], "/program.zx")
native_digest := Field(document, row, "native_sha256")
zx_digest := Field(document, row, "zx_sha256")
portable := PkgReadLimited(zx, 16777216)
if !portable.valid { return false }
assets: [0]Asset
decoded := ExecutableDecode(portable.text, assets[:])
if decoded.problem != .None || decoded.program.count < 12 || decoded.program[:4] != "ZLIR" { return false }
schema: u64
for byte: 0..3 { schema |= cast(u64)decoded.program[8 + byte] << cast(u64)(byte * 8) }
if schema != cast(u64)LirVersion || native_digest.count != 64 || zx_digest.count != 64 ||
Digest(elf) != native_digest || PkgDigest(portable.text) != zx_digest ||
FileBytes(elf) != Integer(document, row, "code_bytes") { return false }
// Map metadata precedes the large ranges array. Read only that bounded
// prefix; old/unknown map layouts fail closed instead of loading megabytes.
command := string.["head", "-c", "4096", PkgJoin(stem, ".map.json")]
prefix := PkgCapture(command[:], "")
cut := TextFind(prefix.text, ",\"ranges\":")
if prefix.code != 0 || cut < 0 || !JsonRead(*metadata, PkgJoin(prefix.text[:cut], "}")) { return false }
identity := JsonMember(*metadata, metadata.root, "identity")
return Field(*metadata, metadata.root, "format") == "ziran-native-map" &&
Field(*metadata, metadata.root, "target") == "x86_64-linux" &&
Field(*metadata, identity, "algorithm") == "sha256" &&
Field(*metadata, identity, "scope") == "complete-elf" &&
Field(*metadata, identity, "digest") == native_digest
}
ReadSelection :: (document: *JsonDocument, corpus: string) -> LearningSelection {
if Integer(document, document.root, "schema_version") != 1 ||
Field(document, document.root, "target") != "x86_64-linux" ||
Field(document, document.root, "learning") != "off" ||
JsonKindOf(document, JsonMember(document, document.root, "checks")) != .False { return .{} }
host := Field(document, document.root, "host")
epoch := Field(document, document.root, "source_epoch_sha256")
measurements := JsonMember(document, document.root, "measurements")
count := JsonCount(document, measurements)
if JsonKindOf(document, measurements) != .Array || count < 2 || count > 128 { return .{} }
samples: Vec(s64)
defer VecFree(samples)
// Fill storage completely before borrowing slices into observation rows.
for index: cast(s32)0..count - 1 {
row := JsonElement(document, measurements, index)
keys := string.["native_ns", "c_ns"]
for key: keys {
array := JsonMember(document, row, key)
size := JsonCount(document, array)
if JsonKindOf(document, array) != .Array || size < 11 || size > 4096 { return .{} }
for sample: cast(s32)0..size - 1 {
value, valid := JsonInteger(document, JsonElement(document, array, sample))
if !valid || !VecPush(samples, value) { return .{} }
}
}
}
observations: Vec(LearningObservation)
defer VecFree(observations)
offset: s64
for index: cast(s32)0..count - 1 {
row := JsonElement(document, measurements, index)
if Field(document, row, "checksum").count == 0 ||
Field(document, row, "checksum") != Field(document, row, "c_checksum") || !Artifact(row, document, corpus) { return .{} }
policy := JsonMember(document, row, "policy")
selected := LearningTuning.{leaf_operations = cast(s32)Integer(document, policy, "leaf_operations"),
unroll_factor = cast(s32)Integer(document, policy, "unroll_factor"),
block_layout = cast(s32)Integer(document, policy, "block_layout"),
allocation = cast(s32)Integer(document, policy, "allocation")}
if !LearningTuningValid(selected) { return .{} }
// Reject out-of-range integers before narrowing can turn them legal.
keys := string.["leaf_operations", "unroll_factor", "block_layout", "allocation"]
for key: keys { if Integer(document, policy, key) < 0 || Integer(document, policy, key) > 1 { return .{} } }
native_count := JsonCount(document, JsonMember(document, row, "native_ns"))
c_count := JsonCount(document, JsonMember(document, row, "c_ns"))
observation := LearningObservation.{workload = Field(document, row, "workload"),
input = Field(document, row, "input_sha256"), artifact = Field(document, row, "native_sha256"), host = host, source_epoch = epoch,
policy = selected, bytes = Integer(document, row, "code_bytes"),
native_ns = VecSlice(samples, offset, offset + native_count), c_ns = VecSlice(samples, offset + native_count, offset + native_count + c_count)}
if !VecPush(observations, observation) { return .{} }
offset += native_count + c_count
}
return LearningSelect(VecSlice(observations, 0, observations.count))
}
// Rewrite only the four policy constants in an already verified rule table.
// Proposal data can never supply optimizer source or alter enabled rules.
PolicyTable :: (table: string, policy: LearningTuning, evidence: string) -> string {
lines := TextLines(table)
defer VecFree(lines)
output: Vec(u8)
mask: s32
for line: lines {
key: string; value: s32; bit: s32
if TextHasPrefix(line, "LearningLeafOperations :: ") { key = "LearningLeafOperations"; value = policy.leaf_operations; bit = 1 }
else if TextHasPrefix(line, "LearningUnrollFactor :: ") { key = "LearningUnrollFactor"; value = policy.unroll_factor; bit = 2 }
else if TextHasPrefix(line, "LearningBlockLayout :: ") { key = "LearningBlockLayout"; value = policy.block_layout; bit = 4 }
else if TextHasPrefix(line, "LearningAllocation :: ") { key = "LearningAllocation"; value = policy.allocation; bit = 8 }
else if TextHasPrefix(line, "LearningTuningEvidence :: ") { continue }
if bit != 0 {
if (mask & bit) != 0 { VecFree(output); return "" }
mask |= bit
BuilderAppend(output, key); BuilderAppend(output, " :: "); BuilderAppend(output, Number(value))
} else { BuilderAppend(output, line) }
BuilderAppend(output, "\n")
}
if mask != 15 { VecFree(output); return "" }
BuilderAppend(output, PkgJoin3("LearningTuningEvidence :: \"", evidence, "\"\n"))
return TextDetach(BuilderFinish(output))
}
// Raw samples stay in the digest-bound input. Save every excluded index and
// median too, so table selection can be audited without rerunning a benchmark.
Receipt :: (input: *JsonDocument, selection: LearningSelection, evidence: string, table: string) -> string {
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
JsonSet(*document, root, "schema_version", JsonNewInteger(*document, 1))
JsonSet(*document, root, "selected_policy", JsonNewInteger(*document, LearningPolicyId(selection.policy)))
JsonSet(*document, root, "measurements_sha256", JsonNewStringCopy(*document, evidence))
JsonSet(*document, root, "table_sha256", JsonNewStringCopy(*document, PkgDigest(table)))
JsonSet(*document, root, "method", JsonNewStringCopy(*document,
"symmetric inclusive-quartile 1.5 IQR; equal artifacts share lowest-policy timings; ties by bytes then policy ID"))
rows := JsonNewArray(*document)
JsonSet(*document, root, "observations", rows)
measurements := JsonMember(input, input.root, "measurements")
for index: cast(s32)0..JsonCount(input, measurements) - 1 {
source := JsonElement(input, measurements, index)
row := JsonNewObject(*document)
unused JsonAppend(*document, rows, row)
JsonSet(*document, row, "workload", JsonNewStringCopy(*document, Field(input, source, "workload")))
JsonSet(*document, row, "native_sha256", JsonNewStringCopy(*document, Field(input, source, "native_sha256")))
keys := string.["native_ns", "c_ns"]
for key: keys {
values: Vec(s64)
array := JsonMember(input, source, key)
for at: cast(s32)0..JsonCount(input, array) - 1 {
value, valid := JsonInteger(input, JsonElement(input, array, at))
if !valid || !VecPush(values, value) { VecFree(values); return "" }
}
statistics := LearningAnalyze(values[:])
VecFree(values)
if !statistics.valid { VecFree(statistics.excluded); return "" }
entry := JsonNewObject(*document)
JsonSet(*document, row, key, entry)
JsonSet(*document, entry, "median_twice", JsonNewInteger(*document, statistics.median_twice))
excluded := JsonNewArray(*document)
JsonSet(*document, entry, "excluded_indices", excluded)
for at: statistics.excluded { unused JsonAppend(*document, excluded, JsonNewInteger(*document, at)) }
VecFree(statistics.excluded)
}
}
return TextDetach(JsonWrite(*document, root, JsonPythonStyle(2)))
}
#scope_export
LearnTune :: (arguments: []string, corpus: string) -> s32 {
measurements: string; table: string; verification: string; output: string
index: s64 = 1
while index < cast(s64)arguments.count {
if index + 1 >= cast(s64)arguments.count { return PkgFail(USAGE) }
flag := arguments[index]; value := arguments[index + 1]
if flag == "--measurements" && measurements.count == 0 { measurements = value }
else if flag == "--table" && table.count == 0 { table = value }
else if flag == "--verification" && verification.count == 0 { verification = value }
else if flag == "--output" && output.count == 0 { output = value }
else { return PkgFail(USAGE) }
index += 2
}
if measurements.count == 0 || table.count == 0 || verification.count == 0 || output.count == 0 || corpus.count == 0 { return PkgFail(USAGE) }
timings := PkgReadLimited(measurements, 16777216)
approved := PkgReadLimited(table, 65536)
certificate := PkgReadLimited(verification, 8192)
document: JsonDocument
defer JsonReset(*document)
if !approved.valid || !certificate.valid || !JsonRead(*document, certificate.text) ||
Integer(*document, document.root, "schema_version") != 1 ||
JsonKindOf(*document, JsonMember(*document, document.root, "verified")) != .True ||
Field(*document, document.root, "table_sha256") != PkgDigest(approved.text) {
return PkgFail("rule table lacks its matching verification certificate")
}
if !timings.valid || !JsonRead(*document, timings.text) { return PkgFail("cannot read policy measurements") }
selected := ReadSelection(*document, corpus)
if !selected.valid { return PkgFail("unverified, incomplete or incompatible policy measurements; table unchanged") }
generated := PolicyTable(approved.text, selected.policy, PkgDigest(timings.text))
if generated.count == 0 { return PkgFail("cannot generate policy table") }
receipt := Receipt(*document, selected, PkgDigest(timings.text), generated)
if receipt.count == 0 || !PkgWriteAtomic(PkgJoin(output, ".training.json"), receipt) { return PkgFail("cannot write training receipt; table unchanged") }
if !PkgWriteAtomic(output, generated) { return PkgFail("cannot write policy table") }
PkgPrint(PkgJoin3("Selected deterministic policy ", Number(LearningPolicyId(selected.policy)),
" from checksum-verified current-format corpus timings; rebuild and run parity before promotion.\n"), false)
return 0
}
+16
View File
@@ -61,6 +61,22 @@ corpus (1024 MB by default), `ziran learn status` shows its size and each
format's programs and records, `ZIRAN_LEARN=on|off` overrides the switch and
`ZIRAN_LEARN_DIR=DIR` moves the corpus.
`ziran learn verify --candidates FILE --repo DIR --output FILE` validates the
C teacher's closed integer rewrite proposals against generated C, boundary and
deterministic random inputs, and the retained parity fixtures. A disagreement
leaves the table unchanged. `bench/bench.zi -- c-teacher` produces the assembly
comparison, sampled rankings and candidate files.
`ziran learn train --measurements FILE --table FILE --verification FILE
--output FILE` selects implemented policies from paired timing receipts joined
to current-format corpus artifacts. It checks the compiler, ZX, ELF and native
map identities, equal C/native checksums, learning-off measurements, common
host and source epoch. It retains symmetric 1.5×IQR filtering and deterministic
size/policy tie breaking. Unsupported unroll and allocation choices are refused.
Review the generated source table, rebuild and run parity before checking it in.
Normal builds use only the versioned table in `cmd/compiler_learning_table.zi`;
recording and offline training never change a running compiler's policy.
Use `ziran run app.zx` for both console and graphical programs. The linker
includes the reachable code of imported modules, including a UI library.
Platform effects such as windows and input are supplied by an installed runtime
+67 -45
View File
@@ -16,55 +16,77 @@ smaller. A learner proposes changes and keeps what passes; it never needs to
understand English. Nothing learned reaches the compiler without passing the
verifier and the tests.
## Current baseline (where machine learning can help)
Owner, verbatim: "analyze the assembly c genrates leran form it to improve natiev assembyl to we have some machine lerlanig or leraning stuff maybe we can enhance it to leran to improve everytihng".
Alpha physical host, `bench/results/wasm-tier-alpha-2026-11-15-records.json`,
revision `77a7ef04`, 2026-11-15T23:27Z, median of 11 samples after 1.5×IQR.
## Open work
| Kernel | C ms | Native ELF ms | Native/C |
| --- | ---: | ---: | ---: |
| Sieve | .0336 | .1432 | 4.3 |
| Records | .0130 | .0611 | 4.7 |
| Hash | .0282 | .1041 | 3.7 |
| Vectors | .0376 | .9677 | 25.8 |
| Calls | .0111 | .0067 | 0.6 (constant-folded) |
| Printing | .0098 | .3294 | 33.8 |
### Remaining C teacher work (2026-11-16)
Records went from 297× C to 4.7× today. The open native-speed lanes own the
remaining Vectors and Printing gaps, which are structural compiler work. The
learner is a parallel track for the remaining 5–20% and for code size, not a
replacement for that plan. Always re-read the newest receipt before comparing.
- Keep future teacher comparisons on a fixed compiler/source epoch. Guard
launcher, zi2c, zi2zx, zx2native, zx2wasm, libziran and harness digests before
and after each finite measurement. Preserve raw disassembly, native map
identity, C parity, SIGPROF IP counts and zero-sample uncertainty. Compare
the kernel and warm-widget receipts separately from sampled startup costs.
- Turn ranked candidates into general transformations. Keep allocation,
aggregate work with the records lane; keep SSA, loop rotation, LICM,
induction variables and strength reduction with the loop lane, vector push
with the records lane, and SIMD reduction with the vectorizer lane, following
the parent's updated assignment. Keep widget/host calls with the
widget lane. Use the teacher's selected scalar idioms and bounded leaf
inliner as the starting point for further measured, parity-covered work.
- Extend `ziran learn` mining beyond constant multiplication. Mine bounded native
machine/LIR windows paired with C idioms from current-format corpus records,
grouped by exact compiler and target. A shorter sequence is a proposal,
never proof. Match widths, signedness, live flags, memory effects, traps and
register constraints; reject unknown semantics and every disagreement.
Acceptance requires proof or deterministic edge/random input differential
execution against generated C plus the retained parity fixtures. The closed
multiply families already have this gate; widen the vocabulary only with
explicit semantics and new parity fixtures. Bind every future candidate to
the corpus ZX, ELF, map and exact compiler identities.
- Harden promotion of the versioned Ziran source table. Record each rule's
semantic preconditions and verifier/test identity. Unknown table versions,
targets or unsupported rule IDs fail closed. Compilation reads only the
checked-in table, with no corpus, clock, random source or online training;
`ZIRAN_LEARN=off` disables recording; explicit offline verify/train commands
remain available and cannot alter the compiler already running.
- Extend measured selection beyond the first bounded leaf calibration: unroll
choices, block layout and allocation policies. The six-kernel leaf comparison
emitted identical artifacts at thresholds zero and one, so the learned table
retains threshold zero. Recalibrate after SSA exposes eligible source-level
leaves. Join corpus artifacts to
checksum-verified timing receipts by digest; compare on one host with the
same input and compiler, retain raw samples and symmetric 1.5×IQR exclusions,
and break ties deterministically by size then policy ID. Treat identical
native artifacts as one experiment so timing noise cannot select a policy.
`ziran learn train` already validates corpus identities and writes deterministic
source plus an exclusion receipt; add more measured legal strategies. Keep correctness
verification independent of speed scores. Serialize the selected choices
into the same reviewed source table; never load a mutable user policy during
ordinary compilation. Scalar leaf inlining and block layout have consumers;
measure both settings before changing the baseline. Reject unroll factors
other than one and allocation policies other than zero until their owning
passes expose alternate, parity-covered legal strategies. The current
allocator has exactly one verified strategy; never revive its removed retry
path as a tuning choice. Use integer-nanosecond samples and exact interpolated
quartiles so filtering does not depend on floating-point rounding.
- Keep future before/after measurements on physical Alpha, following the
parent's updated host instruction, through `build-queue` and `bench/bench.zi`
with learning off. Serialize Alpha benchmarks across lanes and never reset
its checkout during another lane's run. Record the measured pushed revision,
source/artifact digests and raw samples. Builds and local tests stay on Omega.
Revalidate integrated changes with parity, `make check` and
`make check-bootstrap`; a source change during a run requires a new
checkpoint for that change. Commit only each lane's hunks after local
validation, then push; preserve the shared index and other lanes' edits.
## Hardware
- Alpha: NVIDIA RTX 5060 Ti, 16 GB, driver 595.99.02, idle. The CUDA toolkit
(`nvcc`) is not installed. Alpha has 15 GB RAM, often about 5 GB free, and it
is also the benchmark host: training must not run while a benchmark is
measuring, or it adds noise to the receipts.
- Omega: 32 cores, 30 GB RAM. Corpus processing and CPU search run here.
- Ziran has no GPU backend yet (`#parallel_gpu` is a named gap on every target).
## Steps
Recording already exists: `ziran learn on|off|status` (`cmd/package_learn.zi`,
documented in `docs/ZX.md`), on by default, deduplicated by SHA-256 and capped.
Benchmarks run through `bench/bench.zi`, which sets `ZIRAN_LEARN=off`; every new
recording hook must keep honoring that switch. Records are filed per ZX format
(`zx<R>-lir<S>/`) and each carries a `.record.json` naming the exact compiler
(SHA-256 of `zx2native` and `zi2zx`), source, entry and time, so compiler
upgrades and ZX revisions never mix: step 2 and later read only the current
format and group machine code by compiler. A ZX revision bump leaves older
folders unreadable to the new tools; their `source` lets a program be rebuilt.
The ZX byte format is fully specified (`ASSEMBLY/zx-executable-format.md` for
the container, `ASSEMBLY/lowered-format.md` for the instruction payload), but
the meaning of each instruction is not: 25 of the 46 `LirOp` opcodes are named
nowhere in the docs, and `execution-contract.md` covers them only by category.
A per-opcode reference (operands, types, traps, effects) is what step 2's
equivalence checking needs as its written ground truth.
The owner's `ziran` must be reinstalled (`make install-user`) whenever the
recorder changes; the 14:44 install on 2026-11-15 had no `learn` at all.
Keep future corpus work on current `zx<R>-lir<S>` records and exact compiler
identities. A format upgrade must not reinterpret older records; use their
source/entry metadata to rebuild them. Extend the per-opcode execution contract
before widening the learner's semantic vocabulary. Every new recording hook
must honor `ZIRAN_LEARN=off`; benchmark timing must never perform recording.
Update the owner's installed launcher when changes to recording/training are
accepted, and verify that installation independently of builds and pushes.
### 1. Record more of real use
+14
View File
@@ -59,6 +59,20 @@ version), the source and entry and the Unix time. <code>--limit-mb N</code> caps
corpus (1024 MB by default), <code>ziran learn status</code> shows its size and each
format's programs and records, <code>ZIRAN_LEARN=on|off</code> overrides the switch and
<code>ZIRAN_LEARN_DIR=DIR</code> moves the corpus.</p>
<p><code>ziran learn verify --candidates FILE --repo DIR --output FILE</code> validates the
C teacher's closed integer rewrite proposals against generated C, boundary and
deterministic random inputs, and the retained parity fixtures. A disagreement
leaves the table unchanged. <code>bench/bench.zi -- c-teacher</code> produces the assembly
comparison, sampled rankings and candidate files.</p>
<p><code>ziran learn train --measurements FILE --table FILE --verification FILE
--output FILE</code> selects implemented policies from paired timing receipts joined
to current-format corpus artifacts. It checks the compiler, ZX, ELF and native
map identities, equal C/native checksums, learning-off measurements, common
host and source epoch. It retains symmetric 1.5×IQR filtering and deterministic
size/policy tie breaking. Unsupported unroll and allocation choices are refused.
Review the generated source table, rebuild and run parity before checking it in.
Normal builds use only the versioned table in <code>cmd/compiler_learning_table.zi</code>;
recording and offline training never change a running compiler's policy.</p>
<p>Use <code>ziran run app.zx</code> for both console and graphical programs. The linker
includes the reachable code of imported modules, including a UI library.
Platform effects such as windows and input are supplied by an installed runtime
+66
View File
@@ -0,0 +1,66 @@
#import, file "../bench/c_teacher_assembly.zi";
#import, file "../bench/c_teacher_rules.zi";
#import, file "../cmd/compiler_learning_policy.zi";
#import, file "../cmd/compiler_learning_fixture.zi";
#import "std/text_tools"
#import "compiler_learning_tuning_cases"
#import "std/vec"
#program_export
main :: () -> s32 {
tuning := LearningTuningCases()
if tuning != 0 { print("learning tuning case % failed\n", tuning); return 1 }
text := #string ASM
0000000000000010 <demo_Loop>:
10: mov rax,QWORD PTR [rsp+0x8]
15: mov rcx,0x7
1a: mov BYTE PTR [rdi+rax*2],0x1
20: add rax,0x1
24: cmp rax,rcx
27: jl 0x1a <demo_Loop+0xa>
29: jne 15 <demo_Loop+0x5>
2b: mov QWORD PTR [rbp-0x8],rax
30: call 50 <demo_Leaf>
35: ret
0000000000000050 <demo_Leaf>:
50: mov eax,0x1
55: ret
ASM;
instructions := TeacherInstructions(text)
symbols := TeacherSymbols(text)
if instructions.count != 12 || symbols.count != 2 || symbols[0].end != 80 { return 1 }
metrics := TeacherMeasure(VecSlice(instructions, 0, instructions.count), 16, 80)
if metrics.instructions != 10 || metrics.back_edges != 2 || metrics.loop_instructions != 6 ||
metrics.stack_reads != 1 || metrics.stack_writes != 1 || metrics.calls != 1 ||
metrics.indexed != 1 || metrics.branches != 2 || metrics.loop_constants != 3 { return 2 }
loops := TeacherLoops(VecSlice(instructions, 0, instructions.count), 16, 80)
if loops.count != 2 || loops[0].begin != 26 || loops[0].end != 39 || loops[0].instructions != 4 { return 9 }
value, valid := TeacherHex("7fffffffffffffff")
if !valid || value != 9223372036854775807 { return 3 }
value, valid = TeacherHex("8000000000000000")
if valid { return 4 }
value, valid = TeacherHex("not-code")
if valid { return 5 }
empty := TeacherInstructions("a file header\n 00: (bad)\n xyz: ret\n")
if empty.count != 0 { return 6 }
sized := TeacherSizedSymbols("00000010 00000003 T real_fn\n00000020 00000000 T empty_fn\n00000030 00000004 D data\n")
if sized.count != 1 || sized[0].begin != 16 || sized[0].end != 19 { return 7 }
if TeacherIRBinding("library/metrics:Width=host:Width") != "metrics:Width=host:Width" ||
TeacherIRBinding("plain:Read=other/path:Write") != "plain:Read=path:Write" ||
TeacherIRBinding("invalid") != "" { return 8 }
if TeacherLeaFactor("rax,[rdx+rdx*2]") != 3 || TeacherLeaFactor("rax,[rdx+rcx*2]") != 0 ||
TeacherLeaFactor("rax,[rdx+rdx*2+0x8]") != 0 { return 10 }
native := TeacherInstructions("10: imul rax,rax,0x20\n20: imul rbx,rbx,0x3\n30: ret\n")
teacher := TeacherInstructions("50: shl rdx,0x5\n60: lea rcx,[rdi+rdi*2]\n70: ret\n")
rules := TeacherMineRewrites(VecSlice(native, 0, native.count), 16, 49,
VecSlice(teacher, 0, teacher.count), 80, 113)
if rules.count != 2 || rules[0].factor != 32 || rules[1].factor != 3 { return 11 }
if LearningRuleForFactor(7) != .None || LearningRuleForFactor(-3) != .None ||
!LearningCheckFamily(.MultiplyPower) || !LearningCheckFamily(.MultiplyScaledAdd) ||
LearningCheckFamily(.None) { return 12 }
source := LearningFixtureSource()
if source != LearningFixtureSource() || !TextContains(source, "cast(s8)x * cast(s8)1073741824") ||
!TextContains(source, "for iteration: 0..2047") { return 13 }
print("C teacher: function boundaries, loops, candidates, rewrite semantics and deterministic parity fixture\n")
return 0
}
+2 -2
View File
@@ -66,7 +66,7 @@ PlanChecks :: (checks: []CheckCase) -> Vec(s64) {
// Ziran case files that drive the compiler named by their first argument.
CheckCompilerCase :: (name: string) -> bool {
return name == "module_parameters_cases.zi" || name == "insert_source_cases.zi" ||
name == "std_environment_cases.zi" || name == "std_input_cases.zi"
name == "std_environment_cases.zi" || name == "std_input_cases.zi" || name == "c_teacher_cases.zi"
}
CheckArguments :: (name: string, bin: string, repo: string) -> Vec(string) {
@@ -151,7 +151,7 @@ DiscoverChecks :: (repo: string, bin: string, filter: string) -> Vec(CheckCase)
checks: Vec(CheckCase)
tests := CheckPath(repo, "tests")
compiler_cases := string.["module_parameters_cases.zi", "insert_source_cases.zi",
"std_environment_cases.zi", "std_input_cases.zi"]
"std_environment_cases.zi", "std_input_cases.zi", "c_teacher_cases.zi"]
for name: compiler_cases {
if TextContains(name, filter) { VecPush(checks, CheckCase.{.name = name, .cost = 2}) }
}
+45
View File
@@ -0,0 +1,45 @@
#import, file "../cmd/compiler_learning_tuning.zi";
#import, file "../cmd/compiler_learning_policy.zi";
#import "std/vec"
LearningTuningCases :: () -> s32 {
samples := s64.[1000, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1]
statistics := LearningAnalyze(samples[:])
defer VecFree(statistics.excluded)
if !statistics.valid || statistics.median_twice != 20 || statistics.excluded.count != 2 ||
statistics.excluded[0] != 0 || statistics.excluded[1] != 10 { return 1 }
too_few := LearningAnalyze(samples[:10])
defer VecFree(too_few.excluded)
if too_few.valid { return 2 }
c := s64.[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
fast := s64.[200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
slow := s64.[400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400]
digest := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
rows := LearningObservation.[
.{workload = "b", input = digest, host = "omega", source_epoch = digest,
policy = .{unroll_factor = 1, block_layout = 1}, bytes = 100, native_ns = slow[:], c_ns = c[:]},
.{workload = "a", input = digest, host = "omega", source_epoch = digest,
policy = .{leaf_operations = 1, unroll_factor = 1, block_layout = 1}, bytes = 90, native_ns = fast[:], c_ns = c[:]},
.{workload = "a", input = digest, host = "omega", source_epoch = digest,
policy = .{unroll_factor = 1, block_layout = 1}, bytes = 100, native_ns = slow[:], c_ns = c[:]},
.{workload = "b", input = digest, host = "omega", source_epoch = digest,
policy = .{leaf_operations = 1, unroll_factor = 1, block_layout = 1}, bytes = 90, native_ns = fast[:], c_ns = c[:]}]
selected := LearningSelect(rows[:])
if !selected.valid || selected.score != 4.0 || selected.bytes != 180 || LearningPolicyId(selected.policy) != 3 { return 3 }
incomplete := LearningSelect(rows[:3])
if !incomplete.valid || LearningPolicyId(incomplete.policy) != 1 { return 4 }
rows[3].host = "other-host"
if LearningSelect(rows[:]).valid { return 5 }
rows[3].host = "omega"
rows[3].policy.unroll_factor = 2
if LearningSelect(rows[:]).valid { return 6 }
rows[3].policy.unroll_factor = 1
for index: 0..rows.count - 1 { rows[index].artifact = digest }
selected = LearningSelect(rows[:])
if !selected.valid || LearningPolicyId(selected.policy) != 3 { return 7 }
// Equal bytes also tie at the same size; lowest policy wins despite noise.
rows[1].bytes = 100; rows[3].bytes = 100
selected = LearningSelect(rows[:])
if !selected.valid || LearningPolicyId(selected.policy) != 1 { return 8 }
return 0
}
+3
View File
@@ -5,6 +5,7 @@ using IR :: #import "compiler_lowered_ir"
using Opt :: #import "compiler_opt"
using Exec :: #import "compiler_exec"
using Vectors :: #import "std/vec"
using Inlining :: #import "compiler_opt_inline_cases"
using FloatFolds :: #import "compiler_opt_float_cases"
OptInstruction :: (op: LirOp, result: s32, operands: []s32,
@@ -224,6 +225,8 @@ OptRegressionCases :: () -> s32 {
}
main :: (argc: s32, argv: **u8) -> s32 {
inline_result := InlineCases()
if inline_result != 0 { print("leaf inline case % failed\n", inline_result); return 1 }
floats := OptFloatCases()
if floats != 0 { print("float fold case % failed\n", floats); return 1 }
regression := OptRegressionCases()
+49
View File
@@ -0,0 +1,49 @@
using IR :: #import "compiler_lowered_ir"
using Verify :: #import "compiler_lowered_verify"
using Inline :: #import "compiler_opt_inline"
InlineCases :: () -> s32 {
types := LirType.[.{kind = .Void}, .{kind = .Integer, bits = 64}]
modules := string.["inline"]
constants := LirConstant.[.{type = 1, bits = 3}, .{type = 1, bits = 5}]
values := s32.[1, 1, 1]
parameters := s32.[1, 1]
arguments := s32.[0, 1]
returned := s32.[2]
caller_code := LirInstruction.[
.{op = .Constant, result = 0, symbol = 0, origin = -1},
.{op = .Constant, result = 1, symbol = 1, origin = -1},
.{op = .Call, result = 2, operands = arguments[:], symbol = 1, effect = 1, origin = -1},
.{op = .Return, result = -1, operands = returned[:], symbol = -1, origin = -1}]
callee_arguments := s32.[0, 1]
entry_parameters := s32.[0, 1]
callee_code := LirInstruction.[
.{op = .Add, result = 2, operands = callee_arguments[:], symbol = -1, origin = -1},
.{op = .Return, result = -1, operands = returned[:], symbol = -1, origin = -1}]
caller_blocks := LirBlock.[.{instructions = caller_code[:]}]
callee_blocks := LirBlock.[.{parameters = entry_parameters[:], instructions = callee_code[:]}]
functions := LirFunction.[
.{module = 0, name = "main", result = 1, values = values[:], blocks = caller_blocks[:], entry = 0, origin = -1},
.{module = 0, name = "add", parameters = parameters[:], result = 1, values = values[:], blocks = callee_blocks[:], entry = 0, origin = -1}]
program := LirProgram.{version = LirVersion, modules = modules[:], types = types[:],
constants = constants[:], functions = functions[:], entry = 0}
if LirVerify(program, LirDefaultLimits()).problem != .None { return 1 }
disabled := LirInlineLeaves(program, 0, 1000)
if disabled.calls != 0 || caller_code[2].op != .Call { return 2 }
limited := LirInlineLeaves(program, 1, 0)
if !limited.limited || caller_code[2].op != .Call { return 3 }
// A trapping operator is never a leaf candidate.
program.functions[1].blocks[0].instructions[0].op = .Divide
rejected := LirInlineLeaves(program, 1, 1000)
if rejected.calls != 0 || caller_code[2].op != .Call { return 4 }
program.functions[1].blocks[0].instructions[0].op = .Subtract
// Reverse parameters to catch operand-renaming mistakes.
program.functions[1].blocks[0].instructions[0].operands[0] = 1
program.functions[1].blocks[0].instructions[0].operands[1] = 0
inlined := LirInlineLeaves(program, 1, 1000)
if inlined.limited || inlined.calls != 1 || caller_code[2].op != .Subtract ||
caller_code[2].effect != 0 || caller_code[2].operands[0] != 1 ||
caller_code[2].operands[1] != 0 || caller_code[2].result != 2 { return 5 }
if LirVerify(program, LirDefaultLimits()).problem != .None { return 6 }
return 0
}
+8
View File
@@ -117,6 +117,14 @@ main :: (argc: s32, argv: **u8) -> s32 {
bad := string.["learn", "on", "--limit-mb", "0"]
unused PackageCommand(*test, root, bad[:], false)
if test.failed { return 1 }
// Unknown teacher semantics cannot overwrite an existing approved table.
proposal := CheckPath(root, "proposal.json")
table := CheckPath(root, "approved.zi")
if !NativeWrite(*test, proposal, "{\"schema_version\":99}") ||
!NativeWrite(*test, table, "keep this table\n") { return 1 }
reject := string.["learn", "verify", "--candidates", proposal, "--repo", test.repo, "--output", table]
unused PackageCommand(*test, root, reject[:], false)
if !NativeAssert(*test, NativeRead(*test, table) == "keep this table\n", "a rejected teacher proposal replaced the table") { return 1 }
print("Learning corpus: on by default, records each new native build once under its ZX format with its compiler, and honors off, ZIRAN_LEARN and the size cap\n")
return 0
}
+121
View File
@@ -0,0 +1,121 @@
// Synthetic timing values test selection, never claim a measured speed gain.
#import "native_test"
#import "check_support"
#import "std/vec"
#import "std/json_document"
#import "std/file"
#import "std/file_tree_linux"
#import "std/text_tools"
#import, file "../cmd/compiler_bundle.zi";
#import, file "../cmd/compiler_lowered_ir.zi";
TextField :: (document: *JsonDocument, root: s32, key: string, value: string) {
JsonSet(document, root, key, JsonNewStringCopy(document, value))
}
#program_export
main :: (argc: s32, argv: **u8) -> s32 {
test := NativeStart(argc, argv, "learning-tuning-")
if test.failed { return 1 }
defer NativeCleanup(*test)
tools := PathParent(test.ziran)
source := CheckPath(test.work, "probe.zi")
zx := CheckPath(test.work, "probe.zx")
native := CheckPath(test.work, "probe.elf")
if !NativeWrite(*test, source, "main :: () -> s32 { return 7 }\n") { return 1 }
lower := string.[CheckPath(tools, "zi2zx"), "--root", test.work,
"--entry", "probe:main", "-o", zx, source]
encode := string.[CheckPath(tools, "zx2native"), "-o", native, zx]
unused NativeRun(*test, lower[:]); unused NativeRun(*test, encode[:])
if test.failed { return 1 }
digest := CheckHash(native)
zx_digest := CheckHash(zx)
compiler := CheckHash(CheckPath(tools, "zx2native"))
format := CheckConcat("zx", CheckConcat(CheckNumber(ExecutableVersionNumber()), CheckConcat("-lir", CheckNumber(LirVersion))))
corpus := CheckPath(test.work, "corpus")
folder := CheckPath(CheckPath(corpus, format), zx_digest)
stem := CheckPath(folder, CheckConcat("x86_64-", digest))
if !CreateDirectories(folder) { return 1 }
copy_zx := string.["cp", zx, CheckPath(folder, "program.zx")]
copy_elf := string.["cp", native, CheckConcat(stem, ".elf")]
map := string.[CheckPath(tools, "zx2native"), "--emit", "map", "-o", CheckConcat(stem, ".map.json"), zx]
unused NativeRun(*test, copy_zx[:]); unused NativeRun(*test, copy_elf[:]); unused NativeRun(*test, map[:])
if test.failed { return 1 }
record := CheckConcat(stem, ".record.json")
metadata: JsonDocument
defer JsonReset(*metadata)
record_root := JsonNewObject(*metadata)
TextField(*metadata, record_root, "format", format)
TextField(*metadata, record_root, "target", "x86_64")
TextField(*metadata, record_root, "platform", "linux")
TextField(*metadata, record_root, "zx2native_sha256", compiler)
TextField(*metadata, record_root, "input_sha256", zx_digest)
record_text := TextDetach(JsonWrite(*metadata, record_root, JsonCompactStyle()))
if !NativeWrite(*test, record, record_text) { return 1 }
relative := CheckConcat(format, CheckConcat("/", CheckConcat(zx_digest, CheckConcat("/x86_64-", CheckConcat(digest, ".record.json")))))
file := OpenRead(native)
if !file.valid { return 1 }
bytes := FileSize(file)
CloseFile(file)
epoch := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
document: JsonDocument
defer JsonReset(*document)
root := JsonNewObject(*document)
JsonSet(*document, root, "schema_version", JsonNewInteger(*document, 1))
JsonSet(*document, root, "checks", JsonNewBool(*document, false))
TextField(*document, root, "target", "x86_64-linux")
TextField(*document, root, "learning", "off")
TextField(*document, root, "host", "fixture")
TextField(*document, root, "source_epoch_sha256", epoch)
rows := JsonNewArray(*document)
JsonSet(*document, root, "measurements", rows)
for index: 0..1 {
row := JsonNewObject(*document)
unused JsonAppend(*document, rows, row)
TextField(*document, row, "workload", "probe")
TextField(*document, row, "zx_sha256", zx_digest)
TextField(*document, row, "input_sha256", zx_digest)
TextField(*document, row, "native_sha256", digest)
TextField(*document, row, "compiler_sha256", compiler)
TextField(*document, row, "checksum", "7")
TextField(*document, row, "c_checksum", "7")
TextField(*document, row, "corpus_record", relative)
JsonSet(*document, row, "code_bytes", JsonNewInteger(*document, bytes))
native_times := JsonNewArray(*document)
c_times := JsonNewArray(*document)
JsonSet(*document, row, "native_ns", native_times)
JsonSet(*document, row, "c_ns", c_times)
for sample: 0..10 {
unused JsonAppend(*document, native_times, JsonNewInteger(*document, ifx index == 0 then 400 else 200))
unused JsonAppend(*document, c_times, JsonNewInteger(*document, 100))
}
policy := JsonNewObject(*document)
JsonSet(*document, row, "policy", policy)
JsonSet(*document, policy, "leaf_operations", JsonNewInteger(*document, index))
JsonSet(*document, policy, "unroll_factor", JsonNewInteger(*document, 1))
JsonSet(*document, policy, "block_layout", JsonNewInteger(*document, 1))
JsonSet(*document, policy, "allocation", JsonNewInteger(*document, 0))
}
measured := CheckPath(test.work, "timings.json")
table := CheckPath(test.work, "table.zi")
certificate := CheckPath(test.work, "certificate.json")
output := CheckPath(test.work, "selected.zi")
approved := "LearningLeafOperations :: 0\nLearningUnrollFactor :: 1\nLearningBlockLayout :: 1\nLearningAllocation :: 0\n"
if !NativeWrite(*test, measured, JsonWrite(*document, root, JsonCompactStyle())) || !NativeWrite(*test, table, approved) { return 1 }
JsonReset(*metadata)
certificate_root := JsonNewObject(*metadata)
JsonSet(*metadata, certificate_root, "schema_version", JsonNewInteger(*metadata, 1))
JsonSet(*metadata, certificate_root, "verified", JsonNewBool(*metadata, true))
TextField(*metadata, certificate_root, "table_sha256", CheckHash(table))
if !NativeWrite(*test, certificate, JsonWrite(*metadata, certificate_root, JsonCompactStyle())) { return 1 }
NativeSet(*test, "ZIRAN_LEARN_DIR", corpus)
command := string.[test.ziran, "learn", "train", "--measurements", measured, "--table", table, "--verification", certificate, "--output", output]
if NativeInvoke(*test, command[:], "", 600000).code != 0 { return 1 }
selected := NativeRead(*test, output)
if !TextContains(selected, "LearningLeafOperations :: 0\n") || NativeInvoke(*test, command[:], "", 600000).code != 0 ||
NativeRead(*test, output) != selected { return 2 }
if !NativeWrite(*test, record, TextReplace(record_text, compiler, epoch)) { return 1 }
if NativeInvoke(*test, command[:], "", 600000).code == 0 || NativeRead(*test, output) != selected { return 3 }
print("Offline tuning: corpus identities, compiler mismatch rejection, deterministic choice and unchanged table on rejection\n")
return 0
}
+1 -1
View File
@@ -29,7 +29,7 @@ main :: (argc: s32, argv: **u8) -> s32 {
cases := string.["package_self_import", "package_batch_paths", "package_unborn", "package_pin", "package_native_links",
"package_transitive_add", "package_override_graph", "package_artifacts", "package_generated_modules", "package_resolution",
"package_bridges", "package_tooling", "package_wide_exports", "package_templates", "package_cache_repair", "package_diagnostics",
"package_learn"]
"package_learn", "package_learn_tuning"]
for index: cast(s64)0..cases.count - 1 {
if local_only && index >= 5 { break }
name := cases[index]
+32
View File
@@ -0,0 +1,32 @@
// Runtime input values exercise C/native multiplication selection at every
// integer width, including truncation, sign extension and wraparound.
Emit :: (x: u64) {
print("% % % % % % % %\n", x * 2, x * 3, x * 5, x * 9, x * 8, x * 32, x * 128, x * 1073741824)
a := cast(u8)x
b := cast(u16)x
c := cast(u32)x
print("% % % % % %\n", cast(u8)(a * 3), cast(u8)(a * 32),
cast(u16)(b * 5), cast(u16)(b * 128), cast(u32)(c * 9), cast(u32)(c * 1073741824))
d := cast(s8)x
e := cast(s16)x
f := cast(s32)x
print("% % % % % %\n", cast(s8)(d * 3), cast(s8)(d * 32),
cast(s16)(e * 5), cast(s16)(e * 128), cast(s32)(f * 9), cast(s32)(f * 1073741824))
// Both ends of the imm8 range, and the adjacent imm32 values.
print("% % % %\n", x * cast(u64)-128, x * cast(u64)127, x * cast(u64)-129, x * cast(u64)128)
}
main :: () -> s32 {
boundaries := u64.[0, 1, 127, 128, 255, 256, 32767, 32768, 65535, 65536,
2147483647, 2147483648, 4294967295, 4294967296, 9223372036854775807,
9223372036854775808, 18446744073709551615]
for value: boundaries { Emit(value) }
random: u64 = 521288629
for iteration: 0..2047 {
random = (random ^ (random << 13))
random = (random ^ (random >> 7))
random = (random ^ (random << 17))
Emit(random)
}
return 0
}
+32 -1
View File
@@ -4,6 +4,7 @@ using Machine :: #import "compiler_machine_ir"
using Target :: #import "compiler_target"
using Vectors :: #import "std/vec"
using X64 :: #import "compiler_x86_64"
using Encoding :: #import "compiler_x86_bytes"
// Local tests for the direct x86-64 machine-IR encoder. Programs are built
// in the Allocated stage by hand, checked against MachineVerifyAllocated, and
@@ -1168,8 +1169,38 @@ Negatives :: () -> bool {
return Check(!kept.valid && view.code.count == 0 && view.entry == -1, "repeated cleanup")
}
ImmediateMultiplication :: () -> bool {
values := s64.[-129, -128, -1, 0, 127, 128]
expected := string.["4d 69 c8 7f ff ff ff", "4d 6b c8 80", "4d 6b c8 ff",
"4d 6b c8 00", "4d 6b c8 7f", "4d 69 c8 80 00 00 00"]
for index: 0..values.count - 1 {
output: [16]u8
writer := Encoding.X86Writer.{output = output[:], limit = output.count}
Encoding.X86MultiplyImmediate(*writer, R9, R8, values[index])
if !Check(!writer.failed, "multiply immediate encoder") ||
!Bytes(output[:], 0, writer.at, expected[index], "sign-extended multiply boundary") { return false }
measured := Encoding.X86Writer.{limit = output.count}
Encoding.X86MultiplyImmediate(*measured, R9, R8, values[index])
if !Check(!measured.failed && measured.at == writer.at, "multiply immediate measure/write parity") { return false }
}
factors := s64.[1, 2, 3, 5, 9, 8, 32, -1]
idioms := string.["", "4f 8d 04 00", "4f 8d 04 40", "4f 8d 04 80", "4f 8d 04 c0",
"49 c1 e0 03", "49 c1 e0 05", "4d 6b c0 ff"]
for index: 0..factors.count - 1 {
output: [16]u8
writer := Encoding.X86Writer.{output = output[:], limit = output.count}
Encoding.X86MultiplyValue(*writer, R8, R8, factors[index])
if !Check(!writer.failed, "multiply value encoder") ||
!Bytes(output[:], 0, writer.at, idioms[index], "dead-flag multiply idiom") { return false }
measured := Encoding.X86Writer.{limit = output.count}
Encoding.X86MultiplyValue(*measured, R8, R8, factors[index])
if !Check(!measured.failed && measured.at == writer.at, "multiply value measure/write parity") { return false }
}
return true
}
main :: () -> s32 {
if !Basics() || !Calls() || !Aggregates() || !Negatives() { return 1 }
if !ImmediateMultiplication() || !Basics() || !Calls() || !Aggregates() || !Negatives() { return 1 }
print("x86 encoder: exact bytes, REX/ModRM/SIB, immediates, packed aggregates, frames, displacements, relocations, fuel, traps, pre-encoding rejection of invalid call forms and addends, no-output diagnostics and ownership local tests passed\n")
return 0
}
+1 -1
View File
@@ -31,7 +31,7 @@ ParityCases :: (repo: string) -> Vec(ParityCase) {
"vm_scalar_plans_test:Answer", "vm_storage_reads_test:main", "json_scan_test:SelfTest",
"json_scan_test:NativeMain", "json_string_value_test:SelfTest", "json_string_scan_test:SelfTest",
"json_document_lifetime_test:Answer", "std_float_text:SelfTest",
"generic_assembly_test:Answer", "native_assembly_test:Answer"]
"generic_assembly_test:Answer", "native_assembly_test:Answer", "teacher_integer_idioms:main"]
spec_root := CheckPath(repo, "tests/spec")
ParityAdd(*cases, spec_root, "zx_lowered_features:main", CheckPath(spec_root, "zx_lowered_features.zi"))
ParityAdd(*cases, spec_root, "zx_lowered_vec:main", CheckPath(spec_root, "zx_lowered_vec.zi"))