From 699d0c4c673a51c77a2e1b83fdc6b11e97901f0e Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 18:30:23 +0000 Subject: [PATCH 1/8] Choose block lane runs independently of how the host sorts repeated addresses --- dev/src/opt/block_lanes.cpp | 73 ++++++--- .../o3/500-lanes-of-a-copy-written-again.ref | 129 +++++++++++++++ ...es-of-a-copy-written-again.ref.exit_status | 1 + .../o3/500-lanes-of-a-copy-written-again.t | 153 ++++++++++++++++++ 4 files changed, 337 insertions(+), 19 deletions(-) create mode 100644 pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref create mode 100644 pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref.exit_status create mode 100644 pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.t diff --git a/dev/src/opt/block_lanes.cpp b/dev/src/opt/block_lanes.cpp index 9d6593e79c..034b9d17de 100644 --- a/dev/src/opt/block_lanes.cpp +++ b/dev/src/opt/block_lanes.cpp @@ -62,6 +62,7 @@ class BlockLanes }; bool block(BlockId b); + void find_runs(const std::vector& stores, std::vector& lanes, std::vector& runs) const; bool reduction(BlockId b); bool reload(BlockId b, const std::vector& stores, const std::vector& runs); bool quiet(const Instruction& inst) const; @@ -853,6 +854,49 @@ bool BlockLanes::reduction(BlockId b) return false; } +// The runs of adjacent stores of one type that may form a group, from the +// stores sorted by address: each run's stores are laid out in `lanes` from +// its index in `runs`. Any store to a run's first address may begin it and +// any store to its last address end it (each tried in block order), so no +// choice depends on how stores to one address sort; the addresses between +// have one store each. +void BlockLanes::find_runs( + const std::vector& stores, std::vector& lanes, std::vector& runs) const +{ + // Where each address's stores begin, then the end. + std::vector address; + for (size_t i = 0; i < stores.size(); ++i) + if (i == 0 || !(stores[i].at.root == stores[i - 1].at.root) || stores[i].at.offset != stores[i - 1].at.offset) + address.push_back(i); + address.push_back(stores.size()); + for (size_t a = 0; a + 1 < address.size(); ++a) + for (size_t first = address[a]; first < address[a + 1]; ++first) + { + const Type type = body_.instructions[stores[first].id].type; + const unsigned count = type.kind() == TypeKind::F64 ? 2 : 4; + const int64_t step = type.kind() == TypeKind::F64 ? 8 : 4; + bool run = a + count < address.size(); + for (unsigned lane = 1; lane < count && run; ++lane) + { + const Stored& there = stores[address[a + lane]]; + run = there.at.root == stores[first].at.root && + there.at.offset == stores[first].at.offset + lane * step && + (lane + 1 == count || + (address[a + lane + 1] - address[a + lane] == 1 && body_.instructions[there.id].type == type)); + } + for (size_t last = run ? address[a + count - 1] : 0; run && last < address[a + count]; ++last) + { + if (body_.instructions[stores[last].id].type != type || runs.size() >= kBlockStores) + continue; + runs.push_back(lanes.size()); + lanes.push_back(stores[first]); + for (unsigned lane = 1; lane + 1 < count; ++lane) + lanes.push_back(stores[address[a + lane]]); + lanes.push_back(stores[last]); + } + } +} + bool BlockLanes::block(BlockId b) { std::vector stores; @@ -875,37 +919,28 @@ bool BlockLanes::block(BlockId b) return true; if (stores.size() < 2) return false; - std::sort(stores.begin(), stores.end(), [](const Stored& a, const Stored& b) { + // Stores to one address stay in block order. + std::sort(stores.begin(), stores.end(), [this](const Stored& a, const Stored& b) { if (a.at.root.kind != b.at.root.kind) return a.at.root.kind < b.at.root.kind; if (a.at.root.index != b.at.root.index) return a.at.root.index < b.at.root.index; - return a.at.offset < b.at.offset; + if (a.at.offset != b.at.offset) + return a.at.offset < b.at.offset; + return position_[a.id] < position_[b.id]; }); - // The runs of adjacent stores of one type that may form a group. + std::vector lanes; std::vector runs; - for (size_t i = 0; i + 1 < stores.size(); ++i) - { - const Type type = body_.instructions[stores[i].id].type; - const unsigned lanes = type.kind() == TypeKind::F64 ? 2 : 4; - const int64_t step = type.kind() == TypeKind::F64 ? 8 : 4; - bool run = i + lanes <= stores.size(); - for (unsigned lane = 1; lane < lanes && run; ++lane) - run = stores[i + lane].at.root == stores[i].at.root && - stores[i + lane].at.offset == stores[i].at.offset + lane * step && - body_.instructions[stores[i + lane].id].type == type; - if (run) - runs.push_back(i); - } - if (!runs.empty() && reload(b, stores, runs)) + find_runs(stores, lanes, runs); + if (!runs.empty() && reload(b, lanes, runs)) return true; for (size_t r = 0; r < runs.size(); ++r) { - const Type type = body_.instructions[stores[runs[r]].id].type; + const Type type = body_.instructions[lanes[runs[r]].id].type; lanes_ = type.kind() == TypeKind::F64 ? 2 : 4; lane_type_ = type; // (A group changes the block's order: it is read again.) - if (group(b, stores, runs, r)) + if (group(b, lanes, runs, r)) return true; } return false; diff --git a/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref b/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref new file mode 100644 index 0000000000..42e78aba02 --- /dev/null +++ b/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref @@ -0,0 +1,129 @@ +global @source : obj<64x4> = { + f32 1f + f32 2f + f32 3f + f32 4f + f32 5f + f32 6f + f32 7f + f32 8f + f32 9f + f32 10f + f32 11f + f32 12f + f32 13f + f32 14f + f32 15f + f32 16f +} +global @copy : obj<64x4> = { + zero 64 +} + +function @copy_then_set(%p : ptr) -> void [no_inline=yes] { + block ^entry: + %src = addr @source + %dst = addr @copy + %l0 = load typed f32 %src + store typed f32 %l0, %dst + %s1 = index i8 %src, 4 + %l1 = load typed f32 %s1 + %d1 = index i8 %dst, 4 + store typed f32 %l1, %d1 + %s2 = index i8 %src, 8 + %l2 = load typed f32 %s2 + %d2 = index i8 %dst, 8 + store typed f32 %l2, %d2 + %s3 = index i8 %src, 12 + %d3 = index i8 %dst, 12 + %t12 = load v128 %s3 + store v128 %t12, %d3 + %s7 = index i8 %src, 28 + %d7 = index i8 %dst, 28 + %t15 = load v128 %s7 + store v128 %t15, %d7 + %s11 = index i8 %src, 44 + %d11 = index i8 %dst, 44 + %t18 = load v128 %s11 + store v128 %t18, %d11 + %s15 = index i8 %src, 60 + %l15 = load typed f32 %s15 + %d15 = index i8 %dst, 60 + store typed f32 %l15, %d15 + %a0 = load typed f32 %p + store typed f32 %a0, %d1 + %a1 = load typed f32 %p + store typed f32 %a1, %d3 + return void +} +function @main() -> i32 [role=entry] { + slot $v : obj<4x4> + + block ^entry: + %p = addr $v + store typed f32 100f, %p + call void @copy_then_set(%p) + %d = addr @copy + %sum0 = load typed f32 %d + %q1 = index i8 %d, 4 + %r1 = load typed f32 %q1 + %m1 = binary add f32 %r1, %r1 + %sum1 = binary add f32 %sum0, %m1 + %q2 = index i8 %d, 8 + %r2 = load typed f32 %q2 + %m2 = binary mul f32 %r2, 3f + %sum2 = binary add f32 %sum1, %m2 + %q3 = index i8 %d, 12 + %r3 = load typed f32 %q3 + %m3 = binary mul f32 %r3, 4f + %sum3 = binary add f32 %sum2, %m3 + %q4 = index i8 %d, 16 + %r4 = load typed f32 %q4 + %m4 = binary mul f32 %r4, 5f + %sum4 = binary add f32 %sum3, %m4 + %q5 = index i8 %d, 20 + %r5 = load typed f32 %q5 + %m5 = binary mul f32 %r5, 6f + %sum5 = binary add f32 %sum4, %m5 + %q6 = index i8 %d, 24 + %r6 = load typed f32 %q6 + %m6 = binary mul f32 %r6, 7f + %sum6 = binary add f32 %sum5, %m6 + %q7 = index i8 %d, 28 + %r7 = load typed f32 %q7 + %sum7 = binary add f32 %sum6, %r7 + %q8 = index i8 %d, 32 + %r8 = load typed f32 %q8 + %m8 = binary add f32 %r8, %r8 + %sum8 = binary add f32 %sum7, %m8 + %q9 = index i8 %d, 36 + %r9 = load typed f32 %q9 + %m9 = binary mul f32 %r9, 3f + %sum9 = binary add f32 %sum8, %m9 + %q10 = index i8 %d, 40 + %r10 = load typed f32 %q10 + %m10 = binary mul f32 %r10, 4f + %sum10 = binary add f32 %sum9, %m10 + %q11 = index i8 %d, 44 + %r11 = load typed f32 %q11 + %m11 = binary mul f32 %r11, 5f + %sum11 = binary add f32 %sum10, %m11 + %q12 = index i8 %d, 48 + %r12 = load typed f32 %q12 + %m12 = binary mul f32 %r12, 6f + %sum12 = binary add f32 %sum11, %m12 + %q13 = index i8 %d, 52 + %r13 = load typed f32 %q13 + %m13 = binary mul f32 %r13, 7f + %sum13 = binary add f32 %sum12, %m13 + %q14 = index i8 %d, 56 + %r14 = load typed f32 %q14 + %sum14 = binary add f32 %sum13, %r14 + %q15 = index i8 %d, 60 + %r15 = load typed f32 %q15 + %m15 = binary add f32 %r15, %r15 + %sum15 = binary add f32 %sum14, %m15 + %e = cmp eq f32 %sum15, 1103f + %r = select i32 %e, 0, 1 + return i32 %r +} diff --git a/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref.exit_status b/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref.exit_status new file mode 100644 index 0000000000..c1d5c9342c --- /dev/null +++ b/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.ref.exit_status @@ -0,0 +1 @@ +EXIT_SUCCESS diff --git a/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.t b/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.t new file mode 100644 index 0000000000..07123cf831 --- /dev/null +++ b/pa33/tests/regression/o3/500-lanes-of-a-copy-written-again.t @@ -0,0 +1,153 @@ +# An array of f32 is copied between two globals, then some of its elements +# are written again, so those addresses each take two stores. Any store to +# the first or last address of four adjacent ones may begin or end their +# group, tried in block order: the groups do not depend on how the host's +# sort orders stores to one address. +global @source : obj<64x4> = { f32 1 f32 2 f32 3 f32 4 f32 5 f32 6 f32 7 f32 8 f32 9 f32 10 f32 11 f32 12 f32 13 f32 14 f32 15 f32 16 } +global @copy : obj<64x4> = { zero 64 } + +function @copy_then_set(%p : ptr) -> void [no_inline=yes] { + block ^entry: + %src = addr @source + %dst = addr @copy + %l0 = load typed f32 %src + store typed f32 %l0, %dst + %s1 = index i8 %src, 4 + %l1 = load typed f32 %s1 + %d1 = index i8 %dst, 4 + store typed f32 %l1, %d1 + %s2 = index i8 %src, 8 + %l2 = load typed f32 %s2 + %d2 = index i8 %dst, 8 + store typed f32 %l2, %d2 + %s3 = index i8 %src, 12 + %l3 = load typed f32 %s3 + %d3 = index i8 %dst, 12 + store typed f32 %l3, %d3 + %s4 = index i8 %src, 16 + %l4 = load typed f32 %s4 + %d4 = index i8 %dst, 16 + store typed f32 %l4, %d4 + %s5 = index i8 %src, 20 + %l5 = load typed f32 %s5 + %d5 = index i8 %dst, 20 + store typed f32 %l5, %d5 + %s6 = index i8 %src, 24 + %l6 = load typed f32 %s6 + %d6 = index i8 %dst, 24 + store typed f32 %l6, %d6 + %s7 = index i8 %src, 28 + %l7 = load typed f32 %s7 + %d7 = index i8 %dst, 28 + store typed f32 %l7, %d7 + %s8 = index i8 %src, 32 + %l8 = load typed f32 %s8 + %d8 = index i8 %dst, 32 + store typed f32 %l8, %d8 + %s9 = index i8 %src, 36 + %l9 = load typed f32 %s9 + %d9 = index i8 %dst, 36 + store typed f32 %l9, %d9 + %s10 = index i8 %src, 40 + %l10 = load typed f32 %s10 + %d10 = index i8 %dst, 40 + store typed f32 %l10, %d10 + %s11 = index i8 %src, 44 + %l11 = load typed f32 %s11 + %d11 = index i8 %dst, 44 + store typed f32 %l11, %d11 + %s12 = index i8 %src, 48 + %l12 = load typed f32 %s12 + %d12 = index i8 %dst, 48 + store typed f32 %l12, %d12 + %s13 = index i8 %src, 52 + %l13 = load typed f32 %s13 + %d13 = index i8 %dst, 52 + store typed f32 %l13, %d13 + %s14 = index i8 %src, 56 + %l14 = load typed f32 %s14 + %d14 = index i8 %dst, 56 + store typed f32 %l14, %d14 + %s15 = index i8 %src, 60 + %l15 = load typed f32 %s15 + %d15 = index i8 %dst, 60 + store typed f32 %l15, %d15 + %a0 = load typed f32 %p + store typed f32 %a0, %d1 + %a1 = load typed f32 %p + store typed f32 %a1, %d3 + return void +} + +function @main() -> i32 [role=entry] { + slot $v : obj<4x4> + block ^entry: + %p = addr $v + store typed f32 100f, %p + call void @copy_then_set(%p) + %d = addr @copy + %sum0 = load typed f32 %d + %q1 = index i8 %d, 4 + %r1 = load typed f32 %q1 + %m1 = binary mul f32 %r1, 2f + %sum1 = binary add f32 %sum0, %m1 + %q2 = index i8 %d, 8 + %r2 = load typed f32 %q2 + %m2 = binary mul f32 %r2, 3f + %sum2 = binary add f32 %sum1, %m2 + %q3 = index i8 %d, 12 + %r3 = load typed f32 %q3 + %m3 = binary mul f32 %r3, 4f + %sum3 = binary add f32 %sum2, %m3 + %q4 = index i8 %d, 16 + %r4 = load typed f32 %q4 + %m4 = binary mul f32 %r4, 5f + %sum4 = binary add f32 %sum3, %m4 + %q5 = index i8 %d, 20 + %r5 = load typed f32 %q5 + %m5 = binary mul f32 %r5, 6f + %sum5 = binary add f32 %sum4, %m5 + %q6 = index i8 %d, 24 + %r6 = load typed f32 %q6 + %m6 = binary mul f32 %r6, 7f + %sum6 = binary add f32 %sum5, %m6 + %q7 = index i8 %d, 28 + %r7 = load typed f32 %q7 + %m7 = binary mul f32 %r7, 1f + %sum7 = binary add f32 %sum6, %m7 + %q8 = index i8 %d, 32 + %r8 = load typed f32 %q8 + %m8 = binary mul f32 %r8, 2f + %sum8 = binary add f32 %sum7, %m8 + %q9 = index i8 %d, 36 + %r9 = load typed f32 %q9 + %m9 = binary mul f32 %r9, 3f + %sum9 = binary add f32 %sum8, %m9 + %q10 = index i8 %d, 40 + %r10 = load typed f32 %q10 + %m10 = binary mul f32 %r10, 4f + %sum10 = binary add f32 %sum9, %m10 + %q11 = index i8 %d, 44 + %r11 = load typed f32 %q11 + %m11 = binary mul f32 %r11, 5f + %sum11 = binary add f32 %sum10, %m11 + %q12 = index i8 %d, 48 + %r12 = load typed f32 %q12 + %m12 = binary mul f32 %r12, 6f + %sum12 = binary add f32 %sum11, %m12 + %q13 = index i8 %d, 52 + %r13 = load typed f32 %q13 + %m13 = binary mul f32 %r13, 7f + %sum13 = binary add f32 %sum12, %m13 + %q14 = index i8 %d, 56 + %r14 = load typed f32 %q14 + %m14 = binary mul f32 %r14, 1f + %sum14 = binary add f32 %sum13, %m14 + %q15 = index i8 %d, 60 + %r15 = load typed f32 %q15 + %m15 = binary mul f32 %r15, 2f + %sum15 = binary add f32 %sum14, %m15 + %e = cmp eq f32 %sum15, 1103f + %r = select i32 %e, 0, 1 + return i32 %r +} From a1f496a5bfc4fa0ff90acff611f5bbefe8e7c093 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 19:16:53 +0000 Subject: [PATCH 2/8] Make host object classes part of the LowIR contract --- dev/cppgm.cpp | 15 +- dev/lowir_library.cpp | 1 - dev/src/backend/lowir_c_metadata.cpp | 4 +- dev/src/driver/toolchain.cpp | 4 - dev/src/ir_symbol_model.h | 17 +- dev/src/lower/program_lowering.h | 6 +- dev/src/lowir/argument_facts.cpp | 43 +- dev/src/lowir/argument_facts.h | 9 +- dev/src/lowir/literals.h | 2 +- dev/src/lowir/program.h | 18 +- dev/src/lowir/text_parser.cpp | 31 +- dev/src/lowir/text_parser.h | 8 +- dev/src/lowir/text_parser_body.cpp | 10 +- dev/src/lowir/text_writer.cpp | 2 +- dev/src/lowir/validator.cpp | 13 +- pa24/README.md | 5 + ...0-host-object-classes.ref.impl.exit_status | 1 + .../behavior/900-host-object-classes.ref.mir | 551 ++++++++++++++++++ ...ost-object-classes.ref.program.exit_status | 1 + ...900-host-object-classes.ref.program.stdout | 0 pa24/tests/behavior/900-host-object-classes.t | 271 +++++++++ pa33/Makefile | 4 +- pa33/README.md | 9 +- .../run_object_lowir_roundtrip_tests.pl | 19 +- pa8/README.md | 4 +- pa8/lowir.md | 67 ++- ...ad-classes-fixed-argument.ref.exit_status} | 0 .../spec/300-bad-classes-fixed-argument.t | 6 + ...0-bad-classes-large-object.ref.exit_status | 1 + pa8/tests/spec/300-bad-classes-large-object.t | 1 + ...lasses-sseup-after-integer.ref.exit_status | 1 + .../300-bad-classes-sseup-after-integer.t | 1 + pa8/tests/spec/300-bad-classes-unknown.t | 2 +- .../spec/300-bad-result-classes-memory.t | 1 - pa8/tests/spec/300-host-object-classes.ref | 25 + .../300-host-object-classes.ref.exit_status | 1 + .../spec/300-host-object-classes.ref.stdout | 0 pa8/tests/spec/300-host-object-classes.t | 27 + 38 files changed, 1064 insertions(+), 117 deletions(-) create mode 100644 pa24/tests/behavior/900-host-object-classes.ref.impl.exit_status create mode 100644 pa24/tests/behavior/900-host-object-classes.ref.mir create mode 100644 pa24/tests/behavior/900-host-object-classes.ref.program.exit_status create mode 100644 pa24/tests/behavior/900-host-object-classes.ref.program.stdout create mode 100644 pa24/tests/behavior/900-host-object-classes.t rename pa8/tests/spec/{300-bad-result-classes-memory.ref.exit_status => 300-bad-classes-fixed-argument.ref.exit_status} (100%) create mode 100644 pa8/tests/spec/300-bad-classes-fixed-argument.t create mode 100644 pa8/tests/spec/300-bad-classes-large-object.ref.exit_status create mode 100644 pa8/tests/spec/300-bad-classes-large-object.t create mode 100644 pa8/tests/spec/300-bad-classes-sseup-after-integer.ref.exit_status create mode 100644 pa8/tests/spec/300-bad-classes-sseup-after-integer.t delete mode 100644 pa8/tests/spec/300-bad-result-classes-memory.t create mode 100644 pa8/tests/spec/300-host-object-classes.ref create mode 100644 pa8/tests/spec/300-host-object-classes.ref.exit_status create mode 100644 pa8/tests/spec/300-host-object-classes.ref.stdout create mode 100644 pa8/tests/spec/300-host-object-classes.t diff --git a/dev/cppgm.cpp b/dev/cppgm.cpp index e11649ef74..5d3bd7f56d 100644 --- a/dev/cppgm.cpp +++ b/dev/cppgm.cpp @@ -203,7 +203,7 @@ struct SourceOutputInvocation // `--hosted`: the host environment -c uses (include paths, predefined // macros, builtin declarations, hosted analysis), so a hosted source's // views are those of the program -c compiles (--emit-lowir's LowIR view - // always preprocesses so; its object dialect is the object half's, see + // always preprocesses so; the object half's program is -c's, see // run_emit_lowir_mode). `-I`, `-D` and `-U` as the driver takes them. bool hosted = false; bool nostdinc = false; @@ -1107,16 +1107,17 @@ int run_emit_lowir_mode(vector args) // The LowIR half of an object compile: a `.lowir` output (the // toolchain's LowIR object input, `-c x.lowir`) with the object // compile's debug-information level stated (-g0, -gline-tables-only) - // is the program `-c -o x.o` compiles, lowered in host-object mode, in - // the object dialect, so the object it gives is the direct compile's - // (PA33 object roundtrip). Otherwise the output is the course's LowIR - // view in the course dialect, --hosted or not (the help text: --hosted + // is the program `-c -o x.o` compiles, lowered in host-object mode, so + // the object it gives is the direct compile's (PA33 object roundtrip). + // Otherwise the output is the course's LowIR view, --hosted or not + // (the help text: --hosted // selects the host environment, which this view preprocesses in // anyway), which the LowIR lanes compare, the course's lowir and // lowiropt read and the supplied course back end runs (PA12 controls: // `--emit-lowir -O0 -o x.lowir`), as `.obj` names the course's object. - // Both state the instruction facts the lowering proved (lowir.md - // "Instruction Facts"), which the object compile reads. + // Both are LowIR that lowir and lowiropt read, and state the + // instruction facts the lowering proved (lowir.md "Instruction Facts"), + // which the object compile reads. const bool object_half = invocation.debug_level && ends_with(invocation.outfile, ".lowir"); if (object_half) invocation.hosted = true; diff --git a/dev/lowir_library.cpp b/dev/lowir_library.cpp index 24b7bc5579..d1903ee00c 100644 --- a/dev/lowir_library.cpp +++ b/dev/lowir_library.cpp @@ -54,7 +54,6 @@ CppgmLowir* cppgm_lowir_create(uint32_t version, uint32_t target) module->program.target = target == CPPGM_TARGET_LINUX ? target_model::Target::Linux : target_model::Target::MacOS; module->program.explicit_target = true; - module->program.object_facts = true; return module.release(); } catch (const InternalError&) diff --git a/dev/src/backend/lowir_c_metadata.cpp b/dev/src/backend/lowir_c_metadata.cpp index 8fdb9cdddc..34745e9410 100644 --- a/dev/src/backend/lowir_c_metadata.cpp +++ b/dev/src/backend/lowir_c_metadata.cpp @@ -40,7 +40,7 @@ const char* parameter_problem(const CppgmParameter& input, uint32_t index, lowir return "object_bytes metadata requires ptr"; if (!lowir::valid_aggregate_shape(t, shape(input.shape_element, input.shape_count))) return "invalid aggregate parameter shape"; - if (!lowir::text_holds_object_classes(t, input.classes)) + if (!lowir::valid_object_classes(t, input.classes)) return "invalid classes metadata"; if (input.pass == ir_model::PPM_INDIRECT_RESULT && (index != 0 || !result.is_void())) return "invalid indirect result parameter"; @@ -61,7 +61,7 @@ const char* boundary_problem(CppgmType result, const CppgmBoundary& input) return "invalid boundary metadata"; if (!lowir::valid_aggregate_shape(type(result), shape(input.result_shape_element, input.result_shape_count))) return "invalid aggregate result shape"; - if (!lowir::text_holds_object_classes(type(result), input.result_classes)) + if (!lowir::valid_object_classes(type(result), input.result_classes)) return "invalid result_classes metadata"; return nullptr; } diff --git a/dev/src/driver/toolchain.cpp b/dev/src/driver/toolchain.cpp index 5be3bc61e3..fd9c4a74c4 100644 --- a/dev/src/driver/toolchain.cpp +++ b/dev/src/driver/toolchain.cpp @@ -784,11 +784,7 @@ bool compile_unit( bool compile_lowir_unit( const std::string& path, const Invocation& invocation, native::EhModel eh_model, native::object::ObjectFile& object) { - // A host object's LowIR may state what course LowIR cannot (classes of - // x87 and SSEUP data, arguments to `...`, NaN payloads; see - // lowir::Program::object_facts). lowir::Program program; - program.object_facts = true; std::string error; if (!lowir::read_program_files(program, std::vector(1, path), error)) { diff --git a/dev/src/ir_symbol_model.h b/dev/src/ir_symbol_model.h index bf51bf2b8a..246e50d75d 100644 --- a/dev/src/ir_symbol_model.h +++ b/dev/src/ir_symbol_model.h @@ -245,9 +245,9 @@ const unsigned kIndexProjectionKindCount = IPK_FIELD + 1; // passes one directly may state its x86-64 psABI classification (3.2.3) in // one byte: 0 states none (each eightbyte is INTEGER); otherwise // OC_STATED with the classes of eightbytes 0 and 1 in bits 0-1 and 2-3 -// (EightbyteClass), or OC_STATED with OC_MEMORY. OC_X87, OC_COMPLEX_X87 -// and EB_SSEUP occur only in host-object LowIR (the object dialect -// `cppgm -c` reads), never in course LowIR. +// (EightbyteClass), or OC_STATED with OC_MEMORY, OC_X87 (a long double) +// or OC_COMPLEX_X87 (a complex long double). EB_SSEUP is the upper half +// of a 16-byte SSE value. enum EightbyteClass : std::uint8_t { @@ -601,9 +601,9 @@ inline const char* legacy_role_symbol(SymbolRole role) // Object class words // Appends the `classes=` word of `classes` for an object of `bytes` bytes -// (0: unknown): `memory`, or the class of each eightbyte joined by `_` -// (two when the size is unknown); in host objects also `x87` and -// `complex_x87`, and any other value as its number. +// (0: unknown): `memory`, `x87`, `complex_x87`, or the class of each +// eightbyte joined by `_` (two when the size is unknown); any other value +// (no LowIR spells it) as its number. inline void append_object_classes(std::string& out, std::uint8_t classes, std::uint64_t bytes) { if (classes == (OC_STATED | OC_MEMORY)) @@ -635,8 +635,9 @@ inline void append_object_classes(std::string& out, std::uint8_t classes, std::u } // The value of a `classes=` word naming exactly the eightbytes of `bytes` -// (two if 0); the host-object words (`x87`, `complex_x87`, `sseup`) only -// with `extensions`. 0 if the word is not one. +// (two if 0); `x87`, `complex_x87` and `sseup` only with `extensions` +// (LowIR reads them; a reader of the other words alone passes false). 0 +// if the word is not one. inline std::uint8_t object_classes_from_spelling( const char* text, std::size_t length, std::uint64_t bytes, bool extensions) { diff --git a/dev/src/lower/program_lowering.h b/dev/src/lower/program_lowering.h index ec176f0c68..a79c994e1a 100644 --- a/dev/src/lower/program_lowering.h +++ b/dev/src/lower/program_lowering.h @@ -455,11 +455,7 @@ class ProgramLowering // contract's units destroy namespace-scope objects in a `role=fini` // function instead. Thread-local destruction always uses the thread's // exit registration, including serialized LowIR. - void set_object_mode(bool on) - { - object_mode_ = on; - program_.object_facts = on; - } + void set_object_mode(bool on) { object_mode_ = on; } bool object_mode() const { return object_mode_; } // Objects for the host toolchain, rather than the course's `.obj` // runtime: exception-aware list initialization retains the host's diff --git a/dev/src/lowir/argument_facts.cpp b/dev/src/lowir/argument_facts.cpp index 2eb7dd0913..e04089581f 100644 --- a/dev/src/lowir/argument_facts.cpp +++ b/dev/src/lowir/argument_facts.cpp @@ -4,14 +4,27 @@ namespace lowir { -bool text_holds_object_classes(Type type, uint8_t classes) +bool valid_object_classes(Type type, uint8_t classes) { - // A value that is not eightbyte classes is written as a word of its own - // or as its number. - if ((classes & ir_model::OC_STATED) == 0 || (classes & ~(ir_model::OC_STATED | 15)) != 0) + using namespace ir_model; + if (classes == 0) return true; - const uint64_t bytes = object_classes_bytes(type); - return bytes == 0 || bytes > 8 || ir_model::eightbyte_class(classes, 1) == ir_model::EB_NONE; + if (type.kind() == TypeKind::I128) + return classes == (OC_STATED | EB_INTEGER | (EB_INTEGER << 2)); + if (type.kind() == TypeKind::V128) + return classes == (OC_STATED | EB_SSE | (EB_SSEUP << 2)); + if (!type.is_object() || (classes & OC_STATED) == 0) + return false; + if (classes == (OC_STATED | OC_MEMORY)) + return true; + if (classes == (OC_STATED | OC_X87)) + return type.bytes == 16; + if (classes == (OC_STATED | OC_COMPLEX_X87)) + return type.bytes == 32; + const EightbyteClass first = eightbyte_class(classes, 0); + const EightbyteClass second = eightbyte_class(classes, 1); + return (classes & ~(OC_STATED | 15)) == 0 && type.bytes <= 16 && first != EB_SSEUP && + (second != EB_SSEUP || first == EB_SSE) && (type.bytes == 0 || type.bytes > 8 || second == EB_NONE); } bool valid_aggregate_shape(Type type, ir_model::AggregateShape shape) @@ -46,8 +59,6 @@ const char* validate_argument_facts(const Program& program, const FunctionBody& if ((call.op != Opcode::Call && call.op != Opcode::VaArg) || (call.op == Opcode::Call ? fact.argument >= call.extra_count : fact.argument != 0)) return "argument fact does not name a call argument or va_arg result"; - if (fact.classes != 0 && !program.object_facts) - return "argument classes require object facts"; if (fact.type() != TypeKind::Void) { if (static_cast(fact.type()) >= static_cast(TypeKind::Obj)) @@ -70,6 +81,22 @@ const char* validate_argument_facts(const Program& program, const FunctionBody& (value.is(ValueKind::Integer) && !(passed.is_integer() || passed.is_pointer()))) return "argument_type does not match its literal representation"; } + if (fact.classes != 0) + { + Type type = call.type; + if (call.op == Opcode::Call) + { + const Signature* signature = program.call_boundary(call); + const Value value = body.operands[call.extra_first + fact.argument]; + if (signature == nullptr || signature->boundary.arity != ir_model::CAM_VARIADIC || + fact.argument < signature->parameter_count || + (!value.is(ValueKind::Temp) && !value.is(ValueKind::Slot))) + return "argument classes require an unnamed variadic argument's value"; + type = value.is(ValueKind::Temp) ? body.temps[value.index].type : body.slots[value.index].type; + } + if (!valid_object_classes(type, fact.classes)) + return "invalid argument or va_arg classes"; + } const auto shape = fact.shape(); if (shape.element != ir_model::AggregateElement::None) { diff --git a/dev/src/lowir/argument_facts.h b/dev/src/lowir/argument_facts.h index 0d75c2b870..ed0c727799 100644 --- a/dev/src/lowir/argument_facts.h +++ b/dev/src/lowir/argument_facts.h @@ -13,9 +13,12 @@ inline uint64_t object_classes_bytes(Type type) return type.kind() == TypeKind::I128 || type.kind() == TypeKind::F80 ? 16 : (integer_bits(type.kind()) + 7) / 8; } -// A classes value the object dialect's text holds for a value of `type`: -// eightbyte words name only the eightbytes the type has. -bool text_holds_object_classes(Type type, uint8_t classes); +// Classes a value of `type` may state (lowir.md "Object ABI Conventions"): +// none; on a direct object `memory`, `x87` (16 bytes), `complex_x87` (32 +// bytes) or, on one of at most 16 bytes, a class for each eightbyte it has +// (`sseup` only after `sse`); `integer_integer` on an i128 and `sse_sseup` +// on a v128. +bool valid_object_classes(Type type, uint8_t classes); bool valid_aggregate_shape(Type type, ir_model::AggregateShape shape); bool valid_this_return(const Program& program, const Signature& signature); diff --git a/dev/src/lowir/literals.h b/dev/src/lowir/literals.h index 4ead1d8d18..0de8d8615b 100644 --- a/dev/src/lowir/literals.h +++ b/dev/src/lowir/literals.h @@ -38,7 +38,7 @@ enum class SpecialFloat : uint8_t Literal special_float(TypeKind kind, SpecialFloat which, bool negative); -// Object mode (Program::object_facts): the NaN `which` whose fraction bits +// The NaN `which` whose fraction bits // below the quiet bit are `payload` in place of the default ones (an f80 // keeps its integer bit), as `nan()` and `snan()` spell // it. False if the payload does not fit below the quiet bit, or leaves a diff --git a/dev/src/lowir/program.h b/dev/src/lowir/program.h index e3e7460336..bd64f553f9 100644 --- a/dev/src/lowir/program.h +++ b/dev/src/lowir/program.h @@ -161,13 +161,12 @@ struct FunctionBody // --------------------------------------------------------------------------- // Signatures and symbols -// Object mode (Program::object_facts: `classes=` on a parameter, -// `result_classes=` on a boundary), as `obj` carries no +// `classes=` on a parameter, a variadic argument or a va_arg result and +// `result_classes=` on a boundary, as `obj` carries no // field types: the x86-64 psABI classification (3.2.3) of a direct object -// parameter or result (or an i128 one holding a member function pointer's -// pair), which an object-mode lowering states from the class's layout and -// a host object's call boundary follows: ObjectClassBits and -// EightbyteClass of ir_symbol_model.h. +// (or of an i128 holding a member function pointer's pair, or a v128), +// which the lowering states from the class's layout and a call boundary +// follows: ObjectClassBits and EightbyteClass of ir_symbol_model.h. // The named-value metadata (role, linkage, binding, storage and the // SymbolFlag bits) is the scaffold's record; the names are interned. @@ -411,13 +410,6 @@ struct Program std::vector equivalent_entries; std::vector forward_boundaries; std::vector forward_globals; - // A host-object program (the lowering's object mode, or text the - // toolchain reads): its text states the facts the object back end reads - // beyond the course's LowIR (x87 and SSEUP classes, classes of other - // types and of arguments to `...`, repeated data, NaN payloads), so an - // object compiled from it is the one compiled from the program; a - // reader of course LowIR rejects them. - bool object_facts = false; // Object mode, not in the LowIR text: thunks the object back end emits // as `this` adjusted in its register and a jump to the target, so the // arguments past a variadic function's fixed ones stay where the caller diff --git a/dev/src/lowir/text_parser.cpp b/dev/src/lowir/text_parser.cpp index dedb628ebf..58d7f80648 100644 --- a/dev/src/lowir/text_parser.cpp +++ b/dev/src/lowir/text_parser.cpp @@ -733,24 +733,19 @@ bool Parser::at_word(const char* spelling) const return at(TokenKind::Word) && token().length == length && std::memcmp(token().text, spelling, length) == 0; } -uint8_t Parser::parse_object_classes(Type type) +uint8_t Parser::parse_object_classes(const Type* type) { - // lowir.md "Object ABI Conventions": a direct object of at most 16 - // bytes, or its two-integer scalar carrier with eight-byte stack alignment. - const uint64_t bytes = object_classes_bytes(type); - const bool wide_carrier = type.kind() == TypeKind::I128; - if (!program_.object_facts && ((!type.is_object() && !wide_carrier) || bytes > 16)) + // lowir.md "Object ABI Conventions": a direct object, the two-integer + // scalar carrier of one with eight-byte stack alignment, or a v128. An + // argument's or va_arg's classes name two eightbytes, and the validator + // checks them against its type. + if (type != nullptr && !type->is_object() && type->kind() != TypeKind::I128 && type->kind() != TypeKind::V128) fail("classes metadata requires a direct object of matching size"); uint8_t classes = 0; if (at(TokenKind::Word)) - classes = ir_model::object_classes_from_spelling(token().text, token().length, bytes, program_.object_facts); - else if (at(TokenKind::Number) && program_.object_facts) - { - const uint64_t value = parse_positive(token().text, token().length); - classes = value < 256 ? static_cast(value) : 0; - } - if (classes == 0 || - (!program_.object_facts && wide_carrier && classes != (OC_STATED | EB_INTEGER | (EB_INTEGER << 2)))) + classes = ir_model::object_classes_from_spelling( + token().text, token().length, type != nullptr ? object_classes_bytes(*type) : 0, true); + if (classes == 0 || (type != nullptr && !valid_object_classes(*type, classes))) fail("invalid classes metadata"); advance(); return classes; @@ -795,11 +790,9 @@ void Parser::parse_metadata_item( fail("function metadata requires a signature"); if (key == MetadataKey::ResultClasses) { - if (result_classes_ == nullptr) + if (result_classes_ == nullptr || result_type_ == nullptr) fail("result_classes metadata requires a boundary"); - *result_classes_ = parse_object_classes(*result_type_); - if (*result_classes_ == (OC_STATED | OC_MEMORY) && !program_.object_facts) - fail("a memory-class result is returned through an indirect_result parameter"); + *result_classes_ = parse_object_classes(result_type_); return; } if (key == MetadataKey::ResultShape) @@ -1046,7 +1039,7 @@ void Parser::parse_parameter_metadata(Parameter& parameter) if ((seen & bit) != 0) fail("duplicate metadata key: classes"); seen |= bit; - parameter.classes = parse_object_classes(parameter.type); + parameter.classes = parse_object_classes(¶meter.type); continue; } if ((seen & bit) != 0) diff --git a/dev/src/lowir/text_parser.h b/dev/src/lowir/text_parser.h index b05f9cd3c5..de942602cc 100644 --- a/dev/src/lowir/text_parser.h +++ b/dev/src/lowir/text_parser.h @@ -99,10 +99,10 @@ class Parser void advance() { lexer_->advance(); } bool at(TokenKind kind) const { return token().kind == kind; } bool at_word(const char* spelling) const; - // Object mode: an ObjectClassBits word (or number) at the token; - // the program then states object facts. - // Classes of a value of `type` (lowir.md "Object ABI Conventions"). - uint8_t parse_object_classes(Type type); + // The ObjectClassBits word at the token: classes of a value of `*type`, + // or of an argument or va_arg result (null; lowir.md "Object ABI + // Conventions"). + uint8_t parse_object_classes(const Type* type); WordInfo word(const Token& token) const; bool at_keyword(Keyword keyword) const; bool accept(TokenKind kind); diff --git a/dev/src/lowir/text_parser_body.cpp b/dev/src/lowir/text_parser_body.cpp index eb732b968a..56951f2ea6 100644 --- a/dev/src/lowir/text_parser_body.cpp +++ b/dev/src/lowir/text_parser_body.cpp @@ -482,7 +482,7 @@ bool Parser::parse_value_instruction(FunctionBuilder& builder, Opcode keyword, I do { const bool shape = at_word(ir_model::spelling(MetadataKey::Shape)); - if (!shape && (!program_.object_facts || !at_word(ir_model::spelling(MetadataKey::Classes)))) + if (!shape && !at_word(ir_model::spelling(MetadataKey::Classes))) fail("invalid va_arg metadata"); advance(); expect(TokenKind::Equals, "="); @@ -495,8 +495,7 @@ bool Parser::parse_value_instruction(FunctionBuilder& builder, Opcode keyword, I builder.body().argument_facts.push_back(ArgumentFacts{ id, 0, 0, value }); } else - builder.body().argument_facts.push_back( - ArgumentFacts{ id, 0, parse_object_classes(Type::object(16, 3)) }); + builder.body().argument_facts.push_back(ArgumentFacts{ id, 0, parse_object_classes(nullptr) }); } while (accept(TokenKind::Comma)); expect(TokenKind::RBracket, "]"); } @@ -817,8 +816,7 @@ void Parser::parse_call(FunctionBuilder& builder, Instruction& inst) } const bool argument_type = at_word(ir_model::spelling(MetadataKey::ArgumentType)); const bool argument_shape = at_word(ir_model::spelling(MetadataKey::ArgumentShape)); - if (!argument_type && !argument_shape && - (!program_.object_facts || !at_word(ir_model::spelling(MetadataKey::Classes)))) + if (!argument_type && !argument_shape && !at_word(ir_model::spelling(MetadataKey::Classes))) fail("invalid call metadata"); advance(); expect(TokenKind::Equals, "="); @@ -847,7 +845,7 @@ void Parser::parse_call(FunctionBuilder& builder, Instruction& inst) } else { - const uint8_t classes = parse_object_classes(Type::object(16, 3)); + const uint8_t classes = parse_object_classes(nullptr); builder.body().argument_facts.push_back(ArgumentFacts{ id, static_cast(argument), classes }); } } while (accept(TokenKind::Comma)); diff --git a/dev/src/lowir/text_writer.cpp b/dev/src/lowir/text_writer.cpp index 97f03ba2ac..866b08b290 100644 --- a/dev/src/lowir/text_writer.cpp +++ b/dev/src/lowir/text_writer.cpp @@ -1071,7 +1071,7 @@ void Writer::argument_facts(const Instruction& inst, bool& open) } append_aggregate_shape(out_, entry.shape()); } - if (entry.classes != 0 && program_.object_facts) + if (entry.classes != 0) { key(open, MetadataKey::Classes); if (inst.op == Opcode::Call) diff --git a/dev/src/lowir/validator.cpp b/dev/src/lowir/validator.cpp index 298ac61789..3b12914c87 100644 --- a/dev/src/lowir/validator.cpp +++ b/dev/src/lowir/validator.cpp @@ -121,7 +121,8 @@ const char* misplaced_fact(const Instruction& inst) return nullptr; } -// The argument kinds va_arg reads from the variadic area. +// The argument kinds va_arg reads from the variadic area: also an object, +// a long double and an i128 (psABI 3.5.7). bool is_va_arg_type(Type type) { switch (type.kind()) @@ -133,8 +134,11 @@ bool is_va_arg_type(Type type) case TypeKind::I32: case TypeKind::U32: case TypeKind::I64: + case TypeKind::I128: case TypeKind::F64: + case TypeKind::F80: case TypeKind::Ptr: + case TypeKind::Obj: return true; default: return false; @@ -1041,12 +1045,7 @@ bool Validator::check_instruction(InstId id, const Instruction& inst, BlockId bl case Opcode::VaArg: if (!value_type(inst.ops[0], type) || !type.is_pointer()) return fail("va_arg requires a pointer value"); - // A host object's program also reads an object, a long double or an - // i128 (psABI 3.5.7; the toolchain's own LowIR, see - // Program::object_facts). - if (!is_va_arg_type(inst.type) && - !((program_.object_facts || target_model::is_wasm(program_.target)) && - (inst.type.is_object() || inst.type.kind() == TypeKind::F80 || inst.type.kind() == TypeKind::I128))) + if (!is_va_arg_type(inst.type)) return fail("va_arg scalar type is not supported"); return true; case Opcode::ReadMxcsr: diff --git a/pa24/README.md b/pa24/README.md index a37b20f750..1fa7ec6bbc 100644 --- a/pa24/README.md +++ b/pa24/README.md @@ -375,6 +375,11 @@ PA10-PA23, including: eightbyte in a GPR or an XMM register (or nowhere) as the parameter's `classes` or the function's `result_classes` metadata states, and the whole object on the stack for `classes=memory` or when its registers run out +- the host object classes (`../pa8/lowir.md`, Object ABI Conventions): + `sse_sseup` as one XMM register, an `x87` result in `st0`, a `complex_x87` + result in `st0` and `st1`, a `memory` result through the hidden destination, + `x87` and `complex_x87` arguments on the stack, and the classes a call states + for an object passed to `...` and a `va_arg` for the object it reads - `select`, as a conditional move or branches (an `f32` or `f64` result keeps the bits of the chosen value), the `ctz` and `clz` bit scans and `sqrt` - supported variadic calls and `va_start` register-save state for GPR and XMM diff --git a/pa24/tests/behavior/900-host-object-classes.ref.impl.exit_status b/pa24/tests/behavior/900-host-object-classes.ref.impl.exit_status new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/pa24/tests/behavior/900-host-object-classes.ref.impl.exit_status @@ -0,0 +1 @@ +0 diff --git a/pa24/tests/behavior/900-host-object-classes.ref.mir b/pa24/tests/behavior/900-host-object-classes.ref.mir new file mode 100644 index 0000000000..6a692f7186 --- /dev/null +++ b/pa24/tests/behavior/900-host-object-classes.ref.mir @@ -0,0 +1,551 @@ +machine_ir x86_64 linux + +startup + call @main [args=()] + mov rdi, rax + exit + +global @low + storage scalar f64 + init f64 0.0 + +global @wide + storage data + item i64 1 + item i64 2 + item i64 3 + item i64 4 + item i64 5 + item i64 6 + +function @x87_result + abi + param %v -> [rbp+16] : f80 + return obj<16x16> -> rax + frame + stack_size 16 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $home -> [rbp-16] : obj<16x16> + + block ^entry + fmov.f80 [rbp-16], [rbp+16] + fret.f80 [rbp-16] + +function @f80_result + abi + return f80 -> st0 + frame + stack_size 0 + scratch_bytes 0 + frame_pointer keep + epilogues shared + + block ^entry + fret.f80 2.25L + +function @complex_result + abi + param %re -> [rbp+16] : f80 + param %im -> [rbp+32] : f80 + return obj<32x16> -> [rax] + frame + stack_size 32 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $home -> [rbp-32] : obj<32x16> + + block ^entry + fmov.f80 [rbp-32], [rbp+16] + fmov.f80 [rbp-16], [rbp+32] + fret.f80 [rbp-32], [rbp-16] + +function @memory_result + abi + param %a -> rsi : i64 + param %b -> rdx : i64 + return obj<16x8> -> rax + frame + stack_size 32 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $home -> [rbp-16] : obj<16x8> + + block ^entry + store.ptr [rbp-24], rdi + store.i64 [rbp-16], rsi + store.i64 [rbp-8], rdx + load.ptr rax, [rbp-24] + copy_bytes 16x8, rax, [rbp-16] + ret rax + +function @sseup_argument + abi + param %x -> xmm0 : obj<16x16> + param %y -> xmm1 : f64 + return f64 -> xmm0 + frame + stack_size 32 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $home -> [rbp-16] : obj<16x16> + param-slot %x -> [rbp-16] : obj<16x16> + param-slot %y -> [rbp-24] : f64 + + block ^entry + fmov.i128 [rbp-16], xmm0 + fmov.f64 [rbp-24], xmm1 + fmov.f64 xmm0, [rbp-16] + fmov.f64 @low, xmm0 + fmov.f64 xmm0, [rbp-24] + ret xmm0 + +function @sseup_result + abi + param %a -> rdi : i64 + param %b -> rsi : i64 + return obj<16x16> -> rax + frame + stack_size 16 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $home -> [rbp-16] : obj<16x16> + + block ^entry + store.i64 [rbp-16], rdi + store.i64 [rbp-8], rsi + fmov.i128 xmm0, [rbp-16] + ret + +function @read_scalars + abi + param %n -> rdi : i32 + return i32 -> rax + frame + stack_size 208 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $list -> [rbp-24] : obj<24x8> + temp %va-register-save -> [rbp-208] : obj<176x16> + + block ^entry + store.i64 [rbp-208], rdi + store.i64 [rbp-200], rsi + store.i64 [rbp-192], rdx + store.i64 [rbp-184], rcx + store.i64 [rbp-176], r8 + store.i64 [rbp-168], r9 + fmov.i128 [rbp-160], xmm0 + fmov.i128 [rbp-144], xmm1 + fmov.i128 [rbp-128], xmm2 + fmov.i128 [rbp-112], xmm3 + fmov.i128 [rbp-96], xmm4 + fmov.i128 [rbp-80], xmm5 + fmov.i128 [rbp-64], xmm6 + fmov.i128 [rbp-48], xmm7 + va_start [rbp-24], [rbp-208] + va_arg.f64 xmm0, [rbp-24] + va_arg.i64 r8, [rbp-24] + feq.f64 r9, xmm0, 0.5 + cmp.i64 r8, 7 + sete r8 + movzx r8, r8 + and r9, r8 + ret r9 + +function @read_pair + abi + param %n -> rdi : i32 + return i32 -> rax + frame + stack_size 240 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $list -> [rbp-24] : obj<24x8> + slot $home -> [rbp-40] : obj<16x8> + temp %va-register-save -> [rbp-224] : obj<176x16> + temp %pair -> [rbp-240] : obj<16x8> + + block ^entry + store.i64 [rbp-224], rdi + store.i64 [rbp-216], rsi + store.i64 [rbp-208], rdx + store.i64 [rbp-200], rcx + store.i64 [rbp-192], r8 + store.i64 [rbp-184], r9 + fmov.i128 [rbp-176], xmm0 + fmov.i128 [rbp-160], xmm1 + fmov.i128 [rbp-144], xmm2 + fmov.i128 [rbp-128], xmm3 + fmov.i128 [rbp-112], xmm4 + fmov.i128 [rbp-96], xmm5 + fmov.i128 [rbp-80], xmm6 + fmov.i128 [rbp-64], xmm7 + va_start [rbp-24], [rbp-224] + va_arg.obj [rbp-240], [rbp-24] + copy_bytes 16x8, [rbp-40], [rbp-240] + fmov.f64 xmm0, [rbp-40] + load.i64 r8, [rbp-32] + feq.f64 r9, xmm0, 0.5 + cmp.i64 r8, 7 + sete r8 + movzx r8, r8 + and r9, r8 + ret r9 + +function @read_f80 + abi + param %n -> rdi : i32 + return i32 -> rax + frame + stack_size 224 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $list -> [rbp-24] : obj<24x8> + temp %va-register-save -> [rbp-208] : obj<176x16> + temp %v -> [rbp-224] : f80 + + block ^entry + store.i64 [rbp-208], rdi + store.i64 [rbp-200], rsi + store.i64 [rbp-192], rdx + store.i64 [rbp-184], rcx + store.i64 [rbp-176], r8 + store.i64 [rbp-168], r9 + fmov.i128 [rbp-160], xmm0 + fmov.i128 [rbp-144], xmm1 + fmov.i128 [rbp-128], xmm2 + fmov.i128 [rbp-112], xmm3 + fmov.i128 [rbp-96], xmm4 + fmov.i128 [rbp-80], xmm5 + fmov.i128 [rbp-64], xmm6 + fmov.i128 [rbp-48], xmm7 + va_start [rbp-24], [rbp-208] + va_arg.obj [rbp-224], [rbp-24] + feq.f80 rax, [rbp-224], 1.25L + ret rax + +function @read_x87 + abi + param %n -> rdi : i32 + return i32 -> rax + frame + stack_size 256 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $list -> [rbp-24] : obj<24x8> + slot $home -> [rbp-48] : obj<16x16> + temp %va-register-save -> [rbp-224] : obj<176x16> + temp %object -> [rbp-240] : obj<16x16> + temp %v -> [rbp-256] : f80 + + block ^entry + store.i64 [rbp-224], rdi + store.i64 [rbp-216], rsi + store.i64 [rbp-208], rdx + store.i64 [rbp-200], rcx + store.i64 [rbp-192], r8 + store.i64 [rbp-184], r9 + fmov.i128 [rbp-176], xmm0 + fmov.i128 [rbp-160], xmm1 + fmov.i128 [rbp-144], xmm2 + fmov.i128 [rbp-128], xmm3 + fmov.i128 [rbp-112], xmm4 + fmov.i128 [rbp-96], xmm5 + fmov.i128 [rbp-80], xmm6 + fmov.i128 [rbp-64], xmm7 + va_start [rbp-24], [rbp-224] + va_arg.obj [rbp-240], [rbp-24] + copy_bytes 16x16, [rbp-48], [rbp-240] + fmov.f80 [rbp-256], [rbp-48] + feq.f80 rax, [rbp-256], 1.25L + ret rax + +function @read_memory + abi + param %n -> rdi : i32 + return i64 -> rax + frame + stack_size 304 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $list -> [rbp-24] : obj<24x8> + slot $home -> [rbp-72] : obj<48x8> + temp %va-register-save -> [rbp-256] : obj<176x16> + temp %object -> [rbp-304] : obj<48x8> + + block ^entry + store.i64 [rbp-256], rdi + store.i64 [rbp-248], rsi + store.i64 [rbp-240], rdx + store.i64 [rbp-232], rcx + store.i64 [rbp-224], r8 + store.i64 [rbp-216], r9 + fmov.i128 [rbp-208], xmm0 + fmov.i128 [rbp-192], xmm1 + fmov.i128 [rbp-176], xmm2 + fmov.i128 [rbp-160], xmm3 + fmov.i128 [rbp-144], xmm4 + fmov.i128 [rbp-128], xmm5 + fmov.i128 [rbp-112], xmm6 + fmov.i128 [rbp-96], xmm7 + va_start [rbp-24], [rbp-256] + va_arg.obj [rbp-304], [rbp-24] + copy_bytes 48x8, [rbp-72], [rbp-304] + load.i64 r8, [rbp-72] + load.i64 r9, [rbp-64] + load.i64 rdi, [rbp-32] + add r8, r9 + add r8, rdi + ret r8 + +function @read_i128 + abi + param %n -> rdi : i32 + return i128 -> rax + frame + stack_size 224 + scratch_bytes 0 + frame_pointer keep + epilogues shared + slot $list -> [rbp-24] : obj<24x8> + temp %va-register-save -> [rbp-208] : obj<176x16> + temp %v -> [rbp-224] : i128 + + block ^entry + store.i64 [rbp-208], rdi + store.i64 [rbp-200], rsi + store.i64 [rbp-192], rdx + store.i64 [rbp-184], rcx + store.i64 [rbp-176], r8 + store.i64 [rbp-168], r9 + fmov.i128 [rbp-160], xmm0 + fmov.i128 [rbp-144], xmm1 + fmov.i128 [rbp-128], xmm2 + fmov.i128 [rbp-112], xmm3 + fmov.i128 [rbp-96], xmm4 + fmov.i128 [rbp-80], xmm5 + fmov.i128 [rbp-64], xmm6 + fmov.i128 [rbp-48], xmm7 + va_start [rbp-24], [rbp-208] + va_arg.obj [rbp-224], [rbp-24] + load.i64 rax, [rbp-224] + load.i64 rdx, [rbp-216] + ret + +function @main + abi + return i32 -> rax + frame + stack_size 432 + scratch_bytes 0 + frame_pointer keep + epilogues shared + preserve rbx r12 r13 r14 r15 + slot $out -> [rbp-16] : obj<16x16> + slot $complex -> [rbp-48] : obj<32x16> + slot $pair -> [rbp-64] : obj<16x8> + slot $quad -> [rbp-80] : obj<16x16> + slot $extended -> [rbp-96] : obj<16x16> + temp %r0 -> [rbp-112] : f80 + temp %r1 -> [rbp-128] : obj<16x16> + temp %v1 -> [rbp-144] : f80 + temp %r2 -> [rbp-176] : obj<32x16> + temp %re -> [rbp-192] : f80 + temp %im -> [rbp-208] : f80 + temp %e4 -> [rbp-216] : i32 + temp %r5 -> [rbp-240] : obj<16x16> + temp %e5 -> [rbp-248] : i32 + temp %pv -> [rbp-264] : obj<16x8> + temp %e7 -> [rbp-272] : i32 + temp %xv -> [rbp-288] : obj<16x16> + temp %e8 -> [rbp-296] : i32 + temp %e9 -> [rbp-304] : i32 + temp %wv -> [rbp-352] : obj<48x8> + temp %e10 -> [rbp-360] : i32 + temp %r11 -> [rbp-384] : i128 + + block ^entry + mov r8, @x87_result + sub rsp, 16 + fmov.f80 [rsp], 1.5L + call *r8 [args=(), stack=16] + add rsp, 16 + fstp.f80 [rbp-112] + feq.f80 r8, [rbp-112], 1.5L + test.u8 r8, r8 + sete rbx + movzx rbx, rbx + mov r8, @f80_result + call *r8 [args=()] + fstp.f80 [rbp-128] + copy_bytes 16x16, [rbp-16], [rbp-128] + fmov.f80 [rbp-144], [rbp-16] + feq.f80 r8, [rbp-144], 2.25L + test.u8 r8, r8 + sete r12 + movzx r12, r12 + sub rsp, 32 + fmov.f80 [rsp], 0.5L + fmov.f80 [rsp+16], 4.0L + call @complex_result [args=(), stack=32] + add rsp, 32 + fstp.f80 [rbp-176] + fstp.f80 [rbp-160] + copy_bytes 32x16, [rbp-48], [rbp-176] + fmov.f80 [rbp-192], [rbp-48] + fmov.f80 [rbp-208], [rbp-32] + feq.f80 r8, [rbp-192], 0.5L + feq.f80 r9, [rbp-208], 4.0L + and r8, r9 + test.u8 r8, r8 + sete r13 + movzx r13, r13 + mov r8, @memory_result + lea r14, [rbp-64] + mov rdi, r14 + mov rsi, 11 + mov rdx, 12 + call *r8 [args=(rdx,rsi,rdi)] + load.i64 r8, [r14] + load.i64 r9, [r14+8] + cmp.i64 r8, 11 + sete r8 + movzx r8, r8 + cmp.i64 r9, 12 + sete r9 + movzx r9, r9 + and r8, r9 + test.u8 r8, r8 + sete r15 + movzx r15, r15 + mov r8, @sseup_argument + fmov.f64 xmm0, 1.5 + fmov.f64 xmm1, 2.5 + call *r8 [args=(xmm0,xmm1)] + fmov.f64 xmm1, @low + feq.f64 r8, xmm0, 2.5 + feq.f64 r9, xmm1, 1.5 + and r8, r9 + test.u8 r8, r8 + sete r10 + movzx r10, r10 + store.i32 [rbp-216], r10 + mov rdi, 21 + mov rsi, 22 + call @sseup_result [args=(rsi,rdi)] + fmov.i128 [rbp-240], xmm0 + copy_bytes 16x16, [rbp-80], [rbp-240] + load.i64 r8, [rbp-80] + load.i64 r9, [rbp-72] + cmp.i64 r8, 21 + sete r8 + movzx r8, r8 + cmp.i64 r9, 22 + sete r9 + movzx r9, r9 + and r8, r9 + test.u8 r8, r8 + sete r10 + movzx r10, r10 + store.i32 [rbp-248], r10 + fmov.f64 [r14], 0.5 + store.i64 [r14+8], 7 + copy_bytes 16x8, [rbp-264], [r14] + mov rdi, 1 + load.i64 rsi, [rbp-256] + fmov.f64 xmm0, [rbp-264] + mov rax, 1 + call @read_scalars [args=(rax,rsi,rdi,xmm0), variadic] + sext.i32 rax + cmp.i32 rax, 1 + setne r14 + movzx r14, r14 + mov rdi, 1 + mov rsi, 7 + fmov.f64 xmm0, 0.5 + mov rax, 1 + call @read_pair [args=(rax,rsi,rdi,xmm0), variadic] + sext.i32 rax + cmp.i32 rax, 1 + setne r10 + movzx r10, r10 + store.i32 [rbp-272], r10 + fmov.f80 [rbp-96], 1.25L + copy_bytes 16x16, [rbp-288], [rbp-96] + sub rsp, 16 + copy_bytes 16x8, [rsp], [rbp-288] + mov rdi, 1 + mov rax, 0 + call @read_f80 [args=(rax,rdi), stack=16, variadic] + add rsp, 16 + sext.i32 rax + cmp.i32 rax, 1 + setne r10 + movzx r10, r10 + store.i32 [rbp-296], r10 + sub rsp, 16 + fmov.f80 [rsp], 1.25L + mov rdi, 1 + mov rax, 0 + call @read_x87 [args=(rax,rdi), stack=16, variadic] + add rsp, 16 + sext.i32 rax + cmp.i32 rax, 1 + setne r10 + movzx r10, r10 + store.i32 [rbp-304], r10 + copy_bytes 48x8, [rbp-352], @wide + sub rsp, 48 + copy_bytes 48x8, [rsp], [rbp-352] + mov rdi, 1 + mov rax, 0 + call @read_memory [args=(rax,rdi), stack=48, variadic] + add rsp, 48 + cmp.i64 rax, 9 + setne r10 + movzx r10, r10 + store.i32 [rbp-360], r10 + mov rdi, 1 + mov rsi, 5 + mov rdx, 6 + mov rax, 0 + call @read_i128 [args=(rax,rdx,rsi,rdi), variadic] + store.i64 [rbp-384], rax + store.i64 [rbp-376], rdx + set.eq.i128 r8, [rbp-384], 0x00000000000000060000000000000005 + test.u8 r8, r8 + sete r8 + movzx r8, r8 + add.i32 rbx, r12 + sext.i32 rbx + add.i32 rbx, r13 + sext.i32 rbx + add.i32 rbx, r15 + sext.i32 rbx + add.i32 rbx, [rbp-216] + sext.i32 rbx + add.i32 rbx, [rbp-248] + sext.i32 rbx + add.i32 rbx, r14 + sext.i32 rbx + add.i32 rbx, [rbp-272] + sext.i32 rbx + add.i32 rbx, [rbp-296] + sext.i32 rbx + add.i32 rbx, [rbp-304] + sext.i32 rbx + add.i32 rbx, [rbp-360] + sext.i32 rbx + add.i32 rbx, r8 + ret rbx diff --git a/pa24/tests/behavior/900-host-object-classes.ref.program.exit_status b/pa24/tests/behavior/900-host-object-classes.ref.program.exit_status new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/pa24/tests/behavior/900-host-object-classes.ref.program.exit_status @@ -0,0 +1 @@ +0 diff --git a/pa24/tests/behavior/900-host-object-classes.ref.program.stdout b/pa24/tests/behavior/900-host-object-classes.ref.program.stdout new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pa24/tests/behavior/900-host-object-classes.t b/pa24/tests/behavior/900-host-object-classes.t new file mode 100644 index 0000000000..12e7bf2fd1 --- /dev/null +++ b/pa24/tests/behavior/900-host-object-classes.t @@ -0,0 +1,271 @@ +# lowir.md "Object ABI Conventions": each class a host object's boundary +# states places the value where an equivalent form does. Each check calls +# through a pointer whose call signature, or a va_arg, states the other +# form, so a misplaced value fails; main returns the number of failed checks. + +global @low : f64 = 0.0 +global @wide = { + i64 1 + i64 2 + i64 3 + i64 4 + i64 5 + i64 6 +} + +# x87: one long double, returned in st0 as an f80 result is. +function @x87_result(%v : f80) -> obj<16x16> [result_classes=x87, no_inline=yes] { + slot $home : obj<16x16> + block ^entry: + %home = addr $home + store f80 %v, %home + return obj<16x16> $home +} + +function @f80_result() -> f80 [no_inline=yes] { + block ^entry: + return f80 2.25L +} + +# complex_x87: the real part in st0, the imaginary part in st1. +function @complex_result(%re : f80, %im : f80) -> obj<32x16> [result_classes=complex_x87, no_inline=yes] { + slot $home : obj<32x16> + block ^entry: + %home = addr $home + store f80 %re, %home + %high = index i8 [projection=field] %home, 16 + store f80 %im, %high + return obj<32x16> $home +} + +# memory: returned through the hidden destination, as an indirect_result +# parameter's caller passes it. +function @memory_result(%a : i64, %b : i64) -> obj<16x8> [result_classes=memory, no_inline=yes] { + slot $home : obj<16x8> + block ^entry: + %home = addr $home + store i64 %a, %home + %high = index i8 [projection=field] %home, 8 + store i64 %b, %high + return obj<16x8> $home +} + +# sse_sseup: the whole object in one XMM register, so the f64 after it +# takes the next one. +function @sseup_argument(%x : obj<16x16> [classes=sse_sseup], %y : f64) -> f64 [no_inline=yes] { + slot $home : obj<16x16> + block ^entry: + %home = addr $home + copyobj 16x16 %x, %home + %first = load f64 %home + store f64 %first, @low + return f64 %y +} + +function @sseup_result(%a : i64, %b : i64) -> obj<16x16> [result_classes=sse_sseup, no_inline=yes] { + slot $home : obj<16x16> + block ^entry: + %home = addr $home + store i64 %a, %home + %high = index i8 [projection=field] %home, 8 + store i64 %b, %high + return obj<16x16> $home +} + +# Arguments past the fixed parameters: 1 when the values read are 0.5 and 7. +function @read_scalars(%n : i32) -> i32 [arity=variadic, no_inline=yes] { + slot $list : obj<24x8> + block ^entry: + %list = addr $list + va_start %list + %d = va_arg f64 %list + %i = va_arg i64 %list + %d_ok = cmp eq f64 %d, 0.5 + %i_ok = cmp eq i64 %i, 7 + %both = binary and i1 %d_ok, %i_ok + %result = convert zext i32 i1 %both + return i32 %result +} + +function @read_pair(%n : i32) -> i32 [arity=variadic, no_inline=yes] { + slot $list : obj<24x8> + slot $home : obj<16x8> + block ^entry: + %list = addr $list + va_start %list + %pair = va_arg obj<16x8> %list [classes=sse_integer] + %home = addr $home + copyobj 16x8 %pair, %home + %d = load f64 %home + %high = index i8 [projection=field] %home, 8 + %i = load i64 %high + %d_ok = cmp eq f64 %d, 0.5 + %i_ok = cmp eq i64 %i, 7 + %both = binary and i1 %d_ok, %i_ok + %result = convert zext i32 i1 %both + return i32 %result +} + +function @read_f80(%n : i32) -> i32 [arity=variadic, no_inline=yes] { + slot $list : obj<24x8> + block ^entry: + %list = addr $list + va_start %list + %v = va_arg f80 %list + %ok = cmp eq f80 %v, 1.25L + %result = convert zext i32 i1 %ok + return i32 %result +} + +function @read_x87(%n : i32) -> i32 [arity=variadic, no_inline=yes] { + slot $list : obj<24x8> + slot $home : obj<16x16> + block ^entry: + %list = addr $list + va_start %list + %object = va_arg obj<16x16> %list [classes=x87] + %home = addr $home + copyobj 16x16 %object, %home + %v = load f80 %home + %ok = cmp eq f80 %v, 1.25L + %result = convert zext i32 i1 %ok + return i32 %result +} + +# The sum of a 48-byte object's six fields, passed in memory. +function @read_memory(%n : i32) -> i64 [arity=variadic, no_inline=yes] { + slot $list : obj<24x8> + slot $home : obj<48x8> + block ^entry: + %list = addr $list + va_start %list + %object = va_arg obj<48x8> %list [classes=memory] + %home = addr $home + copyobj 48x8 %object, %home + %f0 = load i64 %home + %p1 = index i64 %home, 1 + %f1 = load i64 %p1 + %p5 = index i64 %home, 5 + %f5 = load i64 %p5 + %s1 = binary add i64 %f0, %f1 + %s2 = binary add i64 %s1, %f5 + return i64 %s2 +} + +# An i128 past the fixed parameters takes the next two GPRs, as two i64 +# values do. +function @read_i128(%n : i32) -> i128 [arity=variadic, no_inline=yes] { + slot $list : obj<24x8> + block ^entry: + %list = addr $list + va_start %list + %v = va_arg i128 %list + return i128 %v +} + +function @main() -> i32 [role=entry] { + slot $out : obj<16x16> + slot $complex : obj<32x16> + slot $pair : obj<16x8> + slot $quad : obj<16x16> + slot $extended : obj<16x16> + block ^entry: + %x87p = addr @x87_result + %r0 = call f80 %x87p(1.5L) as (%v : f80) -> f80 + %ok0 = cmp eq f80 %r0, 1.5L + %e0 = select i32 %ok0, 0, 1 + + %f80p = addr @f80_result + %r1 = call obj<16x16> %f80p() as () -> obj<16x16> [result_classes=x87] + %out = addr $out + copyobj 16x16 %r1, %out + %v1 = load f80 %out + %ok1 = cmp eq f80 %v1, 2.25L + %e1 = select i32 %ok1, 0, 1 + + %r2 = call obj<32x16> @complex_result(0.5L, 4.0L) + %complex = addr $complex + copyobj 32x16 %r2, %complex + %re = load f80 %complex + %imp = index i8 [projection=field] %complex, 16 + %im = load f80 %imp + %re_ok = cmp eq f80 %re, 0.5L + %im_ok = cmp eq f80 %im, 4.0L + %ok2 = binary and i1 %re_ok, %im_ok + %e2 = select i32 %ok2, 0, 1 + + %memp = addr @memory_result + %pair = addr $pair + call void %memp(%pair, 11, 12) as (%ret : ptr [pass=indirect_result], %a : i64, %b : i64) -> void + %a3 = load i64 %pair + %b3p = index i8 [projection=field] %pair, 8 + %b3 = load i64 %b3p + %a3_ok = cmp eq i64 %a3, 11 + %b3_ok = cmp eq i64 %b3, 12 + %ok3 = binary and i1 %a3_ok, %b3_ok + %e3 = select i32 %ok3, 0, 1 + + %ssep = addr @sseup_argument + %r4 = call f64 %ssep(1.5, 2.5) as (%a : f64, %b : f64) -> f64 + %first4 = load f64 @low + %y4_ok = cmp eq f64 %r4, 2.5 + %x4_ok = cmp eq f64 %first4, 1.5 + %ok4 = binary and i1 %y4_ok, %x4_ok + %e4 = select i32 %ok4, 0, 1 + + %r5 = call obj<16x16> @sseup_result(21, 22) + %quad = addr $quad + copyobj 16x16 %r5, %quad + %a5 = load i64 %quad + %b5p = index i8 [projection=field] %quad, 8 + %b5 = load i64 %b5p + %a5_ok = cmp eq i64 %a5, 21 + %b5_ok = cmp eq i64 %b5, 22 + %ok5 = binary and i1 %a5_ok, %b5_ok + %e5 = select i32 %ok5, 0, 1 + + store f64 0.5, %pair + store i64 7, %b3p + %pv = load obj<16x8> %pair + %r6 = call i32 @read_scalars(1, %pv) [classes=1:sse_integer] + %ok6 = cmp eq i32 %r6, 1 + %e6 = select i32 %ok6, 0, 1 + + %r7 = call i32 @read_pair(1, 0.5, 7) + %ok7 = cmp eq i32 %r7, 1 + %e7 = select i32 %ok7, 0, 1 + + %extended = addr $extended + store f80 1.25L, %extended + %xv = load obj<16x16> %extended + %r8 = call i32 @read_f80(1, %xv) [classes=1:x87] + %ok8 = cmp eq i32 %r8, 1 + %e8 = select i32 %ok8, 0, 1 + + %r9 = call i32 @read_x87(1, 1.25L) + %ok9 = cmp eq i32 %r9, 1 + %e9 = select i32 %ok9, 0, 1 + + %wv = load obj<48x8> @wide + %r10 = call i64 @read_memory(1, %wv) [classes=1:memory] + %ok10 = cmp eq i64 %r10, 9 + %e10 = select i32 %ok10, 0, 1 + + %r11 = call i128 @read_i128(1, 5, 6) + %expected = const i128 110680464442257309701 + %ok11 = cmp eq i128 %r11, %expected + %e11 = select i32 %ok11, 0, 1 + + %m1 = binary add i32 %e0, %e1 + %m2 = binary add i32 %m1, %e2 + %m3 = binary add i32 %m2, %e3 + %m4 = binary add i32 %m3, %e4 + %m5 = binary add i32 %m4, %e5 + %m6 = binary add i32 %m5, %e6 + %m7 = binary add i32 %m6, %e7 + %m8 = binary add i32 %m7, %e8 + %m9 = binary add i32 %m8, %e9 + %m10 = binary add i32 %m9, %e10 + %m11 = binary add i32 %m10, %e11 + return i32 %m11 +} diff --git a/pa33/Makefile b/pa33/Makefile index 4514831606..a4d1c0ffd7 100644 --- a/pa33/Makefile +++ b/pa33/Makefile @@ -129,7 +129,7 @@ endef define run_object_roundtrip_bucket @if [ -d "$(1)" ] && find "$(1)" \( -type f -o -type l \) \( -name '*.cpp' -o -name '*.t' \) | grep -q .; then \ - scripts/run_object_lowir_roundtrip_tests.pl $(2) --app "$(CPPGM_DRIVER_APP)" --test-root "$(1)"; \ + scripts/run_object_lowir_roundtrip_tests.pl $(2) --app "$(CPPGM_DRIVER_APP)" --lowiropt "$(LOWIROPT_APP)" --test-root "$(1)"; \ else \ if [ "$(REPORT_EMPTY_OPTIONAL_TEST_ROOTS)" = "1" ]; then echo "$(TARGET) $(1): no tests"; fi; \ fi @@ -224,7 +224,7 @@ esac CHECK_RUN = perl ../scripts/run_routed_test_spec.pl "$(TEST)" \ '$(HOST_O1_TEST_ROOT)/*::CPPGM_APP_ARGS="-O1" perl ../scripts/run_cpphostinterop_tests_worker.pl $(CPPGM_DRIVER_APP) check {tests}' \ '$(HOST_O2_TEST_ROOT)/*::CPPGM_APP_ARGS="-O2" perl ../scripts/run_cpphostinterop_tests_worker.pl $(CPPGM_DRIVER_APP) check {tests}' \ - '$(OBJECT_ROUNDTRIP_TEST_ROOT)/*::scripts/run_object_lowir_roundtrip_tests.pl --app $(CPPGM_DRIVER_APP) --test {tests}' \ + '$(OBJECT_ROUNDTRIP_TEST_ROOT)/*::scripts/run_object_lowir_roundtrip_tests.pl --app $(CPPGM_DRIVER_APP) --lowiropt $(LOWIROPT_APP) --test {tests}' \ '$(O0_TEST_ROOT)/*::CPPGM_APP_ARGS=-O0 scripts/run_all_tests.pl $(LOWIROPT_APP) check {tests}' \ '$(O1_TEST_ROOT)/*|$(DEBUGINFO_O1_TEST_ROOT)/*::CPPGM_APP_ARGS=-O1 scripts/run_all_tests.pl $(LOWIROPT_APP) check {tests}' \ '$(O2_TEST_ROOT)/*|$(DEBUGINFO_O2_TEST_ROOT)/*::CPPGM_APP_ARGS=-O2 scripts/run_all_tests.pl $(LOWIROPT_APP) check {tests}' \ diff --git a/pa33/README.md b/pa33/README.md index 6e56985a10..98455acc3c 100644 --- a/pa33/README.md +++ b/pa33/README.md @@ -569,10 +569,11 @@ source-language clauses. experiments. `make test-improvements` checks their behavior and reports work without a speed threshold; see [improvements.md](improvements.md). - `tests/object-roundtrip` compares direct `cppgm -c` output against an - object produced by `cppgm --emit-lowir -O0` followed by `cppgm -c` on - the generated LowIR file. This checks that object emission can be - reconstructed from serialized LowIR instead of from hidden frontend side - data. These tests may be standalone `.cpp` files or symlinks to existing + object produced by `cppgm --emit-lowir -O0`, then `lowiropt -O0`, then + `cppgm -c` on the rewritten LowIR file. This checks that object emission + can be reconstructed from serialized LowIR instead of from hidden frontend + side data, and that `lowiropt` reads and writes every fact a host object's + LowIR states. These tests may be standalone `.cpp` files or symlinks to existing `.t` harness cases; a selected `.t` test expands to its numbered `.t.1`, `.t.2`, ... source files when those sidecars exist. The harness checks no-debug objects at `-O0`, `-O1`, `-O2`, and `-O3`. A diff --git a/pa33/scripts/run_object_lowir_roundtrip_tests.pl b/pa33/scripts/run_object_lowir_roundtrip_tests.pl index 7280a2284a..d3af51c668 100755 --- a/pa33/scripts/run_object_lowir_roundtrip_tests.pl +++ b/pa33/scripts/run_object_lowir_roundtrip_tests.pl @@ -21,10 +21,11 @@ sub detect_jobs { } sub usage { - die "usage: run_object_lowir_roundtrip_tests.pl [--debuginfo] --app APP (--test-root DIR | --test FILE)...\n"; + die "usage: run_object_lowir_roundtrip_tests.pl [--debuginfo] --app APP [--lowiropt APP] (--test-root DIR | --test FILE)...\n"; } my $app = "../dev/cppgm"; +my $lowiropt; my $debuginfo = 0; my @roots; my @tests; @@ -36,6 +37,9 @@ sub usage { if($arg eq "--app") { usage() unless @ARGV; $app = shift @ARGV; + } elsif($arg eq "--lowiropt") { + usage() unless @ARGV; + $lowiropt = shift @ARGV; } elsif($arg eq "--test-root") { usage() unless @ARGV; push @roots, shift @ARGV; @@ -50,6 +54,10 @@ sub usage { die "unknown argument: $arg\n"; } } +# lowiropt beside the driver unless named. +if(!defined $lowiropt) { + ($lowiropt = $app) =~ s{[^/]*\z}{lowiropt}; +} sub collect_tests { my @out; @@ -234,13 +242,18 @@ sub check_mode { return "serialized LowIR lost section=cppgmsec: $source $level_name\n" unless $metadata =~ /(?:^|,\s*)section=cppgmsec(?:,|$)/; } + # The object comes from the text after lowiropt -O0 has read and written + # it, so lowiropt reads every fact the object half states and keeps it. + my $rewritten = "$base.rewritten.lowir"; + my $rewrite_error = run_command($lowiropt, "-O0", "-o", $rewritten, $lowir); + return $rewrite_error if defined $rewrite_error; my $from_lowir_error = run_command($app, "-c", @debug_flags, @optimization_flags, "-o", $from_lowir, - $lowir); + $rewritten); return $from_lowir_error if defined $from_lowir_error; if($source =~ /gnu-section-attribute/) { @@ -261,7 +274,7 @@ sub check_mode { return undef; } - return "object differs after compiling serialized LowIR: $source $debug_label $level_name\n" + return "object differs after compiling serialized LowIR rewritten by lowiropt: $source $debug_label $level_name\n" . "direct bytes: " . length($direct_bytes) . "\n" . "from-lowir bytes: " . length($from_lowir_bytes) . "\n" . "direct symbols:\n" . object_summary($direct) diff --git a/pa8/README.md b/pa8/README.md index ab77068a22..f95a82d119 100644 --- a/pa8/README.md +++ b/pa8/README.md @@ -133,7 +133,9 @@ The required representation includes the forms exercised by `tests/spec/`: - the symbol, parameter, function, storage, projection and debug metadata used by those fixtures, including the required placement and value constraints, among them the object ABI facts `classes`, `result_classes` and - `replaceable`. + `replaceable`. Classes include the host object forms: `x87`, + `complex_x87`, `sse_sseup`, `memory` on a result, and the classes of an + object passed to `...` or read by `va_arg`. Use `lowir.md` for each field's type and meaning, and `pa8.gram` for syntax. Optimized LowIR uses this same boundary: `unary sqrt` computes without diff --git a/pa8/lowir.md b/pa8/lowir.md index 15b2234370..d6d2974bd9 100644 --- a/pa8/lowir.md +++ b/pa8/lowir.md @@ -1107,19 +1107,35 @@ function @scale(%p : obj<16x8> [classes=sse_integer], %k : f64) -> obj<16x8> [re ``` The value names one class for each eightbyte, the first eightbyte first, joined by `_`: -`integer`, `sse`, or `none` for an eightbyte that holds no member (padding, an empty class). -For a direct `obj` parameter or result of at most 16 bytes, classes name +`integer`, `sse`, `none` for an eightbyte that holds no member (padding, an empty class), or +`sseup` for the upper half of a 16-byte SSE value, valid only as `sse_sseup`. For a direct +`obj` parameter or result of at most 16 bytes, classes name exactly its eightbytes. Without them every eightbyte is INTEGER, so the C++ lowering states them exactly when some eightbyte is SSE or `none`, or the object is `memory`; a larger direct -object is always passed in memory. Arguments past a variadic function's fixed parameters -state no classes. +object is always passed in memory. + +An object passed past a variadic function's fixed parameters has no parameter to state its +classes, so the call states them as `classes=:` call metadata, the index +counting from zero across the complete argument list. A `va_arg` that reads an object states +the same classes as `[classes=]`. Eightbyte classes there name two eightbytes for +any object, `none` for a missing second one, and both facts place the object as a parameter +with those classes would be placed (psABI 3.5.7): + +```text +call void @log(2, %pair, %small) [classes=1:sse_integer, classes=2:sse_none] +%pair = va_arg obj<16x8> %list [classes=sse_integer] +``` + +These facts are valid only on an object, `i128` or `v128` value passed to an unnamed +argument, or read by `va_arg`, and follow the rules for that type below. An optimizer may represent an INTEGER-class object of 9–16 bytes and alignment at most 8 as an `i128` value. Such a parameter states `classes=integer_integer`, and such a result may state `result_classes=integer_integer`. This preserves the object's eight-byte stack alignment; an ordinary `i128` parameter without classes has sixteen-byte stack alignment. Both forms use two INTEGER registers when available. -No other class combination is valid on a scalar type. The scalar carrier does not +A `v128` value may state `classes=sse_sseup` or `result_classes=sse_sseup`, the classes it +has without them. No other class combination is valid on a scalar type. The scalar carrier does not enlarge the original object's storage: accesses through its address must stay within the original extent. @@ -1128,18 +1144,27 @@ direct parameter or result, as an `i64` value that states no classes. The value the INTEGER register the object used, so the boundary does not change, and accesses to the object's storage stay within its original extent. -`memory`, valid only on a parameter, instead says the object is passed in memory: an object -with a misaligned member, or with an x87 (`long double`) or 16-byte vector member. A result -with a misaligned member is returned through a `pass=indirect_result` parameter instead of a -direct result. The psABI returns an x87 or 16-byte vector member in `st0` or in a whole XMM -register, which these classes do not describe, so such a result states no classes. +Three words describe a whole object instead of its eightbytes: + +- `memory` says the object is passed in memory: an object with a misaligned member, or with + an x87 (`long double`) or 16-byte vector member. On a result it says the object is + returned through the hidden destination the caller passes, as for a direct result of more + than 16 bytes. The C++ lowering may instead return a result with a misaligned member + through a `pass=indirect_result` parameter. +- `x87`, valid only on a 16-byte object, says the object is one `long double`: passed in + memory and returned in `st0`. +- `complex_x87`, valid only on a 32-byte object, says the object is one `_Complex long + double`: passed in memory and returned in `st0` (real part) and `st1` (imaginary part). + +An object of more than 16 bytes states only `memory` or `complex_x87`. The native backend places an INTEGER eightbyte in the next argument GPR (rax then rdx for a -result), an SSE eightbyte in the next XMM register (xmm0 then xmm1 for a result), and nothing -for a `none` eightbyte. An object whose eightbytes do not all fit in the remaining registers, -or whose classes are `memory`, goes on the stack whole. The placement is the same in course -objects, link mode and `lowir2native` as in host objects, and objects passed this way -interoperate with GCC- and Clang-compiled code. +result), an SSE eightbyte in the next XMM register (xmm0 then xmm1 for a result), an SSEUP +eightbyte in the same XMM register as the SSE eightbyte before it, and nothing for a `none` +eightbyte. An object whose eightbytes do not all fit in the remaining registers, or whose +classes are `memory`, `x87` or `complex_x87`, goes on the stack whole. The placement is the +same in course objects, link mode and `lowir2native` as in host objects, and objects passed +this way interoperate with GCC- and Clang-compiled code. PA8's reader/writer preserves the object-boundary forms exercised by its fixtures. Later C++ lowering creates these boundaries, and the native @@ -1751,7 +1776,9 @@ va_start `va_start` prepares the argument list object `` in a function declared `[arity=variadic]`, and `va_arg` reads the next argument from it as `` and advances -it. These are the stable LowIR lowerings for `__builtin_va_start` and +it. `` is an integer type of 8 to 128 bits, `f64`, `f80`, `ptr` or an object; an +object may state its classes (see [Object ABI Conventions](#object-abi-conventions)). +These are the stable LowIR lowerings for `__builtin_va_start` and `__builtin_va_arg`; neither is a callable external symbol. PA8 only has to carry both forms through the text form, since the argument list layout is part of the calling convention that PA24 fixes. @@ -2295,6 +2322,14 @@ when some eightbyte is SSE or `none` or (a parameter only) the object is classes. - An argument past a variadic function's fixed parameters states none. +The lowering for a host object (`cppgm -c`, and `cppgm --emit-lowir` to a +`.lowir` file at `-g0` or `-gline-tables-only`) states the classes the psABI +gives instead: `x87`, `complex_x87`, `sse_sseup` and `memory` results, +`sse_sseup` parameters, and the classes of objects passed past a variadic +function's fixed parameters and read by `va_arg`. PA33's object roundtrip +checks that text: `cppgm -c` compiles it, after `lowiropt -O0` has read and +written it, to the object it compiles from the source. + `elision=copy`: a direct call of a copy or move constructor that is not trivial states it when the call copy-initializes an object from a conditional expression (5.16) that is a prvalue of the object's own class. diff --git a/pa8/tests/spec/300-bad-result-classes-memory.ref.exit_status b/pa8/tests/spec/300-bad-classes-fixed-argument.ref.exit_status similarity index 100% rename from pa8/tests/spec/300-bad-result-classes-memory.ref.exit_status rename to pa8/tests/spec/300-bad-classes-fixed-argument.ref.exit_status diff --git a/pa8/tests/spec/300-bad-classes-fixed-argument.t b/pa8/tests/spec/300-bad-classes-fixed-argument.t new file mode 100644 index 0000000000..dcaea61f94 --- /dev/null +++ b/pa8/tests/spec/300-bad-classes-fixed-argument.t @@ -0,0 +1,6 @@ +declare function @take(%count : i32) -> void [arity=variadic] +function @pass(%pair : obj<16x8>) -> void { + block ^entry: + call void @take(1, %pair) [classes=0:sse_integer] + return void +} diff --git a/pa8/tests/spec/300-bad-classes-large-object.ref.exit_status b/pa8/tests/spec/300-bad-classes-large-object.ref.exit_status new file mode 100644 index 0000000000..91613c687f --- /dev/null +++ b/pa8/tests/spec/300-bad-classes-large-object.ref.exit_status @@ -0,0 +1 @@ +EXIT_FAILURE diff --git a/pa8/tests/spec/300-bad-classes-large-object.t b/pa8/tests/spec/300-bad-classes-large-object.t new file mode 100644 index 0000000000..6353baa923 --- /dev/null +++ b/pa8/tests/spec/300-bad-classes-large-object.t @@ -0,0 +1 @@ +declare function @f(%x : obj<48x8> [classes=integer_integer]) -> void diff --git a/pa8/tests/spec/300-bad-classes-sseup-after-integer.ref.exit_status b/pa8/tests/spec/300-bad-classes-sseup-after-integer.ref.exit_status new file mode 100644 index 0000000000..91613c687f --- /dev/null +++ b/pa8/tests/spec/300-bad-classes-sseup-after-integer.ref.exit_status @@ -0,0 +1 @@ +EXIT_FAILURE diff --git a/pa8/tests/spec/300-bad-classes-sseup-after-integer.t b/pa8/tests/spec/300-bad-classes-sseup-after-integer.t new file mode 100644 index 0000000000..8eb91a4cc2 --- /dev/null +++ b/pa8/tests/spec/300-bad-classes-sseup-after-integer.t @@ -0,0 +1 @@ +declare function @f(%x : obj<16x8> [classes=integer_sseup]) -> void diff --git a/pa8/tests/spec/300-bad-classes-unknown.t b/pa8/tests/spec/300-bad-classes-unknown.t index 88756d54df..e3ebd05ea6 100644 --- a/pa8/tests/spec/300-bad-classes-unknown.t +++ b/pa8/tests/spec/300-bad-classes-unknown.t @@ -1 +1 @@ -declare function @f(%x : obj<8x8> [classes=x87]) -> void +declare function @f(%x : obj<8x8> [classes=float]) -> void diff --git a/pa8/tests/spec/300-bad-result-classes-memory.t b/pa8/tests/spec/300-bad-result-classes-memory.t deleted file mode 100644 index a4c71e9be2..0000000000 --- a/pa8/tests/spec/300-bad-result-classes-memory.t +++ /dev/null @@ -1 +0,0 @@ -declare function @f() -> obj<16x16> [result_classes=memory] diff --git a/pa8/tests/spec/300-host-object-classes.ref b/pa8/tests/spec/300-host-object-classes.ref new file mode 100644 index 0000000000..8fce96d8c1 --- /dev/null +++ b/pa8/tests/spec/300-host-object-classes.ref @@ -0,0 +1,25 @@ +declare function @extended() -> obj<16x16> [result_classes=x87] +declare function @complex(%x : obj<32x16> [classes=memory]) -> obj<32x16> [result_classes=complex_x87] +declare function @quad(%x : obj<16x16> [classes=sse_sseup]) -> obj<16x16> [result_classes=sse_sseup] +declare function @lanes(%x : v128 [classes=sse_sseup]) -> v128 [result_classes=sse_sseup] +declare function @wide(%x : obj<32x32> [classes=memory]) -> obj<32x32> [result_classes=memory] +declare function @take(%count : i32) -> void [arity=variadic] + +function @pass(%pair : obj<16x8> [classes=sse_integer], %extended : obj<16x16> [classes=memory], %big : obj<48x8> [classes=memory]) -> void { + block ^entry: + call void @take(3, %pair, %extended, %big) [classes=1:sse_integer, classes=2:x87, classes=3:memory] + return void +} +function @read(%count : i32) -> void [arity=variadic] { + slot $list : obj<24x8> + + block ^entry: + %list = addr $list + va_start %list + %pair = va_arg obj<16x8> %list [classes=sse_integer] + %extended = va_arg obj<16x16> %list [classes=x87] + %value = va_arg f80 %list + %wide = va_arg i128 %list + %big = va_arg obj<48x8> %list [classes=memory] + return void +} diff --git a/pa8/tests/spec/300-host-object-classes.ref.exit_status b/pa8/tests/spec/300-host-object-classes.ref.exit_status new file mode 100644 index 0000000000..c1d5c9342c --- /dev/null +++ b/pa8/tests/spec/300-host-object-classes.ref.exit_status @@ -0,0 +1 @@ +EXIT_SUCCESS diff --git a/pa8/tests/spec/300-host-object-classes.ref.stdout b/pa8/tests/spec/300-host-object-classes.ref.stdout new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pa8/tests/spec/300-host-object-classes.t b/pa8/tests/spec/300-host-object-classes.t new file mode 100644 index 0000000000..7f2d2bc6fc --- /dev/null +++ b/pa8/tests/spec/300-host-object-classes.t @@ -0,0 +1,27 @@ +# The classes of host objects (lowir.md "Object ABI Conventions"): x87 and +# complex x87 results, SSEUP halves of 16-byte SSE values, memory for +# results and for objects larger than 16 bytes, and the classes of arguments +# to `...` and of va_arg results. +declare function @extended() -> obj<16x16> [result_classes=x87] +declare function @complex(%x : obj<32x16> [classes=memory]) -> obj<32x16> [result_classes=complex_x87] +declare function @quad(%x : obj<16x16> [classes=sse_sseup]) -> obj<16x16> [result_classes=sse_sseup] +declare function @lanes(%x : v128 [classes=sse_sseup]) -> v128 [result_classes=sse_sseup] +declare function @wide(%x : obj<32x32> [classes=memory]) -> obj<32x32> [result_classes=memory] +declare function @take(%count : i32) -> void [arity=variadic] +function @pass(%pair : obj<16x8> [classes=sse_integer], %extended : obj<16x16> [classes=memory], %big : obj<48x8> [classes=memory]) -> void { + block ^entry: + call void @take(3, %pair, %extended, %big) [classes=1:sse_integer, classes=2:x87, classes=3:memory] + return void +} +function @read(%count : i32) -> void [arity=variadic] { + slot $list : obj<24x8> + block ^entry: + %list = addr $list + va_start %list + %pair = va_arg obj<16x8> %list [classes=sse_integer] + %extended = va_arg obj<16x16> %list [classes=x87] + %value = va_arg f80 %list + %wide = va_arg i128 %list + %big = va_arg obj<48x8> %list [classes=memory] + return void +} From cd3818d0ed5e7fc2668dca8c0467e27ed455f3ef Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 19:17:54 +0000 Subject: [PATCH 3/8] Leave x86-64 classes off soft-float helpers on wasm targets --- dev/src/lower/soft_float_lowering.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dev/src/lower/soft_float_lowering.cpp b/dev/src/lower/soft_float_lowering.cpp index 221ce0a5d2..cf3a13a6fe 100644 --- a/dev/src/lower/soft_float_lowering.cpp +++ b/dev/src/lower/soft_float_lowering.cpp @@ -638,7 +638,8 @@ SoftFloat SoftFloatOfValue(lowir::Type type) uint8_t ProgramLowering::soft_float_classes(SoftFloat kind) const { - if (!object_mode_ || kind == SoftFloat::None) + // Wasm passes them by its own convention (the shape), as object_classes. + if (!object_mode_ || kind == SoftFloat::None || target_model::is_wasm(program_.target)) return 0; return static_cast( lowir::OC_STATED | lowir::EB_SSE | (kind == SoftFloat::Quad ? lowir::EB_SSEUP << 2 : lowir::EB_NONE)); From 9e2115fe21be015c2b8fc81338a4c81b6d5746ca Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 20:08:26 +0000 Subject: [PATCH 4/8] Give the runtime unroller's group loops a block kind of their own --- dev/src/lowir/local_names.cpp | 2 +- dev/src/lowir_local_model.h | 4 ++++ dev/src/opt/loop_unrolling.cpp | 8 +++++--- .../500-o3-unrolled-copy-as-loop-header.cpp | 15 +++++++++++++++ 4 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 pa33/tests/object-roundtrip/500-o3-unrolled-copy-as-loop-header.cpp diff --git a/dev/src/lowir/local_names.cpp b/dev/src/lowir/local_names.cpp index f301e00624..6a6d58cf5e 100644 --- a/dev/src/lowir/local_names.cpp +++ b/dev/src/lowir/local_names.cpp @@ -50,7 +50,7 @@ const char* const kBlockStems[] = { "", "vector_unordered", "vector_compress", "vector_compress_lane", "vector_compress_end", // The optimizer's. "inline_entry", "inline_cont", "inline_copy", "split", "thread", "loop_preheader", "loop_copy", "loop_exit", - "fill_fast", "fill_sized", "fill_same", "wide_loop", "wide_tail", "unrolled", "dead" }; + "fill_fast", "fill_sized", "fill_same", "wide_loop", "wide_tail", "unrolled", "dead", "unrolled" }; static_assert( sizeof kBlockStems / sizeof kBlockStems[0] == static_cast(BlockKind::Count), "one stem per block kind"); diff --git a/dev/src/lowir_local_model.h b/dev/src/lowir_local_model.h index 694f9ddad4..1539a68b39 100644 --- a/dev/src/lowir_local_model.h +++ b/dev/src/lowir_local_model.h @@ -228,6 +228,10 @@ enum class BlockKind : uint8_t WideTail, Unrolled, Dead, + // The header of a loop the runtime unroller made, printed as Unrolled + // is. (Unrolled itself is also what a full unroll's copy of a Plain + // block has, so it does not tell that loop apart.) + UnrolledGroup, Count }; diff --git a/dev/src/opt/loop_unrolling.cpp b/dev/src/opt/loop_unrolling.cpp index e243406023..e8279f91e3 100644 --- a/dev/src/opt/loop_unrolling.cpp +++ b/dev/src/opt/loop_unrolling.cpp @@ -117,8 +117,10 @@ bool ShortLoopUnrolling::chain(uint32_t loop, Shape& s) const return false; s.header = l.header; s.latch = l.latches[0]; - // (Not a loop this pass or the fill widening made, nor what one left.) - if (body_.blocks[s.header].kind == BlockKind::Unrolled || body_.blocks[s.pre].kind == BlockKind::WideTail) + // (Not a loop this pass or the fill widening made, nor what one left. + // A copy keeps the group header's kind; a block's other kinds can be + // the lowering's, which LowIR text does not carry.) + if (body_.blocks[s.header].kind == BlockKind::UnrolledGroup || body_.blocks[s.pre].kind == BlockKind::WideTail) return false; // (Nor the passes a lane loop left, fewer than its lanes: entered from // the lane loop, or from its exit block.) @@ -444,7 +446,7 @@ void ShortLoopUnrolling::rewrite(const Shape& s) const bool guarded = ordered && !zero; const BlockId sized = guarded ? append_block(body_, BlockKind::LoopPreheader) : s.pre; const BlockId enter = append_block(body_, BlockKind::LoopPreheader), - group = append_block(body_, BlockKind::Unrolled); + group = append_block(body_, BlockKind::UnrolledGroup); const BlockId left = s.bottom ? append_block(body_, BlockKind::LoopExit) : kNoId; const BlockId tail = append_block(body_, BlockKind::WideTail); const BlockId out = s.bottom ? left : group; // where the group loop leaves from diff --git a/pa33/tests/object-roundtrip/500-o3-unrolled-copy-as-loop-header.cpp b/pa33/tests/object-roundtrip/500-o3-unrolled-copy-as-loop-header.cpp new file mode 100644 index 0000000000..c56a9860fb --- /dev/null +++ b/pa33/tests/object-roundtrip/500-o3-unrolled-copy-as-loop-header.cpp @@ -0,0 +1,15 @@ +// The inner loop unrolls fully. Its first copy becomes the outer loop's +// header, which the runtime unroller then unrolls. The copy's kind came from +// a lowering kind in memory and from a plain block in the text. +extern "C" int nested_loops(int n) +{ + int total = 0; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < 3; ++j) { + if (j == i % 3) + continue; + total += i + j; + } + } + return total; +} From 31b0cb14b8d843898405d36137b514b3bc8a12e9 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 20:08:32 +0000 Subject: [PATCH 5/8] Compile Wasm objects identically from their LowIR text --- .github/workflows/export-wasm-references.yml | 2 +- dev/cppgm.cpp | 12 ++-- dev/src/driver/toolchain.cpp | 4 +- dev/src/lower/program_lowering.h | 4 +- dev/src/lowir/program.cpp | 11 ++++ dev/src/lowir/program.h | 10 +++ dev/src/lowir/text_writer.cpp | 4 +- dev/src/wasm/backend.cpp | 2 + dev/src/wasm/exception_plan.cpp | 6 +- dev/src/wasm/frame.cpp | 19 +++++- dev/src/wasm/module.cpp | 61 +++++++++++++++---- dev/src/wasm/nonlocal_jumps.cpp | 10 +-- dev/src/wasm/selector.cpp | 16 +++-- dev/src/wasm/selector.h | 9 +++ .../run_object_lowir_roundtrip_tests.pl | 11 +++- pa37/Makefile | 2 +- pa37/README.md | 7 +++ pa38/Makefile | 2 +- scripts/check_wasm.pl | 42 ++++++++++++- scripts/tests/test_wasm_checker.py | 38 +++++++++--- 20 files changed, 223 insertions(+), 49 deletions(-) diff --git a/.github/workflows/export-wasm-references.yml b/.github/workflows/export-wasm-references.yml index e757d83c90..8d8bd7cb21 100644 --- a/.github/workflows/export-wasm-references.yml +++ b/.github/workflows/export-wasm-references.yml @@ -35,7 +35,7 @@ jobs: - name: Install pinned WASI adapter run: npm ci --ignore-scripts --prefix scripts/experimental - name: Build the host compiler - run: make -C dev cppgm lowir2native CXX=g++ CPPGM_HOST_CXX=g++ + run: make -C dev cppgm lowir2native lowiropt CXX=g++ CPPGM_HOST_CXX=g++ - name: Check the optional C assignment on Wasm run: | PATH="$RUNNER_TEMP/wasm-tools/bin:$PATH" \ diff --git a/dev/cppgm.cpp b/dev/cppgm.cpp index 5d3bd7f56d..a9f4a5ebe9 100644 --- a/dev/cppgm.cpp +++ b/dev/cppgm.cpp @@ -1107,8 +1107,9 @@ int run_emit_lowir_mode(vector args) // The LowIR half of an object compile: a `.lowir` output (the // toolchain's LowIR object input, `-c x.lowir`) with the object // compile's debug-information level stated (-g0, -gline-tables-only) - // is the program `-c -o x.o` compiles, lowered in host-object mode, so - // the object it gives is the direct compile's (PA33 object roundtrip). + // is the program `-c -o x.o` compiles, lowered as -c lowers it (in + // host-object mode for a native target), so the object it gives is the + // direct compile's (PA33 object roundtrip). // Otherwise the output is the course's LowIR view, --hosted or not // (the help text: --hosted // selects the host environment, which this view preprocesses in @@ -1134,8 +1135,11 @@ int run_emit_lowir_mode(vector args) const bool optimizing = invocation.optimizer.level > 0; if (!validate && !optimizing) lowering.set_definition_stream(&definitions); - lowering.set_object_mode(object_half); - lowering.set_host_objects(object_half); + // A Wasm object's half is lowered as its -c lowers it, by Wasm's + // conventions rather than the host object's. + const bool host_half = object_half && !target_model::is_wasm(invocation.target); + lowering.set_object_mode(host_half); + lowering.set_host_objects(host_half); lowering.set_macho_objects(invocation.target == native::Target::MacOS); lowering.set_optimizing(object_half || invocation.optimizer.level >= 2); lowering.set_strict_aliasing(invocation.strict_aliasing); diff --git a/dev/src/driver/toolchain.cpp b/dev/src/driver/toolchain.cpp index fd9c4a74c4..64a578b00c 100644 --- a/dev/src/driver/toolchain.cpp +++ b/dev/src/driver/toolchain.cpp @@ -1022,7 +1022,9 @@ bool wasm_input(const Input& input, const Invocation& invocation, const backend: program.target = invocation.target; program.explicit_target = true; lower::ProgramLowering lowering(program); - lowering.set_optimizing(invocation.optimizer.level >= 2); + // An object's LowIR is the same at every level, so the LowIR that + // --emit-lowir writes for it compiles to this object at any level. + lowering.set_optimizing(true); lowering.set_exceptions(invocation.preprocessor.modes.exceptions); lowering.set_strict_aliasing(invocation.strict_aliasing); UnitWork work; diff --git a/dev/src/lower/program_lowering.h b/dev/src/lower/program_lowering.h index a79c994e1a..1f9778e07e 100644 --- a/dev/src/lower/program_lowering.h +++ b/dev/src/lower/program_lowering.h @@ -479,8 +479,8 @@ class ProgramLowering // External C++ runtimes require the same lifetime boundaries in native // objects and Wasm, including compilation through serialized LowIR. bool platform_exception_lifetimes() const { return host_objects_ || target_model::is_wasm(program_.target); } - // An object compile at any level (its LowIR is the same at every - // level) and the LowIR view from -O2: a virtual call tests for the + // An object compile at any level, native or Wasm (its LowIR is the same + // at every level), and the LowIR view from -O2: a virtual call tests for the // function it names and calls that one directly // (FunctionLowering::speculative_call), and a small class moves member // by member (FunctionLowering::copy_members). diff --git a/dev/src/lowir/program.cpp b/dev/src/lowir/program.cpp index 46d47f2401..a3d8de432c 100644 --- a/dev/src/lowir/program.cpp +++ b/dev/src/lowir/program.cpp @@ -50,6 +50,17 @@ SymbolId Program::symbol_for(NameId name) return entry; } +void order_as_written(Program& program) +{ + std::vector written; + written.reserve(program.order.size()); + for (SymbolKind kind : kWrittenSymbolKinds) + for (SymbolId id : program.order) + if (program.symbols[id].kind == kind) + written.push_back(id); + program.order.swap(written); +} + void Program::declare_global(SymbolId id, SymbolKind kind, const Global& global) { Symbol& symbol = symbols[id]; diff --git a/dev/src/lowir/program.h b/dev/src/lowir/program.h index bd64f553f9..0d24da8f0f 100644 --- a/dev/src/lowir/program.h +++ b/dev/src/lowir/program.h @@ -196,6 +196,11 @@ inline bool is_global_kind(SymbolKind kind) return kind == SymbolKind::GlobalDeclaration || kind == SymbolKind::GlobalDefinition; } +// The LowIR text lists symbols one kind at a time in this order, each kind +// in program order. +const SymbolKind kWrittenSymbolKinds[] = { SymbolKind::GlobalDeclaration, SymbolKind::FunctionDeclaration, + SymbolKind::GlobalDefinition, SymbolKind::FunctionDefinition }; + struct Symbol { NameId name; @@ -419,6 +424,11 @@ struct Program std::vector jump_thunks; }; +// Puts the program's order in the written one (kWrittenSymbolKinds), which +// a program read from its LowIR text has, so a consumer that follows the +// order gives the same output from the text as from the program. +void order_as_written(Program& program); + // A consumer of function definitions as a producer completes them (in // order); the producer releases each body after the append. A consumer // that selects code (`needs_boundaries`) is given every direct callee's diff --git a/dev/src/lowir/text_writer.cpp b/dev/src/lowir/text_writer.cpp index 866b08b290..ce6a2914d6 100644 --- a/dev/src/lowir/text_writer.cpp +++ b/dev/src/lowir/text_writer.cpp @@ -435,10 +435,8 @@ void Writer::write() text("\n\n"); } append_assembly_definitions(out_, program_); - const SymbolKind phases[] = { SymbolKind::GlobalDeclaration, SymbolKind::FunctionDeclaration, - SymbolKind::GlobalDefinition, SymbolKind::FunctionDefinition }; bool written = false; - for (SymbolKind phase : phases) + for (SymbolKind phase : kWrittenSymbolKinds) { bool phase_written = false; if (phase == SymbolKind::FunctionDefinition && definitions_ != nullptr) diff --git a/dev/src/wasm/backend.cpp b/dev/src/wasm/backend.cpp index 51ef2ea0ca..7699cdc53d 100644 --- a/dev/src/wasm/backend.cpp +++ b/dev/src/wasm/backend.cpp @@ -74,6 +74,8 @@ bool compile_object( } try { + // The object follows the program's order: the one its LowIR text has. + lowir::order_as_written(program); opt::OptimizerOptions optimization; if (options.optimizer != nullptr) optimization = *options.optimizer; diff --git a/dev/src/wasm/exception_plan.cpp b/dev/src/wasm/exception_plan.cpp index 2ef300e611..87d5813e02 100644 --- a/dev/src/wasm/exception_plan.cpp +++ b/dev/src/wasm/exception_plan.cpp @@ -167,7 +167,11 @@ void prepare_exception_plan(const Program& program, SymbolId symbol, Object& obj return; ObjectData data; data.alignment = 2; - data.name = ".gcc_except_table." + std::to_string(symbol); + // Named by the function's object name, which a program read from its + // LowIR text also has (not by its symbol id). + const Symbol& function = program.symbols[symbol]; + data.name = std::string(".gcc_except_table.") + + program.spelling(function.metadata.object != 0 ? function.metadata.object : function.name); lsda(plan.tables, data); ObjectSymbol table; table.kind = 1; diff --git a/dev/src/wasm/frame.cpp b/dev/src/wasm/frame.cpp index 6e65f10a31..78f9219f3a 100644 --- a/dev/src/wasm/frame.cpp +++ b/dev/src/wasm/frame.cpp @@ -28,8 +28,23 @@ void Selector::prepare_locals() out_.parameter_count = static_cast(out_.locals.size()); locals_.resize(body_.temps.size(), kNoId); incoming_.resize(body_.parameter_count, kNoId); + temp_order_.clear(); + std::vector listed(body_.temps.size(), 0); + auto list = [&](TempId t) { + if (listed[t] == 0) + { + listed[t] = 1; + temp_order_.push_back(t); + } + }; + for (TempId t = 0; t < body_.parameter_count; ++t) + list(t); + for (BlockId block : body_.layout) + for (InstId i = body_.blocks[block].first; i != kNoId; i = body_.instructions[i].next) + if (body_.instructions[i].result != kNoId) + list(body_.instructions[i].result); uint32_t next = hidden_result_ == kNoId ? 0 : 1; - for (uint32_t i = 0; i < body_.temps.size(); ++i) + for (const TempId i : temp_order_) { if (i < body_.parameter_count) { @@ -117,7 +132,7 @@ void Selector::prepare_frame() slots_[i] = follows ? slots_[owners[i]] : reserve(body_.slots[i].type); } objects_.resize(body_.temps.size(), kNoId); - for (uint32_t i = 0; i < body_.temps.size(); ++i) + for (const TempId i : temp_order_) if (memory_value(body_.temps[i].type) && wide_locals_[i] == kNoId && places_.slot_of[i] == kNoId && !(i < body_.parameter_count && boundary_.parameters[i].passing == Passing::Indirect)) objects_[i] = reserve(body_.temps[i].type); diff --git a/dev/src/wasm/module.cpp b/dev/src/wasm/module.cpp index 5ed90d2a6d..eeaf35c559 100644 --- a/dev/src/wasm/module.cpp +++ b/dev/src/wasm/module.cpp @@ -8,14 +8,31 @@ namespace wasm { namespace { +// The type of a signature as the key that identifies it. +std::vector type_key(const Signature& signature) +{ + std::vector key; + for (ValueType parameter : signature.parameters) + key.push_back(static_cast(parameter)); + key.push_back(0); + for (ValueType returned : signature.results) + key.push_back(static_cast(returned)); + return key; +} + +// The type of each signature, numbered in the order the program first refers +// to it: its functions' in program order, then its calls' in block order, +// then any other's. A program read from LowIR text makes its signatures in +// the text's order, so the numbering is the same from the text as from the +// program that wrote it. void function_types(const lowir::Program& program, Module& module) { - std::map, uint32_t> known; - for (const lowir::Signature& source : program.signatures) + std::vector types(program.signatures.size()); + for (size_t s = 0; s < program.signatures.size(); ++s) { - Signature signature; + const lowir::Signature& source = program.signatures[s]; + Signature& signature = types[s]; Boundary boundary; - std::vector key; boundary.result = classify_value(source.result, source.boundary.result_shape, program.pointer_type()); if (boundary.result.passing == Passing::Expand) boundary.result.passing = Passing::Indirect; @@ -41,17 +58,35 @@ void function_types(const lowir::Program& program, Module& module) signature.results.push_back(ValueType::I32); else if (result != ValueType::Void) signature.results.push_back(result); - for (ValueType parameter : signature.parameters) - key.push_back(static_cast(parameter)); - key.push_back(0); - for (ValueType returned : signature.results) - key.push_back(static_cast(returned)); - auto inserted = known.emplace(key, static_cast(module.signatures.size())); - if (inserted.second) - module.signatures.push_back(std::move(signature)); - module.signature_types.push_back(inserted.first->second); module.boundaries.push_back(std::move(boundary)); } + std::map, uint32_t> known; + module.signature_types.assign(types.size(), lowir::kNoId); + const auto number = [&](lowir::SignatureId id) { + if (id == lowir::kNoId || module.signature_types[id] != lowir::kNoId) + return; + const auto inserted = known.emplace(type_key(types[id]), static_cast(module.signatures.size())); + if (inserted.second) + module.signatures.push_back(types[id]); + module.signature_types[id] = inserted.first->second; + }; + for (lowir::SymbolId id : program.order) + if (lowir::is_function_kind(program.symbols[id].kind)) + number(program.functions[program.symbols[id].detail].signature); + for (lowir::SymbolId id : program.order) + { + const lowir::Symbol& symbol = program.symbols[id]; + if (symbol.kind != lowir::SymbolKind::FunctionDefinition) + continue; + const lowir::FunctionBody& body = *program.functions[symbol.detail].body; + for (lowir::BlockId block : body.layout) + for (lowir::InstId inst = body.blocks[block].first; inst != lowir::kNoId; + inst = body.instructions[inst].next) + if ((body.instructions[inst].flags & lowir::IF_SIGNATURE) != 0) + number(static_cast(body.instructions[inst].immediate)); + } + for (lowir::SignatureId id = 0; id < types.size(); ++id) + number(id); } } // namespace diff --git a/dev/src/wasm/nonlocal_jumps.cpp b/dev/src/wasm/nonlocal_jumps.cpp index 45923fbb31..2d753ebc43 100644 --- a/dev/src/wasm/nonlocal_jumps.cpp +++ b/dev/src/wasm/nonlocal_jumps.cpp @@ -84,14 +84,16 @@ void Selector::plan_nonlocal_jumps() if (!any) return; nonlocal_sites_.assign(body_.instructions.size(), kNoId); - uint32_t next = static_cast(body_.blocks.size()); + number_pc_cases(); + // (The code after a setjmp call continues as a case past the blocks'.) + uint32_t next = static_cast(body_.layout.size()); for (BlockId block : body_.layout) { if (exceptions_ != nullptr && exceptions_->active && exceptions_->analysis.eh_live_[exceptions_->layout_of[block]] == 0) continue; InstId first = body_.blocks[block].first, previous = kNoId; - uint32_t id = block; + uint32_t id = pc_cases_[block]; for (InstId i = first; i != kNoId; i = body_.instructions[i].next) { const auto& inst = body_.instructions[i]; @@ -142,7 +144,7 @@ bool Selector::nonlocal_call(const lowir::Instruction& inst) void Selector::nonlocal_dispatch() { pc_ = add_local(ValueType::I32); - out_.emit(Op::I32Const, { body_.layout[0] }); + out_.emit(Op::I32Const, { 0 }); // the entry's case out_.emit(Op::LocalSet, { pc_ }); out_.emit(Op::Loop, { block_type(ValueType::Void) }); out_.emit(Op::Block, { module_.nonlocal_pair_type }); @@ -151,7 +153,7 @@ void Selector::nonlocal_dispatch() { block_type(ValueType::Void), 1, static_cast(CatchKind::TagRef), module_.nonlocal_tag_index, 0 }); out_.relocate(RelocationKind::TagIndex, module_.nonlocal_tag_symbol, 3); const uint32_t count = static_cast(nonlocal_fragments_.size()); - std::vector depths(body_.blocks.size() + count + 1, count); + std::vector depths(body_.layout.size() + count + 1, count); for (uint32_t i = 0; i < count; ++i) depths[nonlocal_fragments_[i].id] = i; for (uint32_t i = 0; i <= count; ++i) diff --git a/dev/src/wasm/selector.cpp b/dev/src/wasm/selector.cpp index d398b15243..cc1468d83a 100644 --- a/dev/src/wasm/selector.cpp +++ b/dev/src/wasm/selector.cpp @@ -275,10 +275,18 @@ void Selector::simple() block(body_.layout[0]); } +void Selector::number_pc_cases() +{ + pc_cases_.assign(body_.blocks.size(), kNoId); + for (uint32_t k = 0; k < body_.layout.size(); ++k) + pc_cases_[body_.layout[k]] = k; +} + void Selector::dispatch() { + number_pc_cases(); pc_ = add_local(ValueType::I32); - out_.emit(Op::I32Const, { body_.layout[0] }); + out_.emit(Op::I32Const, { 0 }); // the entry's case out_.emit(Op::LocalSet, { pc_ }); out_.emit(Op::Loop, { block_type(ValueType::Void) }); // A dense table keeps each fallback edge constant-time even after @@ -292,9 +300,9 @@ void Selector::dispatch() blocks.push_back(id); } const uint32_t count = static_cast(blocks.size()); - std::vector depths(body_.blocks.size() + 1, count); + std::vector depths(body_.layout.size() + 1, count); for (uint32_t i = 0; i < count; ++i) - depths[blocks[i]] = i; + depths[pc_cases_[blocks[i]]] = i; for (uint32_t i = 0; i <= count; ++i) out_.emit(Op::Block, { block_type(ValueType::Void) }); nesting_ = count + 2; @@ -390,7 +398,7 @@ void Selector::edge(BlockId from, BlockId to) } throw WasmError("Wasm structured branch has no active destination"); } - out_.emit(Op::I32Const, { to }); + out_.emit(Op::I32Const, { pc_cases_[to] }); out_.emit(Op::LocalSet, { pc_ }); out_.emit(Op::Br, { nesting_ - 1 }); } diff --git a/dev/src/wasm/selector.h b/dev/src/wasm/selector.h index 77ec7c0a2f..9074e8a9d3 100644 --- a/dev/src/wasm/selector.h +++ b/dev/src/wasm/selector.h @@ -169,6 +169,11 @@ class Selector std::vector locals_; std::vector wide_locals_; std::vector objects_; + // The temporaries that locals and frame objects are given out for, in + // order: the parameters, then as the layout defines them (as the body + // read from its LowIR text numbers them). A temporary no placed + // instruction defines has no reader and no local. + std::vector temp_order_; std::vector incoming_; std::vector call_areas_; std::vector variadic_areas_; @@ -196,6 +201,10 @@ class Selector uint32_t jump_environment_ = lowir::kNoId; uint32_t jump_reference_ = lowir::kNoId; uint32_t pc_ = lowir::kNoId; + // A block's value of pc_: its layout position, which the body read + // from its LowIR text also gives it (its id can differ). + std::vector pc_cases_; + void number_pc_cases(); uint32_t nesting_ = 0; uint32_t dispatch_depth_ = 0; uint32_t current_block_ = 0; diff --git a/pa33/scripts/run_object_lowir_roundtrip_tests.pl b/pa33/scripts/run_object_lowir_roundtrip_tests.pl index d3af51c668..87689fcef9 100755 --- a/pa33/scripts/run_object_lowir_roundtrip_tests.pl +++ b/pa33/scripts/run_object_lowir_roundtrip_tests.pl @@ -21,11 +21,13 @@ sub detect_jobs { } sub usage { - die "usage: run_object_lowir_roundtrip_tests.pl [--debuginfo] --app APP [--lowiropt APP] (--test-root DIR | --test FILE)...\n"; + die "usage: run_object_lowir_roundtrip_tests.pl [--debuginfo] [--target TARGET] --app APP [--lowiropt APP] (--test-root DIR | --test FILE)...\n"; } my $app = "../dev/cppgm"; my $lowiropt; +# The target both compiles name (`--target`), or the driver default. +my @target_flags; my $debuginfo = 0; my @roots; my @tests; @@ -37,6 +39,9 @@ sub usage { if($arg eq "--app") { usage() unless @ARGV; $app = shift @ARGV; + } elsif($arg eq "--target") { + usage() unless @ARGV; + @target_flags = ("--target", shift @ARGV); } elsif($arg eq "--lowiropt") { usage() unless @ARGV; $lowiropt = shift @ARGV; @@ -217,7 +222,7 @@ sub check_mode { my @debug_flags = defined($debug_flag) ? ($debug_flag) : ("-g0"); my @optimization_flags = defined($opt) ? ($opt) : (); - my @direct_cmd = ($app, "-c", @debug_flags, @optimization_flags); + my @direct_cmd = ($app, @target_flags, "-c", @debug_flags, @optimization_flags); my $direct_error = run_command(@direct_cmd, "-o", $direct, $source); return $direct_error if defined $direct_error; # The O0 emission must preprocess exactly like the direct compile. An @@ -225,6 +230,7 @@ sub check_mode { my @preprocess_flags = (defined($opt) && $opt ne "-O0") ? ("-D__OPTIMIZE__=1") : (); my $emit_error = run_command($app, + @target_flags, "--emit-lowir", @debug_flags, "-O0", @@ -248,6 +254,7 @@ sub check_mode { my $rewrite_error = run_command($lowiropt, "-O0", "-o", $rewritten, $lowir); return $rewrite_error if defined $rewrite_error; my $from_lowir_error = run_command($app, + @target_flags, "-c", @debug_flags, @optimization_flags, diff --git a/pa37/Makefile b/pa37/Makefile index 124a8c6a48..7dea24146f 100644 --- a/pa37/Makefile +++ b/pa37/Makefile @@ -13,7 +13,7 @@ WASM_BENCH_ARGS ?= all: dev-shared-target dev-shared-target: - @$(MAKE) -C ../dev CXX="$(CXX)" CPPGM_HOST_CXX="$(CPPGM_HOST_CXX)" $(TARGET) cppgm + @$(MAKE) -C ../dev CXX="$(CXX)" CPPGM_HOST_CXX="$(CPPGM_HOST_CXX)" $(TARGET) cppgm lowiropt test: $(TEST_DEPS) @perl ../scripts/run_all_tests_common.pl control_t $(CPPGM_TEST_APP) my tests diff --git a/pa37/README.md b/pa37/README.md index 8c0d5fa5a4..7ba418fb87 100644 --- a/pa37/README.md +++ b/pa37/README.md @@ -29,6 +29,13 @@ lowir2native --target=wasm32-wasip1 -O2 \ --dump-machine-ir program.mir -o program.wasm source.lowir ``` +The object that `-c` compiles from a source's object LowIR is byte-identical +to the object that `-c` compiles from the source at the same level. This also +holds after `lowiropt -O0` reads and writes that text. The object LowIR is +`--emit-lowir -g0 -O0`, with `-D__OPTIMIZE__=1` for an O1+ level. The checker +compares the two objects at each level, as PA33's object round trip does for +the native targets. + The additional `wasm32-unknown-emscripten` SDK profile carries Emscripten's layout and allocation alignment. Use explicit SDK runtime archives and import declarations for links; it does not generate JS glue. The diff --git a/pa38/Makefile b/pa38/Makefile index 061a0086d6..2f280b3d6b 100644 --- a/pa38/Makefile +++ b/pa38/Makefile @@ -15,7 +15,7 @@ CONTROL_TEST_ROOT ?= tests/controls all: dev-shared-target dev-shared-target: - @if [ "$(CPPGM_SKIP_DEV_REBUILD)" != "1" ]; then $(MAKE) -C ../dev $(TARGET) lowir2native CXX="$(CXX)" CPPGM_HOST_CXX="$(CPPGM_HOST_CXX)"; fi + @if [ "$(CPPGM_SKIP_DEV_REBUILD)" != "1" ]; then $(MAKE) -C ../dev $(TARGET) lowir2native lowiropt CXX="$(CXX)" CPPGM_HOST_CXX="$(CPPGM_HOST_CXX)"; fi CONTROLS_RUN = CPPGM_CONTROL_NATIVE_APP="$(NATIVE_REFERENCE_APP)" \ perl ../scripts/run_all_tests_common.pl control_t $(CPPGM_TEST_APP) my "$(CONTROL_TEST_ROOT)" && \ diff --git a/scripts/check_wasm.pl b/scripts/check_wasm.pl index a554da5b2b..b0c9e7852f 100644 --- a/scripts/check_wasm.pl +++ b/scripts/check_wasm.pl @@ -72,6 +72,8 @@ sub fixture_strings { my $runtime = $ENV{CPPGM_WASMTIME} // 'wasmtime'; my $source_compiler = $ENV{CPPGM_WASM_CPPGM} // File::Spec->catfile(dirname($compiler), $compiler =~ /-ref\z/ ? 'cppgm-ref' : 'cppgm'); +my $lowiropt = $ENV{CPPGM_WASM_LOWIROPT} // File::Spec->catfile(dirname($source_compiler), + 'lowiropt' . ($source_compiler =~ /(-ref|-self)\z/ ? $1 : '')); my $command_sequence = 0; my $checked = CppgmWasmCheckCache->new(validator => $validator, runtime => $runtime); my %lowered_source; @@ -130,10 +132,8 @@ sub archive_inputs { sub standalone_optimizer { my ($level, $lowir) = @_; - my $suffix = $source_compiler =~ /(-ref|-self)\z/ ? $1 : ''; - my $optimizer = $ENV{CPPGM_WASM_LOWIROPT} // File::Spec->catfile(dirname($source_compiler), "lowiropt$suffix"); my $optimized = "$directory/optimized-$level.lowir"; - my ($status, $stdout, $stderr) = command('standalone-optimize', $optimizer, + my ($status, $stdout, $stderr) = command('standalone-optimize', $lowiropt, "-O$level", '--validate', '--verify-passes', $lowir, '-o', $optimized); die "$test: standalone optimizer failed: $stdout$stderr\n" if $status; my $object = "$directory/optimized-$level.o"; @@ -232,6 +232,41 @@ sub reference_link_rejection { push @assembly_objects, $output; } +# The object compiled from an input's LowIR text, after lowiropt -O0 has +# read and written it, is the direct object byte for byte. A source's text +# is the object compile's LowIR (a stated debug level: -g0, the direct +# compile's default), lowered at O0 and preprocessed as the direct compile +# is: an O1+ compile defines __OPTIMIZE__. Each text is lowered and +# rewritten once. +my %rewritten_text; +sub check_text_object { + my ($index, $level, $input, $direct) = @_; + my $target = $expect->{target} // 'wasm32-unknown-unknown'; + my $key = $expect->{source} ? "$input\0" . ($level ? 'optimize' : 'O0') : $input; + my ($status, $stdout, $stderr); + if (!$rewritten_text{$key}) { + my $text = $input; + my $name = "text-$index-" . ($level ? 'optimize' : 'O0'); + if ($expect->{source}) { + $text = "$directory/$name.lowir"; + ($status, $stdout, $stderr) = command("$name-lowir", $source_compiler, '--target', $target, + @target_flags, @{$expect->{flags} // []}, '-g0', '--emit-lowir', '-O0', + ($level ? ('-D__OPTIMIZE__=1') : ()), $input, '-o', $text); + die "$test: LowIR text lowering failed: $stdout$stderr\n" if $status; + } + my $rewritten = "$directory/$name.rewritten.lowir"; + ($status, $stdout, $stderr) = command("$name-rewrite", $lowiropt, '-O0', '-o', $rewritten, $text); + die "$test: lowiropt -O0 rejected the LowIR text: $stdout$stderr\n" if $status; + $rewritten_text{$key} = $rewritten; + } + my $object = "$directory/text-$index-$level.o"; + ($status, $stdout, $stderr) = command("text-object-$index-$level", $source_compiler, '--target', $target, + @target_flags, @{$expect->{flags} // []}, '-g0', "-O$level", '-c', $rewritten_text{$key}, '-o', $object); + die "$test: object compile from LowIR text failed: $stdout$stderr\n" if $status; + die "$test: the object compiled from its LowIR text differs from the direct one at O$level\n" + if read_file($object) ne read_file($direct); +} + for my $level (@{$expect->{levels} // [0, 1, 2, 3]}) { my ($status, $stdout, $stderr); my @provided_objects = @assembly_objects; @@ -315,6 +350,7 @@ sub reference_link_rejection { die "$test: object compile failed: $stdout$stderr\n" if $status; ($status, $stdout, $stderr) = command("object-validate-$index-$level", $validator, 'validate', $object); die "$test: invalid relocatable object: $stdout$stderr\n" if $status; + check_text_object($index, $level, $inputs[$index], $object) if !$expect->{assembly}; push @objects, $object; if ($expect->{source} && !$expect->{assembly} && @units) { my $lowir = $lowered_source{$inputs[$index]} // "$directory/unit-$index.lowir"; diff --git a/scripts/tests/test_wasm_checker.py b/scripts/tests/test_wasm_checker.py index b11e931c38..4a9ff7e137 100644 --- a/scripts/tests/test_wasm_checker.py +++ b/scripts/tests/test_wasm_checker.py @@ -1,4 +1,6 @@ -"""The real checker must retain failure checks and lower each source only once.""" +"""The real checker must retain failure checks, lower each source only once for +its LowIR view and twice for its object text (O0, O1+), and compare the +object compiled from that text with the direct one.""" from pathlib import Path import json import os @@ -38,8 +40,12 @@ if '--emit-lowir' in args: output.write_text('target wasm32 1\nfunction @observe() -> i32 {\n block ^entry:\n return i32 17\n}\n') else: - # A valid core module exporting observe() -> i32, returning 17. - output.write_bytes(bytes.fromhex('0061736d010000000105016000017f03020100070b01076f62736572766500000a0601040041110b')) + # A valid core module exporting observe() -> i32, returning 17 + # (19 from rewritten text in the differing mode). + result = '13' if os.environ.get('TEXT_MODE') == 'differ' and any('rewritten' in x for x in args) else '11' + output.write_bytes(bytes.fromhex('0061736d010000000105016000017f03020100070b01076f62736572766500000a06010400' + result + '0b')) +elif kind == 'lowiropt': + Path(args[args.index('-o') + 1]).write_text(Path(args[-1]).read_text()) elif kind == 'runtime': mode = os.environ.get('TRAP_MODE', 'ok') if mode == 'ok': @@ -52,10 +58,10 @@ class WasmChecker(unittest.TestCase): - def check(self, expect, mode='ok'): + def check(self, expect, mode='ok', text_mode='same'): with tempfile.TemporaryDirectory() as directory: root = Path(directory) - for name, body in [('supervisor', SUPERVISOR), ('compiler', TOOL), + for name, body in [('supervisor', SUPERVISOR), ('compiler', TOOL), ('lowiropt', TOOL), ('validator', TOOL), ('runtime', TOOL)]: path = root / name path.write_text('#!' + sys.executable + '\n' + body) @@ -65,9 +71,10 @@ def check(self, expect, mode='ok'): fixture.with_suffix('.wasm-expect').write_text(json.dumps(expect)) (root / 'extra.cpp').write_text('// supplied source unit\n') env = dict(os.environ, CPPGM_WASM_CPPGM=str(root / 'compiler'), + CPPGM_WASM_LOWIROPT=str(root / 'lowiropt'), CPPGM_WASM_TOOLS=str(root / 'validator'), CPPGM_WASMTIME=str(root / 'runtime'), CPPGM_TEST_SUPERVISOR=str(root / 'supervisor'), - CHECKER_COMMANDS=str(root / 'commands.jsonl'), TRAP_MODE=mode) + CHECKER_COMMANDS=str(root / 'commands.jsonl'), TRAP_MODE=mode, TEXT_MODE=text_mode) result = subprocess.run(['perl', str(ROOT / 'scripts/check_wasm.pl'), str(root / 'compiler'), str(fixture)], env=env, cwd=root, capture_output=True, text=True, timeout=30) @@ -81,11 +88,28 @@ def test_lowering_is_shared_but_all_backend_optimization_levels_run(self): 'calls': [{'export': 'observe', 'result': '17'}]}) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) compiler = [args for tool, args in commands if tool == 'compiler'] - lowered = [args for args in compiler if '--emit-lowir' in args] + lowered = [args for args in compiler if '--emit-lowir' in args and '-g0' not in args] self.assertEqual(len(lowered), 1 + bool(units)) + texts = [args for args in compiler if '--emit-lowir' in args and '-g0' in args] + self.assertEqual(len(texts), 2 * (1 + bool(units))) + self.assertEqual(sum('-D__OPTIMIZE__=1' in args for args in texts), 1 + bool(units)) + rewrites = [args for tool, args in commands if tool == 'lowiropt'] + self.assertEqual(len(rewrites), len(texts)) for level in range(4): self.assertTrue(any('-O' + str(level) in args for args in compiler)) + def test_an_object_compiled_from_its_lowir_text_must_be_the_direct_one(self): + for expect in ({'source': True, 'levels': [2], 'calls': [{'export': 'observe', 'result': '17'}]}, + {'levels': [0], 'calls': [{'export': 'observe', 'result': '17'}]}): + with self.subTest(source=expect.get('source', False)): + result, commands = self.check(expect, text_mode='differ') + self.assertNotEqual(result.returncode, 0) + self.assertIn('differs from the direct one', result.stderr) + result, commands = self.check(expect) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertTrue(any('rewritten' in x for tool, args in commands if tool == 'compiler' + for x in args)) + def test_assembly_uses_direct_source_and_object_paths_without_lowir(self): result, commands = self.check({'source': True, 'assembly': True, 'levels': [0, 3], From 684cceb1eab4db40f545c4a4468097bc833cb4e6 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 21:04:01 +0000 Subject: [PATCH 6/8] Export the optimized LowIR of an object compile with -S -emit-lowir --- TESTING_AND_REFERENCES.md | 6 + dev/cppgm.cpp | 45 ++++--- dev/src/backend/options.h | 2 + dev/src/driver/toolchain.cpp | 118 +++++++++++++++--- dev/src/lowir/program.cpp | 42 +++++++ dev/src/lowir/program.h | 7 ++ dev/src/lowir/text_parser_body.cpp | 1 + dev/src/wasm/backend.cpp | 25 ++-- dev/src/wasm/backend.h | 7 ++ dev/src/wasm/module.cpp | 11 +- pa33/maintainer/Makefile | 5 + .../run_object_lowir_roundtrip_tests.pl | 31 ++++- pa33/tests/o1/200-separate-latch-counter.ref | 2 +- pa37/maintainer/Makefile | 5 + scripts/check_wasm.pl | 25 ++++ scripts/tests/test_wasm_checker.py | 31 ++++- 16 files changed, 307 insertions(+), 56 deletions(-) diff --git a/TESTING_AND_REFERENCES.md b/TESTING_AND_REFERENCES.md index 77f669b352..384d8cc65f 100644 --- a/TESTING_AND_REFERENCES.md +++ b/TESTING_AND_REFERENCES.md @@ -223,6 +223,12 @@ not grow. The source-only `pa34/maintainer/Makefile` retains census and Cachegri targets, which are not student requirements; the course lane `make -C pa34 test-kernels` (PA36's kernels under Cachegrind, at PA34's limit) is one, so `make test-report` needs valgrind. +The PA33 and PA37 `maintainer/Makefile`s also turn on a check of this +solution's `cppgm -S -emit-lowir` (the LowIR that `-c` compiles, after the +LowIR optimizer). PA33's object round trip and PA37's Wasm checker compile +each object again from that text with `-c -fno-lowir-passes`, after +`lowiropt -O0` has read and written it, and compare it with the direct +object byte for byte. Keep solution-specific expectations out of graded course fixtures. ## Reference policy diff --git a/dev/cppgm.cpp b/dev/cppgm.cpp index a9f4a5ebe9..a07ee04e3d 100644 --- a/dev/cppgm.cpp +++ b/dev/cppgm.cpp @@ -675,11 +675,17 @@ DriverInvocation parse_driver_invocation(const vector& args) { throw InvocationError("query flag must be used as a direct invocation"); } - if (args[i] == "-c") + // -S (only with -emit-lowir, which the toolchain checks) compiles + // as -c does and writes the program as LowIR text. + if (args[i] == "-c" || args[i] == "-S") { compile_only = true; continue; } + if (args[i] == "-emit-lowir" || args[i] == "-fno-lowir-passes" || args[i] == "-flowir-passes") + { + continue; + } if (args[i] == "--stats" || args[i] == "--stats-functions" || args[i].compare(0, 15, "--verify-passes") == 0) { continue; @@ -1100,6 +1106,7 @@ void report_lowir_stats(const lower::LoweringCounters& counters, const lowir::Pr // constructed program first (audit builds). int run_emit_lowir_mode(vector args) { + const vector given = args; const bool stats = consume_stats_flag(args); const bool validate = consume_flag(args, "--validate"); SourceOutputInvocation invocation = parse_source_output_invocation(args, true); @@ -1107,9 +1114,19 @@ int run_emit_lowir_mode(vector args) // The LowIR half of an object compile: a `.lowir` output (the // toolchain's LowIR object input, `-c x.lowir`) with the object // compile's debug-information level stated (-g0, -gline-tables-only) - // is the program `-c -o x.o` compiles, lowered as -c lowers it (in - // host-object mode for a native target), so the object it gives is the - // direct compile's (PA33 object roundtrip). + // is the program `-c -o x.o` compiles: the driver's -S -emit-lowir + // writes it, so the object it gives is the direct compile's (PA33 + // object roundtrip). + if (invocation.debug_level && ends_with(invocation.outfile, ".lowir")) + { + if (validate) + throw InvocationError("--validate checks the LowIR view, not an object compile's LowIR"); + vector compile = { "-S", "-emit-lowir" }; + for (const string& arg : given) + if (arg != "--hosted") + compile.push_back(arg); + return driver::run_toolchain(compile, source_preprocessor_options()); + } // Otherwise the output is the course's LowIR view, --hosted or not // (the help text: --hosted // selects the host environment, which this view preprocesses in @@ -1119,9 +1136,6 @@ int run_emit_lowir_mode(vector args) // Both are LowIR that lowir and lowiropt read, and state the // instruction facts the lowering proved (lowir.md "Instruction Facts"), // which the object compile reads. - const bool object_half = invocation.debug_level && ends_with(invocation.outfile, ".lowir"); - if (object_half) - invocation.hosted = true; PreprocessorOptions options = source_preprocessor_options(invocation); // The LowIR view preprocesses in the host environment -c uses (PA33: a // source the driver lanes compile includes host headers). @@ -1135,18 +1149,13 @@ int run_emit_lowir_mode(vector args) const bool optimizing = invocation.optimizer.level > 0; if (!validate && !optimizing) lowering.set_definition_stream(&definitions); - // A Wasm object's half is lowered as its -c lowers it, by Wasm's - // conventions rather than the host object's. - const bool host_half = object_half && !target_model::is_wasm(invocation.target); - lowering.set_object_mode(host_half); - lowering.set_host_objects(host_half); lowering.set_macho_objects(invocation.target == native::Target::MacOS); - lowering.set_optimizing(object_half || invocation.optimizer.level >= 2); + lowering.set_optimizing(invocation.optimizer.level >= 2); lowering.set_strict_aliasing(invocation.strict_aliasing); lowering.set_popcnt(options.popcnt); lowering.set_exceptions(options.modes.exceptions); // The LowIR view carries the source's debug locations when debug - // information is asked for, including the object roundtrip's view. + // information is asked for. lowering.set_debug_locations(invocation.debug_info); lowering.set_debug_types(invocation.debug_types); double front_ms = 0, lower_ms = 0; @@ -1289,7 +1298,13 @@ int run_cppgm(const vector& raw_args) if (has_help_arg(raw_args)) { - cout << cppgm_help_text(); + // The course's flags, then this compiler's (the header: a tool may + // list more). + cout << cppgm_help_text() << "\n" + << "this compiler's flags:\n" + " -S -emit-lowir write the LowIR that -c compiles, after the LowIR optimizer\n" + " (default output: .lowir)\n" + " -fno-lowir-passes compile without the LowIR optimizer; the back end runs at the -O level\n"; return EXIT_SUCCESS; } diff --git a/dev/src/backend/options.h b/dev/src/backend/options.h index 5923307f64..e131936830 100644 --- a/dev/src/backend/options.h +++ b/dev/src/backend/options.h @@ -41,6 +41,8 @@ struct Options bool wasm_atomics = true; WasmLinkOptions wasm_link; const opt::OptimizerOptions* optimizer = nullptr; + // -fno-lowir-passes: the back end takes the program as it is. + bool lowir_passes = true; }; } // namespace backend diff --git a/dev/src/driver/toolchain.cpp b/dev/src/driver/toolchain.cpp index 64a578b00c..fd5f2fe79e 100644 --- a/dev/src/driver/toolchain.cpp +++ b/dev/src/driver/toolchain.cpp @@ -19,6 +19,7 @@ #include "lex/post_tokenizer.h" #include "lower/program_lowering.h" #include "lowir/text_reader.h" +#include "lowir/text_writer.h" #include "native/backend_error.h" #include "native/link/linker.h" #include "native/object/elf_object.h" @@ -115,6 +116,14 @@ struct Invocation std::string standard; native::Target target = native::host_target(); bool compile_only = false; + // -S -emit-lowir: each input's program as -c compiles it, after the + // LowIR optimizer, written as LowIR text instead of an object (clang's + // -S -emit-llvm). + bool emit_lowir = false; + // -fno-lowir-passes: the program goes to the back end (or to the text) + // without the LowIR optimizer; the back end still runs at the -O level. + // A program -S -emit-lowir wrote compiles so to the object -c gives. + bool lowir_passes = true; bool position_independent = false; bool red_zone = true; // -ffunction-sections: each function in a section of its own. @@ -339,6 +348,15 @@ uint32_t parse_wasm_stack_size(const std::string& size) return static_cast(bytes); } +// -S -emit-lowir compiles as -c does: LowIR is the only assembly form this +// driver writes. +void lowir_output(Invocation& invocation, bool assembly_output) +{ + if (assembly_output != invocation.emit_lowir) + throw InvocationError(assembly_output ? "-S requires -emit-lowir" : "-emit-lowir requires -S"); + invocation.compile_only = invocation.compile_only || invocation.emit_lowir; +} + Invocation parse(const std::vector& args, const PreprocessorOptions& base) { Invocation invocation; @@ -350,12 +368,19 @@ Invocation parse(const std::vector& args, const PreprocessorOptions bool pthread = false; bool optimize_size = false, popcnt_explicit = false; unsigned pic_level = 0, pie_level = 0; + bool assembly_output = false; const size_t base_defines = invocation.preprocessor.command_line.size(); for (size_t i = 0; i < args.size(); ++i) { const std::string& arg = args[i]; if (arg == "-c") invocation.compile_only = true; + else if (arg == "-S") + assembly_output = true; + else if (arg == "-emit-lowir") + invocation.emit_lowir = true; + else if (arg == "-flowir-passes" || arg == "-fno-lowir-passes") + invocation.lowir_passes = arg == "-flowir-passes"; else if (arg == "-fPIC" || arg == "-fpic" || arg == "-fPIE" || arg == "-fpie") { invocation.position_independent = true; @@ -538,6 +563,7 @@ Invocation parse(const std::vector& args, const PreprocessorOptions input_language(invocation); if (invocation.inputs.empty()) throw InvocationError("no input files"); + lowir_output(invocation, assembly_output); // GCC's -pthread defines _REENTRANT ahead of every -D and -U wherever // it is written (the host link adds the thread library; link mode's // runtime needs nothing). @@ -643,7 +669,7 @@ void report_census(const native::ObjectStats& stats) // the optimized text (lowiropt and --emit-lowir keep thunks as lowered). void optimize_unit(lowir::Program& program, const Invocation& invocation, native::EhModel eh_model) { - if (invocation.optimizer.level == 0) + if (invocation.optimizer.level == 0 || !invocation.lowir_passes) return; opt::OptimizerOptions options = invocation.optimizer; options.inline_thunk_targets = eh_model == native::EhModel::Course; @@ -707,8 +733,22 @@ bool lower_source(const std::string& path, const Invocation& invocation, lower:: return true; } -bool compile_unit( - const std::string& path, const Invocation& invocation, native::EhModel eh_model, native::object::ObjectFile& object) +// -S -emit-lowir: a unit's program as the back end would take it, written +// to `output` (at -O0 each definition as the lowering completes it, as -c +// encodes it). +bool write_unit_lowir(const lowir::Program& program, lowir::DefinitionStream* definitions, const std::string& output) +{ + if (definitions != nullptr ? lowir::write_program_file(program, *definitions, output) + : lowir::write_program_file(program, output)) + return true; + std::cerr << "ERROR: cannot write " << output << std::endl; + return false; +} + +// With `lowir_output`, -S -emit-lowir: the program is written there as text +// instead of compiled. +bool compile_unit(const std::string& path, const Invocation& invocation, native::EhModel eh_model, + native::object::ObjectFile& object, const std::string* lowir_output = nullptr) { const std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); lowir::Program program; @@ -718,10 +758,14 @@ bool compile_unit( stats.census = invocation.function_census; native::ObjectBuilder builder(program, stats, eh_model, invocation.optimizer.level, invocation.position_independent, invocation.target, invocation.red_zone, invocation.function_sections); - // At -O0 each definition is encoded as the lowering completes it; an - // optimizing level keeps the program until the optimizer has run. - if (invocation.optimizer.level == 0) - lowering.set_definition_stream(&builder); + // At -O0 each definition is encoded (or written) as the lowering + // completes it; an optimizing level keeps the program until the + // optimizer has run. + lowir::DefinitionStream definitions; + const bool streaming = invocation.optimizer.level == 0; + if (streaming) + lowering.set_definition_stream( + lowir_output != nullptr ? static_cast(&definitions) : &builder); lowering.set_object_mode(true); lowering.set_debug_locations(invocation.debug_info); lowering.set_debug_types(invocation.debug_types); @@ -741,6 +785,8 @@ bool compile_unit( return true; lowering.finish(); optimize_unit(program, invocation, eh_model); + if (lowir_output != nullptr) + return write_unit_lowir(program, streaming ? &definitions : nullptr, *lowir_output); object.path = path; builder.finish(object); } @@ -781,8 +827,8 @@ bool compile_unit( // One serialized LowIR unit (PA33's LowIR object input): read and // validated, optimized at the invocation's level, then compiled by the same // object back end as a source's program. -bool compile_lowir_unit( - const std::string& path, const Invocation& invocation, native::EhModel eh_model, native::object::ObjectFile& object) +bool compile_lowir_unit(const std::string& path, const Invocation& invocation, native::EhModel eh_model, + native::object::ObjectFile& object, const std::string* lowir_output) { lowir::Program program; std::string error; @@ -793,6 +839,8 @@ bool compile_lowir_unit( } native::recover_jump_thunks(program, eh_model); optimize_unit(program, invocation, eh_model); + if (lowir_output != nullptr) + return write_unit_lowir(program, nullptr, *lowir_output); native::ObjectStats stats; stats.clocks = invocation.stats; stats.census = invocation.function_census; @@ -807,11 +855,11 @@ bool compile_lowir_unit( return true; } -bool compile_input( - const Input& input, const Invocation& invocation, native::EhModel eh_model, native::object::ObjectFile& object) +bool compile_input(const Input& input, const Invocation& invocation, native::EhModel eh_model, + native::object::ObjectFile& object, const std::string* lowir_output = nullptr) { - return input.kind == Input::Kind::LowIR ? compile_lowir_unit(input.name, invocation, eh_model, object) - : compile_unit(input.name, invocation, eh_model, object); + return input.kind == Input::Kind::LowIR ? compile_lowir_unit(input.name, invocation, eh_model, object, lowir_output) + : compile_unit(input.name, invocation, eh_model, object, lowir_output); } bool regular_file(const std::string& path) @@ -836,13 +884,21 @@ void check_output(const Invocation& invocation, const std::string& output) } } -std::string default_object_name(const std::string& source) +std::string output_name(const std::string& source, const char* suffix) { std::string name = source.substr(source.rfind('/') == std::string::npos ? 0 : source.rfind('/') + 1); const size_t dot = name.rfind('.'); if (dot != std::string::npos && dot != 0) name.erase(dot); - return name + ".o"; + return name + suffix; +} + +// -c's output for an input, or -S -emit-lowir's (.lowir). +std::string default_output_name(const Invocation& invocation, const Input& input) +{ + if (!invocation.output.empty()) + return invocation.output; + return output_name(input.name, invocation.emit_lowir ? ".lowir" : ".o"); } // The exception model of a -c object: a course object (`.obj`, PA25's @@ -868,7 +924,15 @@ int compile_mode(const Invocation& invocation) if (input.kind != Input::Kind::Source && input.kind != Input::Kind::LowIR) throw InvocationError("-c needs C++ source or LowIR inputs: " + input.name); native::object::ObjectFile object; - const std::string output = invocation.output.empty() ? default_object_name(input.name) : invocation.output; + const std::string output = default_output_name(invocation, input); + if (invocation.emit_lowir) + { + check_output(invocation, output); + // (Lowered as a host object is, whatever the output's name.) + if (!compile_input(input, invocation, native::EhModel::Host, object, &output)) + return EXIT_FAILURE; + continue; + } if (!compile_input(input, invocation, object_eh_model(output), object)) return EXIT_FAILURE; std::string error; @@ -990,8 +1054,10 @@ bool wasm_assembly(const Input& input, const Invocation& invocation, wasm::LinkI // One translation unit's posttoken records (`sof`, the PA2 tokens, `eof`); // false after an error. +// With `lowir_output`, -S -emit-lowir: the program is written there as text +// instead of compiled. bool wasm_input(const Input& input, const Invocation& invocation, const backend::Options& options, - wasm::LinkInputs& inputs, std::string& error) + wasm::LinkInputs& inputs, std::string& error, const std::string* lowir_output) { if (input.kind == Input::Kind::Assembly) return wasm_assembly(input, invocation, inputs, error); @@ -1042,6 +1108,14 @@ bool wasm_input(const Input& input, const Invocation& invocation, const backend: << " resolutions=" << work.resolutions << " candidates=" << work.candidates << std::endl; #endif } + if (lowir_output != nullptr) + { + wasm::optimize_object_program(program, options, nullptr); + if (lowir::write_program_file(program, *lowir_output)) + return true; + error = "cannot write " + *lowir_output; + return false; + } std::string dump = "machine_ir wasm32 1\n"; wasm::Object object; if (!wasm::compile_object(program, options, object, dump, error)) @@ -1071,18 +1145,22 @@ int wasm_mode(const Invocation& invocation) if (invocation.wasm_stack_size != 0) options.wasm_stack_size = invocation.wasm_stack_size; options.optimizer = &invocation.optimizer; + options.lowir_passes = invocation.lowir_passes; std::string error; wasm::LinkInputs objects; for (const Input& input : invocation.inputs) { - if (!wasm_input(input, invocation, options, objects, error)) + const std::string lowir_output = invocation.emit_lowir ? default_output_name(invocation, input) : ""; + if (invocation.emit_lowir) + check_output(invocation, lowir_output); + if (!wasm_input(input, invocation, options, objects, error, invocation.emit_lowir ? &lowir_output : nullptr)) { std::cerr << "ERROR: " << error << std::endl; return EXIT_FAILURE; } - if (invocation.compile_only) + if (invocation.compile_only && !invocation.emit_lowir) { - options.output = invocation.output.empty() ? default_object_name(input.name) : invocation.output; + options.output = default_output_name(invocation, input); check_output(invocation, options.output); if (!wasm::output_objects(objects, options, true, error)) { diff --git a/dev/src/lowir/program.cpp b/dev/src/lowir/program.cpp index a3d8de432c..09c18f2e3e 100644 --- a/dev/src/lowir/program.cpp +++ b/dev/src/lowir/program.cpp @@ -61,6 +61,48 @@ void order_as_written(Program& program) program.order.swap(written); } +void number_temps_as_defined(FunctionBody& body) +{ + std::vector map(body.temps.size(), kNoId); + TempId next = body.parameter_count; + bool moved = false; + for (TempId t = 0; t < body.parameter_count; ++t) + map[t] = t; + for (BlockId b : body.layout) + for (InstId i = body.blocks[b].first; i != kNoId; i = body.instructions[i].next) + { + const TempId result = body.instructions[i].result; + if (result == kNoId) + continue; + moved = moved || result != next; + map[result] = next++; + } + if (!moved) + return; + // (A temporary no placed instruction defines keeps its order, after + // the others.) + for (TempId& t : map) + if (t == kNoId) + t = next++; + std::vector temps(body.temps.size()); + for (TempId t = 0; t < body.temps.size(); ++t) + temps[map[t]] = body.temps[t]; + body.temps.swap(temps); + auto remap = [&](Value& v) { + if (v.kind == ValueKind::Temp) + v.index = map[v.index]; + }; + for (Instruction& inst : body.instructions) + { + if (inst.result != kNoId) + inst.result = map[inst.result]; + for (Value& v : inst.ops) + remap(v); + } + for (Value& v : body.operands) + remap(v); +} + void Program::declare_global(SymbolId id, SymbolKind kind, const Global& global) { Symbol& symbol = symbols[id]; diff --git a/dev/src/lowir/program.h b/dev/src/lowir/program.h index 0d24da8f0f..934a4c010d 100644 --- a/dev/src/lowir/program.h +++ b/dev/src/lowir/program.h @@ -429,6 +429,13 @@ struct Program // order gives the same output from the text as from the program. void order_as_written(Program& program); +// Numbers a body's temporaries as its definitions come: the parameters, +// then the results in layout order (as the optimizer leaves a body, +// opt::compact_body). A reader numbers a temporary where the text first +// names it, which is before its definition for a phi's operand along a +// back edge; numbered so, a program read from its text has the ids it had. +void number_temps_as_defined(FunctionBody& body); + // A consumer of function definitions as a producer completes them (in // order); the producer releases each body after the append. A consumer // that selects code (`needs_boundaries`) is given every direct callee's diff --git a/dev/src/lowir/text_parser_body.cpp b/dev/src/lowir/text_parser_body.cpp index 56951f2ea6..6b6ce5f81b 100644 --- a/dev/src/lowir/text_parser_body.cpp +++ b/dev/src/lowir/text_parser_body.cpp @@ -195,6 +195,7 @@ void Parser::finish_body(FunctionBuilder& builder, SymbolId function) fail_at(Position{ source_, temp_uses_[temp] }, std::string("undefined temporary: ") + program_.spelling(body.temps[temp].name)); } + number_temps_as_defined(builder.body()); } // --------------------------------------------------------------------------- diff --git a/dev/src/wasm/backend.cpp b/dev/src/wasm/backend.cpp index 7699cdc53d..2a3dd7056a 100644 --- a/dev/src/wasm/backend.cpp +++ b/dev/src/wasm/backend.cpp @@ -59,6 +59,22 @@ bool write_file(const std::string& path, const void* data, size_t size, std::str } // namespace +void optimize_object_program(lowir::Program& program, const backend::Options& options, opt::OptimizerStats* stats) +{ + // The object follows the program's order: the one its LowIR text has, + // also for the symbols the optimizer adds (such as a switch's table). + lowir::order_as_written(program); + if (!options.lowir_passes) + return; + opt::OptimizerOptions optimization; + if (options.optimizer != nullptr) + optimization = *options.optimizer; + optimization.level = options.optimization_level; + optimization.has_gnu_sincos = target_model::has_gnu_sincos(program.target); + opt::optimize_program(program, optimization, stats); + lowir::order_as_written(program); +} + bool compile_object( lowir::Program& program, const backend::Options& options, Object& object, std::string& dump, std::string& error) { @@ -74,15 +90,8 @@ bool compile_object( } try { - // The object follows the program's order: the one its LowIR text has. - lowir::order_as_written(program); - opt::OptimizerOptions optimization; - if (options.optimizer != nullptr) - optimization = *options.optimizer; - optimization.level = options.optimization_level; - optimization.has_gnu_sincos = target_model::has_gnu_sincos(program.target); opt::OptimizerStats stats; - opt::optimize_program(program, optimization, &stats); + optimize_object_program(program, options, &stats); #if CPPGM_TELEMETRY_ENABLED const auto object_start = std::chrono::steady_clock::now(); #endif diff --git a/dev/src/wasm/backend.h b/dev/src/wasm/backend.h index 34ba7fdbc5..75fad5d821 100644 --- a/dev/src/wasm/backend.h +++ b/dev/src/wasm/backend.h @@ -4,8 +4,15 @@ #include "lowir/program.h" #include "wasm/object.h" +namespace opt { +struct OptimizerStats; +} + namespace wasm { +// The LowIR optimizer as compile_object runs it before the back end: the +// program -S -emit-lowir writes. +void optimize_object_program(lowir::Program& program, const backend::Options& options, opt::OptimizerStats* stats); bool compile_object( lowir::Program& program, const backend::Options& options, Object& object, std::string& dump, std::string& error); bool output_objects(LinkInputs& inputs, const backend::Options& options, bool relocatable, std::string& error); diff --git a/dev/src/wasm/module.cpp b/dev/src/wasm/module.cpp index eeaf35c559..26193ad9dd 100644 --- a/dev/src/wasm/module.cpp +++ b/dev/src/wasm/module.cpp @@ -21,10 +21,11 @@ std::vector type_key(const Signature& signature) } // The type of each signature, numbered in the order the program first refers -// to it: its functions' in program order, then its calls' in block order, -// then any other's. A program read from LowIR text makes its signatures in -// the text's order, so the numbering is the same from the text as from the -// program that wrote it. +// to it: its functions' in program order, then its calls' in block order. A +// program read from LowIR text makes its signatures in the text's order, so +// the numbering is the same from the text as from the program that wrote it. +// A signature nothing refers to (one whose calls the optimizer removed, +// which the text does not write) has no type. void function_types(const lowir::Program& program, Module& module) { std::vector types(program.signatures.size()); @@ -85,8 +86,6 @@ void function_types(const lowir::Program& program, Module& module) if ((body.instructions[inst].flags & lowir::IF_SIGNATURE) != 0) number(static_cast(body.instructions[inst].immediate)); } - for (lowir::SignatureId id = 0; id < types.size(); ++id) - number(id); } } // namespace diff --git a/pa33/maintainer/Makefile b/pa33/maintainer/Makefile index 329e224b88..99046728f9 100644 --- a/pa33/maintainer/Makefile +++ b/pa33/maintainer/Makefile @@ -4,6 +4,11 @@ # this solution's pass-specific choices, outside the course contract. One # fixture's reference is regenerated with the course root pointed at its lane: # make ref-test TEST=tests/regression/o3/x.t O3_TEST_ROOT=tests/regression/o3 +# +# The object round trip also compiles each object from its optimized LowIR +# (-S -emit-lowir, then -c -fno-lowir-passes) byte for byte +# (scripts/run_object_lowir_roundtrip_tests.pl). +export CPPGM_OBJECT_ROUNDTRIP_OPTIMIZED_TEXT := 1 REGRESSION_O0_TEST_ROOT ?= tests/regression/o0 REGRESSION_O1_TEST_ROOT ?= tests/regression/o1 REGRESSION_O2_TEST_ROOT ?= tests/regression/o2 diff --git a/pa33/scripts/run_object_lowir_roundtrip_tests.pl b/pa33/scripts/run_object_lowir_roundtrip_tests.pl index 87689fcef9..c52e9857fe 100755 --- a/pa33/scripts/run_object_lowir_roundtrip_tests.pl +++ b/pa33/scripts/run_object_lowir_roundtrip_tests.pl @@ -21,7 +21,7 @@ sub detect_jobs { } sub usage { - die "usage: run_object_lowir_roundtrip_tests.pl [--debuginfo] [--target TARGET] --app APP [--lowiropt APP] (--test-root DIR | --test FILE)...\n"; + die "usage: run_object_lowir_roundtrip_tests.pl [--debuginfo] [--target TARGET] [--optimized-text] --app APP [--lowiropt APP] (--test-root DIR | --test FILE)...\n"; } my $app = "../dev/cppgm"; @@ -29,6 +29,12 @@ sub usage { # The target both compiles name (`--target`), or the driver default. my @target_flags; my $debuginfo = 0; +# --optimized-text, or CPPGM_OBJECT_ROUNDTRIP_OPTIMIZED_TEXT (this solution's +# lane, outside the course contract): the program -c compiles after the +# LowIR optimizer (-S -emit-lowir), read and written by lowiropt -O0, +# compiles without the optimizer (-fno-lowir-passes) to the direct object +# as well. +my $optimized_text = $ENV{CPPGM_OBJECT_ROUNDTRIP_OPTIMIZED_TEXT} ? 1 : 0; my @roots; my @tests; my $repo_root = abs_path("$Bin/../.."); @@ -53,6 +59,8 @@ sub usage { push @tests, shift @ARGV; } elsif($arg eq "--debuginfo") { $debuginfo = 1; + } elsif($arg eq "--optimized-text") { + $optimized_text = 1; } elsif($arg eq "-h" || $arg eq "--help") { usage(); } else { @@ -278,7 +286,7 @@ sub check_mode { my $direct_bytes = read_bytes($direct); my $from_lowir_bytes = read_bytes($from_lowir); if($direct_bytes eq $from_lowir_bytes) { - return undef; + return $optimized_text ? check_optimized_text($source, $mode, $base, $direct_bytes) : undef; } return "object differs after compiling serialized LowIR rewritten by lowiropt: $source $debug_label $level_name\n" @@ -288,6 +296,25 @@ sub check_mode { . "from-lowir symbols:\n" . object_summary($from_lowir); } +sub check_optimized_text { + my ($source, $mode, $base, $direct_bytes) = @_; + my ($debug_flag, $opt, $level_name) = @$mode; + my @debug_flags = defined($debug_flag) ? ($debug_flag) : ("-g0"); + my @optimization_flags = defined($opt) ? ($opt) : (); + my $text = "$base.optimized.lowir"; + my $rewritten = "$base.optimized.rewritten.lowir"; + my $object = "$base.from-optimized.o"; + my $error = run_command($app, @target_flags, "-S", "-emit-lowir", @debug_flags, @optimization_flags, + "-o", $text, $source) + // run_command($lowiropt, "-O0", "-o", $rewritten, $text) + // run_command($app, @target_flags, "-c", "-fno-lowir-passes", @debug_flags, @optimization_flags, + "-o", $object, $rewritten); + return $error if defined $error; + my $debug_label = defined($debug_flag) ? $debug_flag : "nodebug"; + return undef if read_bytes($object) eq $direct_bytes; + return "object differs after compiling the optimized LowIR without the LowIR optimizer: $source $debug_label $level_name\n"; +} + sub append_keep_going_summary { my ($passed, $total, $failed) = @_; my $counts = $ENV{CPPGM_TEST_COUNTS_FILE} || "$repo_root/" . run_result_name('.test_counts'); diff --git a/pa33/tests/o1/200-separate-latch-counter.ref b/pa33/tests/o1/200-separate-latch-counter.ref index 0b1e4c0822..6a42b203ee 100644 --- a/pa33/tests/o1/200-separate-latch-counter.ref +++ b/pa33/tests/o1/200-separate-latch-counter.ref @@ -31,7 +31,7 @@ function @next_used(%n : i64) -> i64 [no_inline=yes] { block ^latch: %next = binary add i64 %i, 1 - %first = binary add i64 %next, %sum + %first = binary add i64 %sum, %next %total = binary add i64 %i, %first jump ^header diff --git a/pa37/maintainer/Makefile b/pa37/maintainer/Makefile index 523f6e920b..db6e566b66 100644 --- a/pa37/maintainer/Makefile +++ b/pa37/maintainer/Makefile @@ -7,6 +7,11 @@ # make check TEST=tests/regression/x.t REGRESSION_TEST_ROOT ?= tests/regression +# Each fixture's object also compiles from its optimized LowIR +# (-S -emit-lowir, then -c -fno-lowir-passes) byte for byte +# (scripts/check_wasm.pl). +export CPPGM_WASM_OPTIMIZED_TEXT := 1 + test: test-regression test-regression: $(TEST_DEPS) diff --git a/scripts/check_wasm.pl b/scripts/check_wasm.pl index b0c9e7852f..46a8982e8e 100644 --- a/scripts/check_wasm.pl +++ b/scripts/check_wasm.pl @@ -267,6 +267,29 @@ sub check_text_object { if read_file($object) ne read_file($direct); } +# CPPGM_WASM_OPTIMIZED_TEXT (this solution's lane, outside the course +# contract): the program -c compiles after the LowIR optimizer +# (-S -emit-lowir), read and written by lowiropt -O0, compiles without the +# optimizer (-fno-lowir-passes) to the direct object as well. +my $optimized_text = $ENV{CPPGM_WASM_OPTIMIZED_TEXT}; +sub check_optimized_text_object { + my ($index, $level, $input, $direct) = @_; + my @compile = ($source_compiler, '--target', $expect->{target} // 'wasm32-unknown-unknown', + @target_flags, @{$expect->{flags} // []}, "-O$level"); + my $name = "optimized-$index-$level"; + my ($status, $stdout, $stderr) = command("$name-lowir", @compile, '-S', '-emit-lowir', $input, + '-o', "$directory/$name.lowir"); + die "$test: -S -emit-lowir failed: $stdout$stderr\n" if $status; + ($status, $stdout, $stderr) = command("$name-rewrite", $lowiropt, '-O0', '-o', + "$directory/$name.rewritten.lowir", "$directory/$name.lowir"); + die "$test: lowiropt -O0 rejected the optimized LowIR: $stdout$stderr\n" if $status; + ($status, $stdout, $stderr) = command("$name-object", @compile, '-c', '-fno-lowir-passes', + "$directory/$name.rewritten.lowir", '-o', "$directory/$name.o"); + die "$test: object compile from the optimized LowIR failed: $stdout$stderr\n" if $status; + die "$test: the object compiled from its optimized LowIR differs from the direct one at O$level\n" + if read_file("$directory/$name.o") ne read_file($direct); +} + for my $level (@{$expect->{levels} // [0, 1, 2, 3]}) { my ($status, $stdout, $stderr); my @provided_objects = @assembly_objects; @@ -351,6 +374,8 @@ sub check_text_object { ($status, $stdout, $stderr) = command("object-validate-$index-$level", $validator, 'validate', $object); die "$test: invalid relocatable object: $stdout$stderr\n" if $status; check_text_object($index, $level, $inputs[$index], $object) if !$expect->{assembly}; + check_optimized_text_object($index, $level, $inputs[$index], $object) + if $optimized_text && !$expect->{assembly}; push @objects, $object; if ($expect->{source} && !$expect->{assembly} && @units) { my $lowir = $lowered_source{$inputs[$index]} // "$directory/unit-$index.lowir"; diff --git a/scripts/tests/test_wasm_checker.py b/scripts/tests/test_wasm_checker.py index 4a9ff7e137..1ea4b0b7c3 100644 --- a/scripts/tests/test_wasm_checker.py +++ b/scripts/tests/test_wasm_checker.py @@ -37,12 +37,16 @@ log.write(json.dumps([kind, args]) + '\n') if kind == 'compiler': output = Path(args[args.index('-o') + 1]) - if '--emit-lowir' in args: + if '--emit-lowir' in args or '-emit-lowir' in args: output.write_text('target wasm32 1\nfunction @observe() -> i32 {\n block ^entry:\n return i32 17\n}\n') else: # A valid core module exporting observe() -> i32, returning 17 - # (19 from rewritten text in the differing mode). - result = '13' if os.environ.get('TEXT_MODE') == 'differ' and any('rewritten' in x for x in args) else '11' + # (19 from rewritten text, or from the optimized text, in the + # differing modes). + mode = os.environ.get('TEXT_MODE') + differs = (mode == 'differ' and any('rewritten' in x for x in args)) or \ + (mode == 'differ-optimized' and '-fno-lowir-passes' in args) + result = '13' if differs else '11' output.write_bytes(bytes.fromhex('0061736d010000000105016000017f03020100070b01076f62736572766500000a06010400' + result + '0b')) elif kind == 'lowiropt': Path(args[args.index('-o') + 1]).write_text(Path(args[-1]).read_text()) @@ -58,7 +62,7 @@ class WasmChecker(unittest.TestCase): - def check(self, expect, mode='ok', text_mode='same'): + def check(self, expect, mode='ok', text_mode='same', optimized_text=False): with tempfile.TemporaryDirectory() as directory: root = Path(directory) for name, body in [('supervisor', SUPERVISOR), ('compiler', TOOL), ('lowiropt', TOOL), @@ -75,6 +79,9 @@ def check(self, expect, mode='ok', text_mode='same'): CPPGM_WASM_TOOLS=str(root / 'validator'), CPPGM_WASMTIME=str(root / 'runtime'), CPPGM_TEST_SUPERVISOR=str(root / 'supervisor'), CHECKER_COMMANDS=str(root / 'commands.jsonl'), TRAP_MODE=mode, TEXT_MODE=text_mode) + env.pop('CPPGM_WASM_OPTIMIZED_TEXT', None) + if optimized_text: + env['CPPGM_WASM_OPTIMIZED_TEXT'] = '1' result = subprocess.run(['perl', str(ROOT / 'scripts/check_wasm.pl'), str(root / 'compiler'), str(fixture)], env=env, cwd=root, capture_output=True, text=True, timeout=30) @@ -110,6 +117,22 @@ def test_an_object_compiled_from_its_lowir_text_must_be_the_direct_one(self): self.assertTrue(any('rewritten' in x for tool, args in commands if tool == 'compiler' for x in args)) + def test_the_solution_lane_compiles_each_object_from_its_optimized_lowir(self): + for expect in ({'source': True, 'levels': [2], 'calls': [{'export': 'observe', 'result': '17'}]}, + {'levels': [0], 'calls': [{'export': 'observe', 'result': '17'}]}): + with self.subTest(source=expect.get('source', False)): + result, commands = self.check(expect, text_mode='differ-optimized') + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertFalse(any('-emit-lowir' in args for tool, args in commands if tool == 'compiler')) + result, commands = self.check(expect, text_mode='differ-optimized', optimized_text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn('optimized LowIR differs from the direct one', result.stderr) + result, commands = self.check(expect, optimized_text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + compiler = [args for tool, args in commands if tool == 'compiler'] + self.assertTrue(any('-S' in args and '-emit-lowir' in args for args in compiler)) + self.assertTrue(any('-fno-lowir-passes' in args for args in compiler)) + def test_assembly_uses_direct_source_and_object_paths_without_lowir(self): result, commands = self.check({'source': True, 'assembly': True, 'levels': [0, 3], From ef670f5c13368b05960aec736ab91f2f9eaef17c Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 00:24:01 +0000 Subject: [PATCH 7/8] Find Intel dispatches by unique runner identity when gh returns no URL --- scripts/run_intel_benchmarks_once.py | 34 +++++++++++++++++++++++++- scripts/tests/test_intel_benchmarks.py | 31 +++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/scripts/run_intel_benchmarks_once.py b/scripts/run_intel_benchmarks_once.py index f57651a057..f22d14c654 100644 --- a/scripts/run_intel_benchmarks_once.py +++ b/scripts/run_intel_benchmarks_once.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Run trusted Intel benchmarks sequentially, with one temporary runner per job.""" import argparse +from datetime import datetime, timezone import hashlib import json import os @@ -12,6 +13,8 @@ import sys import tarfile import tempfile +import time +from urllib.parse import urlencode import urllib.request SUITES = { @@ -51,6 +54,30 @@ def dispatch_command(args, revision, label): return command +def dispatched_run(repo, workflow, label, since, attempts=12): + """Find this runner's job when older gh versions dispatch without a URL.""" + query = urlencode(dict(event='workflow_dispatch', created='>=' + since, per_page=100)) + for attempt in range(attempts): + matches = set() + page = 1 + while True: + runs = github(f'repos/{repo}/actions/workflows/{workflow}/runs?{query}&page={page}')['workflow_runs'] + for run in runs: + jobs = github(f'repos/{repo}/actions/runs/{run["id"]}/jobs?per_page=100')['jobs'] + if any(label in job.get('labels', []) and job.get('runner_name') == label for job in jobs): + matches.add(str(run['id'])) + if len(runs) < 100: + break + page += 1 + if len(matches) > 1: + raise RuntimeError('multiple workflow runs used this supposedly unique runner') + if matches: + return matches.pop() + if attempt + 1 < attempts: + time.sleep(5) + raise RuntimeError('could not identify the dispatched run by its unique runner; check Actions') + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo', default='vishvananda/cppgm') @@ -97,6 +124,7 @@ def main(): print(f'Runner files and logs: {directory}', flush=True) registered = False run_id = None + queued_at = None try: token = github('--method', 'POST', f'repos/{args.repo}/actions/runners/registration-token')['token'] with (directory / 'configure.log').open('wb') as log: @@ -109,6 +137,7 @@ def main(): registered = True if not args.listen: # Queue the job for this runner's unique label, not any other runner. + queued_at = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') output = subprocess.check_output(dispatch_command(args, revision, label), text=True) print(output, end='', flush=True) match = re.search(r'/actions/runs/(\d+)', output) @@ -134,7 +163,10 @@ def main(): raise RuntimeError(f'runner exited {status}; see {directory / "runner.log"}') if not args.listen: if run_id is None: - raise RuntimeError('gh did not return the run URL; check Actions before starting another suite') + run_id = dispatched_run(args.repo, SUITES[args.suite], label, queued_at) + print(f'CI run: https://github.com/{args.repo}/actions/runs/{run_id}', flush=True) + (directory / 'run.json').write_text(json.dumps(dict(run_id=run_id, revision=revision, + workflow_ref=args.ref, runner_label=label), indent=2) + '\n') # A healthy runner process does not imply a successful benchmark. # Wait for validation and badge publication before the next suite. subprocess.run(['gh', 'run', 'watch', run_id, '--repo', args.repo, '--exit-status'], check=True) diff --git a/scripts/tests/test_intel_benchmarks.py b/scripts/tests/test_intel_benchmarks.py index 227eb05415..d697b5fc8f 100644 --- a/scripts/tests/test_intel_benchmarks.py +++ b/scripts/tests/test_intel_benchmarks.py @@ -17,6 +17,37 @@ class IntelBenchmarkTests(unittest.TestCase): + def test_missing_dispatch_url_uses_exact_job_labels_and_runner_identity(self): + label='cppgm-intel-unique' + def api(endpoint): + if '/workflows/' in endpoint: + return {'workflow_runs': [{'id': 11}, {'id': 12}, {'id': 13}]} + if '/11/' in endpoint: + return {'jobs': [{'labels': ['self-hosted', label], 'runner_name': 'someone-else'}]} + if '/12/' in endpoint: + return {'jobs': [{'labels': ['self-hosted', label], 'runner_name': label}]} + return {'jobs': [{'labels': ['self-hosted', 'different'], 'runner_name': label}]} + with patch.object(launcher, 'github', side_effect=api): + self.assertEqual(launcher.dispatched_run('owner/repo','suite.yml',label,'2026-11-16T00:00:00Z'), '12') + + def test_discovery_waits_for_job_visibility_and_rejects_ambiguous_matches(self): + response=[{'workflow_runs': []}, {'workflow_runs': [{'id': 12}]}, + {'jobs': [{'labels': ['unique'], 'runner_name': 'unique'}]}] + with patch.object(launcher, 'github', side_effect=response), patch.object(launcher.time,'sleep') as sleep: + self.assertEqual(launcher.dispatched_run('owner/repo','suite.yml','unique','since',attempts=2),'12') + sleep.assert_called_once_with(5) + response=[{'workflow_runs':[{'id':11},{'id':12}]}, + {'jobs':[{'labels':['unique'],'runner_name':'unique'}]}, + {'jobs':[{'labels':['unique'],'runner_name':'unique'}]}] + with patch.object(launcher,'github',side_effect=response): + with self.assertRaisesRegex(RuntimeError,'multiple workflow runs'): + launcher.dispatched_run('owner/repo','suite.yml','unique','since') + + def test_discovery_never_guesses_the_latest_unrelated_run(self): + with patch.object(launcher,'github',return_value={'workflow_runs':[]}), patch.object(launcher.time,'sleep'): + with self.assertRaisesRegex(RuntimeError,'could not identify'): + launcher.dispatched_run('owner/repo','suite.yml','unique','since',attempts=1) + def test_plan_pins_all_suites_without_registering_or_dispatching(self): with patch.object(sys, 'argv', ['runner', '--plan', '--ref', 'feature', '--revision', 'main']), \ patch.object(launcher, 'github', return_value={'sha': 'a' * 40}) as api, \ From 476eb5361bb17f8d0141dca774addff39ac9ecb5 Mon Sep 17 00:00:00 2001 From: Vishvananda Abrams Date: Mon, 16 Nov 2026 21:25:04 +0000 Subject: [PATCH 8/8] Run and publish the full WASI self-build on dedicated Intel --- .../workflows/intel-library-benchmarks.yml | 7 +++- .github/workflows/wasm.yml | 9 +++- docs/performance/intel-benchmarks.md | 12 +++++- scripts/experimental/wasi_inception.py | 24 ++++++----- scripts/intel_library_benchmarks.py | 22 +++++++++- scripts/run_intel_benchmarks_once.py | 5 ++- scripts/tests/test_intel_benchmarks.py | 34 ++++++++++++++- scripts/tests/test_public_benchmarks.py | 3 +- scripts/tests/test_wasi_inception.py | 42 +++++++++++++++++++ scripts/tests/test_wasm_benchmarks.py | 17 +++++++- scripts/wasm_benchmark_results.py | 3 +- scripts/wasm_selfbuild_benchmarks.py | 8 +++- 12 files changed, 163 insertions(+), 23 deletions(-) diff --git a/.github/workflows/intel-library-benchmarks.yml b/.github/workflows/intel-library-benchmarks.yml index 69d542be72..eea7771314 100644 --- a/.github/workflows/intel-library-benchmarks.yml +++ b/.github/workflows/intel-library-benchmarks.yml @@ -65,14 +65,18 @@ jobs: apt-get install -y --no-install-recommends bzip2 gdb ;; wasm) apt-get install -y --no-install-recommends curl xz-utils perl util-linux ;; + wasm-selfbuild) + apt-get install -y --no-install-recommends curl xz-utils perl nodejs npm ;; index-cpp|simdjson|internal) ;; *) exit 2 ;; esac git config --global --add safe.directory /work/source git config --global --add safe.directory /work/tools make -C dev cppgm -j16 + jobs=16 + if [ "$SUITE" = wasm-selfbuild ]; then jobs=2; fi python3 -u ../tools/scripts/intel_library_benchmarks.py run \ - --suite "$SUITE" --source /work/source --jobs 16 + --suite "$SUITE" --source /work/source --jobs "$jobs" ' - name: Report if: always() @@ -80,6 +84,7 @@ jobs: SUITE: ${{ inputs.suite }} run: | report="source/obj/$SUITE/details.md" + if [ "$SUITE" = wasm-selfbuild ]; then report="source/obj/$SUITE/summary.md"; fi if [ -f "$report" ]; then cat "$report" >> "$GITHUB_STEP_SUMMARY"; fi - name: Collect results and diagnostics if: always() diff --git a/.github/workflows/wasm.yml b/.github/workflows/wasm.yml index 08a8fd4e44..6e4d934191 100644 --- a/.github/workflows/wasm.yml +++ b/.github/workflows/wasm.yml @@ -27,12 +27,17 @@ on: description: Intel runner label supplied by the temporary-runner helper type: string default: cppgm-intel + intel_suite: + description: Dedicated Intel measurement to run + type: choice + options: [wasm, wasm-selfbuild] + default: wasm permissions: contents: read concurrency: - group: wasm-benchmarks-${{ github.ref }}-${{ inputs.platform || 'github' }} + group: wasm-benchmarks-${{ github.ref }}-${{ inputs.platform || 'github' }}-${{ inputs.intel_suite || 'wasm' }} cancel-in-progress: true jobs: @@ -258,6 +263,6 @@ jobs: contents: write uses: ./.github/workflows/intel-library-benchmarks.yml with: - suite: wasm + suite: ${{ inputs.intel_suite || 'wasm' }} revision: ${{ inputs.revision || github.sha }} runner_label: ${{ inputs.runner_label }} diff --git a/docs/performance/intel-benchmarks.md b/docs/performance/intel-benchmarks.md index d06cfd1945..5884903b22 100644 --- a/docs/performance/intel-benchmarks.md +++ b/docs/performance/intel-benchmarks.md @@ -12,11 +12,21 @@ python3 scripts/run_intel_benchmarks_once.py --plan \ Remove `--plan` to start. The suites run sequentially: public programs, self-build/inception timing, index-cpp, simdjson scalar and SSE, Godot, Boost O3, -the internal C++ source subset, and Wasm O0/O3 kernels. Each suite gets a fresh temporary runner and Ubuntu 26.04 container. The +the internal C++ source subset, Wasm O0/O3 kernels, and the complete WASI compiler +self-build. Each suite gets a fresh temporary runner and Ubuntu 26.04 container. The launcher waits for the suite and publication to pass before starting the next; runner logs and measurements remain in the printed directory. Use `--suite NAME` to refresh just one suite. +The WASI self-build is a separate suite (`--suite wasm-selfbuild`); kernel +measurements do not include it. It uses the same two workers, frozen inputs, +byte checks and paired timing blocks as the hosted comparison. Its results +populate the dedicated Intel row under `wasm-selfbuild`. To run it before merging +workflow changes, use `--ref BRANCH --revision COMPILER_COMMIT`; the WASI package, +source lists and recorded revision all come from that compiler checkout. +The launcher also supports older GitHub CLI versions that omit the dispatch URL, +identifying the completed job by its unique runner label and name. + The internal suite pins both archive checksums from before and after the `cppgm-extended` to `cppgm` rename: only the archive's directory prefix changed. It records the hash actually used, verifies every cohort source unit, and diff --git a/scripts/experimental/wasi_inception.py b/scripts/experimental/wasi_inception.py index 60c0e4254c..b0a6b0efb8 100644 --- a/scripts/experimental/wasi_inception.py +++ b/scripts/experimental/wasi_inception.py @@ -71,13 +71,13 @@ def next_word(): return "\n".join(lines) + "\n" -def source_sets(tools): +def source_sets(tools, repo_root=REPO): """Use the compiler's owning source lists, including each tool's entry point.""" makefile = "include dev/frontend_source_sets.mk\nlist:\n" for name in tools: makefile += "\t@printf '%s\\n' '" + name + "' $(FRONTEND_OBJ_BASENAMES_" + name + ") END\n" lines = subprocess.check_output(["make", "-s", "-f", "-", "list"], - input=makefile.encode(), cwd=REPO).decode().splitlines() + input=makefile.encode(), cwd=repo_root).decode().splitlines() result = {} while lines: name = lines.pop(0) @@ -90,17 +90,18 @@ def source_sets(tools): def prepare(args): package = args.directory.resolve() package.mkdir() # Never replace an existing experiment or its observations. + repo_root = getattr(args, 'repo_root', REPO).resolve(strict=True) inputs = package / "inputs" inputs.mkdir() - copy_tree(REPO / "dev/src", inputs / "dev/src") + copy_tree(repo_root / "dev/src", inputs / "dev/src") tools = getattr(args, "reference_tools", ["cppgm"]) for name in tools: - shutil.copyfile(REPO / ("dev/" + name + ".cpp"), inputs / ("dev/" + name + ".cpp")) + shutil.copyfile(repo_root / ("dev/" + name + ".cpp"), inputs / ("dev/" + name + ".cpp")) for name in ['LICENSE', 'NOTICE']: - shutil.copyfile(REPO / name, inputs / name) - shutil.copyfile(HERE / "wasi_host.h", inputs / "wasi_host.h") - shutil.copyfile(HERE / "wasi_stack.S", inputs / "wasi_stack.S") - tool_sources = source_sets(tools) + shutil.copyfile(repo_root / name, inputs / name) + shutil.copyfile(repo_root / "scripts/experimental/wasi_host.h", inputs / "wasi_host.h") + shutil.copyfile(repo_root / "scripts/experimental/wasi_stack.S", inputs / "wasi_stack.S") + tool_sources = source_sets(tools, repo_root) x86_sources = list(tool_sources["cppgm"]) # These are supplied WASI command-host sources, shared by every exported # tool. Native builds keep their owning frontend source sets unchanged. @@ -109,7 +110,7 @@ def prepare(args): sources.insert(-1, "dev/src/support/wasi_heap.cpp") sources.insert(-1, "wasi_stack.S") sources = tool_sources["cppgm"] - config = (REPO / "obj/generated/cppgm_builtin_host_config.h").read_text() + config = (repo_root / "obj/generated/cppgm_builtin_host_config.h").read_text() paths = re.search(r"kStandardIncludePaths\[\] = \{(.*?)\};", config, re.S) if paths is None: raise RuntimeError("generated host configuration has no include path table") @@ -184,9 +185,9 @@ def prepare(args): for p in sorted((package / "shim").rglob("*")) if p.is_file()}, "runner_files": {name: digest((package / name).read_bytes()) for name in runners}, "sdk_version": (args.sdk / "VERSION").read_text(), - "revision": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=REPO).decode().strip(), + "revision": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo_root).decode().strip(), "tool_sources": tool_sources, - "dirty": bool(subprocess.check_output(["git", "status", "--porcelain"], cwd=REPO)), + "dirty": bool(subprocess.check_output(["git", "status", "--porcelain"], cwd=repo_root)), "source_sha256": digest(json.dumps([(f['path'], f['sha256']) for f in files if f['path'].startswith('dev/')]).encode())} save(package / "manifest.json", manifest) @@ -344,6 +345,7 @@ def main(): commands = parser.add_subparsers(dest="command", required=True) pack = commands.add_parser("prepare") pack.add_argument("--directory", required=True, type=Path) + pack.add_argument("--repo-root", type=Path, default=REPO) pack.add_argument("--sdk", required=True, type=Path) pack.add_argument("--compiler", type=Path, default=REPO / "dev/cppgm") pack.add_argument("--shim", required=True, type=Path) diff --git a/scripts/intel_library_benchmarks.py b/scripts/intel_library_benchmarks.py index 0c4b352aad..98af78c13a 100644 --- a/scripts/intel_library_benchmarks.py +++ b/scripts/intel_library_benchmarks.py @@ -15,11 +15,18 @@ 'boost': 'boost_benchmarks.py', 'internal': 'internal_cpp_benchmarks.py', 'wasm': 'wasm_benchmarks.pl', + 'wasm-selfbuild': 'wasm_selfbuild_benchmarks.py', } DIRECTORY = Path(__file__).resolve().parent def run_command(suite, source, jobs): + if suite == 'wasm-selfbuild': + return [sys.executable, str(DIRECTORY / SCRIPTS[suite]), + '--compiler', str(source / 'dev/cppgm'), '--repo-root', str(source), + '--output', str(source / 'obj' / suite), '--tools', str(source / 'obj/wasm-tools'), + '--shim', str(DIRECTORY / 'experimental/node_modules/@bjorn3/browser_wasi_shim'), + '--jobs', str(jobs)] if suite == 'wasm': return ['perl', str(DIRECTORY / SCRIPTS[suite]), '--compiler', str(source / 'dev/cppgm'), '--repo-root', str(source), '--output', str(source / 'obj' / suite)] @@ -31,6 +38,13 @@ def run_command(suite, source, jobs): def run(args): command = run_command(args.suite, args.source.resolve(strict=True), args.jobs) + if args.suite == 'wasm-selfbuild': + subprocess.run(['perl', str(DIRECTORY / 'install_wasm_tools.pl'), '--prefix', + str(args.source / 'obj/wasm-tools')], check=True) + subprocess.run(['npm', 'ci', '--ignore-scripts', '--prefix', + str(DIRECTORY / 'experimental')], check=True) + subprocess.run(command, check=True) + return if args.suite == 'wasm': tools = args.source / 'obj/wasm-tools' subprocess.run(['perl', str(DIRECTORY / 'install_wasm_tools.pl'), '--prefix', str(tools), @@ -61,7 +75,8 @@ def collect(source, target): for path in source.rglob('*'): relative = path.relative_to(source) if ({'build', 'source'}.intersection(relative.parts) or not path.is_file() - or not (path.suffix in suffixes or path.suffix == '.stdin' or path.name in ('stdout', 'stderr') + or (relative.parts[:2] == ('package', 'inputs') and path.suffix != '.log') + or not (path.suffix in suffixes or path.suffix == '.stdin' or path.name in ('stdout', 'stderr', 'manifest.sha256') or path.name.endswith('probe'))): continue destination = target / relative @@ -93,6 +108,11 @@ def main(): elif args.command == 'collect': collect(args.source, args.target) else: + if args.suite == 'wasm-selfbuild': + subprocess.run([sys.executable, str(DIRECTORY / 'wasm_benchmark_results.py'), 'publish-selfbuild', + str(args.artifact), '--target', str(args.target), '--revision', args.revision, + '--run-url', args.run_url, '--platform', 'intel'], check=True) + return if args.suite == 'wasm': subprocess.run([sys.executable, str(DIRECTORY / 'wasm_benchmark_results.py'), 'publish', str(args.artifact / 'O0'), str(args.artifact / 'O3'), '--target', str(args.target), diff --git a/scripts/run_intel_benchmarks_once.py b/scripts/run_intel_benchmarks_once.py index f22d14c654..d033f9df02 100644 --- a/scripts/run_intel_benchmarks_once.py +++ b/scripts/run_intel_benchmarks_once.py @@ -26,6 +26,7 @@ 'boost': 'boost.yml', 'internal': 'internal-cpp.yml', 'wasm': 'wasm.yml', + 'wasm-selfbuild': 'wasm.yml', } @@ -51,6 +52,8 @@ def dispatch_command(args, revision, label): '-f', f'runner_label={label}'] if args.course_quality and args.suite == 'public': command += ['-f', 'course_quality=true'] + if args.suite == 'wasm-selfbuild': + command += ['-f', 'intel_suite=wasm-selfbuild'] return command @@ -87,7 +90,7 @@ def main(): parser.add_argument('--listen', action='store_true', help='accept one manually queued job instead of dispatching') parser.add_argument('--course-quality', action='store_true', help='also measure the optional course exercises') parser.add_argument('--suite', choices=['all', *SUITES], default='all', - help='run all seven suites sequentially (default), or just one') + help='run all suites sequentially (default), or just one') parser.add_argument('--plan', action='store_true', help='show the pinned campaign without registering runners or starting jobs') args = parser.parse_args() revision = github(f'repos/{args.repo}/commits/{args.revision}')['sha'] diff --git a/scripts/tests/test_intel_benchmarks.py b/scripts/tests/test_intel_benchmarks.py index d697b5fc8f..076b1bf6ac 100644 --- a/scripts/tests/test_intel_benchmarks.py +++ b/scripts/tests/test_intel_benchmarks.py @@ -7,6 +7,7 @@ import subprocess import sys import tempfile +from types import SimpleNamespace import unittest from unittest.mock import patch @@ -68,9 +69,38 @@ def test_library_commands_measure_source_instead_of_workflow_checkout(self): self.assertEqual(command[command.index('--repo-root') + 1], str(source)) self.assertEqual(command[command.index('--compiler') + 1], str(source / 'dev/cppgm')) self.assertEqual(command[command.index('--output') + 1], str(source / 'obj' / suite)) - self.assertEqual('--jobs' in command, suite in ('godot', 'boost', 'internal')) + self.assertEqual('--jobs' in command, suite in ('godot', 'boost', 'internal', 'wasm-selfbuild')) self.assertEqual(Path(command[1]).name, library.SCRIPTS[suite]) + def test_wasi_selfbuild_dispatch_selects_only_its_suite(self): + args = SimpleNamespace(suite='wasm-selfbuild', repo='owner/repo', ref='tooling', course_quality=False) + command = launcher.dispatch_command(args, 'a' * 40, 'unique') + self.assertEqual(command[3], 'wasm.yml') + self.assertIn('intel_suite=wasm-selfbuild', command) + self.assertIn('revision=' + 'a' * 40, command) + self.assertIn('runner_label=unique', command) + args.suite = 'wasm' + self.assertNotIn('intel_suite=wasm-selfbuild', launcher.dispatch_command(args, 'a' * 40, 'unique')) + + def test_wasi_selfbuild_installs_pinned_tools_and_routes_publication(self): + with tempfile.TemporaryDirectory() as temporary: + source = Path(temporary) + args = SimpleNamespace(suite='wasm-selfbuild', source=source, jobs=2) + with patch.object(library.subprocess, 'run') as run: + library.run(args) + calls = [call.args[0] for call in run.call_args_list] + self.assertEqual(len(calls), 3) + self.assertEqual(calls[0][-2:], ['--prefix', str(source / 'obj/wasm-tools')]) + self.assertEqual(calls[1][:3], ['npm', 'ci', '--ignore-scripts']) + self.assertEqual(calls[2], library.run_command('wasm-selfbuild', source, 2)) + with patch.object(sys, 'argv', ['adapter', 'publish', '--suite', 'wasm-selfbuild', + '--artifact', 'artifact', '--target', 'badges', '--revision', 'a' * 40, + '--run-url', 'https://example.org/run']), patch.object(library.subprocess, 'run') as run: + library.main() + command = run.call_args.args[0] + self.assertEqual(command[2:4], ['publish-selfbuild', 'artifact']) + self.assertEqual(command[-2:], ['--platform', 'intel']) + def test_source_metadata_reads_the_selected_clean_checkout(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) @@ -97,10 +127,12 @@ def test_collection_retains_nested_observations_without_build_trees(self): root = Path(temporary) source, target = root / 'run', root / 'artifact' keep = ['results.json', 'compile.stdout', 'compile.stderr', 'counter-probe', + 'package/manifest.json', 'package/manifest.sha256', 'package/inputs/AB-0-0/a.log', 'raw/requests.stdin', 'runtime/observations.jsonl', 'runtime/000/stdout', 'runtime/000/stderr', 'cppgm/libs-json-test/invocations.jsonl', 'cppgm/libs-json-test/b2.log'] discard = ['compiler', 'output.o', 'source/input.json', 'source/tests/result.stdout', + 'package/inputs/dev/header.hpp', 'package/inputs/sysroot/large.json', 'cppgm/build/large.json', 'binary'] for name in keep + discard: path = source / name diff --git a/scripts/tests/test_public_benchmarks.py b/scripts/tests/test_public_benchmarks.py index 067a4c322a..45591ea808 100644 --- a/scripts/tests/test_public_benchmarks.py +++ b/scripts/tests/test_public_benchmarks.py @@ -815,7 +815,8 @@ def run(command, check): with mock.patch.object(intel_runner.subprocess, 'run', side_effect=run): intel_runner.run_suites(args, 'a' * 40, Path('/tmp/runners')) - self.assertEqual(calls, ['public', 'self-build', 'index-cpp', 'simdjson', 'godot', 'boost', 'internal', 'wasm']) + self.assertEqual(calls, ['public', 'self-build', 'index-cpp', 'simdjson', 'godot', 'boost', 'internal', + 'wasm', 'wasm-selfbuild']) def test_suites_dispatch_distinct_workflows(self): args = SimpleNamespace(repo='owner/repo', ref='main', course_quality=True, suite='public') diff --git a/scripts/tests/test_wasi_inception.py b/scripts/tests/test_wasi_inception.py index 92aba3615d..ebe611d3cb 100644 --- a/scripts/tests/test_wasi_inception.py +++ b/scripts/tests/test_wasi_inception.py @@ -3,6 +3,7 @@ import json from pathlib import Path import tempfile +import subprocess import sys from types import SimpleNamespace import unittest @@ -23,6 +24,47 @@ def module(name): class WasiInception(unittest.TestCase): + def test_freeze_uses_selected_checkout_for_sources_lists_and_revision(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source, sdk, shim = root / 'source', root / 'sdk', root / 'shim' + files = { + 'source/dev/frontend_source_sets.mk': 'FRONTEND_OBJ_BASENAMES_cppgm = selected\n', + 'source/dev/src/selected.cpp': 'selected source', + 'source/dev/cppgm.cpp': 'selected entry point', + 'source/LICENSE': 'license', 'source/NOTICE': 'notice', + 'source/scripts/experimental/wasi_host.h': 'selected host', + 'source/scripts/experimental/wasi_stack.S': 'selected stack', + 'source/obj/generated/cppgm_builtin_host_config.h': 'kStandardIncludePaths[] = {nullptr};', + 'source/.gitignore': 'obj/\n', 'compiler': 'binary', + 'shim/dist/index.js': 'shim', + 'shim/package.json': '{"name":"@bjorn3/browser_wasi_shim","version":"0.4.2"}', + 'sdk/VERSION': 'pinned SDK', + 'sdk/lib/clang/23/lib/wasm32-unknown-wasip1/libclang_rt.builtins.a': 'archive', + } + for name in ('crt1-command.o', 'libc.a', 'libc-printscan-long-double.a', + 'eh/libc++.a', 'eh/libc++abi.a', 'eh/libunwind.a'): + files['sdk/share/wasi-sysroot/lib/wasm32-wasip1/' + name] = 'archive' + for name, contents in files.items(): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(contents) + subprocess.run(['git', 'init', '-q', str(source)], check=True) + subprocess.run(['git', '-C', str(source), 'add', '.'], check=True) + subprocess.run(['git', '-C', str(source), '-c', 'user.name=Test', '-c', 'user.email=test@example.org', + 'commit', '-qm', 'selected sources'], check=True) + expected = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip() + package = root / 'package' + frozen.prepare(SimpleNamespace(directory=package, repo_root=source, sdk=sdk, + compiler=root / 'compiler', shim=shim, x86_headers=False, optimization=3)) + manifest = json.loads((package / 'manifest.json').read_text()) + self.assertEqual(manifest['revision'], expected) + self.assertFalse(manifest['dirty']) + self.assertEqual(manifest['x86_sources'][:-1], ['dev/src/selected.cpp', 'dev/cppgm.cpp']) + self.assertEqual((package / 'inputs/dev/src/selected.cpp').read_text(), 'selected source') + self.assertEqual((package / 'inputs/wasi_host.h').read_text(), 'selected host') + frozen.verify(package, manifest) + def test_lane_requires_all_fixed_points_and_x86_levels(self): args = lane.arguments([]) phases = lane.plan(args, Path('/new-package')) diff --git a/scripts/tests/test_wasm_benchmarks.py b/scripts/tests/test_wasm_benchmarks.py index 1a8dde4b29..f3b2fcf50e 100644 --- a/scripts/tests/test_wasm_benchmarks.py +++ b/scripts/tests/test_wasm_benchmarks.py @@ -151,7 +151,7 @@ def row(name, cpu): (artifact / 'observations.json').write_text(json.dumps([row('cppgm-producer', 10.), row('clang-producer', 75.)])) args = argparse.Namespace(artifact=artifact, target=target, revision='a' * 40, - run_url='https://example.org/run') + run_url='https://example.org/run', platform='github') producer.publish_selfbuild(args) directory = target / producer.SELFBUILD self.assertIn('7.50', (directory / 'epyc-compile-clang.svg').read_text()) @@ -161,6 +161,21 @@ def row(name, cpu): self.assertNotIn('commands', published['producers']['cppgm-producer']) self.assertIn('[Results](epyc/report.md)', (directory / 'report.md').read_text()) benchmark_publication.prepare(target) + args.platform = 'intel' + with self.assertRaisesRegex(ValueError, 'Intel hardware'): + producer.publish_selfbuild(args) + metadata['cpu'] = 'Intel Xeon Platinum 8581C' + (artifact / 'results.json').write_text(json.dumps(dict(schema=1, status='complete', metadata=metadata, + phases=phases, warnings=[]))) + producer.publish_selfbuild(args) + self.assertIn('7.50', (directory / 'intel-compile-clang.svg').read_text()) + self.assertIn('0.90', (directory / 'intel-runtime-clang.svg').read_text()) + self.assertIn('7.50', (directory / 'epyc-compile-clang.svg').read_text()) + self.assertIn('n/m', (directory / 'github-intel-runtime-clang.svg').read_text()) + self.assertTrue((directory / 'history' / ('a' * 40) / 'intel/results.json').exists()) + args.platform = 'github' + producer.publish_selfbuild(args) + self.assertIn('0.90', (directory / 'github-intel-runtime-clang.svg').read_text()) args.revision = 'b' * 40 with self.assertRaisesRegex(ValueError, 'clean measured'): producer.publish_selfbuild(args) diff --git a/scripts/wasm_benchmark_results.py b/scripts/wasm_benchmark_results.py index 9e8e688b49..0051d686ff 100644 --- a/scripts/wasm_benchmark_results.py +++ b/scripts/wasm_benchmark_results.py @@ -242,7 +242,7 @@ def publish_selfbuild(args): metadata = document['metadata'] if metadata['dirty'] or metadata['revision'] != args.revision: raise ValueError('publication requires the clean measured compiler revision') - platform = benchmark_hosts.publication_platform(metadata['cpu'], 'github') + platform = benchmark_hosts.publication_platform(metadata['cpu'], args.platform) directory = args.target / SELFBUILD for destination in (directory / platform, directory / 'history' / args.revision / platform): destination.mkdir(parents=True, exist_ok=True) @@ -303,6 +303,7 @@ def main(): selfbuild.add_argument('--target', type=Path, required=True) selfbuild.add_argument('--revision', required=True) selfbuild.add_argument('--run-url', required=True) + selfbuild.add_argument('--platform', choices=['github', 'intel'], default='github') for command in ('report', 'publish'): sub = commands.add_parser(command) sub.add_argument('artifacts', type=Path, nargs='+') diff --git a/scripts/wasm_selfbuild_benchmarks.py b/scripts/wasm_selfbuild_benchmarks.py index 547a3de1a2..7fd7d92593 100644 --- a/scripts/wasm_selfbuild_benchmarks.py +++ b/scripts/wasm_selfbuild_benchmarks.py @@ -138,6 +138,7 @@ def run(args): args.output = args.output.resolve() args.tools = args.tools.resolve() args.compiler = args.compiler.resolve() + args.repo_root = args.repo_root.resolve(strict=True) if hasattr(os, 'sched_getaffinity'): cpus = sorted(os.sched_getaffinity(0))[:args.jobs] os.sched_setaffinity(0, cpus) @@ -145,7 +146,8 @@ def run(args): cpus = [] package = args.output / 'package' inception.prepare(argparse.Namespace(directory=package, sdk=args.tools / 'wasi-sdk', - compiler=args.compiler, shim=args.shim.resolve(), x86_headers=False, optimization=3)) + compiler=args.compiler, shim=args.shim.resolve(), x86_headers=False, optimization=3, + repo_root=args.repo_root)) manifest = json.loads((package / 'manifest.json').read_text()) inception.verify(package, manifest) campaign = Campaign(args, package, manifest) @@ -180,7 +182,8 @@ def run(args): 'link_seconds', 'link_cpu_seconds']} inception.verify(package, manifest) metadata = dict(revision=manifest['revision'], - dirty=bool(subprocess.check_output(['git', 'status', '--porcelain'], cwd=ROOT)), + dirty=manifest['dirty'] or bool(subprocess.check_output( + ['git', 'status', '--porcelain'], cwd=args.repo_root)), sources=len(manifest['sources']), cpu=public_benchmarks.cpu_model(), affinity=cpus, jobs=args.jobs, manifest_sha256=digest(package / 'manifest.json'), candidate_sha256=digest(candidate), reference_sha256=digest(reference), @@ -212,6 +215,7 @@ def run(args): def arguments(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--repo-root', type=Path, default=ROOT, help='compiler source checkout to freeze') parser.add_argument('--tools', type=Path, default=ROOT / 'obj/wasm-tools') parser.add_argument('--compiler', type=Path, default=ROOT / 'dev/cppgm') parser.add_argument('--shim', type=Path, default=ROOT / 'scripts/experimental/node_modules/@bjorn3/browser_wasi_shim')