Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/src/omega_program.c # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / src / omega_program.c` 809 lines ยท 36544 bytes Raw Blame History 1 /* SPDX-License-Identifier: Apache-2.0 2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "omega_program.h" 18 #include "omega_core.h" 19 #include "aarch64_encoder.h" 20 #include "aarch64_decoder.h" 21 #include "omega_canonical.h" 22 #include "omega_exec.h" 23 #include "sha256.h" 24 #include 25 #include 26 #include 27 28 void omega_program_init(OmegaProgram *prog, const char *name) { 29 if (!prog) return; 30 memset(prog, 0, sizeof(OmegaProgram)); 31 if (name) { 32 snprintf(prog->name, sizeof(prog->name), "%.60s", name); 33 } 34 } 35 36 void omega_program_destroy(OmegaProgram *prog) { 37 if (!prog) return; 38 if (prog->graph) { 39 omega_graph_destroy(prog->graph); 40 prog->graph = NULL; 41 } 42 memset(prog, 0, sizeof(OmegaProgram)); 43 } 44 45 int omega_build_constraint_id(ConstraintKind kind, const char *annotation, SemanticId *out_id) { 46 if (!out_id) return -1; 47 OmegaObject obj; 48 memset(&obj, 0, sizeof(OmegaObject)); 49 obj.kind = KIND_CONSTRAINT; 50 size_t len = annotation ? strlen(annotation) : 0; 51 if (len > UINT16_MAX) return -1; 52 if (omega_object_add_constraint(&obj, kind, (const uint8_t*)annotation, (uint16_t)len) != 0) return -1; 53 if (omega_compute_semantic_id(&obj) != 0) return -1; 54 *out_id = obj.id; 55 return 0; 56 } 57 58 /* ---- program identity v2 (spec/program-identity.md) ---------------------- */ 59 60 static bool step_op_valid(uint8_t op) { 61 return op == OP_ADD || op == OP_SUB || op == OP_MUL || op == OP_AND || op == OP_OR; 62 } 63 64 static OmegaObject *build_type_for(OmegaGraph *g, TypeTag tag, uint16_t width) { 65 switch (tag) { 66 case TYPE_UNSIGNED_INT: return omega_build_type_uint(g, width); 67 case TYPE_SIGNED_INT: return omega_build_type_signed_int(g, width); 68 case TYPE_BITVECTOR: return omega_build_type_bitvector(g, width); 69 case TYPE_FP32: return width == 32 ? omega_build_type_fp32(g) : NULL; 70 default: return NULL; 71 } 72 } 73 74 /* FP32 programs (spec/program-fp32.md). A body is FP32-involved when the contract names 75 * TYPE_FP32 or a step is OP_CONVERT. Such a body runs a two-state machine: in the FP32 76 * state a step is ADD SUB MUL DIV with a binary32 constant, or OP_CONVERT to u32; in the 77 * u32 state the only step is OP_CONVERT to FP32 (integer arithmetic stays on the integer 78 * tier). No other step is accepted, so a u32 value never meets an FP32 operation 79 * without an explicit conversion. The overflow policy declared on the operations is 80 * SATURATE: binary32 overflow goes to infinity and F2U clamps. */ 81 static bool body_is_fp32(const OmegaProgram *prog) { 82 if (prog->contract.input_type == TYPE_FP32 || prog->contract.output_type == TYPE_FP32) return true; 83 for (uint16_t i = 0; i < prog->body.step_count && i < OMEGA_PROGRAM_MAX_STEPS; ++i) 84 if (prog->body.steps[i].op == OP_CONVERT) return true; 85 return false; 86 } 87 88 static const OmegaObject *lower_body_fp32(OmegaGraph *g, const OmegaProgram *prog) { 89 const OmegaProgramBody *b = &prog->body; 90 const OmegaContract *c = &prog->contract; 91 if (c->input_width != 32 || c->output_width != 32) return NULL; 92 if ((c->input_type != TYPE_FP32 && c->input_type != TYPE_UNSIGNED_INT) || 93 (c->output_type != TYPE_FP32 && c->output_type != TYPE_UNSIGNED_INT)) return NULL; 94 OmegaObject *tf = omega_build_type_fp32(g); 95 OmegaObject *tu = omega_build_type_uint(g, 32); 96 if (!tf || !tf->has_id || !tu || !tu->has_id) return NULL; 97 SemanticId tfid = tf->id, tuid = tu->id; 98 TypeTag cur_tag = c->input_type; 99 OmegaObject *cur = omega_build_param(g, cur_tag == TYPE_FP32 ? &tfid : &tuid, 0); 100 if (!cur || !cur->has_id) return NULL; 101 SemanticId cur_id = cur->id; 102 for (uint16_t i = 0; i < b->step_count; ++i) { 103 uint8_t op = b->steps[i].op; 104 uint64_t imm = b->steps[i].imm; 105 if (op == OP_CONVERT) { 106 if (imm != TYPE_FP32 && imm != TYPE_UNSIGNED_INT) return NULL; 107 if ((TypeTag)imm == cur_tag) return NULL; 108 const SemanticId *from = cur_tag == TYPE_FP32 ? &tfid : &tuid; 109 const SemanticId *to = imm == TYPE_FP32 ? &tfid : &tuid; 110 OmegaObject *o = omega_graph_add_object(g, KIND_OPERATION); 111 if (!o) return NULL; 112 OperationPayload opp; 113 memset(&opp, 0, sizeof(opp)); 114 opp.opcode = OP_CONVERT; 115 opp.overflow = OVERFLOW_SATURATE; 116 opp.arity = 1; 117 memcpy(opp.type_id.bytes, to->bytes, OMEGA_ID_BYTES); 118 memcpy(opp.input_types[0].bytes, from->bytes, OMEGA_ID_BYTES); 119 memcpy(opp.output_type.bytes, to->bytes, OMEGA_ID_BYTES); 120 memcpy(o->payload, &opp, sizeof(opp)); 121 o->payload_len = sizeof(opp); 122 omega_compute_semantic_id(o); 123 SemanticId opid = o->id; 124 OmegaObject *a = omega_graph_add_object(g, KIND_OPERATION); 125 if (!a) return NULL; 126 ApplyPayload app; 127 memset(&app, 0, sizeof(app)); 128 memcpy(app.op_id.bytes, opid.bytes, OMEGA_ID_BYTES); 129 app.operand_count = 1; 130 memcpy(app.operands[0].bytes, cur_id.bytes, OMEGA_ID_BYTES); 131 memcpy(a->payload, &app, sizeof(app)); 132 a->payload_len = sizeof(app); 133 omega_compute_semantic_id(a); 134 if (!a->has_id) return NULL; 135 cur = a; 136 cur_id = a->id; 137 cur_tag = (TypeTag)imm; 138 continue; 139 } 140 if (cur_tag != TYPE_FP32) return NULL; 141 if (op != OP_ADD && op != OP_SUB && op != OP_MUL && op != OP_DIV) return NULL; 142 if (imm > 0xFFFFFFFFull) return NULL; 143 OmegaObject *k = omega_build_val_uint(g, &tfid, 32, imm); 144 if (!k || !k->has_id) return NULL; 145 SemanticId kid = k->id; 146 OmegaObject *o = omega_build_op_binary(g, (OpCode)op, OVERFLOW_SATURATE, &tfid); 147 if (!o || !o->has_id) return NULL; 148 SemanticId opid = o->id; 149 cur = omega_build_apply(g, &opid, &cur_id, &kid); 150 if (!cur || !cur->has_id) return NULL; 151 cur_id = cur->id; 152 } 153 if (cur_tag != c->output_type) return NULL; 154 return cur; 155 } 156 157 /* Lower the body into g with the existing builders; returns the root object. */ 158 static const OmegaObject *lower_body(OmegaGraph *g, const OmegaProgram *prog) { 159 const OmegaProgramBody *b = &prog->body; 160 if (!b->has_body || b->step_count > OMEGA_PROGRAM_MAX_STEPS) return NULL; 161 if (body_is_fp32(prog)) return lower_body_fp32(g, prog); 162 uint16_t w = prog->contract.input_width; 163 OmegaObject *t = build_type_for(g, prog->contract.input_type, w); 164 if (!t || !t->has_id) return NULL; 165 SemanticId tid = t->id; 166 OmegaObject *cur = omega_build_param(g, &tid, 0); 167 if (!cur || !cur->has_id) return NULL; 168 SemanticId cur_id = cur->id; 169 for (uint16_t i = 0; i < b->step_count; ++i) { 170 if (!step_op_valid(b->steps[i].op)) return NULL; 171 OmegaObject *c = omega_build_val_uint(g, &tid, w, b->steps[i].imm); 172 if (!c || !c->has_id) return NULL; 173 SemanticId cid = c->id; 174 OmegaObject *op = omega_build_op_binary(g, (OpCode)b->steps[i].op, OVERFLOW_WRAP, &tid); 175 if (!op || !op->has_id) return NULL; 176 SemanticId opid = op->id; 177 cur = omega_build_apply(g, &opid, &cur_id, &cid); 178 if (!cur || !cur->has_id) return NULL; 179 cur_id = cur->id; 180 } 181 return cur; 182 } 183 184 int omega_program_body_root_id(const OmegaProgram *prog, SemanticId *out_root) { 185 if (!prog || !out_root) return -1; 186 OmegaGraph *g = omega_graph_create(); 187 if (!g) return -1; 188 const OmegaObject *root = lower_body(g, prog); 189 int rc = -1; 190 if (root) { *out_root = root->id; rc = 0; } 191 omega_graph_destroy(g); 192 return rc; 193 } 194 195 static int type_id_for(TypeTag tag, uint16_t width, SemanticId *out) { 196 OmegaGraph *g = omega_graph_create(); 197 if (!g) return -1; 198 OmegaObject *t = build_type_for(g, tag, width); 199 int rc = -1; 200 if (t && t->has_id) { *out = t->id; rc = 0; } 201 omega_graph_destroy(g); 202 return rc; 203 } 204 205 int omega_program_contract_id(const OmegaProgram *prog, uint8_t out[OMEGA_ID_BYTES]) { 206 SemanticId tin, tout; 207 if (!prog || !out || 208 type_id_for(prog->contract.input_type, prog->contract.input_width, &tin) != 0 || 209 type_id_for(prog->contract.output_type, prog->contract.output_width, &tout) != 0) 210 return -1; 211 static const char domain[] = "aien.vc1.contract.v1"; 212 uint8_t buf[sizeof(domain) + 4 * OMEGA_ID_BYTES]; 213 size_t pos = 0; 214 memcpy(buf, domain, sizeof(domain)); /* includes the terminating 0x00 */ 215 pos += sizeof(domain); 216 memcpy(&buf[pos], tin.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 217 memcpy(&buf[pos], tout.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 218 memcpy(&buf[pos], prog->contract.precondition_id.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 219 memcpy(&buf[pos], prog->contract.postcondition_id.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 220 sha256_hash(buf, pos, out); 221 return 0; 222 } 223 224 int omega_program_compute_id(OmegaProgram *prog) { 225 if (!prog) return -1; 226 memset(prog->program_id.bytes, 0, OMEGA_ID_BYTES); 227 SemanticId root, tin, tout; 228 if (omega_program_body_root_id(prog, &root) != 0 || 229 type_id_for(prog->contract.input_type, prog->contract.input_width, &tin) != 0 || 230 type_id_for(prog->contract.output_type, prog->contract.output_width, &tout) != 0) 231 return -1; 232 233 static const char domain[] = OMEGA_PROGRAM_ID_DOMAIN; 234 uint8_t buf[sizeof(domain) + 5 * OMEGA_ID_BYTES]; 235 size_t pos = 0; 236 memcpy(buf, domain, sizeof(domain)); /* includes the terminating 0x00 */ 237 pos += sizeof(domain); 238 memcpy(&buf[pos], root.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 239 memcpy(&buf[pos], tin.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 240 memcpy(&buf[pos], tout.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 241 memcpy(&buf[pos], prog->contract.precondition_id.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 242 memcpy(&buf[pos], prog->contract.postcondition_id.bytes, OMEGA_ID_BYTES); pos += OMEGA_ID_BYTES; 243 sha256_hash(buf, pos, prog->program_id.bytes); 244 return 0; 245 } 246 247 /* ---- V0 program realization core (spec/program-realization.md) ---------- */ 248 249 static void set_why(char *why, size_t n, const char *fmt, const char *a) { 250 if (why && n) snprintf(why, n, fmt, a ? a : ""); 251 } 252 253 static const char *step_op_name(uint8_t op) { 254 switch (op) { 255 case OP_ADD: return "ADD"; case OP_SUB: return "SUB"; case OP_MUL: return "MUL"; 256 case OP_AND: return "AND"; case OP_OR: return "OR"; case OP_DIV: return "DIV"; 257 default: return "unknown"; 258 } 259 } 260 261 static uint64_t width_mask(uint16_t w) { 262 return w >= 64 ? ~0ull : ((1ull << w) - 1ull); 263 } 264 265 int omega_program_realize_check(const OmegaProgram *prog, uint16_t *out_width, char *why, size_t why_len) { 266 char tmp[160]; 267 if (!prog) { set_why(why, why_len, "no program%s", NULL); return -1; } 268 const OmegaContract *c = &prog->contract; 269 const OmegaProgramBody *b = &prog->body; 270 if (!b->has_body) { set_why(why, why_len, "program has no semantic body: meaning unknown, nothing to compile%s", NULL); return -1; } 271 if (b->step_count > OMEGA_PROGRAM_MAX_STEPS) { set_why(why, why_len, "body has more than 64 steps%s", NULL); return -1; } 272 if (c->input_type != TYPE_UNSIGNED_INT || c->output_type != TYPE_UNSIGNED_INT) { 273 snprintf(tmp, sizeof tmp, "type tags in=0x%02x out=0x%02x: V0 realization compiles unsigned integers only " 274 "(signed/bitvector result representation is not specified)", (unsigned)c->input_type, (unsigned)c->output_type); 275 set_why(why, why_len, "%s", tmp); 276 return -1; 277 } 278 if (c->input_width != c->output_width) { 279 snprintf(tmp, sizeof tmp, "input width %u != output width %u: V0 never converts", c->input_width, c->output_width); 280 set_why(why, why_len, "%s", tmp); 281 return -1; 282 } 283 uint16_t w = c->input_width; 284 if (w != 8 && w != 16 && w != 32 && w != 64) { 285 snprintf(tmp, sizeof tmp, "width %u unsupported: V0 AArch64 realization supports u8 u16 u32 u64", w); 286 set_why(why, why_len, "%s", tmp); 287 return -1; 288 } 289 for (uint16_t i = 0; i < b->step_count; ++i) { 290 uint8_t op = b->steps[i].op; 291 if (!step_op_valid(op)) { 292 if (op == OP_DIV) 293 snprintf(tmp, sizeof tmp, "step %u: DIV fails closed: not in the V0 body op set, no UDIV emitter, " 294 "and evaluator (x/0 = error) and UDIV (x/0 = 0) disagree", i); 295 else 296 snprintf(tmp, sizeof tmp, "step %u: opcode 0x%02x (%s) not in V0 body op set ADD SUB MUL AND OR", 297 i, op, step_op_name(op)); 298 set_why(why, why_len, "%s", tmp); 299 return -1; 300 } 301 if ((b->steps[i].imm & ~width_mask(w)) != 0) { 302 snprintf(tmp, sizeof tmp, "step %u: constant 0x%llx does not fit declared width u%u", i, 303 (unsigned long long)b->steps[i].imm, w); 304 set_why(why, why_len, "%s", tmp); 305 return -1; 306 } 307 } 308 /* The program id must be the id of this body + contract: never compile under a stale id. */ 309 OmegaProgram chk = *prog; 310 chk.graph = NULL; 311 if (omega_program_compute_id(&chk) != 0 || 312 omega_compare_semantic_id(&chk.program_id, &prog->program_id) != 0) { 313 set_why(why, why_len, "program_id is not the v2 id of this body and contract (stale or forged)%s", NULL); 314 return -1; 315 } 316 if (out_width) *out_width = w; 317 if (why && why_len) why[0] = '\0'; 318 return 0; 319 } 320 321 /* Materialize a constant: MOVZ chunk0, then MOVK for each nonzero higher 16-bit chunk. */ 322 static int emit_const(uint8_t *code, size_t *pos, size_t max_len, uint8_t reg, uint64_t imm) { 323 if (aarch64_emit_movz(code, pos, max_len, true, reg, (uint16_t)(imm & 0xFFFF), 0) != 0) return -1; 324 for (unsigned k = 1; k < 4; ++k) { 325 uint16_t chunk = (uint16_t)((imm >> (16 * k)) & 0xFFFF); 326 if (chunk && aarch64_emit_movk(code, pos, max_len, true, reg, chunk, (uint8_t)(16 * k)) != 0) return -1; 327 } 328 return 0; 329 } 330 331 static int emit_op(uint8_t *code, size_t *pos, size_t max_len, uint8_t op, uint8_t rm) { 332 switch (op) { 333 case OP_ADD: return aarch64_emit_add_reg(code, pos, max_len, true, REG_X0, REG_X0, rm); 334 case OP_SUB: return aarch64_emit_sub_reg(code, pos, max_len, true, REG_X0, REG_X0, rm); 335 case OP_MUL: return aarch64_emit_mul_reg(code, pos, max_len, true, REG_X0, REG_X0, rm); 336 case OP_AND: return aarch64_emit_and_reg(code, pos, max_len, true, REG_X0, REG_X0, rm); 337 case OP_OR: return aarch64_emit_orr_reg(code, pos, max_len, true, REG_X0, REG_X0, rm); 338 default: return -1; 339 } 340 } 341 342 int omega_program_emit_schedule(const OmegaProgramBody *body, uint16_t width, OmegaRealizeSchedule sched, 343 uint8_t *code, size_t *code_len, size_t max_len) { 344 if (!body || !code || !code_len || !body->has_body || body->step_count > OMEGA_PROGRAM_MAX_STEPS) return -1; 345 if (width != 8 && width != 16 && width != 32 && width != 64) return -1; 346 if (sched != OMEGA_SCHED_SEQUENTIAL && sched != OMEGA_SCHED_PRELOAD) return -1; 347 /* Plan: the body steps, then (width < 64) one AND with the width mask. Arithmetic is 348 * done in 64-bit registers; ADD SUB MUL AND OR commute with reduction mod 2^w, so one 349 * final mask gives the wrapped u result. */ 350 OmegaProgramStep plan[OMEGA_PROGRAM_MAX_STEPS + 1]; 351 size_t n = 0; 352 for (uint16_t i = 0; i < body->step_count; ++i) { 353 if (!step_op_valid(body->steps[i].op) || (body->steps[i].imm & ~width_mask(width)) != 0) return -1; 354 plan[n++] = body->steps[i]; 355 } 356 if (width < 64) { plan[n].op = OP_AND; plan[n].imm = width_mask(width); n++; } 357 358 size_t pos = 0; 359 if (sched == OMEGA_SCHED_SEQUENTIAL) { 360 for (size_t i = 0; i < n; ++i) 361 if (emit_const(code, &pos, max_len, REG_X1, plan[i].imm) != 0 || 362 emit_op(code, &pos, max_len, plan[i].op, REG_X1) != 0) 363 return -1; 364 } else { 365 /* Preload: in blocks of up to OMEGA_PRELOAD_REGS constants, load all of the block's 366 * constants into X1..Xk first (independent, can issue together), then apply the 367 * block's ops in body order. Only caller-saved scratch registers X1..X15 are used. */ 368 for (size_t base = 0; base < n; base += OMEGA_PRELOAD_REGS) { 369 size_t k = n - base < OMEGA_PRELOAD_REGS ? n - base : OMEGA_PRELOAD_REGS; 370 for (size_t j = 0; j < k; ++j) 371 if (emit_const(code, &pos, max_len, (uint8_t)(REG_X1 + j), plan[base + j].imm) != 0) return -1; 372 for (size_t j = 0; j < k; ++j) 373 if (emit_op(code, &pos, max_len, plan[base + j].op, (uint8_t)(REG_X1 + j)) != 0) return -1; 374 } 375 } 376 if (aarch64_emit_ret(code, &pos, max_len) != 0) return -1; 377 *code_len = pos; 378 return 0; 379 } 380 381 int omega_program_emit_body(const OmegaProgramBody *body, uint8_t *code, size_t *code_len, size_t max_len) { 382 return omega_program_emit_schedule(body, 64, OMEGA_SCHED_SEQUENTIAL, code, code_len, max_len); 383 } 384 385 static uint32_t read_insn(const uint8_t *p) { 386 return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); 387 } 388 389 int omega_program_lift_body(const uint8_t *code, size_t code_len, OmegaProgramBody *out_body) { 390 if (!code || !out_body || code_len < 4 || code_len % 4 != 0 || code_len > AARCH64_MAX_CODE_BYTES) return -1; 391 OmegaProgramBody b; 392 memset(&b, 0, sizeof b); 393 b.has_body = true; 394 size_t n = code_len / 4, i = 0; 395 while (i + 1 < n) { 396 DecodedInsn d; 397 if (aarch64_decode_instruction(read_insn(&code[i * 4]), &d) != 0 || d.op != DECODED_MOVZ || 398 d.rd != REG_X1 || d.hw != 0) 399 return -1; 400 uint64_t imm = d.imm16; 401 i++; 402 while (i < n && aarch64_decode_instruction(read_insn(&code[i * 4]), &d) == 0 && d.op == DECODED_MOVK) { 403 if (d.rd != REG_X1 || d.hw == 0) return -1; 404 imm |= (uint64_t)d.imm16 << (16 * d.hw); 405 i++; 406 } 407 if (i >= n || aarch64_decode_instruction(read_insn(&code[i * 4]), &d) != 0) return -1; 408 uint8_t op; 409 switch (d.op) { 410 case DECODED_ADD: op = OP_ADD; break; 411 case DECODED_SUB: op = OP_SUB; break; 412 case DECODED_MUL: op = OP_MUL; break; 413 case DECODED_AND: op = OP_AND; break; 414 case DECODED_ORR: op = OP_OR; break; 415 default: return -1; 416 } 417 i++; 418 if (b.step_count >= OMEGA_PROGRAM_MAX_STEPS) return -1; 419 b.steps[b.step_count].op = op; 420 b.steps[b.step_count].imm = imm; 421 b.step_count++; 422 } 423 /* Confirm: the re-emitted template must be byte-identical (covers registers, 424 * shifts, sf, chunk order, and the terminal RET that the loose decode above does not check). */ 425 uint8_t re[AARCH64_MAX_CODE_BYTES]; 426 size_t re_len = 0; 427 if (omega_program_emit_body(&b, re, &re_len, sizeof re) != 0 || re_len != code_len || 428 memcmp(re, code, code_len) != 0) 429 return -1; 430 *out_body = b; 431 return 0; 432 } 433 434 /* ---- independent semantic evaluator (over the canonical lowered graph) ------ 435 * Walks the canonical objects the program id binds (APPLY -> OPERATION payload 436 * opcode/overflow/type, VALUE big-endian bytes, the PARAM), and applies the core 437 * definition omega_eval_pure_binary_uint. It never looks at code or at the emitter. */ 438 439 static int eval_node(const OmegaGraph *g, const SemanticId *id, uint64_t x, int depth, uint64_t *out) { 440 if (depth > OMEGA_PROGRAM_MAX_STEPS + 2) return -1; 441 const OmegaObject *o = omega_graph_find_object_const(g, id); 442 if (!o) return -1; 443 if (o->kind == KIND_VALUE) { 444 if (o->payload_len != sizeof(ValuePayload)) return -1; 445 ValuePayload vp; 446 memcpy(&vp, o->payload, sizeof vp); 447 for (uint16_t i = 0; i < o->attr_count; ++i) 448 if (strcmp(o->attributes[i].key, "omega.param") == 0) { 449 if (vp.byte_len != 0) return -1; 450 *out = x; 451 return 0; 452 } 453 if (vp.byte_len == 0 || vp.byte_len > 8) return -1; 454 uint64_t v = 0; 455 for (uint16_t i = 0; i < vp.byte_len; ++i) v = (v << 8) | vp.bytes[i]; 456 *out = v; 457 return 0; 458 } 459 if (o->kind != KIND_OPERATION || o->payload_len != sizeof(ApplyPayload)) return -1; 460 ApplyPayload ap; 461 memcpy(&ap, o->payload, sizeof ap); 462 if (ap.operand_count != 2) return -1; 463 const OmegaObject *op = omega_graph_find_object_const(g, &ap.op_id); 464 if (!op || op->kind != KIND_OPERATION || op->payload_len != sizeof(OperationPayload)) return -1; 465 OperationPayload opp; 466 memcpy(&opp, op->payload, sizeof opp); 467 if (opp.overflow != OVERFLOW_WRAP) return -1; 468 const OmegaObject *ty = omega_graph_find_object_const(g, &opp.type_id); 469 if (!ty || ty->kind != KIND_TYPE || ty->payload_len != sizeof(TypePayload)) return -1; 470 TypePayload tp; 471 memcpy(&tp, ty->payload, sizeof tp); 472 if (tp.tag != TYPE_UNSIGNED_INT || tp.width == 0 || tp.width > 64) return -1; 473 uint64_t a, b; 474 if (eval_node(g, &ap.operands[0], x, depth + 1, &a) != 0 || 475 eval_node(g, &ap.operands[1], x, depth + 1, &b) != 0) 476 return -1; 477 return omega_eval_pure_binary_uint(opp.opcode, opp.overflow, tp.width, a, b, out) == 0 ? 0 : -1; 478 } 479 480 int omega_program_eval(const OmegaProgram *prog, const uint64_t *xs, size_t n, uint64_t *ys) { 481 if (!prog || (n && (!xs || !ys))) return -1; 482 if (omega_program_realize_check(prog, NULL, NULL, 0) != 0) return -1; 483 OmegaGraph *g = omega_graph_create(); 484 if (!g) return -1; 485 const OmegaObject *root = lower_body(g, prog); 486 int rc = root ? 0 : -1; 487 SemanticId rid; 488 if (root) rid = root->id; 489 uint64_t mask = width_mask(prog->contract.input_width); 490 for (size_t i = 0; rc == 0 && i < n; ++i) { 491 if (xs[i] & ~mask) { rc = -1; break; } /* outside the declared input domain */ 492 if (eval_node(g, &rid, xs[i], 0, &ys[i]) != 0) rc = -1; 493 } 494 omega_graph_destroy(g); 495 return rc; 496 } 497 498 /* ---- omega_program_realize: canonical (machine-independent) realization ---- */ 499 500 int omega_program_realize_ex(OmegaProgram *prog, char *why, size_t why_len) { 501 if (!prog) return -1; 502 uint16_t w = 0; 503 if (omega_program_realize_check(prog, &w, why, why_len) != 0) return -2; 504 RealizationObject r; 505 memset(&r, 0, sizeof r); 506 size_t len = 0; 507 if (omega_program_emit_schedule(&prog->body, w, OMEGA_SCHED_SEQUENTIAL, r.code_bytes, &len, 508 sizeof r.code_bytes) != 0) { 509 set_why(why, why_len, "emitter refused the body (code buffer or encoding)%s", NULL); 510 return -2; 511 } 512 r.code_len = len; 513 r.target_profile = AARCH64_PROFILE_V8A_BAREMETAL; 514 r.entry_offset = 0; 515 r.semantic_id = prog->program_id; /* the realization id binds the program */ 516 omega_compute_realization_id(&r); 517 VerifyReport rep; 518 memset(&rep, 0, sizeof rep); 519 if (omega_verify_v0_structural(NULL, &r, &rep) != 0) { 520 set_why(why, why_len, "%s", rep.error_detail); 521 return -1; 522 } 523 prog->realization = r; 524 prog->is_realized = true; 525 prog->is_verified = false; /* realization is not verification */ 526 return 0; 527 } 528 529 int omega_program_realize(OmegaProgram *prog) { 530 return omega_program_realize_ex(prog, NULL, 0); 531 } 532 533 int omega_program_validate_contract(const OmegaProgram *prog, char *err_msg, size_t err_msg_len) { 534 if (!prog) return -1; 535 if (prog->contract.input_type == TYPE_INVALID) { 536 if (err_msg) snprintf(err_msg, err_msg_len, "Program contract has invalid input type"); 537 return -1; 538 } 539 if (prog->contract.output_type == TYPE_INVALID) { 540 if (err_msg) snprintf(err_msg, err_msg_len, "Program contract has invalid output type"); 541 return -1; 542 } 543 if (prog->contract.input_width == 0 || prog->contract.output_width == 0) { 544 if (err_msg) snprintf(err_msg, err_msg_len, "Program contract has 0-width type"); 545 return -1; 546 } 547 bool non_zero_pre = false, non_zero_post = false; 548 for (int i = 0; i < OMEGA_ID_BYTES; ++i) { 549 if (prog->contract.precondition_id.bytes[i]) non_zero_pre = true; 550 if (prog->contract.postcondition_id.bytes[i]) non_zero_post = true; 551 } 552 if (!non_zero_pre || !non_zero_post) { 553 if (err_msg) snprintf(err_msg, err_msg_len, "Program contract has uninitialized constraint SemanticId"); 554 return -1; 555 } 556 return 0; 557 } 558 559 int omega_program_build_unary_op(OmegaProgram *prog, const char *name, OpCode op, uint64_t imm) { 560 if (!prog) return -1; 561 omega_program_init(prog, name); 562 if (!step_op_valid((uint8_t)op)) return -1; 563 /* The realization loads the constant with MOVZ + one MOVK (32 bits). A wider 564 * constant would be truncated in the code while the body kept the full value: 565 * refuse it (spec/program-identity.md section 4). */ 566 if (imm > 0xFFFFFFFFull) return -1; 567 568 prog->contract.input_type = TYPE_UNSIGNED_INT; 569 prog->contract.input_width = 64; 570 prog->contract.output_type = TYPE_UNSIGNED_INT; 571 prog->contract.output_width = 64; 572 snprintf(prog->contract.precondition, sizeof(prog->contract.precondition), "x >= 0"); 573 omega_build_constraint_id(CONST_PRECONDITION, prog->contract.precondition, &prog->contract.precondition_id); 574 575 const char *sym = "?"; 576 switch (op) { 577 case OP_ADD: sym = "+"; break; 578 case OP_SUB: sym = "-"; break; 579 case OP_MUL: sym = "*"; break; 580 case OP_AND: sym = "&"; break; 581 case OP_OR: sym = "|"; break; 582 default: return -1; 583 } 584 snprintf(prog->contract.postcondition, sizeof(prog->contract.postcondition), "x %s %lu", sym, (unsigned long)imm); 585 omega_build_constraint_id(CONST_POSTCONDITION, prog->contract.postcondition, &prog->contract.postcondition_id); 586 587 /* Semantic body: one step. The realization is compiled from it (omega_program_realize). */ 588 prog->body.has_body = true; 589 prog->body.step_count = 1; 590 prog->body.steps[0].op = (uint8_t)op; 591 prog->body.steps[0].imm = imm; 592 593 if (omega_program_compute_id(prog) != 0) return -1; 594 if (omega_program_realize(prog) != 0) return -1; 595 596 prog->cost.insn_count = (uint32_t)(prog->realization.code_len / 4); 597 prog->cost.reg_pressure = 2; 598 prog->cost.memory_bytes = 0; 599 prog->cost.latency_cycles = (op == OP_MUL) ? 3 : 2; 600 601 return 0; 602 } 603 604 /* ---- canonical composed postcondition (spec/program-identity.md 2.4) ------ */ 605 606 int omega_contract_post_seq_id(const SemanticId *leaves, uint16_t n, SemanticId *out) { 607 if (!leaves || !out || n == 0 || n > OMEGA_PROGRAM_MAX_STEPS) return -1; 608 OmegaObject *obj = (OmegaObject *)malloc(sizeof(OmegaObject)); 609 if (!obj) return -1; 610 SemanticId acc = leaves[n - 1]; 611 int rc = 0; 612 for (int i = (int)n - 2; i >= 0 && rc == 0; --i) { 613 memset(obj, 0, sizeof(OmegaObject)); 614 obj->kind = KIND_CONSTRAINT; 615 uint8_t pl[2 * OMEGA_ID_BYTES]; 616 memcpy(pl, leaves[i].bytes, OMEGA_ID_BYTES); 617 memcpy(pl + OMEGA_ID_BYTES, acc.bytes, OMEGA_ID_BYTES); 618 if (omega_object_add_attribute(obj, "omega.compose", (const uint8_t *)"seq", 3) != 0 || 619 omega_object_add_constraint(obj, CONST_POSTCONDITION, pl, sizeof pl) != 0 || 620 omega_compute_semantic_id(obj) != 0) 621 rc = -1; 622 else 623 acc = obj->id; 624 } 625 free(obj); 626 if (rc == 0) *out = acc; 627 return rc; 628 } 629 630 /* The leaf list of a contract's postcondition. A contract whose stored leaves no longer 631 * fold to its postcondition_id (someone replaced the postcondition afterwards) is a leaf. */ 632 static int post_leaves_of(const OmegaContract *c, SemanticId *out, uint16_t *n) { 633 if (c->post_leaf_count >= 2 && c->post_leaf_count <= OMEGA_PROGRAM_MAX_STEPS) { 634 SemanticId f; 635 if (omega_contract_post_seq_id(c->post_leaves, c->post_leaf_count, &f) == 0 && 636 omega_compare_semantic_id(&f, &c->postcondition_id) == 0) { 637 memcpy(out, c->post_leaves, c->post_leaf_count * sizeof(SemanticId)); 638 *n = c->post_leaf_count; 639 return 0; 640 } 641 } 642 out[0] = c->postcondition_id; 643 *n = 1; 644 return 0; 645 } 646 647 int omega_program_compose(const OmegaProgram *a, const OmegaProgram *b, OmegaProgram *out_c, 648 char *err_msg, size_t err_msg_len) { 649 if (!a || !b || !out_c) return -1; 650 651 /* 1. Intermediate Type Unification: OutType(A) must match InType(B) */ 652 if (a->contract.output_type != b->contract.input_type || 653 a->contract.output_width != b->contract.input_width) { 654 if (err_msg) { 655 snprintf(err_msg, err_msg_len, 656 "Type mismatch in composition: A.out (tag 0x%02x, width %u) != B.in (tag 0x%02x, width %u)", 657 a->contract.output_type, a->contract.output_width, 658 b->contract.input_type, b->contract.input_width); 659 } 660 return -1; 661 } 662 663 char c_name[64]; 664 snprintf(c_name, sizeof(c_name), "(%.25s)o(%.25s)", b->name, a->name); 665 omega_program_init(out_c, c_name); 666 667 /* 2. Contract Derivation */ 668 out_c->contract.input_type = a->contract.input_type; 669 out_c->contract.input_width = a->contract.input_width; 670 out_c->contract.output_type = b->contract.output_type; 671 out_c->contract.output_width = b->contract.output_width; 672 out_c->contract.precondition_id = a->contract.precondition_id; 673 snprintf(out_c->contract.precondition, sizeof(out_c->contract.precondition), "%.60s", a->contract.precondition); 674 /* Postcondition: the flattened ordered list of leaf postconditions (A's then B's), so 675 * (a;b);c and a;(b;c) get one canonical id. The text is display only. */ 676 { 677 SemanticId la[OMEGA_PROGRAM_MAX_STEPS], lb[OMEGA_PROGRAM_MAX_STEPS]; 678 uint16_t na = 0, nb = 0; 679 post_leaves_of(&a->contract, la, &na); 680 post_leaves_of(&b->contract, lb, &nb); 681 if ((size_t)na + nb > OMEGA_PROGRAM_MAX_STEPS) { 682 if (err_msg) snprintf(err_msg, err_msg_len, "Composite postcondition overflow (more than %d parts)", OMEGA_PROGRAM_MAX_STEPS); 683 return -1; 684 } 685 memcpy(out_c->contract.post_leaves, la, na * sizeof(SemanticId)); 686 memcpy(out_c->contract.post_leaves + na, lb, nb * sizeof(SemanticId)); 687 out_c->contract.post_leaf_count = (uint16_t)(na + nb); 688 if (omega_contract_post_seq_id(out_c->contract.post_leaves, out_c->contract.post_leaf_count, 689 &out_c->contract.postcondition_id) != 0) { 690 if (err_msg) snprintf(err_msg, err_msg_len, "Composite postcondition id failed"); 691 return -1; 692 } 693 snprintf(out_c->contract.postcondition, sizeof(out_c->contract.postcondition), 694 "%.29s ; %.29s", a->contract.postcondition, b->contract.postcondition); 695 } 696 697 /* 2b. Body: A's steps then B's (innermost first). Without both bodies the 698 * composite's meaning is unknown and it has no identity. */ 699 if (a->body.has_body && b->body.has_body) { 700 if ((size_t)a->body.step_count + b->body.step_count > OMEGA_PROGRAM_MAX_STEPS) { 701 if (err_msg) snprintf(err_msg, err_msg_len, "Composite body overflow (more than %d steps)", OMEGA_PROGRAM_MAX_STEPS); 702 return -1; 703 } 704 out_c->body.has_body = true; 705 out_c->body.step_count = (uint16_t)(a->body.step_count + b->body.step_count); 706 memcpy(out_c->body.steps, a->body.steps, a->body.step_count * sizeof(OmegaProgramStep)); 707 memcpy(out_c->body.steps + a->body.step_count, b->body.steps, b->body.step_count * sizeof(OmegaProgramStep)); 708 } 709 710 /* 3. Cost Derivation: Monotonic cost accumulation */ 711 out_c->cost.insn_count = a->cost.insn_count + b->cost.insn_count; 712 if (out_c->cost.insn_count > 0) out_c->cost.insn_count -= 1; /* Ret eliminated; FP32 library-tier programs carry no code */ 713 out_c->cost.reg_pressure = (a->cost.reg_pressure > b->cost.reg_pressure) ? a->cost.reg_pressure : b->cost.reg_pressure; 714 out_c->cost.memory_bytes = a->cost.memory_bytes + b->cost.memory_bytes; 715 out_c->cost.latency_cycles = a->cost.latency_cycles + b->cost.latency_cycles; 716 717 /* 4. Realization: compiled from the composite body (omega_program_realize), never 718 * spliced from the parts' code. For template parts this is byte-identical to the old 719 * RET-strip-and-concatenate fusion. A body-less composite has no meaning and no 720 * realization. A body V0 realization refuses leaves the composite unrealized. */ 721 omega_program_compute_id(out_c); 722 if (out_c->body.has_body) (void)omega_program_realize(out_c); 723 return 0; 724 } 725 726 int omega_program_exec(const OmegaProgram *prog, uint64_t in_val, uint64_t *out_val) { 727 if (!prog || !out_val || !prog->is_realized || prog->realization.code_len == 0) return -1; 728 return omega_exec_native_f3(&prog->realization, in_val, 0, 0, out_val); 729 } 730 731 int omega_program_verify(OmegaProgram *prog, VerifyReport *report) { 732 if (!prog || !report || !prog->is_realized) return -1; 733 734 /* V0: Structural check */ 735 if (omega_verify_v0_structural(NULL, &prog->realization, report) != 0) { 736 return -1; 737 } 738 739 /* V2: Invariant check */ 740 if (omega_verify_v2_properties(NULL, &prog->realization, report) != 0) { 741 return -1; 742 } 743 744 prog->is_verified = true; 745 return 0; 746 } 747 748 int omega_task_init(SynthesisTask *task, const char *desc, 749 TypeTag in_type, uint16_t in_width, 750 TypeTag out_type, uint16_t out_width, 751 const uint64_t *inputs, const uint64_t *outputs, size_t count) { 752 if (!task || count > 16) return -1; 753 memset(task, 0, sizeof(SynthesisTask)); 754 755 if (desc) snprintf(task->description, sizeof(task->description), "%.120s", desc); 756 task->target_contract.input_type = in_type; 757 task->target_contract.input_width = in_width; 758 task->target_contract.output_type = out_type; 759 task->target_contract.output_width = out_width; 760 761 snprintf(task->target_contract.precondition, sizeof(task->target_contract.precondition), "x >= 0"); 762 omega_build_constraint_id(CONST_PRECONDITION, task->target_contract.precondition, &task->target_contract.precondition_id); 763 snprintf(task->target_contract.postcondition, sizeof(task->target_contract.postcondition), "%.60s", desc ? desc : "task_target"); 764 omega_build_constraint_id(CONST_POSTCONDITION, task->target_contract.postcondition, &task->target_contract.postcondition_id); 765 766 task->cost_budget.insn_count = 10; 767 task->cost_budget.reg_pressure = 4; 768 task->cost_budget.latency_cycles = 10; 769 770 task->example_count = count; 771 for (size_t i = 0; i < count; ++i) { 772 task->inputs[i] = inputs[i]; 773 task->expected_outputs[i] = outputs[i]; 774 } 775 776 /* Hash task ID */ 777 sha256_hash((const uint8_t*)task, sizeof(SynthesisTask) - OMEGA_ID_BYTES, task->task_id.bytes); 778 return 0; 779 } 780 781 int omega_task_evaluate_candidate(const SynthesisTask *task, const OmegaProgram *candidate, bool *out_solved) { 782 if (!task || !candidate || !out_solved) return -1; 783 *out_solved = false; 784 785 if (!candidate->is_realized) return 0; 786 787 /* Check type conformance */ 788 if (candidate->contract.input_type != task->target_contract.input_type || 789 candidate->contract.output_type != task->target_contract.output_type) { 790 return 0; 791 } 792 793 /* Check cost budget */ 794 if (candidate->cost.insn_count > task->cost_budget.insn_count) { 795 return 0; 796 } 797 798 /* Evaluate all input-output examples */ 799 for (size_t i = 0; i < task->example_count; ++i) { 800 uint64_t observed = 0; 801 if (omega_program_exec(candidate, task->inputs[i], &observed) != 0 || 802 observed != task->expected_outputs[i]) { 803 return 0; 804 } 805 } 806 807 *out_solved = true; 808 return 0; 809 }