104 Commits
m5 .. m9
Author SHA1 Message Date
arti 55a0991529 m9: add the Phase 1 tms-cc driver and tms-run 2026-11-17 07:59:44 +00:00
arti d91785457f docs: m9 is the repository default branch 2026-11-17 07:44:09 +00:00
arti 4a9636690f m9: finish the final-review documentation cleanup 2026-11-17 07:42:31 +00:00
arti 95b55dec97 m9: correct the final-review documentation 2026-11-17 07:40:36 +00:00
arti 739e48d8dd M9.4: document the final M9 state and full gate sweep
Record the two-tier counts, 22 flips, four-phase divide evidence, DWARF v5/rnglists gate and the M9/M10 boundary. The Generic sweep now classifies target asm-parser 'invalid instruction mnemonic' errors as unsupported for two x86-asm tests exposed by the inline-asm r support.
2026-11-17 07:26:49 +00:00
arti 24eca1c080 m9: record the fresh two-tier full-suite counts 2026-11-17 05:18:34 +00:00
arti b2dd323e71 m9: gate padded vector zero bytes and the inline-asm memory diagnostic 2026-11-17 04:21:54 +00:00
arti 8711dee37b m9: run the i64div perf gate through the native linker 2026-11-17 04:02:46 +00:00
arti 8b6eed2510 m9: gate vector .data bytes and record inline-asm r flips 2026-11-17 03:59:10 +00:00
arti b005cd13c4 m9: correct the run_wide bounds comment and self-check list 2026-11-17 03:40:22 +00:00
arti 30f0dd688e m9: fix task 3 review findings in the i64div perf gate
Force the wide phase's signed magnitudes to stay at or above 2^32 by capping
the dividend high word with 0x80000000|(lcg & 0x7FFEFFFF) (hi(|a|) is then
0xFFFFFFFF-hi(a) in [0x10000, 0x1FFFF] >= every divisor), so all four forms
take the M8.3 two-DIVU helper; re-pin wide to 0xF56810CFEDA9D656 (the model
shows zero deviating iterations).  Add INT64_MIN magnitude cases for the
single-DIVU divisor 0xFFFFFFFF (unsigned and signed) and a negative
32-bit-magnitude divisor (2^32/-3) to the self-check, and fix the stale
'two workloads'/'both paths' gate text.
2026-11-17 03:35:37 +00:00
arti 9700b5c44f m9: close the pre-v5 and address DWARF gate gaps
Review fix round 1 for the Task 2 DWARF input gate:
- refuse pre-DWARF5 .debug_info/.debug_line in multi-object --keep-debug
  links: their DW_AT_stmt_list is a raw DW_FORM_data4/8, which the merge
  cannot rehome (I1).
- require relocations on DW_FORM_addr (DW_AT_low_pc etc.) and document
  that DW_LNE_set_address / DW_OP_addr inside expressions are not
  decoded (I2).
- require whole 4-byte relocation coverage for 8-byte fields; drop
  supplementary/alternate-file forms from the required set and explain
  why; use the line header's address size; add a need(4) unit helper
  for the standalone walkers.
- add per-walker negatives (line/rnglists/addr/str_offsets) plus an
  unrelocated DW_FORM_addr and a pre-v5 CU; distinguish a producer that
  emits no rnglists (skip) from an unreadable object (fail).
- fix the fixture docstring (--tag AB, current emission behaviour).
2026-11-17 03:34:38 +00:00
arti 8f28483868 m9: form-aware DWARF input gate and .debug_rnglists coverage
Walk .debug_info DIEs through .debug_abbrev, the DWARF v5 line-table
directory/file formats, and the .debug_rnglists/.debug_loclists entries,
and require an R-RELLONG relocation on every section-relative form and
list/address/string-offset entry.  A raw field now fails loudly instead
of being silently mis-merged; the raw CU debug_abbrev_offset is still
patched as before.

Add scripts/tests/m9/dwarf-ranges.sh: a synthetic two-TU .debug_rnglists
fixture (start_end + startx_length, offset rehoming, addr table) plus a
real -O2 -g producer case, validated through the M7 ELF wrapper with
llvm-dwarfdump.  Single-TU bytes keep the M8 layout and the default
strip is unchanged.  Add an unrelocated DW_AT_stmt_list negative to the
tms-link unit gate.
2026-11-17 03:27:15 +00:00
arti 4d2c2dce5c m9: measure the 64/32 single-DIVU divide phase
Adds a fourth equal-iteration phase to the i64div perf driver that forces
hi(N) < D (dividend high word 1..0x10000, divisor >= 0x10001), so every
division takes the new single even-destination DIVU path, and tightens the
M8.3 wide phase to hi(N) >= D so it still measures the two-DIVU helper.
New markers 11/12/13 carry the phase flag and checksum; the Lua gate polls
the phase and requires it to be measurable and materially faster than the
wide phase (1.25x), with the pinned host checksums
fast=0x000000011E6F9AB4 slow=0x00000000007512AE
wide=0xF404E965A20F6984 div32=0x00002C61C63842EE.  The self-check adds
0x1_00000000/3, 0x1_FFFFFFFF/0x10000 and -2^32/3.  The compile-only preflight
now requires the i64div.div32 block; the map check covers 16 marker cells.
2026-11-17 03:27:09 +00:00
arti dd8c5ea3ce docs: M9 scope and plan 2026-11-17 03:15:02 +00:00
arti f340d74472 m8: default the full-loader exceptions to 2ine 2026-11-17 03:14:19 +00:00
arti 2a2efd61d7 m8: two-tier conformance harness (bare by default, loader exceptions) 2026-11-16 18:13:17 +00:00
arti 66d21ebc35 m8: add the 2ine OS/2 harness path and direct-loader default 2026-11-16 16:44:38 +00:00
arti 1315df5548 docs: m8 is the repository default branch 2026-11-16 15:59:53 +00:00
arti af0c5cb617 docs: tick the M8 plan 2026-11-16 12:18:22 +00:00
arti bb78a97313 M8.4: document the final M8 state and full gate sweep 2026-11-16 12:18:04 +00:00
arti e55287f218 M8.3: harden conformance evidence and mixed-provenance report 2026-11-16 06:57:35 +00:00
arti f9b51667c4 M8.3: extend conformance codegen classes and measure the i64 64/32 divide path 2026-11-16 06:30:37 +00:00
arti 5214938b6b tms-link: merge DWARF debug info from multiple translation units 2026-11-16 03:56:43 +00:00
arti dc7de6f3a7 tms-link: address M8 Task 1 review findings
Key archive member labels/placements by member offset so two same-named members cannot overwrite each other; add a dupnamed fixture asserting distinct address ranges. Treat an empty / index as absent, require ASCII decimal sizes, validate odd-member padding and final bounds, and dedupe index entries by member offset. Document the -l/archive ordering and the unit gate's FLIB_LIB/M4_SDK prerequisite (the real-LIB case is skipped with a reason when absent).

Accept the 1990 tools' metadata section bits (0x100/0x400) on allocated sections, which the M6 flib/rts members use, while still writing classic output flags.

Add M6_LINKER=tms-link to runtime.sh and i64.sh: after GSPA, link the same M6.OBJ + flib.lib/rts.lib with tms-link, compare allocated bytes/symbols to the GSPLNK oracle, and run the same MAME marker checks. M8 native-lib now compares tms-link's raw pre-coff-check image.

Add loud-path fixtures for index lies, BSD names, duplicate / and // tables, bad/missing padding, non-ASCII sizes and -l resolution failure; strengthen the no-index exclusion test; add 1990-flag and M5_NATIVE_LINKER docs.
2026-11-16 03:23:49 +00:00
arti 29c30ddcc6 tms-link: read ar archives and extract members selectively
Implement M8.1 native .lib linking: System V !<arch> parsing (/ symbol index, // long-name table, /N references, even-byte padding, loud malformed/truncated errors), in-memory member objects labelled lib(member), and extraction in the archive's own symbol-table order driven by currently undefined globals, iterated to a fixpoint without re-extracting a member. Duplicate definitions and unresolved references fail with object/member names.

Accept archive paths and -l/-lL in the CLI, preserve layout/map/debug behavior, and let scripts/m4/run.sh pass M4_NATIVE_LIBS/M4_NATIVE_RTS archives to tms-link. Relocation addends are now applied as signed 32-bit values (needed by the termtris rts.lib link).

Tests: tms-link archive fixtures and real flib extraction, m7 archive/-l parity, m5 native termtris with tms-link+rts.lib (dis34 match), m6 i64/runtime GSPLNK gates, and scripts/tests/m8/native-lib.sh (FLIB.LIB + RTS.LIB, MAME markers, GSPLNK byte/symbol parity).
2026-11-16 02:56:44 +00:00
arti dc94931eca docs: M8 scope and plan 2026-11-16 02:31:16 +00:00
arti 0f7353c21c docs: point the status line at the M7.4 code heads 2026-11-16 02:23:35 +00:00
arti 2157c24ef8 docs: m7 is the repository default branch 2026-11-16 02:23:23 +00:00
arti 1eaabaa6a0 M7.4: align the remaining COFF-repair comments 2026-11-15 15:56:00 +00:00
arti f471ab8c11 M7.4: soften the COFF-repair mechanism wording 2026-11-15 15:54:09 +00:00
arti 2835990a00 M7.4: make the COFF guard fail and correct the suite attribution 2026-11-15 15:46:35 +00:00
arti 3c024b93b9 docs: tick the M7.4 plan 2026-11-15 15:38:02 +00:00
arti 6e7d5bbe92 M7.4: document the final conformance/performance state
Record the full-suite method, settings, pins and exact counts
(c-torture 1692 = 1366/326/0/0; c-testsuite 220 = 210/10/0/0; all
1912 = 1576/336/0/0), the curated skip classes, the 112 honest pass
flips, the i64 DIVU fast path and its MAME frame measurement, the
conformance-loader COFF repair, and the shipped-tier counts.

Mark M7 complete, keep the M7.1/M7.2/M7.3 counts and limitations
(one debug TU, .lib not readable by tms-link, kept-debug not
loadable, hardware DEFERRED), and state the M7/M8 boundary. Add the
M7.1-M7.4 plan links and the M7.4 gate commands, and distinguish the
curated 48/172 c-testsuite tier from the full-corpus 210/10 result.
2026-11-15 15:37:19 +00:00
arti f8651fcb2f M7.4: triage and curate the full conformance suite 2026-11-15 13:39:28 +00:00
arti 65e6a6e6b8 M7.4: add the full-suite conformance driver and baseline 2026-11-15 08:34:25 +00:00
arti 1e3977132d M7.4: fix the i64div perf gate link, layout and result checks
The M4 default link command's 4 KiB prog region cannot hold the perf
driver's ~8.7 KiB .text, and the old markers at 018A8000 were inside that
.text.  Add a gate-local link command (prog = 40000h) and move the eight
markers to 01A20000, free RAM above the 4 KiB entry stack and inside the
declared ram region.

i64div-map-check.py parses both GSPLNK and tms-link maps and fails if the
marker cells overlap .text/.data/.bss, leave the region, or if a section
leaves its region.  The gate runs it on a host tms-link map and on the
GSPA/GSPLNK map from a link-only pass before MAME, with compile-only and
link-only stop modes for the no-DOSBox checks.

Require the exact deterministic phase checksums (fast 00000001:1E6F9AB4,
slow 00000000:007512AE, hosted and independently recomputed), and extend
the in-image self-check with large-magnitude fast cases: 0xFFFFFFFF/7,
-123/7 (-123 % 7 = -4) and INT32_MIN/3, so a wrong 32-bit quotient or
remainder fails before timing.  The gate documents that -O2 is an
optimizer baseline, not the i64 fast-path measurement.
2026-11-15 08:02:54 +00:00
arti e540db3ca9 M7.4: measure the i64 divide fast path in MAME frames
i64div.sh runs two equal-iteration i64 division workloads on the emulated
part: small operands whose high words are zero (the 32-bit DIVU fast path)
and operands with nonzero high words (the 64-step restoring loop).  The
driver's self-check first proves both paths produce the known M6 values;
the checksums are retained as evidence.

i64div-perf-check.lua polls the start and per-phase completion markers
once per MAME frame and requires the fast phase to complete in materially
fewer frames (slow_frames >= 8 * max(fast_frames,1), slow_frames >= 20).
A frame is a fixed emulated-cycle count, so the comparison is
reproducible.  The gate widens the loader budget to 200..4000 frames for
the slow phase; the M7 full-suite settings are untouched.

The script also has a compile-only preflight (tms-clang + llc, no
DOSBox/MAME) that checks the driver asm for the fast blocks, DIVU and the
slow loop.
2026-11-15 07:48:52 +00:00
arti 5f35a75a0a docs: M7.4 scope and plan 2026-11-15 07:34:12 +00:00
arti 54608c0e32 M7.3: keep hardware evidence and document the bootstrap knobs 2026-11-15 07:26:23 +00:00
arti 11693186bc docs: state the M7.3 gate-change scope precisely 2026-11-15 07:26:15 +00:00
arti ff4cf94176 docs: correct the M7.3 symbol table and evidence claims 2026-11-15 07:26:06 +00:00
arti c756b568ae docs: tick the M7.3 plan 2026-11-15 07:18:02 +00:00
arti 7d07fb787b M7.3: document the runtime/hardware state and rebase the JR fixture 2026-11-15 07:17:33 +00:00
arti 98561252ad M7.3: correct the hardware entry and unit assumptions 2026-11-15 05:16:55 +00:00
arti fe78805872 M7.3: add the real-hardware marker gate with MAME acceptance 2026-11-15 05:09:53 +00:00
arti cdf137f64b M7.3: do not write a byte for fputc(EOF) 2026-11-15 04:55:49 +00:00
arti 38fdeb2e28 M7.3: fix the stderr layout and empty-stream contract 2026-11-15 04:52:25 +00:00
arti 5757f056b0 M7.3: capture stderr as a second conformance stream 2026-11-15 03:55:01 +00:00
arti 9586ed21d1 M7.3: correct the xmore marker comments 2026-11-15 02:23:27 +00:00
arti a6379b206b M7.3: make the xmore flags honest (review round 2)
The ROM builders do not set A8, so markers 4 and 10 are no longer
presented as return values:

- property_called=1 and attrs_called=1 are plain post-call flags.  The
  gate requires the flag, states that the property has no server read-back
  (zero X errors is the only runtime check), and keeps the black margin
  as the real CWBackPixel proof.  Marker 14 pins the 160x120 fill
  geometry (0xA00078) so the margin sample cannot become vacuous.
- InternAtom wording: the display marker only proves the connection was
  live before the call; stage 14 cannot distinguish the intended _XSend
  block from a crash/wrong import.  The isolated probe is narrative entry
  evidence, not a gate check.
- XSetWindowAttributes attrs = {0}; replaces the unsigned int * zeroing
  loop.
- Fix the stale image_roundtrip stage-11 comment (text pixels now set
  stage 12).
- GC wording is 'source call sites; runtime entry not proven', not
  'proves call presence'.
2026-11-15 02:21:08 +00:00
arti 5716e3ca35 M7.3: strengthen the xmore gate evidence (review round 1)
Make the wider-Xlib evidence non-vacuous:

- Child starts with background 1; CWBackPixel=0 and a 160x120 fill leave a
  black margin sampled at screen (300,240).  XChangeWindowAttributes now
  returns a marker (10) and the margin is required; the attrs=1 negative
  control turns it white and fails the gate.
- Marker 4 is the XChangeProperty return (nonzero, not a read-back).
  Marker 11 counts the two explicit XChangeGC calls (presence + no X error;
  the ROM entry is a 2-arg cache flush).  XDrawString is proven by counting
  the set pixels of an XGetImage band (marker 12, 67 in the run).
- Marker 13 stores the live Display just before XInternAtom, so the skip
  cannot be a crash/wrong import; the gate/report state that entry is
  evidenced by the isolated probe.
- Zero the XSetWindowAttributes struct.
- Pin the six wider addresses as constants in validate-syms.sh.
- Print parent(...) instead of win(...) (parent-relative, not child).
- Correct the report's configure/p_img justification and add Fix round 1.
- scripts/m4/run.sh prints M7 MAME: PASS for an M7 marker line; M4 output
  is unchanged.
2026-11-15 02:00:32 +00:00
arti 0cab36a2b0 M7.3: wider VT1200 Xlib surface (xmore)
Add and validate XMapSubwindows, XChangeWindowAttributes,
XConfigureWindow, XInternAtom, XChangeProperty and XChangeGC from the
GUI_APPS table, extend x11m4.h with the X11R4 masks/structs and the ROM
call shapes, and add the xmore client plus its MAME gate.

xmore exercises a parent/child window, XMapSubwindows, the fixed-mask
move/resize ConfigureWindow, WM_NAME (predefined atom 39), CWBackPixel,
XChangeGC, XLoadFont/XDrawString, XFillRectangle, and a heap
XCreateImage/XPutImage/XGetImage/XPutImage/XDestroyImage round trip with
XSync.  Markers at 018A8000+n*20 show stage 14, image 0x13F and 0 errors.

XInternAtom is kept as the last call with an explicit 0xFFFFFFFF skip
marker: the ROM _XSend scatter path (0x3F9B44C0) that carries the name
does not complete in the loader harness (the same direct-send limit the
M4 xshow client records).  If it returns, the client uses the atom and
advances to stage 15.  The GC uses the server default font because the
ROM XLoadFont handle is rejected as GCFont (BadFont); XLoadFont itself is
still exercised and marked.

The M4 runner now accepts M4/M7 marker and PASS lines; M4 behavior is
unchanged.
2026-11-15 01:33:41 +00:00
arti e7f8252470 docs: M7.3 scope and plan 2026-11-15 00:31:17 +00:00
arti 3dccc4d188 docs: scope the M7.2 oracle acceptance to the tested M5 objects 2026-11-15 00:24:27 +00:00
arti e35cb154ce docs: tick the M7.2 plan 2026-11-15 00:16:54 +00:00
arti 8b0b0bcd11 m7.2: document the TI-COFF debug writer and tms-link 2026-11-15 00:14:09 +00:00
arti fefb1daba4 m7.2: prove barrier-synthesized !dbg in the debug gate
Extract the final -O0 @debug_ptr body and require !dbg on the
--bitptr/--lower-bitptr chain (mul, shl, ptrtoint, add, inttoptr) and on
every load/store through the computed pointer.  Line-table rows alone could
stay green if the barrier dropped locations only on the instructions it
synthesizes; this IR-level check fails in that case.

Refresh the stale gate header (three functions, -O2 smoke, indexed
.debug_addr, ptr=30) and note that the exact .debug_addr entry list is
deterministic at the current compiler but should be relaxed on a DWARF
emission change.
2026-11-14 23:01:05 +00:00
arti 46417f53ec m7.2: strengthen Task 3 debug/oracle/cinit gates
- debug.sh: add a pointer/array runtime-GEP function (debug_ptr) with
  asserted line rows/low PC, and build the same TU with tms-clang -g -O2
  through --bitptr/opt/--scale/--lower-bitptr/instcombine; require the
  -O2 object's .debug_* sections and dwarfdump its debug.c/function/low PC.
  Read .debug_addr entries by index and assert the CU low/high PC and
  .debug_line file index.
- oracle.sh: load both the GSPLNK and tms-link images in MAME with the same
  markers; require a minimum count and the names the checks depend on, and
  document the absolute/undefined C_EXT exclusion.
- cinit.sh: assert the object relocation (0x10, .bss/_cinit_target base,
  addend 0), compare the 28-byte optional header with GSPLNK, and link
  CINIT.O alone to exercise the synthesized public cinit symbol.
- tmscoff.py: point the order-relaxation comment at the Task 1 lit test that
  still pins the llc section order.
2026-11-14 22:54:19 +00:00
arti 0075e57c0d m7.2: add object/debug end-to-end gates
- oracle.sh: link the M5 native objects with GSPLNK and tms-link, require
  identical allocated bytes/public symbols through the independent reader,
  then run the tms-link image in MAME and decode _native_value with dis34.
- cinit.sh: a C TI .cinit record table (packed u16 count/u32 destination/
  data words) linked by tms-link, the termtris copy loop in MAME, cinit at
  the .cinit origin, the destination resolved to a bit address, and
  bytes/placement equal to GSPLNK.
- longname.sh: a 44-character public function defined in one TU and called
  from another, linked by tms-link, full name in the map, runs in MAME.
- debug.sh: tms-clang -g -> TI-COFF -> tms-link --keep-debug, .debug_*
  wrapped in a minimal ELF32 container and validated with llvm-dwarfdump
  (debug.c, line rows, low PC 0x314000, high_pc byte size, string names),
  plus the stripped image loading in MAME.
- tms-clang: pass -g through to clang; the bit-pointer passes preserve !dbg.
- tms-link: accept GSPA's .text/.data/.bss/.cinit order as well as llc's
  .text/.data/.cinit/.bss order (the real startup cinit.asm shape).
2026-11-14 22:21:03 +00:00
arti 38ab394c8b m7.2: tighten tms-link oracle and reader (fix round 1) 2026-11-14 21:50:03 +00:00
arti b21e762058 m7.2: add tools/tms-link native TI-COFF linker 2026-11-14 21:36:08 +00:00
arti d7209392f2 docs: M7.2 scope and plan 2026-11-14 20:36:32 +00:00
arti e09d85c99f docs: tick the M7.1 plan 2026-11-14 20:33:05 +00:00
arti ad6b39738a m7.1: close the final-review evidence gaps 2026-11-14 20:32:54 +00:00
arti 4110a24c23 m7.1: document the M7.1 state and refresh the generic manifest 2026-11-14 20:08:43 +00:00
arti f79eadfda1 m7.1: gate the odd-offset pointer and wide-integer .data cases 2026-11-14 18:13:16 +00:00
arti b0048b8151 m7.1: add the .data i64/aggregate/bitfield gate 2026-11-14 17:36:33 +00:00
arti 773dd7597e m7.1: cover the union and non-TMS stride controls 2026-11-14 16:55:45 +00:00
arti e1436ba112 m7.1: add the sub-byte stride diagnostic gate 2026-11-14 15:43:54 +00:00
arti b313de480b m7.1: keep narrowing base casts out of the barrier
Fix the fix-round regression: the base matcher stripped any zext/trunc,
so `(unsigned short)(unsigned)p + 24` lost its 16-bit truncation and
became `p + 24` at both -O0 and -O2.  stripWideningCasts now strips only
zext/sext and truncs to at least the 32-bit pointer width; a trunc below
i32 stops the match, leaving the shape unbarriered with its
`and 0xffff`/`and 0xff` intact (the base commit's value).

Allow widening sext on the base as well, closing the signed 64-bit
pointer-int shape: `(char *)((long long)(int)p + 24)` now becomes
`@__tms_bitptr(i32 24, ptr p)` instead of `getelementptr i8, p, 192`.
Use the fixed 32-bit TMS34010 pointer width rather than an absent module
DataLayout's 64-bit default, which misjudged a trunc to i32.

Add @narrow16/@narrow8/@narrow16and/@late64s to bitptr.ll (narrow shapes
must not emit a call), negative tests for the mismatched declaration,
body and non-call use fatal paths, a late64s M0 check with the late
positive scoped to @late itself, and narrow16/narrow8/late64s runtime
markers plus IR checks in the M7 gate.  Update the pointer-o2.sh header.
2026-11-14 13:57:48 +00:00
arti 9cf31b9b9b m7.1: barrier 64-bit pointer-int shapes
Extend --bitptr's raw inttoptr barrier through the zext/trunc clang emits
for a 64-bit pointer-int expression, so
`inttoptr(add(zext(ptrtoint p), i64 24))` becomes
`@__tms_bitptr(i32 24, ptr p)` instead of a post-scale `getelementptr
i8, p, 192`.  The pointer is 32-bit, so the addend is zext/truncated to
the low word.  The matcher also covers the reversed add operand order and
the sub form (negated addend).

Harden getBitPtrFn/lower_bitptr_calls: an existing @__tms_bitptr with a
mismatched signature or body, or a non-CallInst/mismatched use, now fails
loudly instead of leaving an undefined external.

Add @late64 (and sub/reversed/trunc) to bitptr.ll, assert the
nounwind readnone declaration, add a late64 M0 shape check (24, never
192) and a late64 runtime marker to the M7 gate.  Tighten the gate's
one-scale check to reject a second shl i32 in copy_back and to match
SLL 3/SLL 6 exactly (not SLL 31).  Update the stale M6 comments in
bitscale.cpp and the c-torture -O2 comment.
2026-11-14 13:14:56 +00:00
arti d3f411864d m7.1: add the -O2 bit-pointer semantic barrier
Replace the M6 pre-opt --scale with --bitptr: every source GEP (and an
inttoptr of a bit addend over a ptrtoint base) becomes an opaque
@__tms_bitptr(i32 bitoff, ptr base) call (nounwind readnone), so the
optimizer cannot canonicalize an already-bit offset back into a byte GEP
for the post-opt --scale to multiply by 8 again.

tms-clang -O2 is now clang -> --bitptr -> opt default<O2> -> --scale
(optimizer byte GEPs only) -> --lower-bitptr -> opt instcombine.  -O0 is
clang -> --bitptr -> --lower-bitptr.  --lower-bitptr restores
inttoptr(add(ptrtoint base, bitoff)); the final instcombine restores the
M0 int_diff 8/32 folding and the shim's emit_uint64 needs
instcombine<no-verify-fixpoint> for a known zext/nneg non-idempotent
shape.  Constant-expression GEPs keep the inttoptr/add form.

Remove the shim memmove constant-step workaround (natural d += n) and
add the M7 -O2 pointer gate (C driver at -O2, GSPA/GSPLNK, MAME, exact
markers/bytes and one-scale IR/asm evidence).  Update the M0 shape
checks for the final instcombine's bit-index `getelementptr i8, %p, 24`
late form (still 24 bits; the old 192 is rejected).
2026-11-14 12:26:40 +00:00
arti 91d42be168 docs: M7 scope and M7.1 plan 2026-11-14 11:39:14 +00:00
arti 9dc8f28488 docs: m6 is the repository default branch 2026-11-14 11:27:53 +00:00
arti 827d9315dd m6: refresh the lit count after the narrow-load regression
The new TMS34010 CodeGen test brings the M6 head to 103 CodeGen tests
(28 m6-*) and 107 lit tests including MC.
2026-11-14 10:33:16 +00:00
arti e0cf441118 m6: apply the final-review fixes
- spec 4.2/7.4: the caller-allocated hidden return slot (no sret
  pointer), with the 1987 _mkbig/_callbig oracle recorded as binding;
  spec 8 annotates debug info as M7.
- README: qualify the complete-surface headline, name the sub-byte
  stride in the M7 ownership lists, and flag the default -O2 over-scale.
- shim: %c honours width and the '-' flag; a bare %c is unchanged.
- runtime gate: add %c width output and call rts.lib _isascii, checking
  it in the GSPLNK map (587 bytes, 13 markers).
- aggregate gate: return a packed bitfield struct by value and check
  its fields, sign extension and raw word (49 markers).
- tms-clang: default TMS_CLANG/TMS_OPT to build/llvm-clean-build/bin
  and fail clearly when a tool is missing; update the README example.
2026-11-14 09:46:52 +00:00
arti 8d18ab91b2 docs: M6 language, runtime and conformance status 2026-11-14 07:52:03 +00:00
arti 094d2543f7 tests: correct the classifier format-scan comment 2026-11-14 06:16:40 +00:00
arti 2fec10b039 tests: fix M6 conformance review findings 2026-11-14 06:11:33 +00:00
arti bc92886312 tests: expand M6 conformance coverage 2026-11-14 05:33:50 +00:00
arti 3226a84988 docs: clarify the M6 -O2 pointer over-scale limitation 2026-11-14 04:49:39 +00:00
arti 5760a35867 tests: complete M6 printf coverage and document the bit-scale limits 2026-11-14 04:44:17 +00:00
arti 7aab6a6485 tests: fix printf precision edge cases (#, zero with precision 0) 2026-11-14 04:16:41 +00:00
arti 15201f31ba tests: restore the Task 6 bit-scale pipeline and memmove workaround 2026-11-14 03:22:23 +00:00
arti eb44a1aade Revert "tests: run SROA before the bit scale so pointer int casts stay bit-addressed"
This reverts commit 5379cd4629.
2026-11-14 03:22:10 +00:00
arti 5379cd4629 tests: run SROA before the bit scale so pointer int casts stay bit-addressed 2026-11-14 02:46:46 +00:00
arti 2fca960398 tests: scale the tms-clang pipeline once, after opt 2026-11-14 02:28:42 +00:00
arti 3005647f30 tests: M6 runtime, printf/sprintf and the linked flib/rts gate 2026-11-14 02:27:04 +00:00
arti 85c4a1778a tests: clarify the aggregate gate's linked-symbol check 2026-11-14 01:34:59 +00:00
arti 8be4a978cc tests: fix the aggregate gate and the -O0 driver scale 2026-11-14 01:31:11 +00:00
arti 12cb023b3c tests: M6 aggregate gate and late-GEP scaling
Add the M6 aggregate gate (structs/unions by value, 6-byte/5-word returns,
nested and mixed members, exact-copy guards) and scale every optimizer-created
GEP after opt in tms-clang; --normalize treated SROA's aggregate-split byte
offsets as bits.  The generic sweep now passes multiple-return-values-cross-
block-with-invoke.
2026-11-14 00:33:27 +00:00
arti ae73e6b054 tests: correct i64 memory-order comments 2026-11-13 22:39:15 +00:00
arti ded91f2054 tests: pin little-endian i64 memory and the aggregate-copy case 2026-11-13 22:24:59 +00:00
arti e997b3ff22 tests: add 64-bit bitfield containers to the M6 gate 2026-11-13 22:01:01 +00:00
arti 53f0b3c56b tests: M6 bitfield gate and layout oracle 2026-11-13 21:45:33 +00:00
arti b973ccd250 tests: M6 varargs gate and shim 2026-11-13 20:09:55 +00:00
arti 1a62878e93 tests: exercise M6 float branches, f64 select and rejections 2026-11-13 18:53:14 +00:00
arti f18115314c tests: M6 float/double gate 2026-11-13 17:27:56 +00:00
arti 581a264ab3 tests: harden M6 i64 gate and refresh the M5 boundary notes 2026-11-13 15:00:11 +00:00
arti c1d0378212 tests: M6 i64 gate
Adds the M6 i64 MAME gate (scripts/tests/m6/i64.sh, driver and
entry/check/link helpers) and updates the M5 boundary tests: the 64-bit
multiply diagnostic is now a positive inline-MPYS check, the reject-i64
lit fixtures use i128, and the generic expected-fail manifest drops the
tests that the i64 support now compiles (0 crashes, 121 pass).
2026-11-13 13:54:36 +00:00
arti dad0245d5e tests: harden M6 ABI probe compare/conversion/return 2026-11-13 12:38:01 +00:00
arti fa90562bb9 tests: M6 float/i64 ABI probe 2026-11-13 12:18:46 +00:00
arti ea1222001f docs: M6 language/runtime and floats plan 2026-11-13 12:01:40 +00:00
171 changed files with 24891 additions and 619 deletions

No files matched your search

+1270 -145
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,447 @@
# TMS34010 M6 — Floats, 64-bit Integers, General Varargs, Bitfields, and Aggregates Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** The compiler supports the TI C language surface that M5 deferred — `float`/`double`/`long double`, `long long`/i64, general `va_list`/`va_start`/`va_arg`, bitfields, and structs/unions by value with `sret`/aggregate returns — using the validated `flib.lib`/`rts.lib` runtime, with the conformance tier expanded to the newly supported features.
**Architecture:** M6 keeps the M5 native TI-COFF/GSPLNK path, the all-stack TI ABI, and the M5 asm oracle. The 64-bit and floating-point ABI follows the TI C guide: arguments are pushed on the program stack and widened to 32 bits; a `float`/`double`/`long long` return is written into a caller-allocated stack slot (the same hidden-return rule as struct returns); `long long` occupies two 32-bit slots. Float/double arithmetic and conversions lower to `FS$*`/`FD$*` calls in the TI `flib.lib`; the `rts.lib` supplies the remaining runtime. Bitfields use Clang's packed record layout (the target already sets `PackStruct=1`); aggregates use the M5 `byval`/hidden-return machinery. The conformance shim/classifier gain general varargs and drop the M6 feature skips.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m6`), C++17, CMake/Ninja, `llc`, `llvm-mc`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the TI `flib.lib`/`flibc.lib`/`rts.lib` (1990 SDK), the dwt COFF loader, MAME, `dis34`, `llvm-lit`/FileCheck, the 1987 TI compiler as a differential oracle, pinned GCC 16.2.0 c-torture and c-testsuite.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (§4.2, §7.4–§7.5, §8; M6); the M5 plan `docs/superpowers/plans/2026-11-12-tms34010-m5-native-object-path-and-conformance.md` is the handoff.
## Global Constraints
- Compiler work happens in **`llvm-tms34010`**, branch `m6`, created from `m5` at `f9c593ddd5bca0dc30cc2273c05a995100e576f3`. Project work happens in **`tms-c-compiler`**, branch `m6`, created from `m5` at `5ee3a6592c7d09e8c58635490077df0ef2d7fc99` plus the M6 plan commit. Do not merge into `m0`–`m5`; do not change the default (`m5`).
- Use upstream LLVM `llvmorg-23.1.5`; keep the fork minimal. Use the existing `build/llvm-clean` and `build/llvm-clean-build`.
- The M2–M5 TI ABI is unchanged: A8 scalar return, A13 FP, A14 STK, A15 system stack, `RETS 2/0`, `FS1 = 32`, `FS0 = 16` with the field-extension bit set (`SETF 16,1,0`).
- **Stack ABI:** all arguments are pushed on the program stack and widened to 32 bits; structs by value are rounded to 16 bits. `float`/`double`/`long long` and aggregate returns use a **caller-allocated program-stack slot** (the callee copies the result there), so the call site uses the old-STK save and `RETS 2`.
- **i64 ABI (to be confirmed by Task 1):** `long long` arguments occupy two 32-bit stack slots (low word first at the lower address, matching the TI endianness); the return is an 8-byte caller-allocated slot. If the 1990 C guide or `rts.lib` evidence shows a different TI 64-bit convention, Task 1 records the ruling and adjusts these rules before Tasks 2/6 use them.
- **Float/double:** arguments are 32-bit-widened stack slots (`float` one, `double` two); the return is the caller-allocated stack slot; arithmetic/compare/conversion lowers to the validated `FS$*`/`FD$*` entries in `flib.lib` (or a target sequence for a missing entry). Use the exact TI library names; do not invent libcalls.
- **General varargs:** the M4 contiguous `&last_fixed` pattern remains supported; M6 adds a real `va_list`/`va_start`/`va_arg` for the TI ABI. External variadic definitions (`sprintf`/`printf`) are supported at `-O2`; the M5 static-variadic restriction is lifted once the optimizer no longer drops `...`.
- **Bitfields:** the TI packed structure rules (fully packed; only the first object in an array is 16-bit aligned); Clang's target already sets `PackStruct=1`; verify/adjust the target record layout against the M4 `_Static_assert` offsets and the TI C guide.
- **Aggregates:** structs/unions by value use the 16-bit-rounded stack slots and the hidden return slot; `sret`/`byval`/aggregate returns are M6 (the M5 `byval` slot rule is 16-bit). Keep the M5 `alloca`/memcpy/memmove behavior.
- **Native object path:** TI COFF linked by GSPLNK; the existing loader. The asm path (`-filetype=asm` → GSPA/GSPLNK) remains the oracle; do not delete it.
- Every M2–M5 gate stays green; add `m6-*` lit tests and `scripts/tests/m6/*`. The M5 conformance harness/classifier/lists are the base; the M6 features remove their skips.
- **M6 non-goals (M7):** debug info, a native linker, the wider Xlib surface, real-hardware-only validation, and the full GCC/LLVM suites beyond the supported subset. Document the boundary. Ruling: the spec's M5 re-scope lists debug info as M6, but this plan splits it into M7 as an independent object/debug subsystem; the M6 language/runtime surface is already a complete milestone. Cost if wrong: debug info arrives one milestone later.
- No force-push, no merge into `m0`–`m5`, no default change. Push `m6` after the final gate run and review.
## Review Focus
1. **Float/double/i64 ABI.** A wrong stack/hidden-return layout corrupts every call and return. The tests are Task 1's ABI probe, Task 2's two-slot i64 call/return, and Task 3's float/double call/return in MAME.
2. **Bitfield packed layout.** A wrong bitfield offset or signedness silently reads/writes the wrong bits. The tests are Task 5's TI-offset static asserts and MAME bitfield checks.
3. **General varargs.** A wrong `va_list`/`va_arg` walk corrupts `printf`/`sprintf` output. The tests are Task 4's multi-format output and the expanded c-torture/c-testsuite output.
4. **Aggregates/sret.** A wrong hidden-return pointer or copy size corrupts struct returns. The tests are Task 6's by-value/sret MAME cases.
5. **Soft-float libcalls/constants.** A wrong `FS$`/`FD$` name, argument order, or constant pool entry produces wrong values. The tests are Task 3's `fadd`/`fmul`/`fcmp`/conversion MAME cases and Task 7's runtime.
---
### Task 1: M6 branches, ABI rules, and the soft-float/i64 probe
**Files:**
- Create: `scripts/m6/spike-probe.asm` (hand-written `FS$ADD`/`FD$ADD` and i64 stack probes), `scripts/m6/spike-entry.asm`, `scripts/m6/spike-check.lua`, `scripts/tests/m6/spike.sh`
- Create: `scripts/m6/flib-extract.sh` (or the equivalent extraction into `build/m6-sdk`)
- Modify: `build/llvm-clean/TMS34010.md` (the M6 ABI note), `README.md` (the M6 section)
- Test: `scripts/tests/m6/spike.sh`
**Interfaces:**
- Consumes: the M5 native TI-COFF/GSPLNK harness, the 1990 SDK `flib.lib`/`rts.lib`, the TI C guide.
- Produces: a written/committed ABI rule for i64/float/double args and hidden returns; a linked `flib.lib` probe proving the `FS$`/`FD$` ABI; the exact library symbol list and link line.
- [ ] **Step 1: Write the failing ABI probe**
`spike-probe.asm` pushes the `FS$ADD` float operands (1.5, 2.5) and the i64 two-slot operands on A14, calls the library entries, and stores the results at the M4 markers; `spike-entry.asm` sets FS0/FS1, A14/A13 and calls the probe. The C target does not support float/i64 yet (Tasks 2/3), so this probe is hand-written asm, not a C float call. `scripts/tests/m6/spike.sh` assembles/links with the 1990 `flib.lib`/`rts.lib` and runs the COFF in MAME. The first run must fail because the float/i64 ABI and the `flib` link are not wired.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m6/spike.sh`
Expected: a link/ABI failure (missing `FS$ADD`/`FD$ADD`, wrong hidden-return slot, or the `$` symbol rejected by GSPA).
- [ ] **Step 3: Extract and validate the library/ABI**
`flib-extract.sh` extracts `flib.lib`/`flibc.lib`/`rts.lib` from the 1990 SDK into `build/m6-sdk` and records the exact symbols (`FS$ADD`, `FS$SUB`, `FS$MUL`, `FS$DIV`, `FS$NEG`, `FS$EQ`…, `FD$ADD`, …, the conversion entries) and the `flib` stack ABI (operands on A14, result pushed); verify the `$` symbol handling with GSPA/GSPLNK and record the link line. Confirm the i64 two-slot/hidden-return and float/double hidden-return rules from the C guide/`flib` source.
- [ ] **Step 4: Write the ABI note and run the probe green**
Add the i64/float/double ABI rule to `TMS34010.md`/README (the exact stack order, hidden-return slot, `RETS 2`, library names). Run:
```sh
scripts/tests/m6/spike.sh
```
Expected: the `FS$ADD` result (e.g. 1.5+2.5 == 4.0) and the i64 sum are correct in MAME; the link line and symbol list are recorded.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add TMS34010.md
git -C build/llvm-clean commit -m "tms34010: M6 64-bit/float ABI notes"
git add scripts/m6 scripts/tests/m6/spike.sh README.md
git commit -m "tests: M6 float/i64 ABI probe"
```
### Task 2: `long long` / i64 arguments, returns, and arithmetic
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010CallingConv.td`, `TMS34010InstrInfo.td`, `TMS34010FrameLowering.cpp`
- Test: `llvm/test/CodeGen/TMS34010/m6-i64.ll`, `scripts/tests/m6/i64.sh`
- Reuse: the M5 `byval`/hidden-return stack machinery.
**Interfaces:**
- Consumes: Task 1's i64 ABI rule; the M5 stack/frame.
- Produces: i64 formal/call arguments as two 32-bit slots; an 8-byte caller-allocated return slot; add/sub/and/or/xor/shift/compare and mul/div/rem (sequences or `flib`/`rts` helpers) with correct endianness; `RETS 2`.
- [ ] **Step 1: Write the failing i64 test**
`m6-i64.ll` defines `long long addll(long long, long long)`, `subll`, `mull`, `divll`, `remll`, shifts, and compares; checks the two-slot argument/return shape and the library/sequence. `i64.sh` runs `addll(0x12345678, 0x9ABCDEF0)`, `mull`, `divll`, `remll`, and signed shifts in MAME.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-i64.ll`
Expected: the M5 `only i32/pointer returns`/argument rejection.
- [ ] **Step 3: Implement i64**
Extend `CanLowerReturn`/`LowerReturn`/`LowerFormalArguments`/`LowerCall` for i64 with the Task 1 ABI (two slots, hidden 8-byte return, `RETS 2`). Implement the i64 arithmetic with the 32-bit halves (`ADD`/`ADDC`/`SUBB`, shifts, compares) and the validated helpers/sequences for mul/div/rem. Keep the endianness fixed and documented.
- [ ] **Step 4: Run the i64 gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-i64.ll
scripts/tests/m6/i64.sh
scripts/tests/m2/run.sh
scripts/tests/m3/run.sh
scripts/tests/m4/run.sh
```
Expected: PASS; the MAME values are correct; the M2–M4 gates are unchanged.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-i64.ll
git -C build/llvm-clean commit -m "tms34010: i64 arguments, returns and arithmetic"
git add scripts/tests/m6/i64.sh
git commit -m "tests: M6 i64 gate"
```
### Task 3: `float`/`double` soft-float via `flib.lib`
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010TargetMachine.cpp` (libcall names), `TMS34010InstrInfo.td` (constant pool/loads), `TMS34010AsmPrinter.cpp` (float constants), `TMS34010Subtarget`/TTI as needed
- Test: `llvm/test/CodeGen/TMS34010/m6-float.ll`, `scripts/tests/m6/float.sh`
- Reuse: Task 1's `flib` ABI/link.
**Interfaces:**
- Consumes: Task 1's `FS$`/`FD$` list and stack ABI; Task 2's hidden-return/stack slots.
- Produces: `f32`/`f64` arguments/returns, `FADD`/`FSUB`/`FMUL`/`FDIV`/`FNEG`, comparisons, and int↔float conversions via the exact `FS$`/`FD$` libcalls; constant-pool emission for float/double literals.
- [ ] **Step 1: Write the failing float test**
`m6-float.ll` defines `float fadd(float,float)`, `double dadd(double,double)`, `fmul`, `fdiv`, `fcmp`, and conversions; checks the libcall names, the stack/hidden-return shape, and the constant pool. `float.sh` runs `fadd(1.5,2.5)=4.0`, `fmul`, `fdiv`, `fcmp`, and conversions in MAME, linking `flib.lib`.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-float.ll`
Expected: float/double rejection or a missing libcall/constant pool.
- [ ] **Step 3: Implement the soft-float lowering**
Set the float/double operation actions to `LibCall` and the exact `FS$*`/`FD$*` names; lower float/double args/returns via the Task 1/A2 stack rules; add the constant pool for `f32`/`f64` literals (bit-exact `.long` pairs, 16-bit-aligned); implement the comparisons/conversions through the `flib` entries. Do not hardcode a library address or guess a symbol name.
- [ ] **Step 4: Run the float gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-float.ll
scripts/tests/m6/float.sh
scripts/tests/m6/spike.sh
```
Expected: PASS; the MAME float/double values are correct; the constant pool is bit-exact.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-float.ll
git -C build/llvm-clean commit -m "tms34010: float/double soft-float lowering"
git add scripts/tests/m6/float.sh
git commit -m "tests: M6 float/double gate"
```
### Task 4: General varargs (`va_list`, `va_start`, `va_arg`)
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010CallingConv.td`, `TMS34010FrameLowering.cpp`
- Modify: `scripts/tests/m5/conformance/shim.c` (a real `va_list`-based `printf`/`sprintf` path)
- Test: `llvm/test/CodeGen/TMS34010/m6-varargs.ll`, `scripts/tests/m6/varargs.sh`
**Interfaces:**
- Consumes: the M5 contiguous `&last_fixed` pattern; the M4 `sprintf`/shim; the all-stack ABI.
- Produces: a `va_list` type and `va_start`/`va_arg` lowering for the TI stack layout; external variadic definitions/calls at `-O2`; the M4 contiguous pattern remains.
- [ ] **Step 1: Write the failing varargs test**
`m6-varargs.ll` defines an external variadic `printf`-shaped function and a `va_start`/`va_arg` walk over `int`, `long`, `char *`, `double`; C `varargs.sh` prints `%d %s %f` and compares the output. The first run must fail on the `va_start`/local variadic restriction.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-varargs.ll`
Expected: `Cannot select: va_start`/`vastart` or the M5 local-variadic rejection.
- [ ] **Step 3: Implement the varargs lowering**
Add the `va_list` representation, `va_start`/`va_arg`/`va_end`/`va_copy` lowering, and the external variadic call/definition ABI; keep the contiguous M4 pattern working. Let the static-variadic `-O2` path through once `va_start` keeps `...`; update the M5 diagnostic/tests accordingly. Extend the shim to use the real `va_list` where supported.
- [ ] **Step 4: Run the varargs gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-varargs.ll
scripts/tests/m6/varargs.sh
scripts/tests/m4/varargs.sh
```
Expected: the `%d %s %f` output is exact; the M4 contiguous pattern still passes.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-varargs.ll
git -C build/llvm-clean commit -m "tms34010: general varargs"
git add scripts/tests/m6/varargs.sh scripts/tests/m5/conformance/shim.c
git commit -m "tests: M6 varargs gate and shim"
```
### Task 5: Bitfields
**Files:**
- Modify: `build/llvm-clean/clang/lib/Basic/Targets/TMS34010.cpp/.h` (record/bitfield layout as needed)
- Modify: `TMS34010ISelLowering.cpp` (bitfield load/store masks) if the DAG needs target help
- Test: `llvm/test/CodeGen/TMS34010/m6-bitfield.ll`, `scripts/tests/m6/bitfield.sh`
**Interfaces:**
- Consumes: the Clang `PackStruct=1` target, the M4 packed-struct `_Static_assert` offsets, the TI C guide.
- Produces: TI-compatible packed bitfield offsets/signedness and correct masked loads/stores for `unsigned`/`signed` fields of 1..32 bits, including cross-byte/cross-word fields.
- [ ] **Step 1: Write the failing bitfield test**
`m6-bitfield.ll`/C defines packed structs with adjacent/signed/unsigned/cross-word bitfields and static asserts the TI offsets; `bitfield.sh` reads/writes every field and checks the observed bits in MAME against the TI layout. The first run must fail on a layout/shift/mask mismatch.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-bitfield.ll` / `scripts/tests/m6/bitfield.sh`
Expected: wrong offsets/masks or an unsupported bitfield shape.
- [ ] **Step 3: Implement the layout/adjustments**
Make the Clang record layout match the TI packed rules and the M4 offsets; adjust the target load/store lowering for the signed/unsigned field extraction and insertion if the generic DAG is wrong. Keep ordinary packed structs/arrays unchanged.
- [ ] **Step 4: Run the bitfield gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-bitfield.ll
scripts/tests/m6/bitfield.sh
scripts/tests/m4/layout.sh
```
Expected: the TI offsets and every MAME field value match; the M4 layout is unchanged.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add clang/lib/Basic/Targets/TMS34010.cpp clang/lib/Basic/Targets/TMS34010.h llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-bitfield.ll
git -C build/llvm-clean commit -m "tms34010: TI packed bitfields"
git add scripts/tests/m6/bitfield.sh
git commit -m "tests: M6 bitfield gate"
```
### Task 6: Aggregates by value, `sret`, and aggregate returns
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010CallingConv.td`, `TMS34010FrameLowering.cpp`
- Test: `llvm/test/CodeGen/TMS34010/m6-aggregate.ll`, `scripts/tests/m6/aggregate.sh`
- Reuse: the M5 `byval`/hidden-return/`memcpy` machinery.
**Interfaces:**
- Consumes: Task 1/2's hidden-return slot; the M5 `byval` 16-bit slots; the memcpy/`alloca`.
- Produces: structs/unions by value with 16-bit-rounded slots, `sret`/aggregate returns via the caller-allocated slot, and correct copies; `byval` remains supported.
- [ ] **Step 1: Write the failing aggregate test**
`m6-aggregate.ll`/C defines a 6-byte struct by value, a larger struct by value, a struct return, a union by value, and an `sret` call; static-asserts the offsets/sizes and checks the fields in MAME. The first run must fail on the current sret/aggregate rejection or a copy/size mismatch.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-aggregate.ll` / `scripts/tests/m6/aggregate.sh`
Expected: `sret`/aggregate return rejection or a wrong slot/copy.
- [ ] **Step 3: Implement the aggregate lowering**
Extend `LowerCall`/`LowerFormalArguments`/`CanLowerReturn`/`LowerReturn` for `sret`, structs/unions by value, and aggregate returns using the 16-bit-rounded stack slots and the hidden return pointer; use `memcpy`/the exact object size. Keep the M5 `byval` and scalar ABI.
- [ ] **Step 4: Run the aggregate gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-aggregate.ll
scripts/tests/m6/aggregate.sh
scripts/tests/m5/robust.sh
scripts/tests/m2/run.sh
```
Expected: the MAME fields/sizes match; the M5 byval/robust gate is unchanged.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-aggregate.ll
git -C build/llvm-clean commit -m "tms34010: aggregates by value and sret"
git add scripts/tests/m6/aggregate.sh
git commit -m "tests: M6 aggregate gate"
```
### Task 7: Runtime/libc breadth (`flib`/`rts`, `printf`/`sprintf`)
**Files:**
- Modify: `scripts/m6/link.cmd` / the M6 harness to link `flib.lib`/`rts.lib`; `scripts/tests/m5/conformance/shim.c`
- Test: `scripts/tests/m6/runtime.sh`, `llvm/test/CodeGen/TMS34010/m6-runtime.ll` if needed
**Interfaces:**
- Consumes: Tasks 3/4's float/varargs; the M5 sandbox.
- Produces: a linked runtime with `flib`/`rts` and a `printf`/`sprintf` that handles the M6 formats; the M6 conformance tests reuse it.
- [ ] **Step 1: Write the failing runtime test**
`runtime.sh` builds a C program using `printf("%d %s %f %lld")`, `sprintf`, `memcpy`/`memmove`, and the `flib` arithmetic; the first run must fail on the missing libcall/format.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m6/runtime.sh`
Expected: a missing `FS$`/`FD$` link or a format/output failure.
- [ ] **Step 3: Implement the runtime link/shim**
Wire `flib.lib`/`rts.lib` in the M6 link command; extend the shim/`printf` to the M6 formats (`%f`, `%lld`, `%llu`, width/precision) using the real `va_list`; keep the M5 `printf`/`sprintf` behavior. Do not bypass the `flib`/`rts` where the ABI requires it.
- [ ] **Step 4: Run the runtime gate green**
```sh
scripts/tests/m6/runtime.sh
scripts/tests/m5/robust.sh
scripts/tests/m5/native.sh
```
Expected: the output/values match; the M5 native path stays green.
- [ ] **Step 5: Commit**
```sh
git add scripts/m6/link.cmd scripts/tests/m6/runtime.sh scripts/tests/m5/conformance/shim.c
git commit -m "tests: M6 runtime and printf/sprintf"
```
### Task 8: Conformance expansion
**Files:**
- Modify: `scripts/tests/m5/conformance/classify.sh`, `skip.tsv`, `scripts/tests/m5/c-torture.list`, `c-testsuite.list`
- Create: `scripts/tests/m6/c-torture.sh`, `scripts/tests/m6/c-testsuite.sh` (the M6 wrappers over the M5 runner/expanded lists)
- Test: the expanded gates and reports
**Interfaces:**
- Consumes: Tasks 1–7; the pinned GCC 16.2/c-testsuite corpora.
- Produces: the M6 classifier/allowlists that no longer skip the supported float/i64/varargs/bitfield/aggregate tests; the full supported-suite report and the curated M6 gate; the `printf` output comparison.
- [ ] **Step 1: Write the failing conformance test**
Extend the c-torture/c-testsuite lists with the newly supported tests and remove the corresponding skip rows. The first run must fail because the classifier still skips them or the output/float libcall is missing.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m6/c-torture.sh` / `c-testsuite.sh` (or the expanded M5 scripts)
Expected: skips for now-supported features or a missing `flib` link.
- [ ] **Step 3: Expand the classifier/lists**
Remove the M6 feature skips; keep the genuinely unsupported (debug info, wider Xlib, etc.); add the `printf` output tests; record the full supported-suite counts and reasons. Keep the curated gate runtime bounded (target 40–60 per suite) and the full `--scan` as a report.
- [ ] **Step 4: Run the expanded gates green**
```sh
scripts/tests/m6/c-torture.sh
scripts/tests/m6/c-testsuite.sh
scripts/tests/m5/generic.sh
scripts/tests/m5/conformance/selftest.sh
```
Expected: the expanded lists pass; skipped tests have reasons; the Generic no-crash report still has no crashes.
- [ ] **Step 5: Commit**
```sh
git add scripts/tests/m5/conformance/classify.sh scripts/tests/m5/conformance/skip.tsv scripts/tests/m5/c-torture.list scripts/tests/m5/c-testsuite.list scripts/tests/m6/c-torture.sh scripts/tests/m6/c-testsuite.sh
git commit -m "tests: expand M6 conformance coverage"
```
### Task 9: Docs, full gates, and push
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `symbols/README.md` (if runtime symbols are added)
- Test: the full M6/M5/M4/M3/M2 gate list
- [ ] **Step 1: Update the docs**
Document the M6 i64/float/double ABI, the `flib`/`rts` runtime, general varargs/`printf`, packed bitfields, aggregates/sret, the expanded conformance counts/pins, and the M6/M7 boundary (debug info, native linker, wider Xlib, real hardware). Correct the M5 stale notes.
- [ ] **Step 2: Run every gate**
```sh
ninja -C build/llvm-clean-build llc llvm-mc
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010 --filter='(m2|m3|m4|m5|m6)-'
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/MC/TMS34010
scripts/tests/m6/spike.sh
scripts/tests/m6/i64.sh
scripts/tests/m6/float.sh
scripts/tests/m6/varargs.sh
scripts/tests/m6/bitfield.sh
scripts/tests/m6/aggregate.sh
scripts/tests/m6/runtime.sh
scripts/tests/m6/c-torture.sh
scripts/tests/m6/c-testsuite.sh
scripts/tests/m5/object-smoke.sh
scripts/tests/m5/native-link.sh
scripts/tests/m5/native.sh
scripts/tests/m5/jr.sh
scripts/tests/m5/mmtm.sh
scripts/tests/m5/robust.sh
scripts/tests/m5/policy.sh
scripts/tests/m5/conformance/selftest.sh
scripts/tests/m5/generic.sh
scripts/tests/m4/run.sh
scripts/tests/m4/dis-roundtrip.sh
scripts/tests/m4/layout.sh
scripts/tests/m4/symbols.sh
scripts/tests/m4/termtris.sh
scripts/tests/m3/run.sh
scripts/tests/m3/dis-roundtrip.sh
scripts/tests/m2/run.sh
tools/tms-bitaddr/tests/run.sh
```
All green; the conformance report has no unexpected crashes; skips have reasons.
- [ ] **Step 3: Commit and push**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010 llvm/test/MC/TMS34010 clang/lib/Basic/Targets/TMS34010.cpp clang/lib/Basic/Targets/TMS34010.h TMS34010.md
git -C build/llvm-clean commit -m "tms34010: M6 floats, i64, varargs, bitfields and aggregates"
git -C build/llvm-clean push origin m6
git add README.md symbols scripts/m6 scripts/tests/m6 scripts/tests/m5 scripts/m3
git commit -m "tests/docs: M6 language/runtime coverage"
git push origin m6
```
Do not force-push, merge into `m0`–`m5`, or change the default. The controller updates the default to `m6` after the final review only if the user asks.
---
## Execution Handoff
M6 closes the TI language surface: float/double/i64 ABI, soft-float `flib`, general varargs, packed bitfields, aggregates/sret, and the expanded conformance tier. M7 owns debug info, the native linker, the wider Xlib surface, real-hardware validation, and the full external suites beyond the curated supported subset. The compiler repo is canonical for target code; this project repo holds the plan, harness, pins, and integration tests. The pinned GCC/c-testsuite trees are test-only (GPL) and are not part of the compiler or project distribution.
@@ -0,0 +1,103 @@
# TMS34010 M7.1 — Correctness and ABI Residuals Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Remove the remaining M6 correctness residuals: the `-O2` pointer over-scale, the sub-byte array/nested stride divergence, and the `.data` i64/aggregate/bitfield initializer gap, while keeping every M2–M6 gate green.
**Architecture:** The IR pipeline keeps the proven pre-opt bit scale, but replaces the scaled GEPs with opaque `@__tms_bitptr` calls so the optimizer cannot re-canonicalize them into already-bit GEPs. The post-opt pass scales only optimizer-created byte GEPs; a lowering pass then replaces the calls with `inttoptr(add(ptrtoint,...))` and a final instcombine restores the M0 folding. The sub-byte stride is diagnosed at compile time rather than silently byte-rounded. `.data` emission becomes recursive (i64, structs, unions, arrays, bitfields) in both raw and object modes.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), C++17, Ninja, `llc`, `clang`, `tms-bitaddr`, `tms-clang`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the dwt loader, MAME, `dis34`, `llvm-lit`/FileCheck.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §4.1–§4.2, §8 (M7.1), and the M6 plan/README boundary.
## Global Constraints
- Compiler work in `build/llvm-clean`, branch `m7` (from m6 `bdc16ab8d4b6`); project work in `tms-c-compiler`, branch `m7` (from m6 `9dc8f28`). No force-push, no merge into `m0`–`m6`, no default change.
- Keep the TI all-stack ABI, the native TI-COFF/GSPLNK path, the asm oracle, the `dwt` loader, and every M2–M6 gate green.
- MAME + the loader are the acceptance environment; real hardware is M7.3 and deferred.
- Red/green TDD for every task; commit per task; no push until the M7.1 final review is clean, then push `m7`.
- i64 `.data` words are little-endian (LSW first); the i64 argument/hidden-slot order stays MSW-first.
- Do not silently byte-round a sub-byte record stride: the diagnostic must be loud (default-on warning/error).
- Keep the narrow-load/store nonzero-offset guard from `bdc16ab8d4b6`.
## Review Focus
1. **The bitptr barrier.** Does the optimizer see opaque calls (no folding through them), does the post-opt pass scale only byte GEPs, does the lowering restore the M0 `int_diff = 8/32` shape, and is `p += n` correct at the default `-O2` with one scale?
2. **Sub-byte stride.** Does the diagnostic fire for the 1987 oracle `struct s arr[2]`/`struct nest`, not for byte-multiple records, and is the message actionable?
3. **`.data` exactness.** i64 word order, packed struct/bitfield bytes, unions/arrays, relocations, raw and object modes; no over-read/write; unsupported shapes stay loud.
4. **No M2–M6 regression** and the shim `memmove` workaround removed with the runtime gate proving the natural `d += n`.
---
### Task 1: The `-O2` bit-pointer semantic barrier
**Files:**
- Modify: `tools/tms-bitaddr/bitscale.cpp` (`--bitptr`, `--lower-bitptr`, tests)
- Modify: `tools/tms-bitaddr/tests/run.sh`, add `tests/bitptr.ll`
- Modify: `scripts/tms-clang` (pipeline)
- Modify: `scripts/tests/m5/conformance/shim.c` (remove the `memmove` workaround)
- Create: `scripts/tests/m7/pointer-o2.sh` (C gate)
- Test: `scripts/tests/m0/run.sh`, `scripts/tests/m6/runtime.sh`, the full M2–M6 gates
**Interfaces:**
- Consumes: the M6 pre-opt `--scale` + post-opt `--scale` pipeline and the known `p += n` over-scale.
- Produces: `@__tms_bitptr(i32 bitoff, ptr base)` (nounwind/readnone), `--bitptr`/`--lower-bitptr`, a pipeline that keeps opaque calls through `opt`, scales only post-opt byte GEPs, lowers the calls, and restores the M0 folding.
- [x] **Step 1: Write the failing tests.** Add `tests/bitptr.ll` to the `tms-bitaddr` suite: `--bitptr` turns `getelementptr i8, p, n` into a `@__tms_bitptr` call with the bit offset; `--lower-bitptr` turns it back into `inttoptr(add(ptrtoint p, n*8))`. Add `scripts/tests/m7/pointer-o2.sh`: a C driver with `char *p; p += n; *p = ...;` and the `memmove` overlap shape, compiled at `-O2`, linked with GSPA/GSPLNK, run in MAME, checking the correct bytes.
- [x] **Step 2: Run it red.** The current pipeline double-scales (`%bit.off = shl n,3` twice / `p + n*64` bits) and/or the shim workaround is required; the new gate fails.
- [x] **Step 3: Implement the barrier.** Add the `--bitptr`/`--lower-bitptr` modes; update `tms-clang` to clang → `--bitptr` → `opt` → `--scale` (post-opt byte GEPs) → `--lower-bitptr` → `opt -passes=instcombine` → output (at `-O0`: clang → `--bitptr` → `--lower-bitptr`); remove the shim `memmove` workaround (natural `d += n`).
- [x] **Step 4: Run green.** `scripts/tests/m7/pointer-o2.sh`, `scripts/tests/m0/run.sh` (`int_diff` 8/32, `late` 24), `scripts/tests/m6/runtime.sh` both levels, the full TMS34010 lit suite, and the M2–M6 gates.
- [x] **Step 5: Commit.** `tms-bitaddr` + `tms-clang` + shim + the gate.
### Task 2: Sub-byte array/nested stride diagnostic
**Files:**
- Modify: `clang/lib/Basic/Targets/TMS34010.cpp/.h` (target hook/flag if needed)
- Modify: `clang/lib/Sema/SemaType.cpp` / `SemaDecl.cpp` and `clang/include/clang/Basic/DiagnosticSemaKinds.td`
- Create: `clang/test/Sema/tms34010-subbyte-stride.c` (or the target test location)
- Create: `scripts/tests/m7/stride.sh`
- Test: the oracle `struct s { unsigned a:3; unsigned b:5; int c:4; unsigned d:20; unsigned e:4; }` and `struct nest { struct s a; int b; }`
**Interfaces:**
- Consumes: the M4/M6 packed record layout (36-bit content, 5-byte `sizeof`).
- Produces: a default-on diagnostic for arrays/nested members of records whose bit content is not a byte multiple, naming the byte-rounded and TI bit strides; no warning for byte-multiple records.
- [x] **Step 1: Write the failing test.** `stride.c` with `struct s arr[2];`, `struct nest n;`, and a byte-multiple control (e.g. `struct cross`); compile with `-Werror=tms34010-subbyte-stride`; the first run has no diagnostic (red).
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.** Compute the record bit content (last field bit offset + width, recursively for nested fields) and diagnose an array element/nested field whose content is not a byte multiple. A warning is the acceptance; an implementation of the bit-content stride is optional only if sound.
- [x] **Step 4: Run green.** `stride.sh`; the Sema test; M4/M5/M6 layout/bitfield/aggregate gates.
- [x] **Step 5: Commit.**
### Task 3: `.data` i64/aggregate/bitfield initializers
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010AsmPrinter.cpp` (raw and object initializers)
- Create: `llvm/test/CodeGen/TMS34010/m7-data-initializers.ll`
- Create: `scripts/tests/m7/data.sh` (C + MAME, raw bytes)
- Test: the M5 object/native gates and the M6 runtime/conformance subset
**Interfaces:**
- Consumes: the M5 `.data` emitter (integers ≤32, f32/f64, pointers, byte arrays, zero).
- Produces: recursive struct/union/array/aggregate-zero emission and i64 two-word LSW-first emission in raw and object modes, with relocations; the existing unsupported-type diagnostics stay.
- [x] **Step 1: Write the failing test.** `m7-data-initializers.ll` and `data.sh` with `long long x = 0x1122334455667788;`, a packed struct, a bitfield struct, a union, an array of structs, and a pointer field; the current emitter rejects them (`M2 .data ...`).
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.** Extend `emitDataInitializer` and `emitDataInitializerObject` recursively; i64 LSW-first; exact packed sizes; relocations; keep vectors/i128/unsupported loud.
- [x] **Step 4: Run green.** `data.sh` (raw bytes/MAME), the object path, `m5/native.sh`, `m5/object-smoke.sh`, the M6 runtime/conformance gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.1
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M2–M7.1 gate list
- [x] **Step 1: Update the docs** for the bitptr barrier, the stride diagnostic, `.data` coverage and the new gate counts; keep the M7.2–M7.4 boundary.
- [x] **Step 2: Run every gate** (M2–M6 full list + `scripts/tests/m7/*`; lit; conformance; generic).
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.1 removes the default-`-O2` correctness risk and the M6 `.data`/stride gaps. M7.2 owns debug info and the native linker; M7.3 the wider Xlib/stderr/hardware; M7.4 the full external suites and performance. The compiler repo is canonical; the project holds the harness, plans and gates.
@@ -0,0 +1,119 @@
# TMS34010 M7.2 — Object/Debug (Native Linker and TI-COFF Debug Info) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close the M7.2 object/debug residuals: emit real debug information in the native TI-COFF object, and replace the GSPLNK dependency for the native path with `tools/tms-link`, including `.cinit` and public names longer than GSPA's 31-character limit, while keeping the GSPLNK output as the oracle.
**Architecture:** The MC object writer becomes a small TI-COFF **linker input** producer: optional `.cinit`, optional non-allocated `.debug_*` sections with long names, and the existing `.text`/`.data`/`.bss`. `llc` gains DWARF emission by setting `SupportsDebugInformation`; the asm path is unchanged because the compiler only emits debug for object output and existing IR has no `!dbg`. A new Python linker (`tools/tms-link`) reads those objects, lays out the four sections, resolves symbols and R-RELLONG fixups, and writes a position-dependent linked image the existing dwt loader accepts. Debug sections are stripped from the load image by default and kept with `--keep-debug` for `llvm-dwarfdump`.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), C++17, Ninja, `llc`, `llvm-dwarfdump`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`/FileCheck.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.2), §4.1–§4.2 (ABI) and §7.8 (tooling); the M7.1 plan/README boundary.
## Global Constraints
- Compiler work in `build/llvm-clean` (branch `m7`, base the M7.1 push `065998da6f3c`); project work in `tms-c-compiler` (branch `m7`, base `e09d85c`). No force-push, no merge into `m0`–`m6`, no default change.
- Keep the TI all-stack ABI, the asm oracle (GSPA/GSPLNK), the dwt loader, and every M2–M7.1 gate green.
- The default native gate must keep linking the M5/M6 objects with GSPLNK until the `tms-link` oracle gate proves byte equality; then the gates may link with `tms-link` where they exercise it, while at least one gate keeps GSPLNK as the oracle each run.
- `.cinit` is the TI init-record table (`u16 word count`, `u32 destination`, data words), not a raw image. Do not invent a second format.
- Debug info is object-path only. `-filetype=asm` must not gain `.loc`/`.debug_*` output that GSPA cannot assemble.
- Public names are not truncated on the object path; GSPA's 31-character truncation stays an asm-path limitation.
- MAME + the loader are the acceptance environment; real hardware is M7.3 and deferred.
- Red/green TDD; commit per task; no push until the M7.2 final review is clean.
## Review Focus
1. **TI-COFF exactness.** Section order, bit sizes, long names (`/offset`), `.cinit` flags, `.debug_*` flags 0, relocations in debug sections, optional header fields. Existing three-section objects must be byte-identical when no `.cinit`/debug is present.
2. **Debug validity.** `llvm-dwarfdump` reads the kept `.debug_*` sections after linking; line tables name the source and lines; low-PC values equal the linked addresses; the default image is stripped.
3. **Linker correctness.** Relocation addends (same-section `0xFFFF`, section-symbol and undefined-external forms), alignment/placement, duplicate/undefined symbols, long names, `.cinit` placement, map, and loader acceptance.
4. **Oracle equality.** `tms-link` vs GSPLNK: allocated section bytes and symbol addresses identical for the M5/M6 objects; no gate silently drops one side.
5. **No M2–M7.1 regression** and no asm-output change.
---
### Task 1: TI-COFF writer: `.cinit`, debug sections, long names
**Files:**
- Modify: `llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCObjectWriter.{h,cpp}`
- Modify: `llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCAsmInfo.cpp` (`SupportsDebugInformation`)
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (explicit `.cinit` section lowering if needed)
- Create: `llvm/test/CodeGen/TMS34010/m7-cinit-section.ll`, `m7-debug-info.ll`
- Test: the full TMS34010 lit suite; the M5 object/native gates unchanged
**Interfaces:**
- Consumes: the M7.1 writer (three sections, `/`-less names, bit sizes, R-RELLONG).
- Produces: optional `.cinit` (data flags `0x40`, after `.data`, only when non-empty), optional `.debug_*` sections (flags `0`, long names via the COFF string table), long section names in headers, and DWARF emission from `llc -filetype=obj` when the module has `!dbg`.
- [x] **Step 1: Write failing tests.** `m7-cinit-section.ll`: a global in `section ".cinit"` plus a normal function; `llc -filetype=obj` must produce a fourth section named `.cinit` with the correct bytes/relocation. `m7-debug-info.ll`: a function with `!dbg` locations; `llc -filetype=obj` must produce `.debug_line`/`.debug_info` (long names). A small parser (the project `coff.py` or a new `tools/tms-link/tmscoff.py`) asserts the sections; the current writer fails (`.cinit` has no representation; debug unknown).
- [x] **Step 2: Run red.** Both objects fail as expected; the three-section objects stay unchanged.
- [x] **Step 3: Implement.**
- Make the section list dynamic: `.text`, `.data`, `.cinit` (if present), `.bss`; emit section symbols/aux for each used section; keep `.text` required only when the module has code.
- Section headers: names >8 bytes become `/` + decimal string-table offset; build the string table before writing headers (symbols already share it). The string table starts with its own 4-byte size.
- Debug: set `SupportsDebugInformation = true`; accept non-empty sections whose names start with `.debug_` (and `.debug_*` from the DwarfDebug path), flags 0, with R-RELLONG relocations; keep unknown non-debug sections loud. Omit empty debug sections so existing objects stay three sections.
- Keep `-filetype=asm` free of DWARF: the asm path has no `!dbg` in every existing gate; document that debug is object-only. If AsmPrinter emits `.loc` with debug IR in asm mode, gate it off (target AsmPrinter check) rather than weakening GSPA acceptance.
- `.cinit` explicit section: ensure `__attribute__((section(".cinit")))` and `section ".cinit"` IR lower to an MC section named `.cinit`.
- [x] **Step 4: Run green.** New lit tests; full lit (107 + new); `m5/object-smoke.sh`, `m5/native.sh`, `m5/native-link.sh`; `m7/data.sh` (byte-identical objects); the three-section assertion in `m5/native-link.sh` stays.
- [x] **Step 5: Commit** (compiler + any project test parser).
### Task 2: `tools/tms-link` native linker
**Files:**
- Create: `tools/tms-link/tms-link` (Python 3 CLI), `tools/tms-link/tmscoff.py` (reader/writer)
- Create: `tools/tms-link/tests/run.sh` (+ fixtures)
- Create: `scripts/tests/m7/link.sh` (linker unit/self-test gate)
- Modify: `scripts/m4/run.sh` (`M4_LINKER=tms-link` opt-in path; default GSPLNK)
**Interfaces:**
- Consumes: one or more relocatable TI-COFF objects (Task 1), the entry object, and the M4/M5 defaults (`.text` `018A0000`, `.bss` `01A00000`, `prog`/`ram`).
- Produces: `tms-link -o OUT [--map MAP] [--entry SYM] [--text ADDR] [--data ADDR] [--cinit ADDR] [--bss ADDR] [--keep-debug|--strip-debug] OBJ...`; a linked position-dependent COFF (`nreloc=0`, optional header populated), a map (`%08x %s` lines + `ENTRY POINT SYMBOL: "..."`), symbol resolution for long public names, `.cinit` placement after `.data`, and loud duplicate/undefined/unsupported-relocation errors.
- [x] **Step 1: Write failing tests.** Feed it two tiny relocatable objects produced by `llc` (one defining a global/function, one referencing it) plus a `.cinit` object; assert the linked section addresses, resolved fields, map lines, and `nreloc=0`. Feed it a duplicate definition, an undefined external and an R-RELWORD and require loud failures.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Reader: mirror `vendor/vt1200/dwt/loader/coff.py` (header, sections, long names, symbols with aux, relocations).
- Layout: `.text` at the text origin; `.data` immediately after (`align 16` bits); `.cinit` after `.data`; `.bss` at the bss origin. Sections are word-aligned; sizes stay in bits; `.bss` is virtual.
- Symbols: section symbols get the output paddr; defined globals get paddr + section-relative value; undefined externals resolve to the unique definition; locals are resolved from their section. Public long names are preserved byte-for-byte.
- Relocations: for each R-RELLONG, read the 32-bit field (the bit addend), resolve `S` from the symbol index (`0xFFFF` = the section base), write `S + addend`. Leave no relocations in the output.
- Optional header: magic `0x0108`, vstamp `199`, text/data/bss sizes and starts, entry symbol; match GSPLNK's shape.
- Debug: strip `.debug_*` by default; `--keep-debug` copies them with their relocations resolved against the linked addresses. Refuse more than one debug-bearing object in M7.2 with a clear message.
- Map: section allocation and global symbol addresses in a stable,
greppable form. Source-line ranges are the kept `.debug_*` data (`.debug_line`)
validated with `llvm-dwarfdump` in Task 3; the linker does not parse DWARF
for the text map.
- [x] **Step 4: Run green.** `tools/tms-link/tests/run.sh`, `scripts/tests/m7/link.sh`; link `scripts/m5/native-link.c` + the GSPA entry object and compare allocated bytes/symbol addresses with GSPLNK.
- [x] **Step 5: Commit** (project; plus the `M4_LINKER` hook).
### Task 3: End-to-end object tests and the GSPLNK oracle
**Files:**
- Create: `scripts/tests/m7/oracle.sh` (both linkers, byte/symbol comparison, MAME)
- Create: `scripts/tests/m7/cinit.sh`, `scripts/m7/cinit-entry.asm`, `scripts/m7/cinit.c`
- Create: `scripts/tests/m7/longname.sh`, `scripts/m7/longname-a.c`, `scripts/m7/longname-b.c`
- Create: `scripts/tests/m7/debug.sh`, `scripts/m7/debug.c`, `scripts/m7/elf-debug-wrap.py` (test-only ELF wrapper for `llvm-dwarfdump`)
- Modify: `scripts/tms-clang` (`-g` pass-through) if needed
**Interfaces:**
- Consumes: Task 1's debug objects, Task 2's linker and `M4_LINKER` hook.
- Produces: gates that prove (a) `tms-link` == GSPLNK on the allocated image, (b) `.cinit` records are placed/relocated and the entry copies them in MAME, (c) a 40-character public function links and runs across two TUs, (d) the kept debug image validates with `llvm-dwarfdump` and the default image is stripped.
- [x] **Step 1: Write the failing gates.** `oracle.sh` links the M5 native objects both ways and requires identical `.text`/`.data`/`.bss` bytes and symbol values, plus the existing MAME markers. `cinit.sh` builds a C `.cinit` table, links with `tms-link`, and requires the entry's copy loop to write the expected words in MAME. `longname.sh` defines/calls a >31-character public symbol across two TUs. `debug.sh` compiles with `-g`, links `--keep-debug`, wraps the `.debug_*` sections in a minimal ELF container, and runs `llvm-dwarfdump` for the filename/line/address; it also asserts the default link has no debug sections and the image runs.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement the gates and any missing plumbing** (`tms-clang -g`, `M4_LINKER`, the ELF wrapper, the entry/cinit fixture). Keep each gate runnable alone and serial with MAME.
- [x] **Step 4: Run green.** All four gates, the M5 object/native gates and the M7.1 gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.2
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M0/M2–M7.2 list
- [x] **Step 1: Update the docs** for the debug format and validation path, the native linker (CLI, layout, map, `.cinit`, long names, strip/keep debug), the oracle comparison, the single-debug-TU limit, and the new counts. Correct the M6/M7.1 `.cinit`/debug/native-linker limitation text.
- [x] **Step 2: Run every gate** (M0, M2–M7.2; lit CodeGen + MC + clang Sema/CodeGen; GSPLNK oracle). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.2 makes the native path self-contained: `llc` objects carry `.cinit` and debug data, `tms-link` replaces GSPLNK for linking, and the GSPLNK image is the permanent oracle. M7.3 owns the wider Xlib surface, stderr capture and hardware; M7.4 the full external suites, performance and the final boundary. The compiler repo is canonical; the project holds the linker, harness, plans and gates.
@@ -0,0 +1,113 @@
# TMS34010 M7.3 — Runtime and Hardware (Wider Xlib, stderr, Hardware Harness) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Widen the validated VT1200 Xlib surface and exercise it in MAME, add real stderr capture to the conformance harness, and deliver the real-hardware marker harness with its MAME-equivalent acceptance while the unit is unavailable.
**Architecture:** The Xlib surface stays ROM-import based: each new entry is validated against the v2.2 image with `validate-syms.sh`, declared in `scripts/m4/x11m4.h`, and used by a new client (`xmore`) that MAME runs through the existing loader. The conformance shim gains a second sink and length cell for `stderr`, with the runner/check-lua comparing it exactly. The hardware harness is a thin wrapper around the already-proven `dwt/loader/hostload.py --marker` path: it links the marker client at the real-unit origins, validates the same marker cells in MAME, and invokes hostload only when `VT1200_HOST` is set.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), `tms-clang`, `llc`, GSPA/GSPLNK 2.00 under DOSBox, `tms-link`, TI COFF, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.3), §7.7 (Xlib/ROM imports), §7.9; the M7.2 plan/README boundary.
## Global Constraints
- Project work in `tms-c-compiler` (branch `m7`, base the M7.2 push `3dccc4d`); compiler unchanged (`3c39d1d82190`) unless a real target bug appears.
- Keep every M2–M7.2 gate green, the TI all-stack ABI, the asm oracle, the native path, and the default `m6` branch.
- New Xlib addresses must pass `scripts/m4/validate-syms.sh` (ROM range, 16-bit aligned, real prologue) and come from the Ghidra/dis34 table; never guess.
- stderr is a second stream: stdout bytes/markers stay byte-identical for existing tests; an empty stderr is the default.
- The hardware run is **DEFERRED**: the gate must pass without a unit (MAME-equivalent acceptance) and must not mark the milestone blocked. `VT1200_HOST` enables the real run.
- MAME + the loader are the acceptance environment. Run MAME gates serially.
- Red/green TDD; commit per task; no push until the M7.3 final review is clean.
## Review Focus
1. **Xlib correctness:** each new symbol address is justified and validated; the client uses the correct X11R4 argument shapes; markers prove the calls actually ran (not just returned); no X errors; existing xshow/termtris unchanged.
2. **stderr exactness:** separate buffer/length/magic, no aliasing with stdout, truncation semantics, runner comparison (`--expect-stderr` and `;stderr=`), empty default, and the selftest red cases.
3. **Hardware harness honesty:** the COFF uses the proven hardware origins, the marker cells match `hostload.py`, the MAME check reads the same cells, and the deferred path is explicit and non-blocking.
4. **No M2–M7.2 regression** and no change to the default linker/ABI.
---
### Task 1: Wider Xlib surface
**Files:**
- Modify: `symbols/vt1200-v22.syms` (new validated entries)
- Modify: `scripts/m4/x11m4.h` (prototypes/structs)
- Create: `scripts/m7/xmore.c`, `scripts/m7/xmore-check.lua`
- Create: `scripts/tests/m7/xlib.sh`
- Test: `scripts/m4/validate-syms.sh`, the existing xshow/termtris gates
**Interfaces:**
- Consumes: the v2.2 ROM import table and the M4 Xlib ABI (`Display`, `XImage`, events).
- Produces: validated `XMapSubwindows`, `XChangeWindowAttributes`, `XConfigureWindow`, `XInternAtom`, `XChangeProperty`, `XChangeGC` entries (addresses from `vendor/vt1200/dwt/notes/GUI_APPS.md`), prototypes, and an `xmore` client whose markers prove subwindow mapping, configure, atom/property changes, GC change, text (`XLoadFont`/`XDrawString`), drawing, and a heap `XCreateImage`/`XGetImage`/`XPutImage`/`XDestroyImage` round trip with no X errors.
- [x] **Step 1: Write the failing gate.** `xlib.sh` compiles `xmore.c` with `tms-clang`/`llc`, links via the M4 harness, loads it in MAME, and requires markers (window, child, GC, atom, property, configure, image, errors=0) plus a screenshot pixel check; `validate-syms.sh` currently rejects the new symbols.
- [x] **Step 2: Run red.** `validate-syms.sh` fails on the missing entries; `xmore` does not link.
- [x] **Step 3: Implement.**
- Add the six addresses with the GUI_APPS evidence; run `validate-syms.sh`.
- Declare the prototypes (`XWindowChanges`/`CW*` bits, `XInternAtom`, `XChangeProperty`, `XChangeGC` values) in `x11m4.h` without disturbing the existing ABI assertions.
- Write `xmore.c`: one parent + child, `XMapSubwindows`, `XConfigureWindow` (move/resize), `XInternAtom("WM_NAME")`, `XChangeProperty`, `XChangeWindowAttributes` (background), `XChangeGC` (foreground), `XLoadFont`/`XDrawString`, draw a rectangle/image, `XCreateImage` on the heap, `XGetImage` a small region, `XPutImage`, `XDestroyImage`, `XSync`; markers at `0x018A8000 + n*0x20`; error handler counts X errors.
- If a call is genuinely unusable (e.g. `XGetImage` blocks on the emulated server), keep it in the surface/test with a documented skip marker rather than silently dropping it.
- [x] **Step 4: Run green.** `xlib.sh`, `validate-syms.sh`, the M4 xshow/termtris/symbols gates, and the M7.2/M6/M5 gates touched by the harness.
- [x] **Step 5: Commit.**
### Task 2: stderr capture
**Files:**
- Modify: `scripts/tests/m5/conformance/shim.c` (stderr stream, fprintf/fputs/fputc/fwrite)
- Modify: `scripts/tests/m5/conformance/conformance-check.lua` (err_len/err buffer)
- Modify: `scripts/tests/m5/conformance/run.sh` (`--expect-stderr`, `;stderr=` parsing/comparison)
- Modify: `scripts/tests/m5/conformance/selftest.sh` (empty/formatted/truncated stderr cases)
- Test: the conformance selftest, c-testsuite/c-torture smoke, the M6 runtime gate
**Interfaces:**
- Consumes: the shim's `CONF_OUT`/`CONF_LEN`/`CONF_MAGIC` result block.
- Produces: `stderr` as a real `FILE *` target with `fprintf`/`vfprintf`/`fputs`/`fputc`/`fwrite`, a second buffer (`01B30000`, 16 KiB) and length (`01B00060`), runner expectation support, and selftests proving exact comparison and truncation rejection.
- [x] **Step 1: Write failing tests.** Add selftest sources that write `fprintf(stderr, ...)`; the runner rejects `--expect-stderr` (unknown option) and the shim has no stderr.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Represent `stdout`/`stderr` as distinct sink descriptors; `printf` continues the stdout stream; stderr has its own buffer/length and the same 16 KiB cap.
- Implement the write surface (return value = untruncated length, bytes capped) and `fprintf` via the existing formatter; declare `stderr` in the shim and any headers.
- Extend the check lua to read `ERRLEN`/`ERR` and write `errlen=`/`err=`; extend the runner's spec parser and comparison, preserving `stdout` defaults.
- Selftests: empty stderr passes; expected formatted stderr passes/fails correctly; `errlen >= CAP` is rejected as truncation.
- [x] **Step 4: Run green.** conformance selftest, the c-testsuite/c-torture gates (no changed stdout), the M6 runtime gate.
- [x] **Step 5: Commit.**
### Task 3: Real-hardware harness with MAME-equivalent acceptance
**Files:**
- Create: `scripts/m7/hwmark.c` (or `.s`), `scripts/m7/hw-entry.asm`
- Create: `scripts/tests/m7/hardware.sh`, `scripts/m7/hw-check.lua`
- Test: the M4/M5 loader path; `dwt/loader/hostload.py` dry contract; no real unit required
**Interfaces:**
- Consumes: the proven hardware origins (`.text 018C0000`, `.data 018D0000`, `.bss 018D8000`) and `hostload.py`'s `MARKER_CELLS` (`018E0000` start, `018E0020` data=0xDEADBEEF, `018E0040` data2=0x12345678, `018E0060` bss=0, `018E0080` live counter).
- Produces: a marker COFF (linked with `tms-link` or GSPLNK), a MAME run that checks the same cells through the loader, and a guarded real-hardware invocation: `VT1200_HOST=... scripts/tests/m7/hardware.sh` runs `hostload.py --marker --coff ...`; without it the gate prints `HARDWARE: DEFERRED` and passes on the MAME evidence.
- [x] **Step 1: Write the failing gate.** `hardware.sh` requires the marker cells in MAME and prints the deferred marker; no marker client exists yet.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Build the marker client at the hardware origins (entry sets STK/FP, calls `_main`, writes the sentinels and a live counter; `.data` holds the sentinels).
- MAME: link/load/run the same COFF (loader.lua + `hw-check.lua`), assert the five cells and loader status 0.
- Real path: invoke `dwt/loader/hostload.py` with `--coff`, `--marker`, `--host "$VT1200_HOST"`, and an evidence directory; propagate its failures. Do not fake a hardware pass; without the host, `HARDWARE: DEFERRED`.
- Document the unit's MAC/IP/host assumptions and the deferred status.
- [x] **Step 4: Run green.** `hardware.sh` (MAME + deferred), the M4/M5 native gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.3
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M0/M2–M7.3 list
- [x] **Step 1: Update the docs** for the wider Xlib table and client, the stderr protocol (`01B00060`/`01B30000`), the hardware harness/origins/deferred status, and the new gate counts.
- [x] **Step 2: Run every gate** (M0, M2–M7.3; lit; clang; conformance; generic; validate-syms; xshow/termtris). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.3 completes the runtime surface and makes the hardware campaign reproducible while the unit is away. M7.4 owns the full external suites, performance and the final M7 boundary. The compiler repo is canonical for target code; this project repo holds the Xlib table, harness, plans and gates.
@@ -0,0 +1,97 @@
# TMS34010 M7.4 — Conformance, Performance and the M7 Boundary Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close M7 with the full pinned external corpora, an i64 divide/remainder fast path with measured evidence, and the final M7 docs/counts/limitations/M8 boundary.
**Architecture:** A full-suite driver runs every file in the two pinned corpora through the existing conformance classifier and runner with the fast native loader settings, records per-test pass/skip/failure-category, and proves no unclassified crashes. The i64 division outliner gains a branch: when both operands' high words are zero it uses one 32-bit `DIVU`/`DIVS` (via i32 div/rem in IR) instead of the 64-step restoring loop; signed forms reuse the absolute-value normalization. A frame/cycle-based gate measures the small-divisor workload against the loop path.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), `tms-clang`, `llc`, `tms-link`, TI COFF, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`/FileCheck, the conformance harness, GCC 16.2.0/c-testsuite pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.4), §7.9; the M7.3 plan/README boundary.
## Global Constraints
- Project work in `tms-c-compiler` (branch `m7`, base the M7.3 push `54608c0`); compiler work in `build/llvm-clean` (branch `m7`, `bbec928ba807`).
- Keep every M2–M7.3 gate green, the TI all-stack ABI, the native path, the asm oracle, and the default `m6` branch.
- Full-suite runs use the pinned corpora under `vendor/conformance` and the fast loader settings (`LOADER_AT=200`, `LOADER_END=1000`) in `native` mode; the default conformance gates keep their existing settings.
- A test that is classifier-supported but fails must get an honest per-test skip reason or a recorded failure category; never count a skip as a pass. No MAME/loader crash.
- The i64 fast path must preserve every M6 i64 semantic (signed truncation, remainder sign, divide-by-zero undefined) and the existing `m6-i64.ll` checks.
- No push until the M7.4 final review is clean; default stays `m6`.
## Review Focus
1. **Full-suite honesty:** all 1,692 + 220 files accounted for; classifier-supported pass/skip/failure categories exact; no crash counted as pass; the report/log retained.
2. **Fast path correctness:** the high-word check, zero divisor, signed normalization, 64-bit results, and the slow path unchanged; `m6-i64` and the runtime gate green.
3. **Measurement:** the perf gate compares the fast path against a genuine slow-path workload, not a compile-time constant fold; the metric is reproducible.
4. **No regression** and the final docs/boundary are accurate.
---
### Task 1: Full-suite harness and baseline run
**Files:**
- Create: `scripts/tests/m7/full-suite.sh` (driver + report)
- Create: `scripts/tests/m7/full-suite.skip` (generated/triaged skip reasons; Task 3 fills failures)
- Test: the existing conformance runner/classifier; c-testsuite/c-torture smoke
**Interfaces:**
- Consumes: `vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute/*.c` (1,692) and `vendor/conformance/c-testsuite/tests/single-exec/*.c` (220), `scripts/tests/m5/conformance/{run.sh,classify.sh}`.
- Produces: `full-suite.sh [--corpus c-torture|c-testsuite|all] [--jobs 1]` with `LOADER_AT=200 LOADER_END=1000`, `--mode native`, per-test `pass/skip/fail:<category>` rows, a summary (`total/pass/skip/fail/crash`), and a retained log/report; a nonzero exit only on a crash or an unclassified failure.
- [x] **Step 1: Write the failing driver.** It builds sorted full lists, runs the runner with `--classify --mode native --expect-status 0 --ignore-output` (c-torture) and the `.expected` comparison (c-testsuite), and prints a summary. The first run has no triage file and fails on the known failing tests.
- [x] **Step 2: Run a bounded sample red.** Pick 20 c-torture files and show pass/skip/fail; the failing ones are the red evidence.
- [x] **Step 3: Implement.** Run tests serially (MAME); classify skips; categorize failures (compile/diagnostic, loader status, mismatch, timeout) into a stable `fail:<category>` form; write `full-suite-results.tsv`, `full-suite-report.txt`, and the per-test logs under a work directory; never treat a skip as a pass. Keep the default conformance gates untouched.
- [x] **Step 4: Run the full c-testsuite (220) and start/complete the full c-torture (1,692).** Record exact counts; the run may take hours, so retain the log and resume from completed rows if interrupted (idempotent per id).
- [x] **Step 5: Commit** the driver (and the initial results summary).
### Task 2: i64 divide/remainder fast path
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (`TMS34010LowerI64::lowerDivRem`)
- Modify: `llvm/test/CodeGen/TMS34010/m6-i64.ll` (fast-path checks) or create `m7-i64div-fast.ll`
- Create: `scripts/m7/i64div-perf.c`, `scripts/m7/i64div-perf-check.lua`, `scripts/tests/m7/i64div.sh`
- Test: `scripts/tests/m6/i64.sh`, the M6 runtime gate, `m6-i64.ll`
**Interfaces:**
- Consumes: the inline restoring-division outliner (`lowerDivRem`, 64 iterations) and the target `DIVU`/`DIVS`.
- Produces: a pre-check `(N >> 32) == 0 && (D >> 32) == 0`; on that path, `zext(udiv/urem (trunc N), (trunc D))` (32-bit `DIVU`) for unsigned, and for signed after the absolute-value normalization, with the same sign correction; the loop otherwise unchanged. A perf gate that measures a small-divisor workload (fast path) against a high-word-divisor workload (loop) using MAME frames/cycles or an equivalent instrumented counter.
- [x] **Step 1: Write failing tests.** `m7-i64div-fast.ll` requires the 32-bit `DIVU`/`DIVS` fast path (and the loop label still present); the perf gate requires the small-divisor workload to complete in materially fewer frames/iterations than the slow path. Current output has only the loop.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement** the fast path in `lowerDivRem`, keeping the zero-divisor undefined behavior, signed truncation and remainder sign; verify the IR/asm.
- [x] **Step 4: Run green.** The new lit test, the perf gate, `m6/i64.sh`, `m6/runtime.sh`, the M7.2/M7.3 gates.
- [x] **Step 5: Commit** (compiler + project).
### Task 3: Full-suite triage, skip curation and exact counts
**Files:**
- Modify: `scripts/tests/m7/full-suite.skip` (per-test honest reasons)
- Modify: `scripts/tests/m7/full-suite.sh` (summaries/categories)
- Create: `scripts/tests/m7/full-suite-report.txt` (retained)
- Test: the full-suite driver (idempotent resume), no crashes
**Interfaces:**
- Consumes: Task 1's per-test results.
- Produces: every failing test either fixed or skipped with a feature/curation reason; exact total/pass/skip/fail-category counts for both corpora; a retained report reproducible from the pins.
- [x] **Step 1: Triage** the failures by root cause; fix cheap target/driver issues; otherwise add a per-test `full-suite.skip` reason (one line each) and re-run only those.
- [x] **Step 2: Verify** the full results: no crash, no unclassified failure, every skip has a reason and is classifier-consistent.
- [x] **Step 3: Record the exact counts** and anomalies in the report.
- [x] **Step 4: Commit.**
### Task 4: Final M7 docs, full gates, final review, push M7.4/M7
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (M7 status)
- Test: the full M0/M2–M7.4 list
- [x] **Step 1: Update the docs** for the full-suite method/counts/skips, the i64 fast path and measurement, the complete M7 counts/limitations, and the M7/M8 boundary. Mark M7 complete (M8 owns multi-TU DWARF merging, `.lib` linking, hardware completion, remaining performance).
- [x] **Step 2: Run every gate** (M0, M2–M7.4; lit; clang; conformance; full suites; perf; generic). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.4 closes the conformance and performance surface and freezes the M7 boundary. M8 owns the remaining object/debug depth (multi-TU DWARF), `.lib` linking, the hardware run once the unit returns, and any further performance work.
@@ -0,0 +1,103 @@
# TMS34010 M8 — Native Archives, Multi-TU DWARF, Conformance Depth and Hardware Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close the M7/M8 boundary: make `tms-link` read the 1990 TI-COFF archives so the native path no longer needs GSPLNK for `flib`/`rts`, merge debug information from multiple translation units, deepen the conformance pass rate and performance evidence, and close out M8 with the hardware status and boundary.
**Architecture:** `tms-link` gains an `ar` reader with iterative selective extraction over its existing TI-COFF object model, then a DWARF merge stage that rehomes section-relative offsets and relocations across objects. The conformance/perf work uses the existing full-suite driver and the i64 measurement harness. The hardware harness already exists; M8.4 only runs it if the unit is available and records the result.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m8`), `tms-clang`, `llc`, `tms-link`, TI COFF and `ar` archives, the dwt loader, MAME, `dis34`, `llvm-dwarfdump`, Python 3, the conformance harness, GCC 16.2.0/c-testsuite pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M8.1–M8.4); the M7 README/ledger boundary.
## Global Constraints
- M8 baseline: compiler `llvm-tms34010` `m7` at `e924e0c86343`, project `tms-c-compiler` `m7` at `0f7353c`; work on `m8` in both repos. `m7` remains the repository default unless the user asks; no force-push and no merge into `m0`–`m7`.
- Keep every M2–M7.4 gate green, the TI all-stack ABI, the asm/GSPLNK oracle, and the native loader contract (`nreloc=0` linked image).
- `.lib` archives are test/runtime inputs; do not vendor them. The 1990 `flib.lib`/`rts.lib` are System V `ar` (`!<arch>`) with TI-COFF members.
- Debug merging must keep section-relative DWARF offsets correct; the default load image stays debug-stripped and `--keep-debug` is the tool image.
- Full-suite accounting remains one row per file; no crash/unclassified result; skips always carry a reason.
- No push until the M8 final review is clean; then push `m8`.
## Review Focus
1. **Archive correctness:** `ar` header/member parsing, long names, symbol resolution, iterative extraction, duplicate/undefined behavior, determinism, GSPLNK parity.
2. **DWARF merge correctness:** CU/abbrev/str/line/addr offset rehoming, relocations, section-relative values, dwarfdump validation, single-TU compatibility, stripped load image unchanged.
3. **Conformance honesty:** full accounting, flipped classes recorded, no hidden passes, performance measurement causal.
4. **No regression** and the final boundary accurate.
---
### Task 1: Native `.lib` linking in `tms-link`
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `tools/tms-link/tests/` archive fixtures/cases
- Modify: `scripts/m4/run.sh` (`M4_LINKER=tms-link` accepts `M4_NATIVE_LIBS`/`M4_NATIVE_RTS`)
- Test: `tools/tms-link/tests/run.sh`, `scripts/tests/m7/link.sh`, `scripts/tests/m5/native.sh`, `scripts/tests/m6/runtime.sh`, `scripts/tests/m6/i64.sh`
**Interfaces:**
- Consumes: `ar` archives with TI-COFF members (`build/m4-sdk/FLIB.LIB`, `RTS.LIB`), the existing object reader/linker, and the M4 hook.
- Produces: archive detection/reader; selective extraction of members that define currently-undefined symbols (iterated to a fixpoint); `-l`/path CLI support; duplicate definitions/undefined symbols/unsupported members loud; a linked image with the same section/loader contract.
- [x] **Step 1: Write failing tests.** A tiny archive fixture (2–3 members, one symbol each) linked by `tms-link`; a missing-symbol and a duplicate-definition negative; a `flib`-only program (e.g. `FD$ADD`) linked without GSPLNK; the current CLI does not read archives.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Parse `!<arch>\n`, 60-byte member headers, decimal sizes, even-byte padding, `/` and `//` special members, and `/N`/name forms; reject malformed archives loudly.
- Add archive members to the link as candidate objects; extract only members that define an undefined symbol, iterating (archive semantics), never re-extracting a member; duplicate/undefined symbols fail with names.
- CLI: accept `-l LIB` and archive paths; preserve object inputs, `--entry`, layout, map, debug strip/keep.
- `scripts/m4/run.sh`: allow `M4_LINKER=tms-link` with `M4_NATIVE_LIBS`/`M4_NATIVE_RTS`; pass library paths; keep GSPLNK the default and the oracle.
- [x] **Step 4: Run green.** Unit/archive tests; the M5 native and M6 runtime/i64 links with `tms-link` + libs; GSPLNK byte/symbol parity; MAME markers; one full native run. Do not regress non-library links.
- [x] **Step 5: Commit** (project; compiler unchanged unless a target bug appears).
### Task 2: Multi-TU DWARF merging
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `scripts/tests/m8/dwarf-multi.sh`, fixtures (`scripts/m8/debug-a.c`, `debug-b.c`, entry)
- Test: `scripts/tests/m7/debug.sh` (single-TU compatibility), `llvm-dwarfdump`, MAME
**Interfaces:**
- Consumes: multiple `--keep-debug`-capable debug-bearing objects from Task 1's linker and the M7 debug sections.
- Produces: merged `.debug_info`/`.debug_abbrev`/`.debug_str`/`.debug_str_offsets`/`.debug_line`/`.debug_addr` (and related) sections with rehomed section-relative offsets/relocations across CUs; single-TU output unchanged; loud failure on unsupported shapes.
- [x] **Step 1: Write failing tests.** Two TUs with functions/lines, linked `--keep-debug`; the current linker refuses >1 debug object. Wrap the sections in the test ELF container and require `llvm-dwarfdump` to show both TUs' files/functions/lines/addresses.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Concatenate `.debug_info`/`.debug_line`/etc. while relocating each object's section-relative contributions: `.debug_abbrev` offsets in CU headers, `.debug_str_offsets` bases, `.debug_addr` bases, `.debug_line`/`.debug_line_str` offsets, and cross-section relocations to allocated sections.
- Resolve relocations against the linked section layout; keep debug sections section-relative (paddr 0), `nreloc=0`.
- Preserve the single-debug-TU output; refuse unsupported DWARF shapes loudly.
- [x] **Step 4: Run green.** Multi-TU dwarfdump, single-TU `m7/debug.sh`, the stripped image in MAME, the M7.2 gates.
- [x] **Step 5: Commit.**
### Task 3: Conformance depth and performance
**Files:**
- Modify: the relevant target lowering/tests for fixed classes; the full-suite skip file; the perf driver if extending it
- Test: `scripts/tests/m7/full-suite.sh` (accounting), `scripts/tests/m7/c-torture.sh`/`c-testsuite.sh`, `scripts/tests/m7/i64div.sh`
**Interfaces:**
- Consumes: the M7.4 full-suite baseline (1,576 pass / 336 skip / 0 fail / 0 crash).
- Produces: additional fixed classes with flipped counts, an updated honest skip list, and at least one new measured performance path (e.g. 64/32 i64 division when the divisor fits 32 bits).
- [x] **Step 1: Pick the highest-value classes** from the retained skip classes (rotates/`cttz`/`bswap`/`blockaddress`; inline-asm constraints; one ABI return shape; one timeout/image-size case) and write failing lit/runtime tests.
- [x] **Step 2: Implement** the fixes, update the skip curation only where the class remains a genuine M8/M9 boundary, and re-run the affected full-suite rows.
- [x] **Step 3: Performance:** implement and measure the 64/32 fast path (or an equally justified path) against the existing slow path; record frames/checksums.
- [x] **Step 4: Run green** and record the new exact counts/flips.
- [x] **Step 5: Commit.**
### Task 4: Hardware status, final M8 docs, full gates, final review, push
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, the spec (M8 status)
- Test: the full M0–M8 list
- [x] **Step 1: Hardware.** If the VT1200 is available, run `VT1200_HOST=… scripts/tests/m7/hardware.sh` and record the real-unit evidence; otherwise keep `HARDWARE: DEFERRED` explicit. Do not fake a pass.
- [x] **Step 2: Docs.** Record M8.1/M8.2/M8.3 results, the final full-suite/perf counts, the remaining limitations, and the M8/M9 boundary.
- [x] **Step 3: Gates and review.** Run the full serial list, commit, final whole-branch review, then push `m8` (default stays `m7` unless asked).
---
## Execution Handoff
M8.1 makes the native path library-complete; M8.2 makes debug info multi-TU; M8.3 raises the conformance/performance surface; M8.4 closes the milestone with the hardware status and boundary. The compiler repo remains canonical for target code; the project holds the linker, harness, plans and gates.
@@ -0,0 +1,101 @@
# TMS34010 M9 — Conformance Classes, Debug Depth and Performance Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Raise the full-suite pass rate with the highest-value remaining classes, close the M8 DWARF/linker caveats, add a measured 64/32 divide fast path, and close M9 with the hardware status and boundary.
**Architecture:** Vector `.data` becomes another recursive aggregate in both the raw and object emitters; the target supplies an inline-asm register resolver for the A-register classes. The linker gains a form-aware DWARF input check (or walker) plus `.debug_rnglists` merging. The i64 outliner adds a single-DIVU 64/32 path when the quotient fits. The bare conformance tier and the full-loader list remain the two-tier harness.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m9`), `tms-clang`, `llc`, `tms-link`, TI COFF, the dwt loader, MAME, `llvm-dwarfdump`, Python 3, the M8 two-tier harness and pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M9.1–M9.4); the M8 README/ledger boundary.
## Global Constraints
- M9 baseline: compiler `m8`/`e3ad91edd130`, project `m8`/`f340d74`; work on `m9`. The default is promoted to `m9` only after the final review.
- Keep every M2–M8.4 gate green, the TI all-stack ABI, the asm/GSPLNK oracle, the native loader contract, and the two-tier harness.
- `M5_CONFORMANCE_BARE=1` remains the conformance default; full-loader exceptions need a reason in `full-suite.full-loader`.
- Vector and inline-asm changes must be tested at `-O0` and `-O2`; unsupported shapes stay loud.
- DWARF merging must stay section-relative and stripped-image compatible; single-TU output remains byte-compatible with M8.
- Full-suite accounting remains one row per file; no crash/unclassified result; skips always carry a reason.
- No push until the M9 final review is clean; then push `m9`, promote it, and update the README.
## Review Focus
1. **Vector bytes:** exact element order/padding for integer/fp vectors, packed widths, aggregate zero, raw and object paths; no over-read/write; existing scalar/record output unchanged.
2. **Inline asm:** constraint mapping for i16/i32, clobbers, output/input ties, unsupported constraints loud; `-O0`/`-O2`.
3. **DWARF:** form walker completeness, rnglists merging, offset rehoming, single-TU compatibility, dwarfdump and stripped MAME.
4. **Divide:** 64/32 condition and quotient-fit, magnitudes/sign, `INT64_MIN`, divide-by-zero, measured frames/checksums, no M8 path regression.
5. **No M2–M8.4 regression**, two-tier counts, and the final boundary.
---
### Task 1: Vector `.data` and inline-asm `r` constraints
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010AsmPrinter.cpp` (raw/object vector initializers)
- Modify: `llvm/lib/Target/TMS34010/TMS34010ISelLowering.{h,cpp}` (inline-asm register resolver)
- Create/modify: `llvm/test/CodeGen/TMS34010/m9-vector-data.ll`, `m9-inline-asm.ll`
- Test: `scripts/tests/m7/data.sh`, the full-suite vector/inline-asm rows, M6/M5 gates
**Interfaces:**
- Consumes: the recursive `.data` emitter and the A-register classes (`ARegs`, `ARegsEven`, …).
- Produces: exact vector initializer bytes (integer/fp element vectors, aggregate zero, byte-multiple only) in raw and object modes; `getRegForInlineAsmConstraint` mapping `r`/`=r` (and documented accepted subsets) to the target register classes; unsupported vectors/constraints loud.
- [ ] **Step 1: Write failing tests.** `m9-vector-data.ll` with `<2 x i32>`, `<4 x i16>`, an fp vector if supported, and a vector zero; `data.sh` raw/object bytes. `m9-inline-asm.ll` with `r` input/output at `-O0`/`-O2`. Current emitter rejects vectors; inline asm fails to allocate.
- [ ] **Step 2: Run red.**
- [ ] **Step 3: Implement.** Vector constants as ordered element bytes with exact alloc size; `ConstantAggregateZero` vector zero; keep unsupported widths/types loud. Implement the inline-asm resolver and clobber handling; reject unsupported constraints with a named error.
- [ ] **Step 4: Run green.** Lit, data.sh, and the affected full-suite rows (bare/full-loader as appropriate); record flips.
- [ ] **Step 5: Commit** (compiler + project gates/tests).
### Task 2: DWARF form walker and `.debug_rnglists`
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `scripts/tests/m9/dwarf-ranges.sh`, fixtures
- Test: `scripts/tests/m8/dwarf-multi.sh`, `scripts/tests/m7/debug.sh`, `llvm-dwarfdump`
**Interfaces:**
- Consumes: M8's multi-TU debug merge and the current CU-abbrev-only raw patch.
- Produces: a form-aware check/walker that rejects (or correctly patches) unrelocated section-relative fields, and `.debug_rnglists` concatenation/rehoming with a fixture; single-TU bytes unchanged.
- [ ] **Step 1: Write failing tests.** A synthetic object with an unrelocated `DW_AT_stmt_list`/`strp` (or a documented rejection), and a multi-TU `.debug_rnglists` fixture; current code silently assumes relocations.
- [ ] **Step 2: Run red.**
- [ ] **Step 3: Implement** the form walk (or input gate) and rnglists merge; keep the loud paths.
- [ ] **Step 4: Run green.** `dwarf-ranges.sh`, `dwarf-multi.sh`, `m7/debug.sh`, stripped MAME.
- [ ] **Step 5: Commit.**
### Task 3: 64/32 single-DIVU fast path
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (`lowerDivRem`)
- Create/modify: `llvm/test/CodeGen/TMS34010/m9-i64div-64-32.ll`
- Modify: `scripts/m7/i64div-perf.c`, `scripts/tests/m7/i64div.sh`
- Test: `scripts/tests/m6/i64.sh`, `m6/runtime.sh`, `i64div.sh`
**Interfaces:**
- Consumes: the M8 fast/wide/loop CFG and the target `DIVU` 64-bit pair.
- Produces: when the divisor's high word is zero and the quotient fits 32 bits (e.g. `hi(N) < D`), a single even-destination `DIVU` fast path; otherwise the M8 two-DIVU/loop path. Signed normalization and fixups unchanged.
- [ ] **Step 1: Write failing tests.** A 64/32 case with `hi(N) < D` requiring one `DIVU`; the M8 wide cases still two; perf phase measured.
- [ ] **Step 2: Run red.**
- [ ] **Step 3: Implement** the single-DIVU branch; preserve `INT64_MIN`, divide-by-zero UB and signs.
- [ ] **Step 4: Run green.** Lit, M6 i64/runtime, i64div measurements; record frames/checksums.
- [ ] **Step 5: Commit.**
### Task 4: Hardware status, final M9 docs, full gates, review, promote
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, spec (M9 status)
- Test: the full M0–M9 list
- [ ] **Step 1: Hardware.** Run `VT1200_HOST=… scripts/tests/m7/hardware.sh` if a unit is available; otherwise keep `HARDWARE: DEFERRED`.
- [ ] **Step 2: Docs.** Record M9.1/M9.2/M9.3 results, flips, perf, the final two-tier counts and the M9/M10 boundary; update the gate commands.
- [ ] **Step 3: Gates and review.** Run the full serial list, commit, final whole-branch review, then push `m9`.
- [ ] **Step 4: Promote.** Set `m9` as the repository default on both remotes (per the standing policy), update the README/docs default language, and verify `refs/heads/m9` is HEAD.
---
## Execution Handoff
M9 closes the highest-value conformance classes, the DWARF future-producer and rnglists caveats, and adds a measured 64/32 divide fast path. The remaining classes (`blockaddress`, nested functions, VLAs, sret/aggregate/variadic/float returns, libm), broader hardware/link depth and any further performance work are M10. The compiler repo is canonical; the project holds the linker, harness, plans and gates.
@@ -71,11 +71,13 @@ early GEP-scaling pass.
- Registers: A0–A12 general, A8 return value, A13 FP, A14 STK (program stack),
A15 system stack. B0–B14 are unused by TI's C compiler.
- Caller: if arguments are passed or a float/double is returned, push the old
STK on the system stack (`MOVE STK,-*SP`); push arguments on the program
stack in reverse order, widened to 32 bits; structs by value rounded to
16 bits; struct return address pushed on the program stack; call with
`CALLA` (direct) or `CALL Rs` (indirect).
- Caller: if arguments are passed or a float/double/`i64`/aggregate is
returned, push the old STK on the system stack (`MOVE STK,-*SP`); reserve
the hidden return slot (if any) at the top of the program stack **before**
saving STK; push arguments on the program stack in reverse order, widened
to 32 bits; structs by value rounded to 16 bits; call with `CALLA` (direct)
or `CALL Rs` (indirect). There is no `sret` pointer argument in the TI
ABI.
- Callee: save used A registers except A8 on the system stack (`MMTM SP,…`);
set `FP = STK`; `ADDI frame_size,STK`; locals at positive FP offsets, first
argument at `FP(-32)`; restore STK from `*SP(offset)`; `MMFM`; `RETS 2` if
@@ -83,9 +85,14 @@ early GEP-scaling pass.
- `FS1` must be 32 inside C code and `FS0` must be 16 with its field-extension
bit set (`SETF 16,1,0`, sign-extending); both must be re-established after
every call because Xlib may change the field-size state.
- Struct return: caller allocates, pushes the address; callee copies. Float/
double return: caller allocates space on the program stack, callee copies.
(C guide §5.3.)
- Hidden returns: the caller reserves `alignTo(size,2)` bytes at the top of
the program stack (before saving STK) for a struct/union, `float`/`double`
or `i64` result; the callee copies the object bytes to `saved_STK-size`
(the top of the slot) and ends `RETS 2`; the caller copies the bytes out
and releases the slot. The caller does not push a return address. Float/
double and `i64` use the same rule with a 4/8-byte object. (The 1987
`_mkbig`/`_callbig` oracle in the plan and `TMS34010.md` binds this form;
it supersedes the earlier sret wording in this document.)
- Symbols use a leading underscore (`_main`); sections are `.text`, `.data`,
`.bss`; code is position-dependent and linked at fixed bit addresses.
@@ -263,16 +270,22 @@ non-constant pointer expression by 8×.
- Custom calling convention `CC_TMS34010`.
- `LowerFormalArguments` / `LowerCall` / `LowerReturn` implement the caller and
callee rules in §4.2 exactly; `sret` and `byval` follow the TI layout.
callee rules in §4.2 exactly; `byval` follows the TI layout. An explicit
`sret` pointer is rejected: aggregate returns use the hidden slot above.
- **Explicit arguments**: pushed on the program stack (A14) in reverse order,
each widened to 32 bits. The first explicit argument is at `FP(-32)`, the
second at `FP(-64)`, etc.
- **Struct return**: the caller pushes the return-space address **after** the
explicit arguments, so it is the top program-stack slot: the callee reads it
at `FP(-32)` and the first explicit argument is at `FP(-64)`.
- **Hidden return slot**: for a struct/union, `float`/`double` or `i64`
result, the caller reserves `alignTo(size,2)` bytes at the top of its own
frame **before** saving STK and passes no return pointer. The callee
writes the object at `saved_STK-size` (= `FP-(argbytes+size)`) and ends
`RETS 2`; the caller copies the bytes out and releases the slot with
`ADDI -size,STK`. This is the 1987 `_mkbig`/`_callbig` form and supersedes
the earlier sret wording; an explicit `sret` argument is rejected.
- **Old STK**: the caller saves A14 on the system stack only when it passes
arguments or the callee returns a float/double. A no-argument function with
locals has no saved old STK; the callee restores STK from FP before `RETS 0`.
arguments or the callee returns a `float`/`double`/`i64`/aggregate through
the hidden slot. A no-argument function with locals has no saved old STK;
the callee restores STK from FP before `RETS 0`.
- **System stack layout** (grows down), after the callee's `MMTM` of `n`
registers:
@@ -434,13 +447,268 @@ appears in MAME (real unit when available).
no X errors.
**M5 — robustness and native path.** `memcpy`, `alloca`, `byval`, varargs
(`sprintf`), floats, bitfields, `long long`; native COFF and debug info.
(`sprintf`), floats, bitfields, `long long`; native COFF and debug info
(debug info was re-scoped to M6 below, then moved to **M7** by the M6
plan/ledger ruling).
> **M5 re-scoped (2026-11-13):** floats/double, bitfields, `long long`/i64,
> **M5 re-scoped (2026-11-13):** floats/double, bitfields, `long long`/i64 and
> general varargs (`va_list`/`va_start`/`va_arg` beyond the contiguous
> `sprintf` form) and debug info are **M6**. M5 delivers the integer/pointer
> native object path, `alloca`/`byval`/narrow returns, `memcpy`/`memset`/
> `memmove`, `JR`/`MMTM`, and the curated conformance tier.
> `sprintf` form) are **M6**. M5 delivers the integer/pointer native object
> path, `alloca`/`byval`/narrow returns, `memcpy`/`memset`/`memmove`,
> `JR`/`MMTM`, and the curated conformance tier. **Debug info is M7** per
> the M6 plan and ledger ruling (`progress.md`), not M6.
### M7 — correctness residuals, object/debug, hardware, conformance
M7 closes the M6 boundary in four sequential sub-milestones. Each has its own
design/plan, subagent-driven execution, task reviews, final whole-branch
review, and a push of the `m7` branch (default unchanged unless the user
asks). M2–M6 remain binding.
- **M7.1 — correctness and ABI residuals.** (a) The `-O2` bit-pointer
semantic barrier: `tms-clang` scales GEPs to calls to an opaque
`@__tms_bitptr(i32 bitoff, ptr base)` before the optimizer, scales only the
optimizer-created byte GEPs afterwards, then lowers the bitptr calls to
`inttoptr(add(ptrtoint,...))` and runs a final instcombine. This removes the
`p += n` over-scale while preserving the M0 `int_diff = 8/32` contract; the
shim `memmove` workaround is removed. (b) The sub-byte array/nested-record
stride: emit a loud, default-on diagnostic for arrays and nested members of
records whose bit content is not a byte multiple (TI advances by the bit
content; Clang's byte-rounded `sizeof` would silently diverge), or implement
the bit-content stride if a sound lowering is found. (c) `.data`
initializers for i64, aggregates/unions and bitfield globals, including the
object path and relocations; i64 words are little-endian/least-significant
first. (d) Keep the nonzero byte-offset narrow-load/store guard.
- **M7.2 — object/debug.** (a) Debug info in the native TI-COFF object:
`llc -march=tms34010 -filetype=obj` on a module with `!dbg` metadata emits
DWARF line/source sections (`.debug_info`, `.debug_abbrev`, `.debug_line`,
`.debug_str`, and the auxiliary sections LLVM produces) as non-allocated
COFF sections; long section names use the COFF `/offset` string-table form.
The native linker resolves their relocations and, by default, strips them
from the load image; `--keep-debug` retains them for tools. M7.2 supports one
debug-bearing object per link (multi-TU DWARF merging is loud, M8); the
`tms-link --map` output includes the section allocation and global symbol
map; source-line information lives in the kept `.debug_line` sections and is
dumped/validated with `llvm-dwarfdump` (Task 3), not parsed by the linker. (b) `tools/tms-link`
is a native TI-COFF linker: it reads relocatable objects, resolves public
symbols including names longer than GSPA's 31-character limit, lays out
`.text`/`.data`/`.cinit` in the `prog` region and `.bss` in `ram`, applies
the R-RELLONG fixups, and emits a position-dependent linked COFF with
`nreloc = 0`, an optional header (entry, text/data/bss start and size) and a
map. `.cinit` is a first-class section (TI init-record table: u16 word count,
u32 destination, data words), placed after `.data`; the linker defines the
public `cinit` symbol. (c) Object-path gates compare `tms-link` output with
GSPLNK for the same objects (byte-identical allocated sections, identical
symbol addresses, same MAME markers) and cover `.cinit`, >31-character
public names, and a `llvm-dwarfdump`-validated debug image.
M7.2 acceptance: `llc -filetype=obj` emits a debug-bearing TI-COFF whose
`.debug_*` sections validate with `llvm-dwarfdump` after the linker keeps them;
the default linked image is debug-stripped and the loader/MAME acceptance is
unchanged; `tms-link` links the M5 native objects with allocated-section
bytes and symbol addresses equal to GSPLNK (the M6 gates continue to link
with GSPLNK; both use the same object writer); a C `.cinit` table is placed,
relocated and processed by an entry in MAME; two TUs with a 40-character public
function link and run; every M2–M7.1 gate stays green.
- **M7.3 — runtime and hardware.** (a) The wider Xlib surface: add the
remaining ROM-validated entries from the Ghidra/dis34 table
(`XMapSubwindows`, `XChangeWindowAttributes`, `XConfigureWindow`,
`XInternAtom`, `XChangeProperty`, `XChangeGC`), extend `x11m4.h`, and add a
client (`xmore`) that exercises them together with text (`XLoadFont`,
`XDrawString`), drawing, and a heap image (`XCreateImage`/`XGetImage`/
`XPutImage`/`XDestroyImage`), with MAME markers and no X errors;
`scripts/m4/validate-syms.sh` validates every added address. (b) stderr
capture: the conformance shim exposes a distinct `stderr` stream
(`fprintf`/`fputs`/`fputc`/`fwrite`) into a second buffer/length cell, the
runner and MAME check compare it (`--expect-stderr`/`;stderr=`), and
selftests cover empty, non-empty and truncated stderr. (c) Real-hardware
validation for the VT1200: a harness builds the marker client at the proven
hardware origins (`018C0000`/`018D0000`/`018D8000`), runs the same COFF in
MAME (the permanent acceptance), and, with `VT1200_HOST` set, drives
`dwt/loader/hostload.py --marker` over rdebug against the real unit. The
unit is unavailable for the first two weeks, so the hardware run is
**DEFERRED** and does not block M7; the harness and its MAME-equivalent
acceptance are delivered now.
M7.3 acceptance: `xmore` runs in MAME with the expected markers and no X
errors, and every added Xlib address passes `validate-syms`; the stderr
selftests prove empty, formatted and truncated stderr; the hardware gate
passes its MAME marker check and reports `HARDWARE: DEFERRED` without a unit
(the same command runs `hostload.py --marker` when `VT1200_HOST` is set); every
M2–M7.2 gate stays green.
- **M7.4 — conformance and performance.** (a) Full external suites: run the
pinned GCC 16.2.0 `gcc.c-torture/execute` corpus (1,692 files) and the
c-testsuite `single-exec` corpus (220) beyond the curated lists, at `-O0`
with the conformance classifier; every test is pass, an honest
feature/curation skip with a reason, or a recorded failure category — never
an unclassified crash. The bounded `-O2` subsets stay as the optimization
smoke tier. (b) Performance: an i64 divide/remainder fast path that, after
the signed absolute-value normalization, uses one 32-bit `DIVU` when both
normalized high words are zero instead of the 64-step restoring loop (the
signed forms divide magnitudes, so they also select `DIVU`), with the same
quotient/remainder sign fixup, unit/asm coverage, the M6 i64 gate, and a
cycle/frame-based measurement gate. (c) Final M7
docs, exact counts, known limitations, and the M7/M8 boundary (M8 owns
multi-TU DWARF merging, `.lib` linking, the real VT1200 run if still
deferred, and any remaining performance work).
M7.4 acceptance (met, M7 complete): the full pinned corpora account for
**1,912** files — c-torture **1,692 = 1,366 pass / 326 skip / 0 fail / 0
crash** and c-testsuite **220 = 210 pass / 10 skip / 0 fail / 0 crash** —
with every skip carrying a classifier or curation reason and the 272 curated
rows re-run without skips (272/272 still failed). The i64 fast path uses one
32-bit `DIVU` when both normalized operands' high words are zero; the
implementation divides magnitudes for the signed forms as well, so `DIVU` is
emitted and `DIVS` is not (this matches the M6 loop's unsigned
compare/subtract). The MAME measurement is `fast_frames=90 slow_frames=2424
ratio=26.9` for the same 16,384 iterations, status `600D600D`, checksums
`000000011E6F9AB4`/`00000000007512AE`. Every M2–M7.3 gate stays green; lit is
**118/118** (114 CodeGen + 4 MC) and the shipped c-testsuite tier remains the
curated 48 pass / 172 skip. The real VT1200 run is still **DEFERRED**; M8
owns multi-TU DWARF merging, `.lib` linking under `tms-link`, the hardware
run, the remaining conformance classes and further performance work.
M7.1 acceptance: the `p += n` shape is correct at the default `-O2` with one
scale; M0 `int_diff` 8/32; the stride diagnostic fires for the oracle shapes
and not for byte-multiple records; `.data` i64/aggregate/bitfield globals
assemble/link/load with exact bytes; every M2–M6 gate stays green; MAME and
the dwt loader are the acceptance environment.
### M8 — object/link completeness, conformance depth, hardware
M8 closes the M7/M8 boundary in four workstreams, using the same plan,
subagent-driven execution, review and push discipline as M7. The `m7` branch
is the M8 baseline and the repository default; M8 work is on `m8` and does not
change the default unless the user asks.
- **M8.1 — native `.lib` linking.** `tools/tms-link` reads System V/`ar`
archives (the 1990 `flib.lib`/`rts.lib` are `!<arch>` with TI-COFF members),
performs iterative selective extraction of members that define needed
symbols, resolves duplicate/undefined symbols loudly, and exposes the
libraries through the CLI and the `M4_LINKER=tms-link` path. GSPLNK remains
the oracle; the M5/M6 native and runtime gates must produce the same
allocated bytes/symbol addresses (and MAME markers) with either linker.
Acceptance: M4/M5/M6 native links that need `flib`/`rts` link with
`tms-link`, produce a loader-accepted image with the expected markers, and
match GSPLNK on the allocated image; unmatched/duplicate archive symbols
fail loudly.
- **M8.2 — multi-TU DWARF merging.** The native linker merges debug
information from multiple debug-bearing objects: concatenate `.debug_info`
CUs while adjusting `.debug_abbrev`/`.debug_str_offsets`/`.debug_addr`/
`.debug_line` section-relative contributions and their relocations; keep
section-relative offsets correct, resolve line/file tables, and validate the
result with `llvm-dwarfdump`. The default load image remains debug-stripped;
`--keep-debug` is the tool image. Acceptance: a two- or three-TU program
built with debug info links with `--keep-debug`, `llvm-dwarfdump` reports
every TU's functions/lines/addresses, and the stripped image still runs in
MAME; a single-TU link remains byte-compatible with M7.
- **M8.3 — conformance depth and performance.** Raise the full-suite pass
rate by fixing or honestly re-curating the remaining classes (codegen
rotates/`cttz`/`bswap`/`blockaddress`/vectors, inline-asm constraints,
sret/aggregate/variadic/float returns, VLAs, nested functions, libm and the
frame-limited timeouts), and extend performance work beyond the 32-bit i64
fast path (e.g. a 64/32 path when the divisor fits 32 bits) with measured
evidence. Acceptance: the full pinned corpora still account for every file
with 0 unclassified crashes and an honest skip list; the newly fixed classes
flip to pass and are recorded; any new performance path is measured against
the existing slow path.
- **M8.4 — hardware and close-out.** Run the real VT1200 hardware harness when
the unit is available (the harness and MAME-equivalent acceptance already
exist), record the real-unit evidence, and produce the final M8 docs/counts/
limitations and the M8/M9 boundary. The hardware run remains deferred and
does not block M8.1–M8.3; if it is still unavailable, mark it deferred and
state that explicitly.
M8.3 also runs the corpora on a bare-metal MAME tier by default (sections
mapped, `.bss` zeroed, PC/SP set, no firmware/loader), using the 2ine-hosted
1990 OS/2 assembler and `tms-link`; the curated M5/M6 loader gates, X11/runtime
and an explicit full-loader exception list keep the loader tier. The accounting
and acceptance counts are unchanged.
M8.1 acceptance: a library-only link (no GSPLNK) resolves the needed members
and runs; M8.2 acceptance: multi-TU debug links and validates; M8.3
acceptance: the full corpora remain fully accounted with the recorded flips;
M8.4 acceptance: the final docs/boundary are accurate and the hardware status
is explicit.
M8 acceptance (met, M8 complete): `tms-link` reads the System V `ar`
`FLIB.LIB`/`RTS.LIB`, extracts needed members iteratively and links the M4/M5/
M6 library programs with allocated bytes, section metadata and public symbols
equal to GSPLNK 2.00 (`scripts/tests/m8/native-lib.sh`, 3 sections, 16 public
`C_EXT` addresses, MAME markers). Multi-TU `--keep-debug` concatenates and
rehomes the supported DWARF5 sections; `llvm-dwarfdump` shows both TUs'
functions, lines and linked PCs, the stripped image runs in MAME, and the
single-TU link is byte-identical to M7 (`scripts/tests/m8/dwarf-multi.sh`).
The bit-op class (rotate/`cttz`/`ctpop`/`ctlz`/`bswap`) lowers without invented
instructions. At M8 the three-phase gate measured the 64/32 i64 divide path at
**218** frames versus **2,440** for the 64-step loop (11.2×) and the fits-32
path at **87** (28.0×), status `600D600D`, checksums
`000000011E6F9AB4`/`00000000007512AE`/`00025AF70AF974E0`; M9.3 makes the gate
four-phase, narrows the wide input to force the two-`DIVU` helper, and re-pins
the wide checksum (see the M9 acceptance). The fresh end-to-end full suite
accounts for **1,912 = 1,596 pass / 316 skip / 0 fail / 0 crash** (c-torture
**1,386 / 306**, c-testsuite **210 / 10**), with 64 classifier plus 252
curated skips, each with a reason; the 20 flipped rows are the six rotates,
six `cttz`, four `bswap` and four per-test `LOADER_END=2000` runtime rows.
Lit is **120/120** (116 CodeGen + 4 MC) and clang Sema/CodeGen **5/5**. The
real VT1200 run remains **DEFERRED** (`VT1200_HOST` unset; the hardware gate
prints `HARDWARE: DEFERRED` on the MAME-equivalent acceptance). M9 closed vector
`.data` and inline-asm `r`, the DWARF future-producer/`.debug_rnglists`
caveats and the 64/32 divide path; M10 owns the remaining classes
(`blockaddress`, vector runtime, inline-asm memory constraints, nested
functions, VLAs, sret/aggregate/variadic/float returns, libm, runtime aborts),
the pre-existing `pr63843` hang, further performance work and the real VT1200
run when the unit is available.
### M9 — conformance classes, debug depth, performance
M9 builds on the M8 baseline (`m8`, default) and uses the same plan,
subagent-driven loop, review and push discipline. Work is on `m9`; the default
is promoted to `m9` only after the final review, per the repository policy.
- **M9.1 — conformance classes.** Remove the highest-value remaining M8 skips:
vector `.data` initializers (integer/fp vector constants emitted as their
exact element bytes in the raw and object paths) and inline-asm `r`/`=r`
register constraints (map the target's A-register classes; reject
unsupported constraints loudly). The affected full-suite rows must flip to
pass and be recorded; `blockaddress`, nested functions, VLAs, sret/
aggregate/variadic/float returns and libm remain explicit M10 boundaries.
- **M9.2 — debug/linker depth.** Replace the M8 raw-offset assumption with a
form-aware DWARF walker (or an input gate that rejects any unrelocated
section-relative field), add a `.debug_rnglists` fixture and merged-range
validation, and keep the single-TU output byte-compatible. The default load
image stays stripped; `--keep-debug` remains the tool image.
- **M9.3 — performance.** Add a single `DIVU` 64/32 fast path when the divisor
fits 32 bits and the quotient fits (or another equally justified path),
measured against the M8 64/32 two-DIVU path and the 64-step loop. The bare
conformance tier remains the default; no test-accounting regression.
- **M9.4 — hardware and close-out.** Run the real VT1200 harness when the unit
is available; otherwise keep `HARDWARE: DEFERRED` explicit. Produce the final
M9 docs/counts/limitations and the M9/M10 boundary.
M9 acceptance (met, M9 complete): vector `.data` and inline-asm `r`/`=r`
constraints are fixed with **22** recorded flips (20 inline-asm `r`, `simd-5`
and `pr123625-2`), and the five remaining candidates stay curated with
corrected reasons (i64 `r` pair, timeout, two vector runtime aborts, memory
operand). Lit is **129/129** (125 CodeGen + 4 MC). The multi-object
`--keep-debug` path walks every form and refuses pre-v5 producers and any
unrelocated section-relative field loudly; the two-TU `.debug_rnglists`
fixture and a real `-O2 -g` producer both validate with `llvm-dwarfdump`, the
single-TU bytes keep the M8 layout, and the stripped image still runs. The
four-phase i64 gate measures fast **88**, slow **3,302**, wide **221** and
div32 **120** frames — **37.5×** (fast) and **14.9×** (wide) versus the loop,
and **1.8×** for div32 versus the two-DIVU wide phase — with
status `600D600D` and checksums `000000011E6F9AB4`/`00000000007512AE`/
`F56810CFEDA9D656`/`00002C61C63842EE`; the new path is correct for
signed/unsigned, divide-by-zero UB, and `INT64_MIN` (which never fits 32 bits:
it keeps the two-step helper for a divisor of at most `2^31` and takes the
single-`DIVU` path for a divisor in `(2^31, 2^32)`). The fresh two-tier full
suite accounts for every file: **1,912 = 1,618 pass / 294 skip / 0 fail / 0
crash** (c-torture **1,408 / 284**, c-testsuite **210 / 10**), with every skip
carrying a reason and the 10 full-loader exceptions explicit. Every M2–M8.4
gate stays green and the new M9 lit/DWARF gates pass, while the real VT1200
run remains **DEFERRED**. M9 is complete; the remaining classes are the M9/M10
boundary.
## 9. Risks and mitigations
+236
View File
@@ -0,0 +1,236 @@
#!/usr/bin/env python3
"""Validate (and repair) a linked TI-COFF image for the VT1200 loader.
GSPLNK 2.00 has two observed output shapes that the loader rejects:
* when the test object has no initialised .data, it writes a fully zeroed
20-byte file header + 28-byte optional header, while the section table at
byte 48 is valid (loader status 3, "bad COFF magic");
* an odd-length .bss makes the section's bit size not a whole word (loader
status 4, "section size not whole words").
This helper validates the magic, the section table and the section sizes. With
--repair it reconstructs the zeroed header/optional header from the intact
section table and the linker map entry point, and rounds only .bss up to a
16-bit word. It never touches .text/.data contents or the entry point.
Usage: coff-check.py [--repair] [--entry HEX] FILE
"""
import argparse
import struct
import sys
FILE_MAGIC = 0x0090
OPT_MAGIC = 0x0108
OPT_VERSION = 0x00C7
FILE_FLAGS = 0x0103
OPT_HDR_SIZE = 28
ZERO_HEADER_SIZE = 20 + OPT_HDR_SIZE
def u16(data, off):
return struct.unpack_from("<H", data, off)[0]
def u32(data, off):
return struct.unpack_from("<I", data, off)[0]
def put_u16(data, off, value):
struct.pack_into("<H", data, off, value)
def put_u32(data, off, value):
struct.pack_into("<I", data, off, value)
def section_at(data, off):
raw = data[off:off + 8]
name = raw.split(b"\0", 1)[0].decode("ascii", "replace")
return {
"off": off,
"name": name,
"paddr": u32(data, off + 8),
"size": u32(data, off + 16),
"scnptr": u32(data, off + 20),
"flags": u32(data, off + 36),
}
def parse(data):
if len(data) < 20:
raise ValueError("file is shorter than the 20-byte COFF header")
magic = u16(data, 0)
nscns = u16(data, 2)
opt = u16(data, 16)
return {
"magic": magic,
"nscns": nscns,
"opthdr": opt,
"optmagic": u16(data, 20) if opt else 0,
"entry": u32(data, 20 + 16) if opt else 0,
"textstart": u32(data, 20 + 20) if opt else 0,
}
def scan_recoverable_sections(data):
"""Recover the section table of GSPLNK's zero-header shape.
GSPLNK always leaves the 20-byte file header and 28-byte optional header
(48 bytes) zero, then writes the section table at byte 48. Stop at the
first entry whose name does not start with '.', so a trailing symbol table
is not mistaken for a section.
"""
if len(data) < ZERO_HEADER_SIZE + 40:
raise ValueError("no room for a recovered section table")
sections = []
off = ZERO_HEADER_SIZE
while off + 40 <= len(data) and len(sections) < 96:
sec = section_at(data, off)
if not sec["name"].startswith("."):
break
sections.append(sec)
off += 40
if not sections:
raise ValueError("zero header and no section table at byte 48")
return sections
def validate(data, sections, label):
bad = []
for sec in sections:
name = sec["name"]
size = sec["size"]
if not name:
bad.append("empty section name")
if size % 16 != 0 and name != ".bss":
bad.append(f"{name}: bit size {size} is not a whole word")
if name == ".bss" and size % 16 != 0:
bad.append(".bss: bit size %d is not a whole word" % size)
# scnptr points at raw bytes for non-.bss sections; the file must
# contain size/8 bytes there. .bss has no file payload.
if name != ".bss" and sec["scnptr"]:
need = sec["scnptr"] + (size + 7) // 8
if need > len(data):
bad.append(f"{name}: payload ends past EOF ({need} > {len(data)})")
if bad:
raise ValueError(f"{label}: " + "; ".join(bad))
def repair(data, entry):
header_zero = data[:20] == b"\0" * 20
opt_zero = data[20:ZERO_HEADER_SIZE] == b"\0" * OPT_HDR_SIZE
changed = []
if header_zero and opt_zero:
sections = scan_recoverable_sections(data)
names = {sec["name"]: sec for sec in sections}
for required in (".text", ".data", ".bss"):
if required not in names:
raise ValueError(f"recoverable header lacks {required}")
text = names[".text"]
dat = names[".data"]
bss = names[".bss"]
bss_size = (bss["size"] + 15) & ~15
if bss_size != bss["size"]:
put_u32(data, bss["off"] + 16, bss_size)
changed.append(f".bss size {bss['size']} -> {bss_size} bits")
# File header: magic, section count, timestamp, symbol pointer/count,
# optional-header size, flags.
put_u16(data, 0, FILE_MAGIC)
put_u16(data, 2, len(sections))
put_u32(data, 4, 0)
put_u32(data, 8, 0)
put_u32(data, 12, 0)
put_u16(data, 16, OPT_HDR_SIZE)
put_u16(data, 18, FILE_FLAGS)
# Optional header: magic, version, text/data/bss bits, entry and the
# text/data origins.
put_u16(data, 20, OPT_MAGIC)
put_u16(data, 22, OPT_VERSION)
put_u32(data, 24, text["size"])
put_u32(data, 28, dat["size"])
put_u32(data, 32, bss_size)
put_u32(data, 36, entry)
put_u32(data, 40, text["paddr"])
put_u32(data, 44, dat["paddr"])
changed.append("reconstructed zeroed file/optional header")
return changed, sections
info = parse(data)
if info["magic"] != FILE_MAGIC:
raise ValueError(f"bad COFF magic {info['magic']:#06x}, want {FILE_MAGIC:#06x}")
if info["nscns"] == 0 or info["opthdr"] != OPT_HDR_SIZE:
raise ValueError(
f"invalid header nscns={info['nscns']} opthdr={info['opthdr']}")
base = 20 + info["opthdr"]
if base + info["nscns"] * 40 > len(data):
raise ValueError("section table runs past EOF")
sections = [section_at(data, base + i * 40) for i in range(info["nscns"])]
for sec in sections:
if sec["name"] == ".bss" and sec["size"] % 16 != 0:
new_size = (sec["size"] + 15) & ~15
put_u32(data, sec["off"] + 16, new_size)
# Keep the optional header's bss-size field consistent.
put_u32(data, 32, new_size)
changed.append(f".bss size {sec['size']} -> {new_size} bits")
sec["size"] = new_size
return changed, sections
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--repair", action="store_true",
help="repair the observed GSPLNK header/.bss shapes")
ap.add_argument("--entry", default="018A0000",
help="entry bit address for a reconstructed header")
ap.add_argument("file")
args = ap.parse_args()
try:
entry = int(args.entry, 16) if not args.entry.startswith("0x") else int(args.entry, 0)
except ValueError:
print(f"coff-check: bad --entry {args.entry}", file=sys.stderr)
return 2
try:
data = bytearray(open(args.file, "rb").read())
except OSError as exc:
print(f"coff-check: {exc}", file=sys.stderr)
return 1
try:
info = parse(data)
zero_header = info["magic"] == 0 and info["nscns"] == 0
if zero_header and not args.repair:
raise ValueError("zeroed file/optional header (GSPLNK shape); rerun with --repair")
if args.repair:
changed, sections = repair(data, entry)
if changed:
with open(args.file, "wb") as out:
out.write(data)
for item in changed:
print(f"coff-check: repaired {item}")
info = parse(data)
if info["magic"] != FILE_MAGIC:
raise ValueError(f"bad COFF magic {info['magic']:#06x}")
if info["nscns"] == 0 or info["opthdr"] != OPT_HDR_SIZE:
raise ValueError(
f"invalid header nscns={info['nscns']} opthdr={info['opthdr']}")
base = 20 + info["opthdr"]
if base + info["nscns"] * 40 > len(data):
raise ValueError("section table runs past EOF")
sections = [section_at(data, base + i * 40) for i in range(info["nscns"])]
validate(data, sections, "post-repair")
except ValueError as exc:
print(f"coff-check: FAIL: {exc}", file=sys.stderr)
return 1
names = ",".join(sec["name"] for sec in sections)
print(f"coff-check: OK sections={len(sections)} [{names}] entry={info['entry']:#010x}")
return 0
if __name__ == "__main__":
sys.exit(main())
+150 -16
View File
@@ -16,16 +16,41 @@
# M4_ROM_SYMBOLS=1 append the per-ROM import stubs from symbols
# M4_EXTRA_ASM="/a.asm /b.asm" extra assembly to concatenate
# M4_EXTRA_INCLUDES="-I dir" extra tms-clang include flags
# M4_EXTRA_CFLAGS="-std=..." extra tms-clang language flags (default empty;
# the conformance sweep uses this for c-torture's
# gnu89 dialect; shipped gates pass nothing)
# M4_NATIVE=1 compile with llc -filetype=obj and link the
# objects with GSPLNK (the default is GSPA text)
# M4_NATIVE_SKIP_ASM=1 in native mode, do not also emit .s for a TU
# whose raw GSPA form is intentionally rejected
# (for example an odd-offset pointer record)
# M4_NATIVE_RTS=1 add `-l rts.lib` to the native link
# M4_NATIVE_LIBS="a b" add `-l a -l b` to the native link (library
# files must already be in the SDK directory; the
# conformance shim uses flib.lib/rts.lib for %f)
# M4_NATIVE_PROG_LEN=8000h native program region length (bits)
# M4_NATIVE_RAM_LEN=80000h native RAM region length (bits)
# M4_LINK_CMD=/path/link.cmd asm-path GSPLNK command file (default link.cmd)
# M4_LINKER=tms-link native-mode opt-in: link the GSPA entry/extras
# objects and any M4_NATIVE_LIBS/M4_NATIVE_RTS
# archives with tools/tms-link instead of GSPLNK
# (default: gsplnk, which remains the oracle).
# Requires M4_NATIVE=1.
# M4_OS2=1 assemble/link with the 1990 r5.01 OS/2 tools
# under 2ine+qemu-i386 instead of DOSBox (run
# scripts/m8/setup-os2.sh first; the 1987
# GSPA/GSPLNK oracle is still the default)
# M4_OS2_LX=/path ../../2ine-tms34010/build-qemu/lx_loader
# M4_OS2_SDK=/path extracted r5.01 tree (bin/ and lib/)
# M4_SKIP_MAME=1 stop after a clean GSPA/GSPLNK link
# M4_COFF_REPAIR=1 validate the linked COFF magic/section sizes and
# repair GSPLNK's observed zero-header and
# odd-.bss shapes (default 1; set 0 to validate
# only and fail on the defect)
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX DOSBOX_CONF
# SDK_IMG M4_WORK M4_COFF M4_SDK M4_SYMS LOADER_AT LOADER_END
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC TMS_LINK MAME DOSBOX
# DOSBOX_CONF SDK_IMG M4_WORK M4_COFF M4_SDK M4_SYMS LOADER_AT
# LOADER_END M4_COFF_REPAIR
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
@@ -36,6 +61,7 @@ TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
TMS_OPT=${TMS_OPT:-$LLVM_BIN/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
@@ -58,11 +84,17 @@ CHECK_LUA=${M4_CHECK_LUA:-$DIR/m4-check.lua}
CLANG_OPT=${M4_CLANG_OPT:--O0}
LLC_OPT=${M4_LLC_OPT:--O0}
EXTRA_INCLUDES=${M4_EXTRA_INCLUDES:-}
EXTRA_CFLAGS=${M4_EXTRA_CFLAGS:-}
NATIVE=${M4_NATIVE:-0}
OS2=${M4_OS2:-0}
NATIVE_SKIP_ASM=${M4_NATIVE_SKIP_ASM:-0}
NATIVE_RTS=${M4_NATIVE_RTS:-0}
NATIVE_LIBS=${M4_NATIVE_LIBS:-}
NATIVE_PROG_LEN=${M4_NATIVE_PROG_LEN:-8000h}
NATIVE_RAM_LEN=${M4_NATIVE_RAM_LEN:-80000h}
LINK_CMD=${M4_LINK_CMD:-$DIR/link.cmd}
LINKER=${M4_LINKER:-gsplnk}
COFF_REPAIR=${M4_COFF_REPAIR:-1}
fail() {
echo "m4: $*" >&2
@@ -72,6 +104,14 @@ fail() {
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
case $LINKER in
gsplnk|tms-link) ;;
*) fail "M4_LINKER must be 'gsplnk' or 'tms-link', got '$LINKER'" ;;
esac
if [ "$LINKER" = tms-link ]; then
[ "$NATIVE" = 1 ] || fail "M4_LINKER=tms-link requires M4_NATIVE=1"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
fi
[ -f "$ENTRY" ] || fail "missing entry: $ENTRY"
mkdir -p "$ASM" "$WORK/evidence" "$WORK/run/nvram" "$WORK/run/cfg"
@@ -79,6 +119,7 @@ mkdir -p "$(dirname "$COFF")"
echo "== compile and select ($CLANG_OPT / llc $LLC_OPT)"
export TMS_CLANG TMS_OPT TMS_BITADDR
export TMS_CLANG_EXTRA_FLAGS="$EXTRA_CFLAGS"
for name in $SOURCES; do
case $name in
*/*) src=$name ;;
@@ -89,15 +130,20 @@ for name in $SOURCES; do
# shellcheck disable=SC2086
"$ROOT/scripts/tms-clang" "$CLANG_OPT" $EXTRA_INCLUDES \
-o "$ASM/$base.ll" "$src"
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
if [ "$NATIVE" = 1 ]; then
if [ "$NATIVE_SKIP_ASM" != 1 ]; then
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
fi
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=obj \
"$ASM/$base.ll" -o "$ASM/$base.o" \
|| fail "llc -filetype=obj failed for $name"
echo " $base.o: $(wc -c < "$ASM/$base.o") bytes"
else
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
echo " $base.s: $(grep -c . "$ASM/$base.s") lines"
fi
done
@@ -157,6 +203,12 @@ strip_end() {
sed '/^[[:space:]]*\.end[[:space:]]*$/d' "$1"
}
# Optional host-side 1990 OS/2 r5.01 assembler/linker path (2ine + qemu-i386).
if [ "$OS2" = 1 ]; then
. "$ROOT/scripts/m8/os2-toolchain.sh"
os2_init
fi
EXTRAS=
if [ -n "${M4_EXTRA_ASM:-}" ]; then
for extra in $M4_EXTRA_ASM; do
@@ -207,13 +259,29 @@ if [ "$NATIVE" = 1 ]; then
fi
if [ "$NATIVE_RTS" = 1 ]; then
[ -f "$SDK/RTS.LIB" ] || fail "RTS.LIB not extracted into $SDK"
NATIVE_LIBS="$NATIVE_LIBS rts.lib"
fi
# Resolve the library names to SDK paths for tms-link. GSPLNK keeps
# consuming the -l lines in M4.CMD; the order is identical.
NATIVE_LIB_PATHS=
for lib in $NATIVE_LIBS; do
dos=$(printf '%s' "$lib" | tr '[:lower:]' '[:upper:]')
if [ -f "$lib" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $lib"
elif [ -f "$SDK/$dos" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $SDK/$dos"
elif [ -f "$SDK/$lib" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $SDK/$lib"
else
fail "$lib not extracted into $SDK"
fi
done
{
printf '%s\n' '-a' '-o M4.OUT' '-m M4.MAP' '-e _start'
printf '%s\n' "$NATIVE_OBJS"
if [ "$NATIVE_RTS" = 1 ]; then
printf '%s\n' '-l rts.lib'
fi
for lib in $NATIVE_LIBS; do
printf '%s\n' "-l $lib"
done
printf '%s\n' 'MEMORY' '{'
printf ' prog: origin = 018A0000h, length = %s\n' "$NATIVE_PROG_LEN"
printf ' ram: origin = 01A00000h, length = %s\n' "$NATIVE_RAM_LEN"
@@ -267,7 +335,33 @@ run_dosbox() {
-noprimaryconf -nolocalconf "$@" > "$WORK/dosbox.log" 2>&1
}
if [ "$NATIVE" = 1 ] && [ -n "$EXTRAS" ]; then
if [ "$OS2" = 1 ]; then
os2_gspa M4
if [ -f "$SDK/M4EXT.ASM" ]; then
os2_gspa M4EXT
fi
# tms-link is a host tool and runs below; the asm/GSPLNK path links here.
if [ "$NATIVE" != 1 ] || [ "$LINKER" != tms-link ]; then
os2_gsplnk
fi
elif [ "$NATIVE" = 1 ] && [ "$LINKER" = tms-link ]; then
# tms-link is a host tool: GSPA still assembles the entry/extras objects,
# but GSPLNK is not run.
if [ -n "$EXTRAS" ]; then
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "gspa M4EXT M4EXT.obj M4EXT.lst -l" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
else
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
fi
elif [ "$NATIVE" = 1 ] && [ -n "$EXTRAS" ]; then
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
@@ -284,6 +378,23 @@ else
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
fi
if [ "$NATIVE" = 1 ] && [ "$LINKER" = tms-link ]; then
TMSLINK_INPUTS=
for obj in $NATIVE_OBJS; do
TMSLINK_INPUTS="$TMSLINK_INPUTS $SDK/$obj"
done
echo "== link with tools/tms-link"
# shellcheck disable=SC2086
"$TMS_LINK" -o "$SDK/M4.OUT" --map "$SDK/M4.MAP" --entry _start \
--text 018A0000 --bss 01A00000 \
--prog-len "$NATIVE_PROG_LEN" --ram-len "$NATIVE_RAM_LEN" \
$TMSLINK_INPUTS $NATIVE_LIB_PATHS \
|| fail "tms-link failed"
# Keep the pre-coff-check image so parity gates can compare tms-link's
# raw output; the repaired $COFF below remains the loader image.
cp "$SDK/M4.OUT" "$WORK/M4.RAW.OUT"
fi
check_lst() {
lst=$1
[ -f "$SDK/$lst.LST" ] \
@@ -299,16 +410,35 @@ check_lst() {
check_lst M4
[ -z "$EXTRAS" ] || [ "$NATIVE" != 1 ] || check_lst M4EXT
[ -f "$SDK/M4.OUT" ] || fail "GSPLNK produced no M4.OUT"
[ -f "$SDK/M4.OUT" ] || fail "$LINKER produced no M4.OUT"
sed 's/\r$//' "$SDK/M4.MAP" > "$WORK/m4.map"
cp "$SDK/M4.OUT" "$COFF"
cp "$SDK/M4.ASM" "$WORK/m4.asm"
[ ! -f "$SDK/M4EXT.ASM" ] || cp "$SDK/M4EXT.ASM" "$WORK/m4ext.asm"
ENTRY_ADDR=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m4.map")
ENTRY_ADDR=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m4.map" | tr 'a-f' 'A-F')
[ "$ENTRY_ADDR" = "018A0000" ] || fail "linker entry _start is '$ENTRY_ADDR', want 018A0000"
grep -q 'ENTRY POINT SYMBOL: "_start"' "$WORK/m4.map" \
|| fail "linker map has no _start entry point"
# GSPLNK 2.00 can zero the 48-byte file+optional header (observed on links
# whose test object contributed no initialized .data), and can emit an odd
# .bss size.
# Validate every linked COFF and repair only those two known shapes; any other
# malformed image is a hard link failure.
command -v python3 >/dev/null 2>&1 || fail "python3 is required for COFF validation"
if [ "$COFF_REPAIR" = 1 ]; then
coff_out=$(python3 "$ROOT/scripts/m4/coff-check.py" --repair \
--entry "$ENTRY_ADDR" "$COFF" 2>&1) \
|| { printf '%s\n' "$coff_out" | sed 's/^/ /' >&2; \
fail "COFF validation/repair failed for $COFF"; }
else
coff_out=$(python3 "$ROOT/scripts/m4/coff-check.py" --entry "$ENTRY_ADDR" \
"$COFF" 2>&1) \
|| { printf '%s\n' "$coff_out" | sed 's/^/ /' >&2; \
fail "COFF validation failed for $COFF"; }
fi
printf '%s\n' "$coff_out" | sed 's/^/ /'
echo " linked .text at 018A0000, M4.OUT -> $COFF"
if [ -n "${M4_SKIP_MAME:-}" ]; then
@@ -341,15 +471,19 @@ timeout "${MAME_TIMEOUT:-900}" "$MAME" vt1200 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
MARKERS=$(grep -E '^M4: ' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M4 markers"; }
MARKERS=$(grep -E '^(M4|M7|M8 LIB): ' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M4/M7/M8 LIB markers"; }
echo " $MARKERS"
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; fail "COFF loader did not report status 0"; }
grep -q 'placed \.text .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -q '^M4 MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "M4 marker check failed"; }
grep -qE '^M[47] MAME: PASS|^M8 LIB MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "marker check failed"; }
echo "M4 MAME: PASS"
case "$MARKERS" in
M7:*) echo "M7 MAME: PASS" ;;
M8\ LIB:*) echo "M8 LIB MAME: PASS" ;;
*) echo "M4 MAME: PASS" ;;
esac
+5 -5
View File
@@ -3,11 +3,11 @@
* driver's late-GEP policy.
*
* The optimizer's switch-to-lookup-table transform creates a new i8 GEP after
* tms-bitaddr --scale; --normalize cannot tell that index apart from an
* already-scaled bit offset, so the table would be indexed one bit per slot.
* tms-clang passes -switch-to-lookup=false; this source makes the hazard
* reachable at -O2 (termtris' init_game and runesc switches are the real
* cases).
* tms-bitaddr --scale. tms-clang's post-opt --scale converts that byte/element
* index to bits (M6 Task 6 generalized this beyond the old switch.table-only
* normalize rule). This source makes the hazard reachable at -O2 (termtris'
* init_game and runesc switches are the real cases): a missed scale would
* index the table one bit per slot.
*/
int sw_tile(int c)
{
+107 -1
View File
@@ -39,6 +39,16 @@ ROM_HI=$((0x3FFFFFFF))
MAPWINDOW=$((0x3FD64F60))
RAISEWINDOW=$((0x3FD645B0))
# M7.3 wider surface: the six GUI_APPS table entries, pinned as addresses as
# well as by opcode/helper. A table edit to a different builder with the same
# opcode still fails here.
WIDER_MAPSUBWINDOWS=$((0x3FD64BF0))
WIDER_CHANGEWATTRS=$((0x3FD38770))
WIDER_CONFIGUREWINDOW=$((0x3FD3A510))
WIDER_INTERNATOM=$((0x3FD5E420))
WIDER_CHANGEPROPERTY=$((0x3FD37330))
WIDER_CHANGEGC=$((0x3F999F80))
fail() {
echo "m4 validate-syms: FAIL: $*" >&2
exit 1
@@ -79,6 +89,10 @@ require_match() { # require_match DIS_TEXT ERE WHAT
}
}
require_addr() { # require_addr NAME ADDR WANT WHAT
[ "$(($2))" -eq "$3" ] || fail "$1 is $2, expected $(printf '0x%08X' "$3") ($4)"
}
check_prologue() { # check_prologue NAME ADDR
_name=$1
_addr=$2
@@ -229,6 +243,97 @@ check_xcreateimage() {
echo " ok XCreateImage allocates an 88-byte XImage"
}
# The M7.3 wider surface: six public entries from the GUI_APPS table. Each
# body is the ROM request builder named by that table, so pin the request
# opcode (and the helper each builder calls) rather than trusting the name.
# XMapSubwindows opcode 9
# XChangeWindowAttributes opcode 2, values walker 0x3FDA A550
# XConfigureWindow opcode 12, fixed CWX|CWY|CWWidth|CWHeight mask 15
# XInternAtom opcode 16, strlen on the name
# XChangeProperty opcode 18, blit_copy for the value bytes
# XChangeGC opcode 56 (0x38), GC cache serializer 0x3F997AD0
check_wider_xlib() {
_addr=$(sym_addr XMapSubwindows)
[ -n "$_addr" ] || fail "table has no XMapSubwindows entry"
require_addr XMapSubwindows "$_addr" "$WIDER_MAPSUBWINDOWS" "GUI_APPS"
dis_at "$((_addr))" 384 "$TMP/mapsubwindows"
require_match "$TMP/mapsubwindows" 'movk[[:space:]]+9,[[:space:]]+a[0-9]+' \
"XMapSubwindows does not build MapSubwindows request opcode 9"
require_match "$TMP/mapsubwindows" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XMapSubwindows does not write its request opcode to the buffer"
echo " ok XMapSubwindows builds MapSubwindows opcode 9"
_addr=$(sym_addr XChangeWindowAttributes)
[ -n "$_addr" ] || fail "table has no XChangeWindowAttributes entry"
require_addr XChangeWindowAttributes "$_addr" "$WIDER_CHANGEWATTRS" "GUI_APPS"
dis_at "$((_addr))" 448 "$TMP/changewattrs"
require_match "$TMP/changewattrs" 'movk[[:space:]]+2,[[:space:]]+a[0-9]+' \
"XChangeWindowAttributes does not build ChangeWindowAttributes request opcode 2"
require_match "$TMP/changewattrs" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeWindowAttributes does not write its request opcode to the buffer"
require_match "$TMP/changewattrs" 'calla[[:space:]]+0x3fdaa550' \
"XChangeWindowAttributes does not call the XSetWindowAttributes value walker"
echo " ok XChangeWindowAttributes builds opcode 2 + value walker"
_addr=$(sym_addr XConfigureWindow)
[ -n "$_addr" ] || fail "table has no XConfigureWindow entry"
require_addr XConfigureWindow "$_addr" "$WIDER_CONFIGUREWINDOW" "GUI_APPS"
dis_at "$((_addr))" 448 "$TMP/configurewindow"
require_match "$TMP/configurewindow" 'movk[[:space:]]+12,[[:space:]]+a[0-9]+' \
"XConfigureWindow does not build ConfigureWindow request opcode 12"
require_match "$TMP/configurewindow" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XConfigureWindow does not write its request opcode to the buffer"
require_match "$TMP/configurewindow" 'movk[[:space:]]+15,[[:space:]]+a[0-9]+' \
"XConfigureWindow does not arm the fixed CWX|CWY|CWWidth|CWHeight mask 15"
require_match "$TMP/configurewindow" '\*a13\(0xffa0\)' \
"XConfigureWindow does not read the x argument (a13-12)"
require_match "$TMP/configurewindow" '\*a13\(0xff80\)' \
"XConfigureWindow does not read the y argument (a13-16)"
require_match "$TMP/configurewindow" '\*a13\(0xff60\)' \
"XConfigureWindow does not read the width argument (a13-20)"
require_match "$TMP/configurewindow" '\*a13\(0xff40\)' \
"XConfigureWindow does not read the height argument (a13-24)"
echo " ok XConfigureWindow builds opcode 12, fixed mask 15, x/y/width/height"
_addr=$(sym_addr XInternAtom)
[ -n "$_addr" ] || fail "table has no XInternAtom entry"
require_addr XInternAtom "$_addr" "$WIDER_INTERNATOM" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/internatom"
require_match "$TMP/internatom" 'movk[[:space:]]+16,[[:space:]]+a[0-9]+' \
"XInternAtom does not build InternAtom request opcode 16"
require_match "$TMP/internatom" 'calla[[:space:]]+0x3fb458d0' \
"XInternAtom does not strlen the atom name"
require_match "$TMP/internatom" '\*a13\(0xffa0\)' \
"XInternAtom does not read the only_if_exists argument (a13-12)"
echo " ok XInternAtom builds opcode 16, strlens the name"
_addr=$(sym_addr XChangeProperty)
[ -n "$_addr" ] || fail "table has no XChangeProperty entry"
require_addr XChangeProperty "$_addr" "$WIDER_CHANGEPROPERTY" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/changeproperty"
require_match "$TMP/changeproperty" 'movk[[:space:]]+18,[[:space:]]+a[0-9]+' \
"XChangeProperty does not build ChangeProperty request opcode 18"
require_match "$TMP/changeproperty" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeProperty does not write its request opcode to the buffer"
require_match "$TMP/changeproperty" 'calla[[:space:]]+0x3fb44400' \
"XChangeProperty does not copy its value bytes through blit_copy"
require_match "$TMP/changeproperty" '\*a13\(0xff00\)' \
"XChangeProperty does not read the nelements argument (a13-32)"
echo " ok XChangeProperty builds opcode 18, blit_copy value bytes"
_addr=$(sym_addr XChangeGC)
[ -n "$_addr" ] || fail "table has no XChangeGC entry"
require_addr XChangeGC "$_addr" "$WIDER_CHANGEGC" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/changegc"
require_match "$TMP/changegc" 'movi[[:space:]]+0x38,[[:space:]]+a[0-9]+' \
"XChangeGC does not build ChangeGC request opcode 56 (0x38)"
require_match "$TMP/changegc" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeGC does not write its request opcode to the buffer"
require_match "$TMP/changegc" 'calla[[:space:]]+0x3f997ad0' \
"XChangeGC does not call the GC value-cache serializer"
echo " ok XChangeGC builds opcode 56, flushes the GC value cache"
}
# The error-handler setters write the per-process XG block: IO at +0x40,
# protocol error at +0x60. The defaults are the ROM's _XDefaultIOError and
# _XDefaultError.
@@ -273,6 +378,7 @@ check_image_requests
check_font_copy
check_pixmap_focus
check_xcreateimage
check_wider_xlib
check_error_handlers
echo "m4 validate-syms: PASS ($count v2.2 entries in ROM, aligned, prologues valid; XMapWindow/XRaiseWindow pinned)"
echo "m4 validate-syms: PASS ($count v2.2 entries in ROM, aligned, prologues valid; XMapWindow/XRaiseWindow pinned; M7.3 wider Xlib opcodes pinned)"
+141 -3
View File
@@ -230,6 +230,107 @@ typedef union _XEvent {
#define XYPixmap 1
#define ZPixmap 2
/*
* M7.3 wider Xlib surface. The VT1200 ROM is X11R4: these are the X11R4
* value-mask bits and struct layouts (32-bit fields, packed by the TMS34010
* C ABI). The ROM's own request builders use the same ordering: the
* ConfigureWindow entry arms CWX|CWY|CWWidth|CWHeight (mask 15), and the
* window-attributes walker reads background_pixel from byte 4.
*/
typedef struct {
int x, y;
int width, height;
int border_width;
Window sibling;
int stack_mode;
} XWindowChanges;
#define CWBackPixmap (1L << 0)
#define CWBackPixel (1L << 1)
#define CWBorderPixmap (1L << 2)
#define CWBorderPixel (1L << 3)
#define CWBitGravity (1L << 4)
#define CWWinGravity (1L << 5)
#define CWBackingStore (1L << 6)
#define CWBackingPlanes (1L << 7)
#define CWBackingPixel (1L << 8)
#define CWOverrideRedirect (1L << 9)
#define CWSaveUnder (1L << 10)
#define CWEventMask (1L << 11)
#define CWDontPropagate (1L << 12)
#define CWColormap (1L << 13)
#define CWCursor (1L << 14)
#define CWX (1L << 0)
#define CWY (1L << 1)
#define CWWidth (1L << 2)
#define CWHeight (1L << 3)
#define CWBorderWidth (1L << 4)
#define CWSibling (1L << 5)
#define CWStackMode (1L << 6)
/* X11R4 XSetWindowAttributes: background_pixel is byte 4 (CWBackPixel). */
typedef struct {
unsigned long background_pixmap;
unsigned long background_pixel;
unsigned long border_pixmap;
unsigned long border_pixel;
int bit_gravity;
int win_gravity;
int backing_store;
unsigned long backing_planes;
unsigned long backing_pixel;
Bool save_under;
long event_mask;
long do_not_propagate_mask;
Bool override_redirect;
Colormap colormap;
Cursor cursor;
} XSetWindowAttributes;
/* X11R4 XGCValues: the ROM value walker reads GCFont's field at byte 60. */
typedef struct {
int function;
unsigned long plane_mask;
unsigned long foreground;
unsigned long background;
int line_width;
int line_style;
int cap_style;
int join_style;
int fill_style;
int fill_rule;
int arc_mode;
Pixmap tile;
Pixmap stipple;
int ts_x_origin;
int ts_y_origin;
Font font;
int subwindow_mode;
int graphics_exposures;
int clip_x_origin;
int clip_y_origin;
Pixmap clip_mask;
int dash_offset;
char dashes;
} XGCValues;
#define GCFunction (1L << 0)
#define GCPlaneMask (1L << 1)
#define GCForeground (1L << 2)
#define GCBackground (1L << 3)
#define GCLineWidth (1L << 4)
#define GCLineStyle (1L << 5)
#define GCCapStyle (1L << 6)
#define GCJoinStyle (1L << 7)
#define GCFillStyle (1L << 8)
#define GCFillRule (1L << 9)
#define GCTile (1L << 10)
#define GCStipple (1L << 11)
#define GCTileStipXOrigin (1L << 12)
#define GCTileStipYOrigin (1L << 13)
#define GCFont (1L << 14)
#define True 1
#define False 0
#define None 0L
@@ -241,9 +342,10 @@ typedef int (*XIOErrorHandler)(Display *);
* Real Xlib entry points. The VT1200 ROM exports these names; Task 5
* validates their bit addresses in symbols/vt1200-v22.syms.
*
* XCreateGC's XGCValues* and XLookupString's XComposeStatus* are modelled as
* void*: the layout is not needed by the M4 clients and the 32-bit pointer
* ABI is unchanged.
* XCreateGC's values argument stays void* (the 32-bit pointer ABI is
* unchanged); the X11R4 XGCValues layout is declared above for the M7.3
* wider-surface client and its offset checks. XLookupString's
* XComposeStatus* is modelled as void*.
*/
extern Display *XOpenDisplay(const char *name);
extern Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
@@ -252,6 +354,38 @@ extern Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
unsigned long border,
unsigned long background);
extern int XMapWindow(Display *display, Window window);
/*
* M7.3 wider surface, validated in symbols/vt1200-v22.syms.
*
* XMapSubwindows maps every child of `window` (MapSubwindows opcode 9).
*/
extern int XMapSubwindows(Display *display, Window window);
/*
* The ROM's ConfigureWindow entry (0x3FD3A510) is the fixed-mask builder:
* opcode 12, value-mask CWX|CWY|CWWidth|CWHeight, and four scalar arguments.
* That is Xlib's XMoveResizeWindow call shape, not the XWindowChanges-pointer
* shape; XWindowChanges above documents the same four values.
*/
extern int XConfigureWindow(Display *display, Window window, int x, int y,
unsigned int width, unsigned int height);
/* ChangeWindowAttributes opcode 2 (XSetWindowAttributes value walker). */
extern int XChangeWindowAttributes(Display *display, Window window,
unsigned long valuemask,
XSetWindowAttributes *attributes);
/* InternAtom opcode 16; only_if_exists False creates the atom. */
extern Atom XInternAtom(Display *display, const char *name,
Bool only_if_exists);
/* ChangeProperty opcode 18; format 8, mode PropModeReplace = 0. */
extern int XChangeProperty(Display *display, Window window, Atom property,
Atom type, int format, int mode,
const unsigned char *data, int nelements);
/*
* ChangeGC opcode 56. The ROM entry's public shape is (display, gc): it
* serializes the GC's pending value cache (the same serializer the drawing
* primitives call). Values are selected by the cache setters, e.g.
* XSetForeground, or by XCreateGC's XGCValues.
*/
extern int XChangeGC(Display *display, GC gc);
/* CreatePixmap opcode 0x35; depth 1 for the image client's 1-bit pixmap. */
extern Pixmap XCreatePixmap(Display *display, Drawable drawable,
unsigned int width, unsigned int height,
@@ -298,6 +432,10 @@ extern XImage *XCreateImage(Display *display, Visual *visual,
extern int XPutImage(Display *display, Drawable drawable, GC gc, XImage *image,
int src_x, int src_y, int dest_x, int dest_y,
unsigned int width, unsigned int height);
/* GetImage opcode 0x49: synchronous reply; format is XYPixmap or ZPixmap. */
extern XImage *XGetImage(Display *display, Drawable drawable, int x, int y,
unsigned int width, unsigned int height,
unsigned long plane_mask, int format);
extern int XDestroyImage(XImage *image);
extern XErrorHandler XSetErrorHandler(XErrorHandler handler);
extern XIOErrorHandler XSetIOErrorHandler(XIOErrorHandler handler);
+8 -1
View File
@@ -13,7 +13,11 @@
# M4_NATIVE=1, links them with GSPLNK and runs the M4 image/event MAME check.
# The asm/GSPA path remains the default of run.sh.
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC LLVM_BIN
# M5_NATIVE_LINKER=tms-link runs the same native builds through tools/tms-link
# (the termtris run also exercises the rts.lib archive path); the default is
# GSPLNK, which remains the oracle.
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC LLVM_BIN M5_NATIVE_LINKER
# M5_XSHOW_WORK TERMTRIS_WORK TERMTRIS_SDK VT1200_TERMTRIS
# M4_SDK DOSBOX DOSBOX_CONF SDK_IMG MAME LOADER_AT LOADER_END
set -eu
@@ -23,6 +27,7 @@ MODE=${1:-termtris}
DIR=$ROOT/scripts/m4
TERMTRIS_DIR=$DIR/termtris
VENDOR=${VT1200_TERMTRIS:-$ROOT/vendor/vt1200-termtris}
LINKER=${M5_NATIVE_LINKER:-gsplnk}
fail() {
echo "M5 native driver: $*" >&2
@@ -33,6 +38,7 @@ case $MODE in
xshow)
WORK=${M5_XSHOW_WORK:-$ROOT/build/m5-native-xshow}
M4_NATIVE=1 \
M4_LINKER="$LINKER" \
M4_SOURCES="xshow xgfix" \
M4_ENTRY="$DIR/xshow-entry.asm" \
M4_CHECK_LUA="$DIR/xshow-check.lua" \
@@ -61,6 +67,7 @@ termtris)
# section non-empty, so the empty cinit.asm is sufficient (the asm gate's
# CINITZ fallback is only needed when no library contributes .cinit).
M4_NATIVE=1 \
M4_LINKER="$LINKER" \
M4_SKIP_MAME=1 \
M4_SOURCES="$SRC/vt1200/main.c $SRC/game.c $SRC/vt1200/scoredb.c $SRC/vt1200/x11.c $SRC/vt1200/compat.c $SRC/vt1200/xgfix.c" \
M4_EXTRA_INCLUDES="-I $SRC -I $SRC/vt1200 -I $TERMTRIS_DIR/include" \
+85
View File
@@ -0,0 +1,85 @@
/*
* abi-oracle.c -- the 1987 TI C compiler ABI oracle for M6 task 1.
*
* The 1987 GSP C compiler is on the 1987-11-06 "Simulator-C Tools-ASM Tools"
* image (::/C2). Run it under DOSBox with the module name (no extension):
*
* gspcpp oracle.c
* gspcc oracle.c
* gspcg oracle.c
*
* ORACLE.ASM then shows the exact stack sequences reproduced in
* build/llvm-clean/TMS34010.md ("M6 state"):
* - _dadd/_dcall: GSP double argument order and the caller-allocated
* hidden return slot (the callee writes saved_STK-64/saved_STK-32);
* - _fadd: a float return uses the single word at saved_STK-32 (the K&R
* compiler promotes the parameters, so it calls FD$ADD + FD$DTOF);
* - _mkpair/_callpair: a 64-bit struct return uses the same hidden slot
* and the caller releases it with ADDI -64,STK;
* - _d2i/_i2d: the FD$DTOI/FD$ITOD conversion entries.
*
* The 1987 compiler is K&R-only; long long did not exist, so i64 has no
* external oracle. M6 i64 memory is little-endian (LSW at the lower
* address, per spec §4.1); the argument/hidden-slot order is MSW-first and
* is documented
* in TMS34010.md and pinned by scripts/m6/spike-probe.asm.
*/
double dadd(a, b)
double a;
double b;
{
return a + b;
}
double dcall(a, b)
double a;
double b;
{
double r;
r = dadd(a, b);
return r;
}
long d2i(a)
double a;
{
return (long)a;
}
double i2d(a)
long a;
{
return (double)a;
}
float fadd(a, b)
float a;
float b;
{
return a + b;
}
struct pair {
long a;
long b;
};
struct pair mkpair(a, b)
long a;
long b;
{
struct pair p;
p.a = a;
p.b = b;
return p;
}
long callpair(a, b)
long a;
long b;
{
struct pair p;
p = mkpair(a, b);
return p.a + p.b;
}
+91
View File
@@ -0,0 +1,91 @@
-- aggregate-check.lua -- read the M6 aggregate marker words and compare them
-- with the expected ABI/layout values.
--
-- AGGREGATE_MARKERS is the bit address of _aggregate_markers from the linker
-- map. Each marker is one 32-bit word at base + n*0x20 bits. The raw-object
-- markers pin the byte layout (little-endian, fields in ascending order) and
-- the guards prove an aggregate copy does not overrun the object.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("AGGREGATE_MARKERS"), 16)
local N = 49
local frames = 0
local checked = false
local expect = {
[0] = 0x11223344, [1] = 0x00005566, -- mk_six fields
[2] = 0x11223344, [3] = 0x00005566, -- raw six object word/half
[4] = 0x600D600D, -- guard after a 6-byte copy
[5] = 0xAABBCCDD, [6] = 0x0000005A, -- mk_five fields (5-byte object)
[7] = 0xAABBCCDD, [8] = 0x0000005A, -- raw five object word/byte
[9] = 0x000000A5, -- guard after a 5-byte copy
[10] = 0x00000010, [11] = 0x00000011, -- mk_big fields
[12] = 0x00000012, [13] = 0x00000013,
[14] = 0x00000014,
[15] = 0x00000010, [16] = 0x00000011, -- raw big object words
[17] = 0x00000012, [18] = 0x00000013,
[19] = 0x00000014,
[20] = 0xAAAA5555, [21] = 0x12345678, -- mk_pair (the 1987 _mkpair)
[22] = 0x00000100, [23] = 0x00000009, -- mk_outer nested fields
[24] = 0x00000003,
[25] = 0xDEADBEEF, [26] = 0xDEADBEEF, -- mk_uni field and raw word
[27] = 0x3366EF96, -- sum_six(six, 100)
[28] = 0x00000024, -- sum_big(big)
[29] = 0x12345678, -- sum_uni(uni)
[30] = 0x000000CF, -- c_usesix(50)
[31] = 0x00000018, -- c_usebig(10)
[32] = 0x00000405, -- c_useouter(0x200)
[33] = 0x0BADF00D, -- c_useuni(...)
[34] = 0x0000000B, -- c_sumpair({5,6})
[35] = 0x00000030, -- c_sumsix({0x10,0x20})
[36] = 0x112233C2, -- c_sumuni(l + c[5])
[37] = 0x000000D2, -- c_usemixed(100)
[38] = 0x00000064, -- mixed raw a
[39] = 0x00000064, -- mixed raw i64 LSW (little-endian)
[40] = 0x00000000, -- mixed raw i64 MSW
[41] = 0x00000000, -- mixed raw double LSW (GSP 1.5)
[42] = 0x400C0000, -- mixed raw double MSW
[43] = 0x40D00000, -- mixed raw float (GSP 2.5)
[44] = 0x00000007, -- mixed raw char
[45] = 0x000B1405, -- c_mkbits fields a=5 b=20 c=-5
[46] = 0xFFFFFFFB, -- signed int c:4 sign-extends
[47] = 0x00000BA5, -- raw packed bitfield word
[48] = 0x5A5A5A5A, -- marker after aggregate_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 aggregate:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 AGGREGATE MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 aggregate: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 AGGREGATE MAME: FAIL")
end
end
end, "aggregate-check")
+28
View File
@@ -0,0 +1,28 @@
; aggregate-entry.asm -- M6 aggregate gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver aggregate_run() and writes a post-return marker. aggregate.sh
; concatenates the llc output for m6-aggregate.ll and the compiled driver
; after this file, so _aggregate_run and the aggregate functions are in the
; same assembly.
;
; The marker array is in .bss (linked at the ram origin); aggregate-check.lua
; reads its address from the linker map and checks 49 words (markers 0..48,
; the last one written after aggregate_run returns). Marker n is 0x20 bits
; above marker n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _aggregate_run
movi 5A5A5A5Ah, a0
movi _aggregate_markers+1536, a2 ; marker 48, the post-return word
move a0, *a2, 1
rets
.globl _aggregate_markers
.bss _aggregate_markers, 1568, 16 ; 49 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+351
View File
@@ -0,0 +1,351 @@
/* M6 aggregate gate driver.
*
* Calls the hand-written ABI functions in m6-aggregate.ll through the TI
* aggregate rules and writes result words to the marker array defined by the
* entry assembly. The .ll callees are *not* compiled by Clang, so the driver
* pins the caller side against independently written lowering; the C
* functions below then exercise the compiler's own callee side (and its
* caller side calling itself).
*
* The ABI under test (1987 `_mkbig`/`_callbig`):
* - the caller reserves an alignTo(size, 2)-byte slot at the top of its
* frame before saving STK, pushes the arguments, calls;
* - the callee copies the object bytes to saved_STK-size (the object sits
* at the top of the rounded slot) and ends with LOADSTK + RETS 2;
* - the caller copies the bytes out and releases the slot;
* - struct/union arguments are still byval copies in the argument area;
* - no sret pointer argument and no A8 aggregate return.
*
* Marker word n lives at aggregate_markers[n], i.e. 0x20 bits above the
* previous one; scripts/m6/aggregate-check.lua reads them by bit address from
* the linker map.
*/
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
typedef unsigned long long u64;
struct six {
int a;
short b;
};
struct five {
int a;
char b;
};
/* A packed bitfield struct returned by value: the Task 5 (bitfields) / Task 6
* (aggregate return) seam. The 12 field bits fit one 16-bit word, so the
* hidden slot is 2 bytes and the callee stores the packed bits directly. */
struct bits {
unsigned int a : 3;
unsigned int b : 5;
int c : 4;
};
struct big {
long a, b, c, d, e;
};
struct pair {
long a, b;
};
struct inner {
long a;
short b;
};
struct outer {
struct inner i;
long c;
};
union uni {
long l;
char c[6];
};
struct mixed {
long a;
long long b;
double d;
float f;
char c;
};
struct six_guard {
struct six s;
unsigned int guard;
};
struct five_guard {
struct five f;
unsigned char guard;
};
/* Layout contract: TI packs records, so a 5-byte object is possible and the
* 6-byte slot rounds it up by one byte. */
_Static_assert(sizeof(struct six) == 6, "six");
_Static_assert(__builtin_offsetof(struct six, b) == 4, "six.b");
_Static_assert(sizeof(struct bits) == 2, "bits");
_Static_assert(sizeof(struct five) == 5, "five");
_Static_assert(__builtin_offsetof(struct five, b) == 4, "five.b");
_Static_assert(sizeof(struct big) == 20, "big");
_Static_assert(sizeof(struct pair) == 8, "pair");
_Static_assert(sizeof(struct inner) == 6, "inner");
_Static_assert(sizeof(struct outer) == 10, "outer");
_Static_assert(__builtin_offsetof(struct outer, c) == 6, "outer.c");
_Static_assert(sizeof(union uni) == 6, "uni");
_Static_assert(sizeof(struct mixed) == 25, "mixed");
_Static_assert(__builtin_offsetof(struct mixed, b) == 4, "mixed.b");
_Static_assert(__builtin_offsetof(struct mixed, d) == 12, "mixed.d");
_Static_assert(__builtin_offsetof(struct mixed, f) == 20, "mixed.f");
_Static_assert(__builtin_offsetof(struct mixed, c) == 24, "mixed.c");
extern volatile u32 aggregate_markers[];
/* Callees defined in m6-aggregate.ll. */
extern struct six mk_six(int, int);
extern struct five mk_five(int, int);
extern struct big mk_big(int);
extern struct pair mk_pair(int, int);
extern struct outer mk_outer(int);
extern union uni mk_uni(int);
extern int sum_six(struct six, int);
extern int sum_big(struct big);
extern int sum_uni(union uni);
/* Keep raw object copies in .bss so the exact bytes can be inspected. */
static volatile struct six six_raw;
static volatile struct five five_raw;
static volatile struct big big_raw;
static volatile union uni uni_raw;
static volatile struct mixed mixed_raw;
static volatile struct six_guard six_guard_slot;
static volatile struct five_guard five_guard_slot;
static volatile struct bits bits_raw;
static void mark(u32 n, u32 v) { aggregate_markers[n] = v; }
/* --- C-side aggregate callees (the compiler's callee lowering) ----------- */
static __attribute__((noinline)) struct six c_mksix(int a, int b)
{
struct six s;
s.a = a;
s.b = (short)b;
return s;
}
static __attribute__((noinline)) int c_usesix(int x)
{
struct six s = c_mksix(x, 7);
return s.a * 3 + s.b + x;
}
/* The bitfield-struct return: fields come from x so the callee cannot fold
* the result, and the caller reads them back through the returned object.
* c uses the low bits only: a (x >> 8) & mask source would exercise an
* unrelated generic load-narrowing path on this bit-addressed target. */
static __attribute__((noinline)) struct bits c_mkbits(int x)
{
struct bits v;
v.a = x & 7;
v.b = (x >> 3) & 31;
v.c = -(x & 7);
return v;
}
static __attribute__((noinline)) struct big c_mkbig(int x)
{
struct big b;
b.a = x;
b.b = x + 1;
b.c = x + 2;
b.d = x + 3;
b.e = x + 4;
return b;
}
static __attribute__((noinline)) int c_usebig(int x)
{
struct big b = c_mkbig(x);
return b.a + b.e;
}
static __attribute__((noinline)) struct outer c_mkouter(int x)
{
struct outer o;
o.i.a = x;
o.i.b = 2;
o.c = x + 3;
return o;
}
static __attribute__((noinline)) int c_useouter(int x)
{
struct outer o = c_mkouter(x);
return o.i.a + o.i.b + o.c;
}
static __attribute__((noinline)) union uni c_mkuni(int x)
{
union uni u;
u.l = x;
return u;
}
static __attribute__((noinline)) int c_useuni(int x)
{
union uni u = c_mkuni(x);
return u.l;
}
static __attribute__((noinline)) struct mixed c_mkmixed(int x)
{
struct mixed m;
m.a = x;
m.b = x;
m.d = 1.5;
m.f = 2.5f;
m.c = 7;
return m;
}
static __attribute__((noinline)) int c_usemixed(int x)
{
struct mixed m = c_mkmixed(x);
return (long)m.a + (long)m.b + (long)m.d + (long)m.f + (long)m.c;
}
static __attribute__((noinline)) int c_sumpair(struct pair p) { return p.a + p.b; }
static __attribute__((noinline)) int c_sumsix(struct six s) { return s.a + s.b; }
static __attribute__((noinline)) int c_sumuni(union uni u) { return u.l + u.c[5]; }
void aggregate_run(void)
{
struct six s6;
struct five f5;
struct big b5;
struct pair p2;
struct outer o;
union uni u;
volatile u32 *w;
volatile u8 *pb;
/* The .ll 6-byte struct return and its raw memory image. */
s6 = mk_six(0x11223344, 0x5566);
mark(0, (u32)s6.a);
mark(1, (u16)s6.b);
six_raw = s6;
w = (volatile u32 *)&six_raw;
mark(2, w[0]);
pb = (volatile u8 *)&six_raw;
mark(3, pb[4] | ((u32)pb[5] << 8));
/* A 6-byte object must not overwrite the next object. */
six_guard_slot.guard = 0x600D600D;
six_guard_slot.s = mk_six(0x11223344, 0x5566);
mark(4, six_guard_slot.guard);
/* The 5-byte object in a 6-byte slot; the guard proves the copy is exact
* (the slot's pad byte is not written into the caller's object). */
f5 = mk_five(0xAABBCCDD, 0x5A);
mark(5, (u32)f5.a);
mark(6, (u8)f5.b);
five_raw = f5;
w = (volatile u32 *)&five_raw;
mark(7, w[0]);
pb = (volatile u8 *)&five_raw;
mark(8, pb[4]);
five_guard_slot.guard = 0xA5;
five_guard_slot.f = mk_five(0x01020304, 0x7E);
mark(9, five_guard_slot.guard);
/* The 5-word / 160-bit case. */
b5 = mk_big(0x10);
mark(10, (u32)b5.a);
mark(11, (u32)b5.b);
mark(12, (u32)b5.c);
mark(13, (u32)b5.d);
mark(14, (u32)b5.e);
big_raw = b5;
w = (volatile u32 *)&big_raw;
mark(15, w[0]);
mark(16, w[1]);
mark(17, w[2]);
mark(18, w[3]);
mark(19, w[4]);
/* The 2-word case (1987 `_mkpair`). */
p2 = mk_pair(0xAAAA5555, 0x12345678);
mark(20, (u32)p2.a);
mark(21, (u32)p2.b);
/* Nested struct: flattened fields at 0, 4 and 6. */
o = mk_outer(0x100);
mark(22, (u32)o.i.a);
mark(23, (u32)o.i.b);
mark(24, (u32)o.c);
/* Union return and its raw low word. */
u = mk_uni(0xDEADBEEF);
mark(25, (u32)u.l);
uni_raw = u;
w = (volatile u32 *)&uni_raw;
mark(26, w[0]);
/* Struct/union by value as arguments: the callee receives a private copy
* in the argument area (the driver is the caller here). */
mark(27, (u32)sum_six(s6, 100));
mark(28, (u32)sum_big(b5));
mark(29, (u32)sum_uni(mk_uni(0x12345678)));
/* C-defined callees (the compiler's own callee lowering), called from C. */
mark(30, (u32)c_usesix(50));
mark(31, (u32)c_usebig(10));
mark(32, (u32)c_useouter(0x200));
mark(33, (u32)c_useuni(0x0BADF00D));
p2.a = 5;
p2.b = 6;
mark(34, (u32)c_sumpair(p2));
s6.a = 0x10;
s6.b = 0x20;
mark(35, (u32)c_sumsix(s6));
u.l = 0x11223344;
u.c[5] = 0x7E;
mark(36, (u32)c_sumuni(u));
/* The aggregate can mix i64, double and float members. */
mark(37, (u32)c_usemixed(100));
mixed_raw = c_mkmixed(100);
w = (volatile u32 *)&mixed_raw;
mark(38, w[0]);
mark(39, w[1]);
mark(40, w[2]);
mark(41, w[3]);
mark(42, w[4]);
mark(43, w[5]);
pb = (volatile u8 *)&mixed_raw;
mark(44, pb[24]);
/* Packed bitfield struct returned by value (Task 5/6 seam): fields, the
* signed field and the raw packed word. c_mkbits(0x1A5) is a=5, b=20,
* c=-5 in one 16-bit word. */
{
struct bits v = c_mkbits(0x1A5);
volatile u8 *bb;
mark(45, (u32)v.a | ((u32)v.b << 8) |
((u32)(v.c & 0xF) << 16));
mark(46, (u32)v.c);
bits_raw = v;
bb = (volatile u8 *)&bits_raw;
mark(47, (u32)bb[0] | ((u32)bb[1] << 8));
}
}
+116
View File
@@ -0,0 +1,116 @@
-- bitfield-check.lua -- read the M6 bitfield marker words and compare them
-- with the oracle's expected values.
--
-- BITFIELD_MARKERS is the bit address of _bitfield_markers from the linker
-- map; each marker is one 32-bit word at base + n*0x20 bits. The struct
-- case is the Task 5 oracle: a:3@0, b:5@3, c:4@8 (signed), d:20@12, e:4@32,
-- and the raw word0/byte4 markers pin the actual storage bytes, not just the
-- compiled read-back.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("BITFIELD_MARKERS"), 16)
local N = 62
local frames = 0
local checked = false
local expect = {
[0] = 5, -- struct s.a (bits 0..2)
[1] = 21, -- struct s.b (bits 3..7)
[2] = 0xFFFFFFFD, -- struct s.c = -3, signed 4-bit
[3] = 0x000ABCDE, -- struct s.d (bits 12..31)
[4] = 9, -- struct s.e (bits 32..35)
[5] = 0xABCDEDAD, -- raw word0 = a|b<<3|c<<8|d<<12
[6] = 0x09, -- raw byte4 low nibble = e
[7] = 7, -- c = +7
[8] = 0xFFFFFFF8, -- c = -8 (the 4-bit minimum)
[9] = 0x000FEDCB, -- cross.x
[10] = 0x00012345, -- cross.y at bit 20, crossing bit 32
[11] = 0x345FEDCB, -- raw word0: x | (y low 12) << 20
[12] = 0x12, -- raw byte4: y high 8 bits
[13] = 3, -- zw.a
[14] = 17, -- zw.b after the ignored :0 (bit 3)
[15] = 0x8B, -- raw byte = 3 | 17 << 3
[16] = 0xFFFFFFFF, -- one.s = -1 (signed 1-bit)
[17] = 1, -- one.u
[18] = 0x03, -- raw byte: s in bit 0, u in bit 1
[19] = 0, -- one.s = 0
[20] = 1, -- one.u = 1
[21] = 0x02, -- raw byte
[22] = 0xFFFFFFFF, -- one.s = -1
[23] = 0, -- one.u = 0
[24] = 0x01, -- raw byte
[25] = 0xDEADBEEF, -- word.w (full 32-bit field)
[26] = 1, -- word.v at bit 32
[27] = 0xDEADBEEF, -- raw word0
[28] = 0x01, -- raw byte4
[29] = 0x01234567, -- edge.p (28 bits)
[30] = 0xA5, -- edge.q at bit 28, crossing bit 32
[31] = 0x0C, -- edge.r at bit 36
[32] = 0x51234567, -- raw word0: p | (q low nibble) << 28
[33] = 0xCA, -- raw byte4: q high nibble | r << 4
[34] = 0xFFFFFFFD, -- sx.a = -3 (signed 3-bit)
[35] = 2, -- sx.b
[36] = 0xFFFFFF38, -- sx.c = -200 (signed 9-bit)
[37] = 0xFFFE0000, -- sx.d = -131072 (signed 18-bit)
[38] = 0x80002715, -- raw word0 of the packed signed fields
[39] = 0xFA0A1F00, -- sy.e = -100000000 (signed 30-bit)
[40] = 0xFFFFFFEC, -- sy.f = -20 (signed 6-bit, crosses bit 32)
[41] = 0x3A0A1F00, -- raw word0
[42] = 0x0B, -- raw byte4: f high nibble
[43] = 1, -- g2.a through a pointer
[44] = 30, -- g2.b
[45] = 0xFFFFFFFE, -- g2.c = -2
[46] = 0x00054321, -- g2.d
[47] = 15, -- g2.e
[48] = 0x54321EF1, -- g2 raw word0
[49] = 0x0F, -- g2 raw byte4
[50] = 6, -- lz.a (leading :0 ignored)
[51] = 9, -- lz.b at bit 3
[52] = 0x4E, -- raw byte = 6 | 9 << 3
[53] = 0x12345678, -- l64.f = 0x12345678 (bit 33)
[54] = 0x00000000, -- l64 raw word0 (pad)
[55] = 0x2468ACF0, -- l64 raw word1 (pad[32] | f<<1)
[56] = 0x89ABCDEF, -- q64.q low word
[57] = 0x89ABCDEF, -- q64 raw word0 (LSW)
[58] = 0x01234567, -- q64 raw word1 (MSW)
[59] = 0x12345678, -- copy_l64 read-back after an aggregate copy
[60] = 0x2468ACF0, -- copied l64 raw MSW
[61] = 0x5A5A5A5A, -- marker after bitfield_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 bitfield:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 BITFIELD MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 bitfield: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 BITFIELD MAME: FAIL")
end
end
end, "bitfield-check")
+27
View File
@@ -0,0 +1,27 @@
; bitfield-entry.asm -- M6 bitfield gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver bitfield_run() and writes a post-return marker. bitfield.sh
; concatenates the compiled driver after this file, so _bitfield_run and its
; helpers are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); bitfield-check.lua
; reads its address from the linker map and checks 62 words (markers 0..61,
; the last one written after bitfield_run returns). Marker n is 0x20 bits
; above marker n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _bitfield_run
movi 5A5A5A5Ah, a0
movi _bitfield_markers+1952, a2 ; marker 61, the post-return word
move a0, *a2, 1
rets
.globl _bitfield_markers
.bss _bitfield_markers, 2048, 16 ; 62 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+255
View File
@@ -0,0 +1,255 @@
/* M6 bitfield gate driver.
*
* Every struct below is the 1987 GSP C compiler's packed bitfield layout:
* bitfields are allocated LSB-first at the next free bit, with no padding
* between adjacent fields and across the 32-bit word boundary; an unnamed
* `:0` bitfield is ignored (the oracle's `b` after `a:3; :0` is at bit 3).
* Clang's record layout for the target must agree; the _Static_asserts check
* the byte-expressible part (sizeof/alignof) and the runtime markers check
* the bit offsets by setting each field to a known value, reading it back and
* checking the raw storage bytes.
*
* The structs are volatile so the accesses survive -O2; the marker array is
* volatile too. Marker word n lives at bitfield_markers[n], i.e. 0x20 bits
* above the previous one; scripts/m6/bitfield-check.lua reads them from the
* linker map.
*
* Raw storage is read little-endian (the target's data layout is `e`): byte 0
* holds struct bits 0..7. The 1987 oracle's `g` is `.bss _g,36,16`, and the
* object allocator rounds that to 48 bits; the M6 .bss emitter rounds every
* object to a 16-bit unit, so a standalone object matches. Arrays, nested
* members and pointer arithmetic on a struct whose content is not a whole
* byte are the documented divergence:
* TI strides by the 36-bit content, Clang by the byte-rounded 5-byte sizeof.
*/
typedef unsigned int u32;
/* The oracle struct from the Task 5 notes (BITS.C). */
struct s {
unsigned a:3;
unsigned b:5;
int c:4;
unsigned d:20;
unsigned e:4;
};
struct cross { unsigned x:20; unsigned y:20; };
struct zw { unsigned a:3; unsigned :0; unsigned b:5; };
struct one { int s:1; unsigned u:1; };
struct word { unsigned w:32; unsigned v:1; };
struct edge { unsigned p:28; unsigned q:8; unsigned r:4; };
struct sx { int a:3; unsigned b:2; int c:9; int d:18; };
struct sy { int e:30; int f:6; };
struct lz { unsigned :0; unsigned a:3; unsigned b:5; };
/* A 31-bit field at bit 33 needs an i64 container (LSB-first). */
struct l64 { unsigned long long pad:33; unsigned f:31; };
struct q64 { unsigned long long q:57; };
volatile struct s g;
volatile struct s g2;
volatile struct cross cg;
volatile struct zw zg;
volatile struct one og;
volatile struct word wg;
volatile struct edge eg;
volatile struct sx sx;
volatile struct sy sy;
volatile struct lz lz;
volatile struct l64 l64g;
volatile struct l64 l64h;
volatile struct q64 q64g;
extern volatile u32 bitfield_markers[];
/* The oracle's sizeof values: 36 bits -> 5 bytes, 40 -> 5, 8 -> 1, 2 -> 1,
* 33 -> 5. TI reports the byte-rounded size; Clang must agree. */
_Static_assert(sizeof(struct s) == 5, "oracle sizeof(struct s)");
_Static_assert(sizeof(struct cross) == 5, "cross is a whole 40-bit word pair");
_Static_assert(sizeof(struct zw) == 1, "the :0 is ignored; a+b is 8 bits");
_Static_assert(sizeof(struct one) == 1, "two 1-bit fields fit one byte");
_Static_assert(sizeof(struct word) == 5, "32+1 bits round to 5 bytes");
_Static_assert(sizeof(struct edge) == 5, "28+8+4 bits = 40");
_Static_assert(sizeof(struct sx) == 4, "3+2+9+18 bits = 32");
_Static_assert(sizeof(struct sy) == 5, "30+6 bits = 36, rounded to 5 bytes");
_Static_assert(sizeof(struct lz) == 1, "leading :0 is ignored");
_Static_assert(sizeof(struct l64) == 8, "33+31 bits = 64");
_Static_assert(sizeof(struct q64) == 8, "57 bits round to 8 bytes");
_Static_assert(_Alignof(struct s) == 1, "packed record alignment is 1 byte");
static u32 raw_byte(volatile void *p, int i)
{
return ((volatile unsigned char *)p)[i];
}
static u32 raw_word0(volatile void *p)
{
volatile unsigned char *b = (volatile unsigned char *)p;
return (u32)b[0] | ((u32)b[1] << 8) | ((u32)b[2] << 16) |
((u32)b[3] << 24);
}
static u32 raw_word1(volatile void *p)
{
volatile unsigned char *b = (volatile unsigned char *)p;
return (u32)b[4] | ((u32)b[5] << 8) | ((u32)b[6] << 16) |
((u32)b[7] << 24);
}
static void set_l64(unsigned f) { l64g.f = f; }
static unsigned get_l64(void) { return l64g.f; }
static void set_q64(unsigned long long q) { q64g.q = q; }
static unsigned long long get_q64(void) { return q64g.q; }
/* An aggregate copy: at -O2 the optimizer may forward the i64 copy
* into the field read, so the memory order must match the IR. */
static unsigned copy_l64(struct l64 *dst, struct l64 *src)
{
*dst = *src;
return dst->f;
}
void bitfield_run(void)
{
volatile struct s *gp = &g2;
/* The oracle struct: a:3@0, b:5@3, c:4@8 (signed), d:20@12, e:4@32.
* Expected bytes: AD ED CD AB 09 (word0 ABCDEDADh, then e in byte 4). */
g.a = 5;
g.b = 21;
g.c = -3;
g.d = 0xABCDE;
g.e = 9;
bitfield_markers[0] = g.a;
bitfield_markers[1] = g.b;
bitfield_markers[2] = (u32)g.c;
bitfield_markers[3] = g.d;
bitfield_markers[4] = g.e;
bitfield_markers[5] = raw_word0((volatile void *)&g);
bitfield_markers[6] = raw_byte((volatile void *)&g, 4);
/* Signed nibble boundaries: +7 and the minimum -8 must sign-extend. */
g.c = 7;
bitfield_markers[7] = (u32)g.c;
g.c = -8;
bitfield_markers[8] = (u32)g.c;
/* struct cross: y:20 at bit 20 crosses bit 32.
* word0 345FEDCBh, byte4 12h. */
cg.x = 0xFEDCB;
cg.y = 0x12345;
bitfield_markers[9] = cg.x;
bitfield_markers[10] = cg.y;
bitfield_markers[11] = raw_word0((volatile void *)&cg);
bitfield_markers[12] = raw_byte((volatile void *)&cg, 4);
/* struct zw: a:3, unnamed :0 ignored, b:5 at bit 3.
* byte 8Bh (a=3 in bits 0..2, b=17 in bits 3..7). */
zg.a = 3;
zg.b = 17;
bitfield_markers[13] = zg.a;
bitfield_markers[14] = zg.b;
bitfield_markers[15] = raw_byte((volatile void *)&zg, 0);
/* struct one: the signed 1-bit field is the SEXT1 case (SLL 31/SRA 31).
* A 1-bit signed field holds 0 or -1: s=-1,u=1 -> byte 3; s=0,u=1 ->
* byte 2; s=-1,u=0 -> byte 1. */
og.s = -1;
og.u = 1;
bitfield_markers[16] = (u32)og.s;
bitfield_markers[17] = og.u;
bitfield_markers[18] = raw_byte((volatile void *)&og, 0);
og.s = 0;
og.u = 1;
bitfield_markers[19] = (u32)og.s;
bitfield_markers[20] = og.u;
bitfield_markers[21] = raw_byte((volatile void *)&og, 0);
og.s = -1;
og.u = 0;
bitfield_markers[22] = (u32)og.s;
bitfield_markers[23] = og.u;
bitfield_markers[24] = raw_byte((volatile void *)&og, 0);
/* struct word: w:32 at bit 0 (a full-word field) and v:1 at bit 32. */
wg.w = 0xDEADBEEF;
wg.v = 1;
bitfield_markers[25] = wg.w;
bitfield_markers[26] = wg.v;
bitfield_markers[27] = raw_word0((volatile void *)&wg);
bitfield_markers[28] = raw_byte((volatile void *)&wg, 4);
/* struct edge: q:8 at bit 28 crosses bit 32 (low nibble in word0 bits
* 28..31, high nibble in byte4 bits 0..3); r:4 at bit 36.
* word0 51234567h, byte4 CAh. */
eg.p = 0x1234567;
eg.q = 0xA5;
eg.r = 0xC;
bitfield_markers[29] = eg.p;
bitfield_markers[30] = eg.q;
bitfield_markers[31] = eg.r;
bitfield_markers[32] = raw_word0((volatile void *)&eg);
bitfield_markers[33] = raw_byte((volatile void *)&eg, 4);
/* Signed fields at odd offsets inside one 32-bit word:
* a:3@0, b:2@3, c:9@5, d:18@14; word0 80002715h. */
sx.a = -3;
sx.b = 2;
sx.c = -200;
sx.d = -131072;
bitfield_markers[34] = (u32)sx.a;
bitfield_markers[35] = sx.b;
bitfield_markers[36] = (u32)sx.c;
bitfield_markers[37] = (u32)sx.d;
bitfield_markers[38] = raw_word0((volatile void *)&sx);
/* A signed field crossing the word boundary: e:30@0, f:6@30.
* e=-100000000 (-100000000 & 3FFFFFFF = 3A0A1F00h), f=-20 (2Ch: low
* two bits 0 in word0 bits 30..31, high nibble Bh in byte4 bits 0..3). */
sy.e = -100000000;
sy.f = -20;
bitfield_markers[39] = (u32)sy.e;
bitfield_markers[40] = (u32)sy.f;
bitfield_markers[41] = raw_word0((volatile void *)&sy);
bitfield_markers[42] = raw_byte((volatile void *)&sy, 4);
/* The same oracle struct through a pointer, so the access path is a
* GEP/load/store rather than a fixed global address.
* word0 54321EF1h, byte4 0Fh. */
gp->a = 1;
gp->b = 30;
gp->c = -2;
gp->d = 0x54321;
gp->e = 15;
bitfield_markers[43] = gp->a;
bitfield_markers[44] = gp->b;
bitfield_markers[45] = (u32)gp->c;
bitfield_markers[46] = gp->d;
bitfield_markers[47] = gp->e;
bitfield_markers[48] = raw_word0((volatile void *)&g2);
bitfield_markers[49] = raw_byte((volatile void *)&g2, 4);
/* A leading unnamed :0 is ignored too: a:3@0, b:5@3, byte 4Eh. */
lz.a = 6;
lz.b = 9;
bitfield_markers[50] = lz.a;
bitfield_markers[51] = lz.b;
bitfield_markers[52] = raw_byte((volatile void *)&lz, 0);
/* 64-bit containers: LSW at the lower address. f@33, 31 bits;
* raw word0 = pad[0..31], raw word1 = pad[32] | f << 1. */
set_l64(0x12345678u);
bitfield_markers[53] = get_l64();
bitfield_markers[54] = raw_word0((volatile void *)&l64g);
bitfield_markers[55] = raw_word1((volatile void *)&l64g);
/* 57-bit field: LSW = q[0..31], MSW = q[32..56]. */
set_q64(0x0123456789ABCDEFull);
bitfield_markers[56] = (u32)get_q64();
bitfield_markers[57] = raw_word0((volatile void *)&q64g);
bitfield_markers[58] = raw_word1((volatile void *)&q64g);
/* Aggregate copy: GVN may forward the i64 copy into the field read at
* -O2, so the memory order must match the IR. (A constant-initialized
* i64 aggregate still hits the pre-existing M2 .data limitation at -O0.) */
bitfield_markers[59] = copy_l64(&l64h, &l64g);
bitfield_markers[60] = raw_word1((volatile void *)&l64h);
}
+183
View File
@@ -0,0 +1,183 @@
#!/bin/sh
# Extract and validate the 1990-11 TMS340 Family SDK floating-point/runtime
# libraries for the M6 ABI work.
#
# scripts/m6/flib-extract.sh
#
# The 1990 r5.01 Code Generation Tools are OS/2 1.x NE binaries and do not run
# under DOSBox, but their TI-COFF libraries are ordinary ar archives. The 1987
# GSPA 2.00/GSPLNK 2.00 tools assemble and link them unchanged, `$` symbols
# included.
#
# Outputs (all under build/m6-sdk, which is git-ignored):
# flib.lib flibc.lib flibi.lib rts.lib flib.src rts.src
# flib-members/ rts-members/ extracted archive members
# flib-symbols.txt exact external definitions
#
# Overridable: M6_SDK_OUT
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
OUT=${M6_SDK_OUT:-$ROOT/build/m6-sdk}
ZIPDIR="$ROOT/vendor/vt1200/tools/tms34010-sdk/1990-11 TMS340 Family SDK"
ZIP1="$ZIPDIR/1990-11-19 TMS340 Family Code Generation Tools (1 of 2) r5.01 rev2564062-1641.zip"
ZIP2="$ZIPDIR/1990-11-19 TMS340 Family Code Generation Tools (2 of 2) r5.01 rev2564062-1641.zip"
fail() {
echo "m6 flib-extract: FAIL: $*" >&2
exit 1
}
command -v unzip >/dev/null 2>&1 || fail "unzip is required"
command -v ar >/dev/null 2>&1 || fail "ar is required"
mkdir -p "$OUT"
if [ ! -f "$OUT/flib.lib" ] || [ ! -f "$OUT/rts.lib" ]; then
[ -f "$ZIP2" ] || fail "1990 SDK archive not found: $ZIP2"
unzip -o -q "$ZIP2" -d "$OUT"
# The tool archives are not needed to link (the 1987 tools are used), but
# extracting them records the exact 1990 release the libraries came from.
if [ -f "$ZIP1" ]; then
unzip -o -q "$ZIP1" -d "$OUT"
fi
fi
for f in flib.lib flibc.lib flibi.lib rts.lib flib.src rts.src; do
[ -f "$OUT/$f" ] || fail "missing $OUT/$f after extraction"
done
extract_members() {
lib=$1
dir=$OUT/$2
rm -rf "$dir"
mkdir -p "$dir"
(cd "$dir" && ar x "$OUT/$lib")
chmod -R u+rw "$dir"
}
extract_members flib.lib flib-members
extract_members flibc.lib flibc-members
extract_members flibi.lib flibi-members
extract_members rts.lib rts-members
python3 - "$ROOT" "$OUT" <<'PY'
import os
import struct
import sys
root, out = sys.argv[1], sys.argv[2]
sys.path.insert(0, os.path.join(root, "vendor", "vt1200", "dwt", "loader"))
import coff
def symname(c, sym):
"""Return a TI-COFF symbol name, resolving the long-name string table."""
d = c["data"]
raw = d[c["symptr"] + sym["index"] * 18:][:8]
if raw[:4] == b"\0\0\0\0":
off = struct.unpack_from("<I", raw, 4)[0]
base = c["symptr"] + c["nsyms"] * 18
end = d.index(b"\0", base + off)
return d[base + off:end].decode("latin1")
return raw.rstrip(b"\0").decode("latin1")
lines = [
"# 1990-11 TMS340 Family SDK r5.01 external symbol definitions",
"# generated by scripts/m6/flib-extract.sh; do not edit",
"#",
"# flib.lib is the GSP-format floating-point library used by the TI C",
"# compiler by default. flibc.lib/flibi.lib are identified as the",
"# 34082/IEEE variants from member-code inspection (see the variant",
"# section at the end); the 1990 compiler was not run. M6 links flib.lib.",
"",
]
for lib, members in (("flib.lib", "flib-members"), ("rts.lib", "rts-members")):
lines.append("== %s" % lib)
d = os.path.join(out, members)
for fn in sorted(os.listdir(d)):
c = coff.parse(os.path.join(d, fn))
ext = [symname(c, s) for s in c["symbols"]
if s["sclass"] == 2 and s["secno"] > 0]
if ext:
lines.append("%-14s %s" % (fn, " ".join(ext)))
lines.append("")
def text_bits(c):
for s in c["sections"]:
if s["name"] == ".text":
return s["size"]
return 0
lines.append("== variant inspection (not linked by M6)")
for lib, members in (("flib.lib", "flib-members"),
("flibc.lib", "flibc-members"),
("flibi.lib", "flibi-members")):
parts = []
for fn in ("fs_add.obj", "fd_add.obj"):
c = coff.parse(os.path.join(out, members, fn))
parts.append("%s .text %d bits" % (fn, text_bits(c)))
lines.append("%-11s %s" % (lib, "; ".join(parts)))
lines.extend([
"# flibc/flibi are identified as the 34082/IEEE variants from member-code",
"# inspection (their members begin with the 34082 path and are larger) and",
"# release naming, not by running the OS/2-only 1990 compiler. M6 links",
"# flib.lib only.",
"",
])
text = "\n".join(lines) + "\n"
with open(os.path.join(out, "flib-symbols.txt"), "w") as f:
f.write(text)
sys.stdout.write(text)
PY
# The exact entries M6 tasks 2/3/6 depend on. If a name is missing the ABI
# contract in TMS34010.md/README.md is stale, so fail loudly.
for sym in \
'FS$ADD' 'FS$SUB' 'FS$SUB_R' 'FS$MUL' 'FS$DIV' 'FS$DIV_R' 'FS$NEG' \
'FS$EQ' 'FS$NE' 'FS$LT' 'FS$LE' 'FS$GT' 'FS$GE' 'FS$ZERO' 'FS$INC' \
'FS$INCR' 'FS$DEC' 'FS$DECR' \
'FD$ADD' 'FD$SUB' 'FD$SUB_R' 'FD$MUL' 'FD$DIV' 'FD$DIV_R' 'FD$NEG' \
'FD$EQ' 'FD$NE' 'FD$LT' 'FD$LE' 'FD$GT' 'FD$GE' 'FD$ZERO' 'FD$INC' \
'FD$INCR' 'FD$DEC' 'FD$DECR' \
'FD$DTOF' 'FD$FTOD' 'FD$FTOI' 'FD$FTOU' 'FD$DTOI' 'FD$DTOU' \
'FD$ITOF' 'FD$ITOD' 'FD$UTOF' 'FD$UTOD'
do
grep -Fq " $sym" "$OUT/flib-symbols.txt" \
|| fail "expected flib symbol $sym is missing"
done
# rts.lib is the C runtime, not a 64-bit arithmetic source: M6 task 2 must use
# target sequences, not invented helpers. Record that fact as a checked one.
if grep -Eiq '(^| )(__ll|_ll|llmul|lldiv|lladd|llsub|\$ll|\$i64|__i64)' "$OUT/flib-symbols.txt"; then
fail "unexpected 64-bit helper in flib/rts symbol list; re-check the ABI note"
fi
cat > "$OUT/m6-abi.txt" <<EOF
flib ABI (from flib.src and the 1987 C compiler output):
* arithmetic: operands are pushed on A14, first operand first, second last;
the result is pushed on A14 (one word for FS\$, two for FD\$);
* compares: both operands are popped from A14; the boolean is in A8
(1 true, 0 false); nothing is pushed;
* conversions: FD\$FTOI/FTOU and FD\$DTOI/DTOU pop the float/double from A14
and return the integer in A8; FD\$ITOF/UTOF and FD\$ITOD/UTOD take the
integer in A8 and push one float / two double words on A14;
FD\$FTOD pops a float and pushes two double words, FD\$DTOF pops a double
and pushes one float word;
* flib routines end in RETS (not RETS 2): pop the pushed result (if any),
then restore the caller A14 from the old-STK word saved on the system
stack;
* flib.lib uses the GSP floating format: 1.5 = 40600000h (float) and
00000000h/400C0000h (double, LSW at the lower address);
* float arguments are one 32-bit slot (ANSI/FS\$ rule; the 1987 K&R oracle
promotes float parameters to double, so it does not pin this slot).
link line:
GSPLNK -l flib.lib -l rts.lib (scripts/m6/link.cmd)
symbol list: $OUT/flib-symbols.txt
EOF
cat "$OUT/m6-abi.txt"
+139
View File
@@ -0,0 +1,139 @@
# 1990-11 TMS340 Family SDK r5.01 external symbol definitions
# generated by scripts/m6/flib-extract.sh; do not edit
#
# flib.lib is the GSP-format floating-point library used by the TI C
# compiler by default. flibc.lib/flibi.lib are identified as the
# 34082/IEEE variants from member-code inspection (see the variant
# section at the end); the 1990 compiler was not run. M6 links flib.lib.
== flib.lib
fc_dtof.obj FD$DTOF
fc_dtoi.obj FD$DTOI
fc_dtou.obj FD$DTOU
fc_ftod.obj FD$FTOD
fc_ftoi.obj FD$FTOI
fc_ftou.obj FD$FTOU
fc_itod.obj FD$ITOD
fc_itof.obj FD$ITOF
fc_utod.obj FD$UTOD
fc_utof.obj FD$UTOF
fd_add.obj FD$ADD FD$SUB_R FD$SUB
fd_cmp.obj FD$GE FD$LE FD$GT FD$LT
fd_decr.obj FD$DECR FD$DEC
fd_div.obj FD$DIV_R FD$DIV
fd_eq.obj FD$EQ
fd_error.obj _fp_error
fd_incr.obj FD$INCR FD$INC
fd_mul.obj FD$MUL
fd_ne.obj FD$NE
fd_neg.obj FD$NEG
fd_zero.obj FD$ZERO
fs_add.obj FS$SUB_R FS$ADD FS$SUB
fs_decr.obj FS$DECR FS$DEC
fs_div.obj FS$DIV FS$DIV_R
fs_eq.obj FS$EQ
fs_ge.obj FS$GE
fs_gt.obj FS$GT
fs_incr.obj FS$INC FS$INCR
fs_le.obj FS$LE
fs_lt.obj FS$LT
fs_mul.obj FS$MUL
fs_ne.obj FS$NE
fs_neg.obj FS$NEG
fs_zero.obj FS$ZERO
== rts.lib
abs.obj _labs _abs
asctime.obj _asctime
asin.obj _acos _asin
atan.obj _atan2 _atan
atof.obj _atof
atoi.obj _atoi _atol
boot.obj _c_int00 __present82
bsearch.obj _bsearch
check82.obj _check82
clock.obj _clock
ctime.obj _ctime
ctype.obj __ctypes_
difftime.obj _difftime
div.obj _div _ldiv
dtos.obj _dtos
ecvt.obj _ecvt
errno.obj _errno
exit.obj _abort _exit _atexit
exp.obj _exp
fabs.obj _fabs
fconvert.obj _fconvert
fcvt.obj _fcvt
floor.obj _ceil _floor
fmod.obj _fmod
frexp.obj _frexp
gmtime.obj _gmtime
isalnum.obj _isalnum
isalpha.obj _isalpha
isascii.obj _isascii
iscntrl.obj _iscntrl
isdigit.obj _isdigit
isgraph.obj _isgraph
islower.obj _islower
isprint.obj _isprint
ispunct.obj _ispunct
isspace.obj _isspace
isupper.obj _isupper
isxdigit.obj _isxdigit
ldexp.obj _ldexp
localtim.obj _localtime
log.obj _log _log10
ltoa.obj _ltoa
memchr.obj _memchr
memcmp.obj _memcmp
memmov.obj _memmove _memcpy
memory.obj _minit _malloc _realloc _free _calloc
memset.obj _memset
mktime.obj _mktime
modf.obj _modf
pow.obj _pow
qsort.obj _qsort
rand.obj _srand _rand
scheck.obj s$check
setjmp.obj _longjmp __setjmp _setjmp
sin.obj _cos _sin
sinh.obj _sinh _cosh
sqrt.obj _sqrt
strcat.obj _strcat
strchr.obj _strchr
strcmp.obj _strcmp
strcoll.obj _strcoll
strcpy.obj _strcpy
strcspn.obj _strcspn
strerror.obj _strerror
strftime.obj _strftime
strlen.obj _strlen
strncat.obj _strncat
strncmp.obj _strncmp
strncpy.obj _strncpy
strpbrk.obj _strpbrk
strrchr.obj _strrchr
strspn.obj _strspn
strstr.obj _strstr
strtod.obj _strtod
strtok.obj _strtok
strtol.obj _strtol
strtoul.obj _strtoul
strxfrm.obj _strxfrm
tan.obj _tan
tanh.obj _tanh
time.obj _time
toascii.obj _toascii
tolower.obj _tolower
toupper.obj _toupper
== variant inspection (not linked by M6)
flib.lib fs_add.obj .text 2384 bits; fd_add.obj .text 3728 bits
flibc.lib fs_add.obj .text 3328 bits; fd_add.obj .text 4864 bits
flibi.lib fs_add.obj .text 3328 bits; fd_add.obj .text 4864 bits
# flibc/flibi are identified as the 34082/IEEE variants from member-code
# inspection (their members begin with the 34082 path and are larger) and
# release naming, not by running the OS/2-only 1990 compiler. M6 links
# flib.lib only.
+114
View File
@@ -0,0 +1,114 @@
-- float-check.lua -- read the M6 float/double marker words and compare them
-- with the expected GSP bit patterns.
--
-- FLOAT_MARKERS is the bit address of _float_markers from the linker map. Each
-- marker is one 32-bit word at base + n*0x20 bits. Doubles are pairs: LSW
-- first (the lower address), MSW second, which is also the GSP memory order.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("FLOAT_MARKERS"), 16)
local N = 80
local frames = 0
local checked = false
local expect = {
[0] = 0x41400000, -- fadd(1.5,2.5) = 4.0
[1] = 0x40400000, -- fsub(2.5,1.5) = 1.0
[2] = 0xC0400000, -- fsub(1.5,2.5) = -1.0
[3] = 0x41C00000, -- fmul(4.0,2.0) = 8.0
[4] = 0x40C00000, -- fdiv(4.0,2.0) = 2.0
[5] = 0xC0600000, -- fneg(1.5) = -1.5
[6] = 0x41400000, -- C body float_add(1.5,2.5)
[7] = 0x40600000, -- C float_ret() = 1.5
[8] = 0x00000000, [9] = 0x40280000, -- dadd(1.5,2.5) = 4.0
[10] = 0x00000000, [11] = 0x40080000, -- dsub(2.5,1.5) = 1.0
[12] = 0x00000000, [13] = 0xC0080000, -- dsub(1.5,2.5) = -1.0
[14] = 0x00000000, [15] = 0x40380000, -- dmul(4.0,2.0) = 8.0
[16] = 0x00000000, [17] = 0x40180000, -- ddiv(4.0,2.0) = 2.0
[18] = 0x00000000, [19] = 0xC00C0000, -- dneg(1.5) = -1.5
[20] = 0x00000000, [21] = 0x40280000, -- C double_add(1.5,2.5) = 4.0
[22] = 0x00000000, [23] = 0x401A0000, -- C double_ret() = 2.5
[24] = 1, -- fcmpeq(1.5,1.5)
[25] = 0, -- fcmpeq(1.5,2.5)
[26] = 1, -- fcmplt(1.5,2.5)
[27] = 0, -- fcmplt(2.5,1.5)
[28] = 1, -- fcmple(2.5,2.5)
[29] = 1, -- fcmpgt(2.5,1.5)
[30] = 0, -- fcmpge(1.5,2.5)
[31] = 1, -- fcmpne(1.5,2.5)
[32] = 0, -- fcmpne(1.5,1.5)
[33] = 1, -- dcmplt(1.5,2.5)
[34] = 0, -- dcmplt(2.5,1.5)
[35] = 1, -- dcmpeq(2.5,2.5)
[36] = 2, -- ftoi(2.5)
[37] = 0xFFFFFFFF, -- ftoi(-1.5) = -1
[38] = 3, -- ftou(3.9)
[39] = 2, -- dtoi(2.5)
[40] = 3, -- dtou(3.9)
[41] = 0x41700000, -- itof(7) = 7.0
[42] = 0x41700000, -- utof(7) = 7.0
[43] = 0xC0E00000, -- itof(-3) = -3.0
[44] = 0x00000000, [45] = 0x402E0000, -- itod(7) = 7.0
[46] = 0x00000000, [47] = 0x402E0000, -- utod(7) = 7.0
[48] = 0x00000000, [49] = 0x400C0000, -- ftod(1.5f) = 1.5
[50] = 0x40D00000, -- dtof(2.5) = 2.5
[51] = 0x41700000, -- constant 7.0f
[52] = 0xC0E00000, -- constant -3.0f
[53] = 0x00000000, [54] = 0x402E0000, -- constant 7.0
[55] = 0x00000000, [56] = 0xC01C0000, -- constant -3.0
[57] = 1, -- fcmpge(2.5,2.5)
[58] = 0, -- fcmpgt(1.5,1.5)
[59] = 0xFFFFFFFF, -- dtoi(-1.5) = -1
[60] = 0, -- fcmple(2.5,1.5)
[61] = 0, -- dcmpeq(1.5,2.5)
[62] = 11, -- fb_lt(1.5,2.5) true path
[63] = 22, -- fb_lt(2.5,1.5) false path
[64] = 33, -- db_lt(1.5,2.5) true path
[65] = 44, -- db_lt(2.5,1.5) false path
[66] = 3, -- fcount_lt(1.5,4.0): 1.5,2.5,3.5
[67] = 0x00000000, [68] = 0x400C0000, -- dsel_i(1,1.5,2.5) = 1.5
[69] = 0x00000000, [70] = 0x401A0000, -- dsel_i(0,1.5,2.5) = 2.5
[71] = 0x00000000, [72] = 0x40280000, -- dsel_f(<,4.0,8.0) = 4.0
[73] = 0x00000000, [74] = 0x40380000, -- dsel_f(>,4.0,8.0) = 8.0
[75] = 0x00000000, -- fnegzero(): GSP canonicalises -0.0
[76] = 0x00000000, -- fposzero()
[77] = 0x00000000, [78] = 0x00000000, -- dnegzero(): two zero words
[79] = 0x5A5A5A5A, -- marker after float_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 float:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 FLOAT MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 float: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 FLOAT MAME: FAIL")
end
end
end, "float-check")
+27
View File
@@ -0,0 +1,27 @@
; float-entry.asm -- M6 float/double gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver float_run() and writes a post-return marker. float.sh concatenates
; the llc output for m6-float.ll and the compiled driver after this file, so
; _float_run and the float/double functions are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); float-check.lua reads
; its address from the linker map and checks 80 words (markers 0..79, the last
; one written after float_run returns). Marker n is 0x20 bits above marker
; n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _float_run
movi 5A5A5A5Ah, a0
movi _float_markers+2528, a2 ; marker 79, the post-return word
move a0, *a2, 1
rets
.globl _float_markers
.bss _float_markers, 2560, 16 ; 80 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+241
View File
@@ -0,0 +1,241 @@
/* M6 float/double gate driver.
*
* Calls the compiled float/double functions in m6-float.ll through the M6
* flib ABI and writes the expected GSP result words to the marker array
* defined by the entry assembly. Compiling this driver also exercises the
* compiler's caller side (hidden float/double return slot, stack argument
* pushes, LSW-first doubles) and the callee side of its own C functions
* (float_add, double_add, float_ret, double_ret).
*
* Values are written as raw GSP words, not converted: a float union member
* and an array of two 32-bit words for a GSP double (u[0] = LSW, u[1] = MSW).
*
* Marker word n lives at float_markers[n], i.e. 0x20 bits above the previous
* one; scripts/m6/float-check.lua reads them by bit address from the linker
* map.
*/
typedef unsigned int u32;
typedef union {
float f;
u32 u;
} fu;
typedef union {
double d;
u32 u[2];
} du;
extern volatile u32 float_markers[];
/* Callees defined in m6-float.ll. */
extern float fadd(float, float);
extern float fsub(float, float);
extern float fmul(float, float);
extern float fdiv(float, float);
extern float fneg(float);
extern double dadd(double, double);
extern double dsub(double, double);
extern double dmul(double, double);
extern double ddiv(double, double);
extern double dneg(double);
extern int fcmpeq(float, float);
extern int fcmplt(float, float);
extern int fcmple(float, float);
extern int fcmpgt(float, float);
extern int fcmpge(float, float);
extern int fcmpne(float, float);
extern int dcmplt(double, double);
extern int dcmpeq(double, double);
extern int ftoi(float);
extern int ftou(float);
extern int dtoi(double);
extern int dtou(double);
extern float itof(int);
extern float utof(u32);
extern double itod(int);
extern double utod(u32);
extern double ftod(float);
extern float dtof(double);
/* Control flow on floating-point comparisons. These are the shapes that were
* missing: `if (a < b)` on float/double and `?:` on a double. */
static int fb_lt(float a, float b)
{
if (a < b)
return 11;
return 22;
}
static int db_lt(double a, double b)
{
if (a < b)
return 33;
return 44;
}
/* A while loop whose condition is a float compare and whose body is float
* arithmetic: a(float) = 1.5, b(float) = 4.0 iterates 1.5, 2.5, 3.5 and stops
* at 4.5, so it counts 3. */
static int fcount_lt(float a, float b)
{
int n = 0;
while (a < b) {
a = a + 1.0f;
n++;
}
return n;
}
/* An f64 select with an integer condition. */
static double dsel_i(int c, double x, double y)
{
return c ? x : y;
}
/* An f64 select with a floating-point condition. */
static double dsel_f(double a, double b, double x, double y)
{
return (a < b) ? x : y;
}
/* GSP has no signed zero: -0.0 must lower to the same all-zero words as +0.0,
* exactly as GSPA prints `.float -0.0`. These markers pin that. */
static float fnegzero(void)
{
return -0.0f;
}
static float fposzero(void)
{
return 0.0f;
}
static double dnegzero(void)
{
return -0.0;
}
static void mark_f(u32 n, float v)
{
fu x;
x.f = v;
float_markers[n] = x.u;
}
static void mark_d(u32 n, double v)
{
du x;
x.d = v;
float_markers[n] = x.u[0]; /* LSW: the lower address in GSP order */
float_markers[n + 1] = x.u[1]; /* MSW */
}
/* C-side callees: the compiler must emit the flib calls for these bodies. */
float float_add(float a, float b)
{
return a + b;
}
double double_add(double a, double b)
{
return a + b;
}
float float_ret(void)
{
return 1.5f;
}
double double_ret(void)
{
return 2.5;
}
void float_run(void)
{
/* Single-precision arithmetic, including the reversed subtraction order
* and a negative result. */
mark_f(0, fadd(1.5f, 2.5f)); /* 4.0 */
mark_f(1, fsub(2.5f, 1.5f)); /* 1.0 */
mark_f(2, fsub(1.5f, 2.5f)); /* -1.0 */
mark_f(3, fmul(4.0f, 2.0f)); /* 8.0 */
mark_f(4, fdiv(4.0f, 2.0f)); /* 2.0 */
mark_f(5, fneg(1.5f)); /* -1.5 */
mark_f(6, float_add(1.5f, 2.5f)); /* C body */
mark_f(7, float_ret()); /* C no-argument hidden return */
/* Double-precision arithmetic, LSW then MSW. */
mark_d(8, dadd(1.5, 2.5)); /* 4.0 */
mark_d(10, dsub(2.5, 1.5)); /* 1.0 */
mark_d(12, dsub(1.5, 2.5)); /* -1.0 */
mark_d(14, dmul(4.0, 2.0)); /* 8.0 */
mark_d(16, ddiv(4.0, 2.0)); /* 2.0 */
mark_d(18, dneg(1.5)); /* -1.5 */
mark_d(20, double_add(1.5, 2.5)); /* C body */
mark_d(22, double_ret()); /* C no-argument hidden return */
/* Float compares: true and false cases. */
float_markers[24] = (u32)fcmpeq(1.5f, 1.5f);
float_markers[25] = (u32)fcmpeq(1.5f, 2.5f);
float_markers[26] = (u32)fcmplt(1.5f, 2.5f);
float_markers[27] = (u32)fcmplt(2.5f, 1.5f);
float_markers[28] = (u32)fcmple(2.5f, 2.5f);
float_markers[29] = (u32)fcmpgt(2.5f, 1.5f);
float_markers[30] = (u32)fcmpge(1.5f, 2.5f);
float_markers[31] = (u32)fcmpne(1.5f, 2.5f);
float_markers[32] = (u32)fcmpne(1.5f, 1.5f);
/* Double compares. */
float_markers[33] = (u32)dcmplt(1.5, 2.5);
float_markers[34] = (u32)dcmplt(2.5, 1.5);
float_markers[35] = (u32)dcmpeq(2.5, 2.5);
/* float/double -> integer: truncation toward zero. */
float_markers[36] = (u32)ftoi(2.5f); /* 2 */
float_markers[37] = (u32)ftoi(-1.5f); /* -1 */
float_markers[38] = (u32)ftou(3.9f); /* 3 */
float_markers[39] = (u32)dtoi(2.5); /* 2 */
float_markers[40] = (u32)dtou(3.9); /* 3 */
/* integer -> float/double. */
mark_f(41, itof(7)); /* 7.0 */
mark_f(42, utof(7)); /* 7.0 */
mark_f(43, itof(-3)); /* -3.0 */
mark_d(44, itod(7)); /* 7.0 */
mark_d(46, utod(7)); /* 7.0 */
mark_d(48, ftod(1.5f)); /* 1.5 */
mark_f(50, dtof(2.5)); /* 2.5 */
/* Constants materialised from the GSP pool, including a negative one. */
mark_f(51, 7.0f);
mark_f(52, -3.0f);
mark_d(53, 7.0);
mark_d(55, -3.0);
float_markers[57] = (u32)fcmpge(2.5f, 2.5f); /* 1 */
float_markers[58] = (u32)fcmpgt(1.5f, 1.5f); /* 0 */
float_markers[59] = (u32)dtoi(-1.5); /* -1 */
float_markers[60] = (u32)fcmple(2.5f, 1.5f); /* 0 */
float_markers[61] = (u32)dcmpeq(1.5, 2.5); /* 0 */
/* Control flow on float/double comparisons: the true and false path of a
* float and a double branch, and a float-compared while loop. */
float_markers[62] = (u32)fb_lt(1.5f, 2.5f); /* true: 11 */
float_markers[63] = (u32)fb_lt(2.5f, 1.5f); /* false: 22 */
float_markers[64] = (u32)db_lt(1.5, 2.5); /* true: 33 */
float_markers[65] = (u32)db_lt(2.5, 1.5); /* false: 44 */
float_markers[66] = (u32)fcount_lt(1.5f, 4.0f); /* 3 iterations */
/* ?: on a double, with an integer and a floating-point condition. */
mark_d(67, dsel_i(1, 1.5, 2.5)); /* 1.5 */
mark_d(69, dsel_i(0, 1.5, 2.5)); /* 2.5 */
mark_d(71, dsel_f(1.5, 2.5, 4.0, 8.0)); /* 4.0 */
mark_d(73, dsel_f(2.5, 1.5, 4.0, 8.0)); /* 8.0 */
/* Signed zero: both spellings lower to all-zero GSP words. */
mark_f(75, fnegzero()); /* 0 */
mark_f(76, fposzero()); /* 0 */
mark_d(77, dnegzero()); /* 0 / 0 */
}
+81
View File
@@ -0,0 +1,81 @@
-- i64-check.lua -- read the M6 i64 marker words and compare them with the
-- expected ABI/arithmetic values.
--
-- I64_MARKERS is the bit address of _i64_markers from the linker map. Each
-- marker is one 32-bit word at base + n*0x20 bits. The values are pairs:
-- MSW first, LSW second, so the word order is checked as well as the result.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("I64_MARKERS"), 16)
local N = 57
local frames = 0
local checked = false
local expect = {
[0] = 0x2345678A, [1] = 0x00000001, -- addll(carry)
[2] = 0x00000000, [3] = 0xACF13568, -- addll(12345678h,9ABCDEF0h)
[4] = 0xFEDCBA98, [5] = 0x00000005, -- subll borrow
[6] = 0x0000000A, [7] = 0x00000008, -- mull cross terms
[8] = 0xFFFFFFFF, [9] = 0xFFFFFFF1, -- (-3)*5
[10] = 0x00010004, [11] = 0xC016906B, -- divll / 1234h
[12] = 0x00000000, [13] = 0x00000334, -- remll / 1234h
[14] = 0x00000000, [15] = 0x10000000, -- divll by a >32-bit divisor
[16] = 0x00000000, [17] = 0x0ABCDEF0, -- remll by a >32-bit divisor
[18] = 0xFFFFFFDE, [19] = 0xBD0CFDB7, -- sdivll(-1e12, 7)
[20] = 0xFFFFFFFF, [21] = 0xFFFFFFFF, -- sremll(-1e12, 7) == -1
[22] = 0xFFFFFFFF, [23] = 0xFFFFFFEF, -- sdivll(123, -7) == -17
[24] = 0x00000000, [25] = 0x00000004, -- sremll(123, -7) == 4
[26] = 0x00000100, [27] = 0x00000000, -- 1 << 40
[28] = 0x00000000, [29] = 0x00000001, -- 8000000000000000h >> 63
[30] = 0xFFFFFFFF, [31] = 0xFFFFFFFC, -- -16 >> 2
[32] = 1, [33] = 0, -- cmplt(-1,1), cmplt(1,-1)
[34] = 1, [35] = 0, -- cmpeq both halves
[36] = 0x00000006, [37] = 0x00000004, -- i64_slot LSW/MSW word order
[38] = 0x00000004, [39] = 0x00000006, -- i64 load round-trip
[40] = 0x0F0F0000, [41] = 0x0F0F0000, -- and
[42] = 0xFFFF0F0F, [43] = 0xFFFF0F0F, -- or
[44] = 0xF0F00F0F, [45] = 0xF0F00F0F, -- xor
[46] = 0x11223344, [47] = 0x55667788, -- zero-argument i64 return
[48] = 0x11223344, [49] = 0x55667788, -- shll(x, 0)
[50] = 0x55667788, [51] = 0x00000000, -- shll(x, 32)
[52] = 0x00000000, [53] = 0x11223344, -- srl(x, 32)
[54] = 0xFFFFFFFF, [55] = 0x80000000, -- sra(8000..., 32)
[56] = 0x5A5A5A5A, -- marker after i64_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 i64:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 I64 MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 i64: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 I64 MAME: FAIL")
end
end
end, "i64-check")
+27
View File
@@ -0,0 +1,27 @@
; i64-entry.asm -- M6 i64 gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver i64_run() and writes a post-return marker. i64.sh concatenates the
; llc output for m6-i64.ll and the compiled driver after this file, so
; _i64_run and the i64 functions are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); i64-check.lua reads
; its address from the linker map and checks 57 words (markers 0..56, the last
; one written after i64_run returns). Marker n is 0x20 bits above marker n-1,
; matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _i64_run
movi 5A5A5A5Ah, a0
movi _i64_markers+1792, a2 ; marker 56, the post-return word
move a0, *a2, 1
rets
.globl _i64_markers
.bss _i64_markers, 2048, 16 ; 57 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+127
View File
@@ -0,0 +1,127 @@
/* M6 i64 gate driver.
*
* Calls the compiled `long long` functions in m6-i64.ll through the M6 ABI and
* writes the expected result words to the marker array defined by the entry
* assembly. Compiling this driver also exercises the compiler's *caller*
* side of the hidden-return slot and the two-slot i64 argument pushes; the
* callee side (argument reads, ADD/ADDC, MPYS/MPYU, the division loop, RETS 2)
* comes from the same llc output the lit test checks.
*
* Marker word n lives at i64_markers[n], i.e. 0x20 bits above the previous
* one; scripts/m6/i64-check.lua reads them by bit address from the linker map.
*/
typedef unsigned int u32;
typedef unsigned long long u64;
typedef long long s64;
extern u64 addll(u64, u64);
extern u64 subll(u64, u64);
extern u64 mull(u64, u64);
extern u64 divll(u64, u64);
extern u64 remll(u64, u64);
extern s64 sdivll(s64, s64);
extern s64 sremll(s64, s64);
extern u64 andll(u64, u64);
extern u64 orll(u64, u64);
extern u64 xorll(u64, u64);
extern u64 shll(u64, u32);
extern u64 srl(u64, u32);
extern s64 sra(s64, u32);
extern u32 cmplt(s64, s64);
extern u32 cmpeq(u64, u64);
extern u64 ret64(void);
extern volatile u32 i64_markers[];
/* Every value is written as MSW first, LSW second, so the marker pair pins
* the word order as well as the numeric result. */
static void mark64(u32 n, u64 v)
{
i64_markers[n] = (u32)(v >> 32);
i64_markers[n + 1] = (u32)v;
}
/* i64 memory order: little-endian, LSW at the lower address. */
volatile u64 i64_slot;
void i64_run(void)
{
u64 r;
/* addll(12345678FFFFFFFEh, 1111111100000003h) = 2345678A00000001h.
* This is the Task 1 probe value; the low-word carry must reach the
* high word. */
mark64(0, addll(0x12345678FFFFFFFEull, 0x1111111100000003ull));
/* The literal brief case addll(12345678h, 9ABCDEF0h) = ACF13568h. */
mark64(2, addll(0x12345678ull, 0x9ABCDEF0ull));
/* subll(1111111100000003h, 12345678FFFFFFFEh) = FEDCBA9800000005h:
* the borrow crosses from the low into the high word. */
mark64(4, subll(0x1111111100000003ull, 0x12345678FFFFFFFEull));
/* mull(0000000100000002h, 0000000300000004h) = 0000000A00000008h:
* both cross terms are needed. */
mark64(6, mull(0x0000000100000002ull, 0x0000000300000004ull));
/* (-3) * 5 = -15 = FFFFFFFFFFFFFFF1h. */
mark64(8, mull(0xFFFFFFFFFFFFFFFDull, 5ull));
/* 123456789ABCDEF0h / 1234h = 10004C016906Bh, remainder 334h. */
mark64(10, divll(0x123456789ABCDEF0ull, 0x1234ull));
mark64(12, remll(0x123456789ABCDEF0ull, 0x1234ull));
/* A divisor above 32 bits forces the full 64x64 path:
* 123456789ABCDEF0h / 123456789h = 100000000h, remainder ABCDEF0h. */
mark64(14, divll(0x123456789ABCDEF0ull, 0x123456789ull));
mark64(16, remll(0x123456789ABCDEF0ull, 0x123456789ull));
/* Signed division truncates toward zero: -1000000000000 / 7 =
* -142857142857 = FFFFFFDEBD0CFDB7h, remainder -1. */
mark64(18, (u64)sdivll(-1000000000000ll, 7ll));
mark64(20, (u64)sremll(-1000000000000ll, 7ll));
/* 123 / -7 = -17 = FFFFFFFFh/FFFFFFEFh, remainder 4. */
mark64(22, (u64)sdivll(123ll, -7ll));
mark64(24, (u64)sremll(123ll, -7ll));
/* Variable-amount shifts: 1 << 40 = 10000000000h. */
mark64(26, shll(1ull, 40));
/* 8000000000000000h >> 63 = 1. */
mark64(28, srl(0x8000000000000000ull, 63));
/* -16 >> 2 = -4 = FFFFFFFFFFFFFFFCh (arithmetic). */
mark64(30, (u64)sra(-16ll, 2));
/* Compares: signed high-half ordering and equality across both halves. */
i64_markers[32] = cmplt(-1ll, 1ll);
i64_markers[33] = cmplt(1ll, -1ll);
i64_markers[34] = cmpeq(0x123456789ABCDEF0ull, 0x123456789ABCDEF0ull);
i64_markers[35] = cmpeq(0x123456789ABCDEF1ull, 0x123456789ABCDEF0ull);
/* i64 store then load through a volatile object, plus a direct word
* read: little-endian memory puts the LSW at the lower address. */
i64_slot = addll(0x0000000100000002ull, 0x0000000300000004ull);
{
volatile u32 *w = (volatile u32 *)&i64_slot;
i64_markers[36] = w[0];
i64_markers[37] = w[1];
}
r = i64_slot;
mark64(38, r);
/* Word-wise logic: and/or/xor of both halves. */
mark64(40, andll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
mark64(42, orll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
mark64(44, xorll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
/* A zero-argument i64 return: the caller still saves STK for the hidden
* slot and the callee must LOADSTK + RETS 2 with no argument area. */
mark64(46, ret64());
/* Variable-shift edges: 0, 32, and the arithmetic sign fill. */
mark64(48, shll(0x1122334455667788ull, 0));
mark64(50, shll(0x1122334455667788ull, 32));
mark64(52, srl(0x1122334455667788ull, 32));
mark64(54, (u64)sra(0x8000000000000000ull, 32));
}
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+139
View File
@@ -0,0 +1,139 @@
-- runtime-check.lua -- read the M6 runtime gate marker words and the shim's
-- printf output block, and compare them with the expected values.
--
-- RUNTIME_MARKERS is the bit address of _runtime_markers from the linker map;
-- each marker is one 32-bit word at base + n*0x20 bits. The shim's CONF
-- output block is fixed: length at 01B00020h, bytes at 01B10000h (one byte per
-- 8 bits). The checker compares the whole output byte-for-byte, including the
-- newlines, so the format implementation is the runtime oracle.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local BASE = tonumber(os.getenv("RUNTIME_MARKERS"), 16)
local LEN_ADDR = 0x01B00020
local OUT = 0x01B10000
local CAP = 16384
local N = 13 -- markers 0..12 are written by the driver
local SENT = 15 -- marker 15 is written after runtime_run returns
local frames = 0
local checked = false
local expect = {
[0] = 31, -- printf("%d %s %f %lld\n", ...) length
[1] = 9, -- sprintf("%d|%s|%.1f", 7, "abc", 2.5) length
[2] = 19, -- sprintf("%lld", 1234567890123456789) length
[3] = 300, -- sprintf truncation: full length, not the stored one
[4] = 255, -- strlen after truncation (SPRINTF_CAP-1)
[5] = 1, -- the truncated buffer is NUL-terminated
[6] = 4, -- (int)(1.5 + 2.5), flib FD$ADD + FD$DTOI
[7] = 3, -- (int)(1.5 * 2.5), flib FD$MUL + FD$DTOI
[8] = 1, -- memcpy result equals the source
[9] = 1, -- overlapping memmove forward ("aabcdef")
[10] = 1, -- overlapping memmove backward ("3456567")
[11] = 17, -- printf("S[%s] (%d)\n", ...) length
[12] = 1, -- rts.lib _isascii('A') nonzero, (0xC8) zero
}
local lines = {
"-42 hi 3.250000 -1234567890123",
"[ 42][-0042][7 ][+5][ 5][ff][0xff][10][010][ abc]",
"c=[ A][B ][C]",
"9223372036854775807 -9223372036854775808 " ..
"18446744073709551615 0 -1 4294967295 " ..
"[-0000000000000000005]",
"int=[-123456789][123456789abcdef0][110642547423257157360][00042][42 ]",
"-3.250000 -3.25 3 1.3 3.25 3.25 +3.250000",
"0.000000|00003.25|0.00| 3.25| 3.250000|3.|3.250000",
"cap=2147483520.000000",
"prec=[010][][][][][][0][0][ ]",
"round=10.000000 ncap=-2147483520.000000",
"S[7|abc|2.5] (9)",
"T(300,255,1)",
"mem=abcdefg abcdefg",
"mov=aabcdef",
"mov2=3456567",
"rts=1",
"flib 4.000000 3.750000",
}
local want_out = table.concat(lines, "\n") .. "\n"
local function read_string(space, addr, len)
local s = {}
for i = 0, len - 1 do
s[#s + 1] = string.char(space:read_u8(addr + i * 8))
end
return table.concat(s)
end
local function escape(s)
return (s:gsub("\n", "\\n"))
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
got[SENT] = prog:read_u32(BASE + SENT * 0x20)
if got[SENT] ~= 0x5A5A5A5A then
bad = bad + 1
end
io.write(string.format("M6 runtime:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write(string.format(" %08X\n", got[SENT]))
local len = prog:read_u32(LEN_ADDR)
if len > CAP then
print(string.format("M6 runtime: output length %d > cap %d",
len, CAP))
bad = bad + 1
len = 0
end
local out = read_string(prog, OUT, len)
print(string.format("M6 runtime out(%d): '%s'", len, escape(out)))
if out ~= want_out then
local diff = 1
while diff <= #out and diff <= #want_out and
out:sub(diff, diff) == want_out:sub(diff, diff) do
diff = diff + 1
end
print(string.format(
"M6 runtime: output differs at byte %d: got '%s' want '%s'",
diff, escape(out:sub(diff, diff + 20)),
escape(want_out:sub(diff, diff + 20))))
bad = bad + 1
end
if bad == 0 then
print("M6 RUNTIME MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 runtime: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
if got[SENT] ~= 0x5A5A5A5A then
print(string.format(
"M6 runtime: sentinel got %08X want 5A5A5A5A",
got[SENT]))
end
print("M6 RUNTIME MAME: FAIL")
end
end
end, "runtime-check")
+47
View File
@@ -0,0 +1,47 @@
; runtime-entry.asm -- M6 runtime gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver runtime_run() and writes a post-return marker. runtime.sh
; concatenates the compiled driver and the shared conformance shim after this
; file, so _runtime_run, printf/sprintf and the string/memory functions share
; one assembly.
;
; The marker array is in .bss (linked at the ram origin); runtime-check.lua
; reads its address from the linker map and checks 13 words (0..12 written by
; the driver), 15 after runtime_run returns, and leaves 13..14 zero/unchecked.
; Marker n is 0x20 bits above marker n-1.
;
; The shim's printf output goes to its own CONF_* block above the linked RAM
; region (length at 01B00020h, bytes at 01B10000h); the checker compares those
; bytes with the expected text.
;
; GSPA requires `.ref` for an external symbol used by CALLA. The AsmPrinter
; emits it for the flib `$` ExternalSymbols but not for an ordinary C
; declaration (a GlobalAddress), so declare the rts.lib entry here.
.ref _isascii
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
; Clear the shim's stream lengths. This entry does not otherwise touch
; the result block, and the shim's shadows cannot repair a cell it never
; writes (an empty stream), so clear both cells here.
movi 01B00020h, a1
sub a0, a0
move a0, *a1, 1
movi 01B00060h, a1
move a0, *a1, 1
movi _cstack, a14
move a14, a13
calla _runtime_run
movi 5A5A5A5Ah, a0
movi _runtime_markers+480, a2 ; marker 15, the post-return word
move a0, *a2, 1
rets
.globl _runtime_markers
.bss _runtime_markers, 512, 16 ; 16 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+142
View File
@@ -0,0 +1,142 @@
/* M6 runtime gate driver.
*
* Exercises the linked M6 runtime surface through the shared shim:
* - printf("%d %s %f %lld", ...) with a negative int, a string, a GSP double
* with a fraction, and a negative 64-bit value;
* - the M5 integer formats/flags/width/alternate forms;
* - i64/unsigned-i64 boundaries, %ld/%lu and a zero-padded %lld;
* - %f sign/space/plus/zero/width/precision, star width/precision, and the
* documented half-up rounding of %.0f / %.1f;
* - sprintf return values (C: the full untruncated length), NUL
* termination, and safe truncation at the shim's SPRINTF_CAP;
* - memcpy and memmove, including an overlapping backward copy;
* - a double add and multiply that must call flib.lib (FD$ADD/FD$MUL) and be
* converted back to an int by the compiler's fptosi path (FD$DTOI).
*
* The shim writes printf output to the CONF_* block (0x01B00020 length,
* 0x01B10000 bytes); runtime-check.lua compares those bytes exactly with the
* expected text. Marker word n is runtime_markers[n], 0x20 bits apart, in the
* .bss array defined by runtime-entry.asm.
*/
typedef unsigned int u32;
extern volatile u32 runtime_markers[];
extern int printf(const char *fmt, ...);
extern int sprintf(char *buf, const char *fmt, ...);
extern void *memcpy(void *dst, const void *src, unsigned int n);
extern void *memmove(void *dst, const void *src, unsigned int n);
extern int memcmp(const void *a, const void *b, unsigned int n);
extern unsigned int strlen(const char *s);
/* A real rts.lib scalar entry (isascii.obj; no data/.cinit dependency). The
* 1990 `_div`/`_ldiv` wrappers also live in rts.lib but return div_t/ldiv_t
* with the 1990 sret form, not M6's 1987 hidden slot, so calling them would
* not be valid M6 ABI evidence. */
extern int rts_isascii(int c) __asm__("isascii");
void runtime_run(void)
{
char sbuf[256]; /* the shim's sprintf cap (SPRINTF_CAP) */
char lng[301];
char m1[8] = "abcdefg";
char m2[8];
char m3[8] = "1234567";
volatile double a = 1.5; /* volatile: keep FD$ADD/FD$MUL at -O2 */
volatile double b = 2.5;
double d, e;
int i, n;
/* 1. The required mixed conversion: int, string, GSP double, i64. */
runtime_markers[0] = (u32)printf("%d %s %f %lld\n",
-42, "hi", 3.25,
-1234567890123LL);
/* 2. M5 flags/width/alternate plus the new %s precision and width. */
printf("[%5d][%05d][%-5d][%+d][% d][%x][%#x][%o][%#o][%8.3s]\n",
42, -42, 7, 5, 5, 255, 255, 8, 8, "abcdef");
/* 2b. %c honours width/left; a bare %c is unchanged. */
printf("c=[%3c][%-3c][%c]\n", 'A', 'B', 'C');
/* 3. i64/unsigned-i64 boundaries, 32-bit long, zero-padded i64. */
printf("%lld %lld %llu %llu %lld %lu [%020lld]\n",
9223372036854775807LL, (-9223372036854775807LL - 1),
0xFFFFFFFFFFFFFFFFULL, 0ULL, -1LL, 0xFFFFFFFFUL, -5LL);
/* 3b. %ld, 64-bit hex/octal, integer precision and a negative `*`
* width (left-justify with the magnitude of the width). */
printf("int=[%ld][%llx][%llo][%.5d][%*d]\n",
-123456789L, 0x123456789ABCDEF0ULL,
0x123456789ABCDEF0ULL, 42, -6, 42);
/* 4. %f sign/flags/width/precision; %.0f and %.1f round half-up. */
printf("%f %.2f %.0f %.1f %10.2f %-10.2f %+f\n",
-3.25, -3.25, 2.5, 1.25, 3.25, 3.25, 3.25);
/* 5. Zero, zero-padded, star width/precision, space and '#' flags;
* %.9f proves the documented 6-digit precision cap. */
printf("%f|%08.2f|%.2f|%*.*f|% f|%#.0f|%.9f\n",
0.0, 3.25, -0.0, 7, 2, 3.25, 3.25, 2.5, 3.25);
/* 5b. The documented i32-range cap: an out-of-range magnitude is clamped
* instead of taking FD$DTOI's error path. */
printf("cap=%f\n", 3000000000.0);
/* 5c. C precision edge cases: the octal '#' must not add a second
* leading zero when precision already supplies one, and zero with
* precision 0 produces no digits (except `%#.0o`/`%#o`, which keep
* one). */
printf("prec=[%#.3o][%.0d][%.0i][%.0u][%.0x][%.0X][%#.0o][%#o][%5.0d]\n",
8, 0, 0, 0, 0, 0, 0, 0, 0);
/* 5d. Rounding carry through the fraction into the integer part
* (9.9999999 -> 10.000000) and the negative magnitude clamp. */
printf("round=%f ncap=%f\n", 9.9999999, -3000000000.0);
/* sprintf into the caller buffer and print it; the return is the
* C number of characters written (no NUL). */
n = sprintf(sbuf, "%d|%s|%.1f", 7, "abc", 2.5);
runtime_markers[1] = (u32)n;
runtime_markers[11] = (u32)printf("S[%s] (%d)\n", sbuf, n);
/* sprintf return value at the 64-bit boundary (19 digits). */
runtime_markers[2] = (u32)sprintf(sbuf, "%lld",
1234567890123456789LL);
/* sprintf truncation: 300 characters into the 256-byte shim cap. */
for (i = 0; i < 300; i++)
lng[i] = 'a';
lng[300] = 0;
n = sprintf(sbuf, "%s", lng);
runtime_markers[3] = (u32)n;
runtime_markers[4] = strlen(sbuf);
runtime_markers[5] = (u32)(sbuf[255] == 0);
printf("T(%d,%u,%d)\n", n, strlen(sbuf), sbuf[255] == 0);
/* memcpy; then memmove in both directions (overlapping ranges). */
memcpy(m2, m1, 8);
runtime_markers[8] = (u32)(memcmp(m2, m1, 8) == 0);
printf("mem=%s %s\n", m2, m1);
memmove(m1 + 1, m1, 6);
runtime_markers[9] = (u32)(memcmp(m1, "aabcdef", 8) == 0);
printf("mov=%s\n", m1);
memmove(m3, m3 + 2, 4);
runtime_markers[10] = (u32)(memcmp(m3, "3456567", 8) == 0);
printf("mov2=%s\n", m3);
/* rts.lib is linked for real: _isascii is a scalar entry with the TI ABI
* (the 1990 _div/_ldiv wrappers are sret-form and are not called). */
i = (rts_isascii('A') != 0) && (rts_isascii(0xC8) == 0);
runtime_markers[12] = (u32)i;
printf("rts=%d\n", i);
/* flib.lib double arithmetic, formatted back through %f. The volatile
* operands keep the add/multiply from folding at -O2, so both levels
* link and call the real FD$ entries. */
d = a + b;
e = a * b;
runtime_markers[6] = (u32)(int)d;
runtime_markers[7] = (u32)(int)e;
printf("flib %f %f\n", d, e);
}
+70
View File
@@ -0,0 +1,70 @@
-- spike-check.lua -- load the M6 ABI-spike COFF with dwt/loader/loader.lua and
-- read the marker words written by scripts/m6/spike-probe.asm and
-- spike-entry.asm.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
--
-- Markers (0x20 bits apart) are the M4 marker convention:
-- 018A8000 FS$ADD float 4.0 (GSP) == 41400000h
-- 018A8020 FD$ADD double 4.0 MSW (GSP) == 40280000h
-- 018A8040 FD$ADD double 4.0 LSW == 00000000h
-- 018A8060 _m6_dadd hidden-return MSW == 40280000h
-- 018A8080 _m6_dadd hidden-return LSW == 00000000h
-- 018A80A0 i64 sum high word == 2345678Ah
-- 018A80C0 i64 sum low word == 00000001h
-- 018A80E0 FS$SUB(2.5,1.5) float 1.0 == 40400000h
-- 018A8100 FS$EQ(1.5,1.5) boolean in A8 == 00000001h
-- 018A8120 FD$FTOI(1.5) integer in A8 == 00000001h
-- 018A8140 FD$ITOF(1) float 1.0 pushed on A14 == 40400000h
-- 018A8160 _m6_fadd hidden-return float 4.0 == 41400000h
-- 018A8180 _start marker after _m6_probe returns == 5A5A5A5Ah
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local frames = 0
local checked = false
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local m = {}
for i = 0, 12 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M6: fs_add=%08X fd_add=%08X/%08X dadd=%08X/%08X i64=%08X/%08X fsub=%08X feq=%d ftoi=%d itof=%08X fadd=%08X ret=%08X",
m[0], m[1], m[2], m[3], m[4], m[5], m[6],
m[7], m[8], m[9], m[10], m[11], m[12]))
local want = {
0x41400000, -- FS$ADD 1.5 + 2.5
0x40280000, -- FD$ADD 4.0 MSW
0x00000000, -- FD$ADD 4.0 LSW
0x40280000, -- hidden-return 4.0 MSW
0x00000000, -- hidden-return 4.0 LSW
0x2345678A, -- i64 sum high
0x00000001, -- i64 sum low
0x40400000, -- FS$SUB(2.5,1.5) = 1.0
0x00000001, -- FS$EQ(1.5,1.5) = true in A8
0x00000001, -- FD$FTOI(1.5) = 1 in A8
0x40400000, -- FD$ITOF(1) = float 1.0 pushed on A14
0x41400000, -- _m6_fadd hidden-return 4.0
0x5A5A5A5A, -- _start after _m6_probe returns
}
local ok = true
for i = 0, 12 do
if m[i] ~= want[i + 1] then
ok = false
end
end
if ok then
print("M6 MAME: PASS")
else
print("M6 MAME: FAIL (want fs_add=41400000 fd_add=40280000/00000000 dadd=40280000/00000000 i64=2345678A/00000001 fsub=40400000 feq=1 ftoi=1 itof=40400000 fadd=41400000 ret=5A5A5A5A)")
end
end
end, "m6-check")
+25
View File
@@ -0,0 +1,25 @@
; spike-entry.asm -- M6 ABI spike entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the spike stack and calls the
; hand-written probe. The probe is assembly because the compiler does not
; support float/i64 calls until tasks 2/3.
;
; scripts/m6/spike-probe.asm the FS$/FD$ and i64 stack probes
; scripts/m6/spike-check.lua the MAME marker check
; scripts/tests/m6/spike.sh assemble, link with flib.lib/rts.lib, run
;
; FS0 is 16 and FS1 is 32 with the field-extension bit set, exactly as the M2
; ABI requires. A13 is FP and A14 is STK. spike.sh concatenates
; spike-probe.asm after this file, so _m6_probe is defined in the same assembly.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _m6_probe
move a8, @018A8180h, 1 ; marker after the probe returns
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+274
View File
@@ -0,0 +1,274 @@
; spike-probe.asm -- M6 float/double/i64 stack-ABI probe.
;
; The M6 compiler does not lower float/double or i64 calls yet (tasks 2/3), so
; this probe is hand-written assembly that exercises the TI C stack ABI and
; the 1990 SDK flib.lib entry points directly:
;
; 1. FS$ADD(1.5, 2.5) single-precision float, GSP format
; 2. FD$ADD(1.5, 2.5) double precision, GSP format
; 3. _m6_dadd(1.5, 2.5) a C-ABI double function with a caller-allocated
; hidden 8-byte return slot; it calls FD$ADD
; 4. _m6_i64_add two 32-bit argument words per i64 argument and a
; caller-allocated hidden 8-byte return slot
; 5. FS$SUB(2.5, 1.5) pins the arithmetic push order (2.5 first)
; 6. FS$EQ(1.5, 1.5) compare result in A8, not on A14
; 7. FD$FTOI/FD$ITOF integer conversion in A8 / float push on A14
; 8. _m6_fadd(1.5,2.5) a C-ABI float function with a one-word hidden slot
; 9. a marker after _m6_probe returns, so a broken A14 restore/RETS fails
;
; Results are written at the M4 marker addresses (0x20 bits apart) for
; scripts/m6/spike-check.lua:
;
; 018A8000 FS$ADD float 4.0 == 41400000h (GSP)
; 018A8020 FD$ADD double 4.0 most-significant word == 40280000h (GSP)
; 018A8040 FD$ADD double 4.0 least-significant word == 00000000h
; 018A8060 _m6_dadd hidden-return MSW == 40280000h
; 018A8080 _m6_dadd hidden-return LSW == 00000000h
; 018A80A0 i64 sum high word == 2345678Ah
; 018A80C0 i64 sum low word == 00000001h
; 018A80E0 FS$SUB(2.5,1.5) float 1.0 == 40400000h
; 018A8100 FS$EQ(1.5,1.5) boolean in A8 == 00000001h
; 018A8120 FD$FTOI(1.5) integer in A8 == 00000001h
; 018A8140 FD$ITOF(1) float 1.0 pushed on A14 == 40400000h
; 018A8160 _m6_fadd hidden-return float 4.0 == 41400000h
; 018A8180 _start marker after _m6_probe returns == 5A5A5A5Ah
;
; 1990 flib.lib is the GSP-format library (flibc.lib/flibi.lib are the
; 34082/IEEE variants by member inspection, not linked here). A GSP double is
; stored least-significant word first:
; the lower stack address holds the mantissa word, the higher address holds the
; sign/exponent word. The M6 i64 stack-slot order is MSW-first, so its
; most-significant word is at the lower address.
FP .set A13
STK .set A14
.ref FS$ADD
.ref FS$SUB
.ref FS$EQ
.ref FD$ADD
.ref FD$FTOI
.ref FD$ITOF
.text
.globl _m6_probe
_m6_probe:
setf 16, 1, 0
setf 32, 0, 1
move a14, -*sp, 1 ; preserve the probe's entry STK
move a13, -*sp, 1 ; preserve the probe's entry FP
; ---------------------------------------------------------------------------
; 1. FS$ADD: 1.5 + 2.5 == 4.0 (one 32-bit slot per float, GSP format)
; ---------------------------------------------------------------------------
move a14, -*sp, 1 ; flib uses RETS, not RETS 2
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
movi 040D00000h, a0 ; 2.5
move a0, *a14+, 1
calla FS$ADD
move -*a14, a8, 1 ; result 4.0
move *sp+, a14, 1 ; restore STK
move a8, @018A8000h, 1
; ---------------------------------------------------------------------------
; 2. FD$ADD: 1.5 + 2.5 == 4.0 (two 32-bit slots per double, GSP format).
; GSP puts the least-significant (mantissa) word at the lower address, so
; push it first; the sign/exponent word is the top of the operand.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
clr a0 ; 1.5 LSW
move a0, *a14+, 1
movi 0400C0000h, a0 ; 1.5 MSW
move a0, *a14+, 1
clr a0 ; 2.5 LSW
move a0, *a14+, 1
movi 0401A0000h, a0 ; 2.5 MSW
move a0, *a14+, 1
calla FD$ADD
move -*a14, a0, 1 ; result MSW (top)
move -*a14, a1, 1 ; result LSW
move *sp+, a14, 1
move a0, @018A8020h, 1
move a1, @018A8040h, 1
; ---------------------------------------------------------------------------
; 3. _m6_dadd(1.5, 2.5): the caller reserves the 8-byte return slot at the top
; of its frame, then saves STK, then pushes the arguments. The callee
; writes the result at saved_STK-64 (LSW) and saved_STK-32 (MSW).
; ---------------------------------------------------------------------------
addi 64, a14 ; caller-allocated return slot
move a14, -*sp, 1 ; save STK for the callee
clr a0 ; b=2.5 LSW
move a0, *a14+, 1
movi 0401A0000h, a0 ; b=2.5 MSW
move a0, *a14+, 1
clr a0 ; a=1.5 LSW
move a0, *a14+, 1
movi 0400C0000h, a0 ; a=1.5 MSW
move a0, *a14+, 1
calla _m6_dadd
move -*a14, a0, 1 ; result MSW (saved_STK-32)
move -*a14, a1, 1 ; result LSW (saved_STK-64)
move a0, @018A8060h, 1
move a1, @018A8080h, 1
; ---------------------------------------------------------------------------
; 4. _m6_i64_add(12345678FFFFFFFEh, 1111111100000003h) == 2345678A00000001h.
; Each i64 argument is two 32-bit slots, most-significant word first; the
; return is the 8-byte caller-allocated slot (MSW at saved_STK-64, LSW at
; saved_STK-32).
; ---------------------------------------------------------------------------
addi 64, a14 ; caller-allocated i64 return slot
move a14, -*sp, 1
movi 011111111h, a0 ; b high
move a0, *a14+, 1
movi 3, a0 ; b low
move a0, *a14+, 1
movi 012345678h, a0 ; a high
move a0, *a14+, 1
movi 0FFFFFFFEh, a0 ; a low
move a0, *a14+, 1
calla _m6_i64_add
move -*a14, a0, 1 ; result low (saved_STK-32)
move -*a14, a1, 1 ; result high (saved_STK-64)
move a1, @018A80A0h, 1
move a0, @018A80C0h, 1
; ---------------------------------------------------------------------------
; 5. FS$SUB(2.5, 1.5) == 1.0. The first operand is pushed first; the library
; pops the second (top) and subtracts it from the first. Reversing the
; push order would yield -1.0 (C0400000h), so this pins the order.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040D00000h, a0 ; 2.5 (first)
move a0, *a14+, 1
movi 040600000h, a0 ; 1.5 (second)
move a0, *a14+, 1
calla FS$SUB
move -*a14, a0, 1 ; result 1.0
move *sp+, a14, 1
move a0, @018A80E0h, 1
; ---------------------------------------------------------------------------
; 6. FS$EQ(1.5, 1.5) -> A8=1. A compare pops both operands and does not push
; a result; the boolean is in A8.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
move a0, *a14+, 1
calla FS$EQ
move *sp+, a14, 1 ; compare popped both; no result push
move a8, @018A8100h, 1 ; boolean true
; ---------------------------------------------------------------------------
; 7. FD$FTOI(1.5) -> A8=1 (float input on A14, integer result in A8), then
; FD$ITOF(1) -> float 1.0 pushed on A14 (integer input in A8).
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
calla FD$FTOI
move *sp+, a14, 1 ; input popped; no result push
move a8, @018A8120h, 1 ; integer 1
move a14, -*sp, 1 ; A8 still holds 1
calla FD$ITOF
move -*a14, a0, 1 ; result float 1.0 = 40400000h
move *sp+, a14, 1
move a0, @018A8140h, 1
; ---------------------------------------------------------------------------
; 8. _m6_fadd(1.5, 2.5): the caller reserves a one-word return slot
; (ADDI 32,STK), the callee writes it at saved_STK-32 and RETS 2.
; ---------------------------------------------------------------------------
addi 32, a14 ; caller-allocated float return slot
move a14, -*sp, 1
movi 040D00000h, a0 ; b=2.5
move a0, *a14+, 1
movi 040600000h, a0 ; a=1.5
move a0, *a14+, 1
calla _m6_fadd
move -*a14, a0, 1 ; result 4.0 (saved_STK-32)
move a0, @018A8160h, 1
; ---------------------------------------------------------------------------
; 9. Return a known A8 after all A14 save/restore pairs. spike-entry.asm
; stores it after CALLA _m6_probe, so a broken restore or RETS cannot pass.
; ---------------------------------------------------------------------------
movi 05A5A5A5Ah, a8
move *sp+, a13, 1 ; restore entry FP
move *sp+, a14, 1 ; restore entry STK
rets
; ---------------------------------------------------------------------------
; _m6_dadd: double dadd(double a, double b) with the TI C hidden-return rule.
; a at FP(-64)=LSW, FP(-32)=MSW; b at FP(-128)=LSW, FP(-96)=MSW
; result at saved_STK-64=LSW, saved_STK-32=MSW
; ---------------------------------------------------------------------------
.globl _m6_dadd
_m6_dadd:
mmtm sp, a0, a1, a2
move a13, -*sp, 1
move a14, a13
move *a13(-64), *a14+, 1 ; a LSW
move *a13(-32), *a14+, 1 ; a MSW
move *a13(-128), *a14+, 1 ; b LSW
move *a13(-96), *a14+, 1 ; b MSW
calla FD$ADD
move -*a14, a2, 1 ; result MSW
move -*a14, a1, 1 ; result LSW
move *sp(160), a14, 1 ; caller's saved STK (3 regs+FP+PC)
move a14, a0
subi 64, a0
move a1, *a0+, 1 ; LSW at saved_STK-64
move a2, *a0, 1 ; MSW at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1, a2
rets 2
; ---------------------------------------------------------------------------
; _m6_fadd: float fadd(float a, float b) with the TI C hidden-return rule.
; One 32-bit slot per float: a at FP(-32), b at FP(-64).
; result at saved_STK-32.
; ---------------------------------------------------------------------------
.globl _m6_fadd
_m6_fadd:
mmtm sp, a0, a1
move a13, -*sp, 1
move a14, a13
move *a13(-32), *a14+, 1 ; a
move *a13(-64), *a14+, 1 ; b
calla FS$ADD
move -*a14, a1, 1 ; result
move *sp(128), a14, 1 ; caller's saved STK (2 regs+FP+PC)
move a14, a0
subi 32, a0
move a1, *a0, 1 ; result at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1
rets 2
; ---------------------------------------------------------------------------
; _m6_i64_add: long long add(long long a, long long b), hidden 8-byte return.
; a high at FP(-64), a low at FP(-32); b high at FP(-128), b low at FP(-96).
; The caller pushes b high, b low, a high, a low, so the pop order is
; a low, a high, b low, b high.
; ---------------------------------------------------------------------------
.globl _m6_i64_add
_m6_i64_add:
mmtm sp, a0, a1, a2, a3
move a13, -*sp, 1
move a14, a13
move -*a14, a2, 1 ; a low
move -*a14, a1, 1 ; a high
move -*a14, a0, 1 ; b low
move -*a14, a3, 1 ; b high
add a0, a2 ; low = a low + b low, sets carry
addc a3, a1 ; high = a high + b high + carry
move *sp(192), a14, 1 ; caller's saved STK (4 regs+FP+PC)
move a14, a0
subi 64, a0
move a1, *a0+, 1 ; high at saved_STK-64
move a2, *a0, 1 ; low at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1, a2, a3
rets 2
+87
View File
@@ -0,0 +1,87 @@
-- varargs-check.lua -- read the M6 varargs marker words and the formatted
-- output buffer, and compare them with the expected values.
--
-- VARARGS_MARKERS is the bit address of _varargs_markers from the linker map;
-- each marker is one 32-bit word at base + n*0x20 bits. VARARGS_OUT is the
-- bit address of the C driver's `char varargs_out[64]`; the checker reads the
-- bytes of the expected string (TMS34010 memory is byte-addressed at the low
-- end of a bit address, one byte per 8 bits).
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("VARARGS_MARKERS"), 16)
local OUT = tonumber(os.getenv("VARARGS_OUT"), 16)
local N = 15
local frames = 0
local checked = false
local expect = {
[0] = 100, -- vsum(4, 10, 20, 30, 40): int walk
[1] = 42, -- vlong(0, 42): long is one slot
[2] = 1, -- vptr(0, 0x12345678): char * is one slot
[3] = 2, -- vdbl(0, 2.5): GSP double, MSW at the top
[4] = 0x9ABCDEF0, -- vll(0, 123456789ABCDEF0h): i64 LSW at the top
[5] = 257, -- mixed_di(0, 2.5, 7): double then int
[6] = 0x5566BD76, -- mixed_llp(0, 1122334455667788h, CAFEh)
[7] = 13, -- vcopy(0, 4, 5, 6): va_copy independence
[8] = 24, -- vforward(3, 7, 8, 9): forwarded va_list
[9] = 11, -- vnoargs(11): no fixed argument
[10] = 77, -- vlastd(1.5, 77): double last fixed argument
[11] = 4, -- myfmt("n=%d", -7) length
[12] = 19, -- myfmt("v=%d s=%s d=%f", ...) length
[13] = 2, -- call_vf32(): one-slot f32 va_arg
[14] = 0x5A5A5A5A, -- marker after varargs_run returns
}
local want_out = "v=42 s=hello d=3.25"
local function read_string(space, addr, len)
local s = {}
for i = 0, len - 1 do
s[#s + 1] = string.char(space:read_u8(addr + i * 8))
end
return table.concat(s)
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 varargs:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
local out = read_string(prog, OUT, #want_out)
print(string.format("M6 varargs out: '%s'", out))
if out ~= want_out then
print(string.format("M6 varargs: output got '%s' want '%s'",
out, want_out))
bad = bad + 1
end
if bad == 0 then
print("M6 VARARGS MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 varargs: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 VARARGS MAME: FAIL")
end
end
end, "varargs-check")
+28
View File
@@ -0,0 +1,28 @@
; varargs-entry.asm -- M6 varargs gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver varargs_run() and writes a post-return marker. varargs.sh
; concatenates the llc output for m6-varargs.ll and the compiled driver after
; this file, so _varargs_run and the variadic functions share one assembly.
;
; The marker array is in .bss (linked at the ram origin); varargs-check.lua
; reads its address from the linker map and checks 15 words (markers 0..14, the
; last one written after varargs_run returns). Marker n is 0x20 bits above
; marker n-1. varargs_out is the formatted-output buffer defined by the C
; driver (zero-initialized .bss); the checker also reads its bytes.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _varargs_run
movi 5A5A5A5Ah, a0
movi _varargs_markers+448, a2 ; marker 14, the post-return word
move a0, *a2, 1
rets
.globl _varargs_markers
.bss _varargs_markers, 512, 16 ; 15 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+175
View File
@@ -0,0 +1,175 @@
/* M6 varargs gate driver.
*
* Calls the compiled variadic functions in m6-varargs.ll through the TI
* all-stack ABI and writes the expected result words to the marker array
* defined by the entry assembly. Compiling this driver exercises the
* compiler's own caller side (variadic call pushes) and callee side (a real
* __builtin_va_list walk in myfmt, including a GSP double read).
*
* myfmt is the `%d %s %f` style output: it walks its va_list downward and
* writes "v=42 s=hello d=3.25" into varargs_out. The MAME checker compares
* those bytes exactly, so the formatted text is the runtime oracle for the
* int, pointer (string) and double va_arg paths in one call.
*
* Marker word n lives at varargs_markers[n], i.e. 0x20 bits above the
* previous one; scripts/m6/varargs-check.lua reads them by bit address from
* the linker map.
*/
typedef unsigned int u32;
typedef long long s64;
extern volatile u32 varargs_markers[];
/* Callees defined in m6-varargs.ll. The driver and the .ll must agree on the
* argument sequence; the IR signatures are the authoritative side.
*
* `vnoargs` is really `int vnoargs(...)`. ISO C cannot declare a variadic
* function with no named parameter, so the driver declares a variadic
* prototype with one int. The call site is variadic (so the caller saves STK,
* which is what a variadic callee needs), and the callee treats that pushed
* word as its first variadic argument. The declaration must not be used for
* any other callee. */
extern int vsum(int, ...);
extern int vlong(int, ...);
extern char *vptr(int, ...);
extern int vdbl(int, ...);
extern int vll(int, ...);
extern int mixed_di(int, ...);
extern int mixed_llp(int, ...);
extern int vcopy(int, ...);
extern int vforward(int, ...);
extern int vnoargs(int, ...);
extern int vlastd(double, ...);
extern int call_vf32(void);
char varargs_out[64];
static int outn;
static void out_char(char c)
{
if (outn < 64)
varargs_out[outn++] = c;
}
static void out_str(const char *s)
{
while (*s)
out_char(*s++);
}
static void out_num(int v)
{
char tmp[12];
int n = 0;
unsigned int uv;
if (v < 0) {
out_char('-');
uv = ~(unsigned int)v + 1U;
} else {
uv = (unsigned int)v;
}
if (uv == 0)
tmp[n++] = '0';
while (uv) {
tmp[n++] = (char)('0' + uv % 10);
uv /= 10;
}
while (n--)
out_char(tmp[n]);
}
/* printf-shaped variadic callee using the real va_list: %d, %s and %f with
* two fraction digits. The double is converted through the flib ftoi path, so
* this also exercises a float-to-int conversion on a variadic value. */
int myfmt(const char *fmt, ...)
{
__builtin_va_list ap;
const char *p;
__builtin_va_start(ap, fmt);
outn = 0;
for (p = fmt; *p; p++) {
if (*p != '%') {
out_char(*p);
continue;
}
p++;
switch (*p) {
case 'd': {
int v = __builtin_va_arg(ap, int);
out_num(v);
break;
}
case 's': {
char *s = __builtin_va_arg(ap, char *);
out_str(s);
break;
}
case 'f': {
double d = __builtin_va_arg(ap, double);
int scaled = (int)(d * 100.0);
int frac = scaled % 100;
out_num(scaled / 100);
out_char('.');
if (frac < 10)
out_char('0');
out_num(frac);
break;
}
default:
out_char('%');
out_char(*p);
break;
}
}
__builtin_va_end(ap);
return outn;
}
void varargs_run(void)
{
/* int walk over a fixed argument plus four variadic ints. */
varargs_markers[0] = (u32)vsum(4, 10, 20, 30, 40);
/* long (one slot). */
varargs_markers[1] = (u32)vlong(0, 42);
/* char * (one slot): compare the returned bit address. */
varargs_markers[2] = (u32)(vptr(0, (char *)0x12345678UL) ==
(char *)0x12345678UL);
/* double (two slots, MSW at the higher address): 2.5 -> 2. */
varargs_markers[3] = (u32)vdbl(0, 2.5);
/* long long (two slots, LSW at the higher address): low word. */
varargs_markers[4] = (u32)vll(0, 0x123456789ABCDEF0LL);
/* Mixed sequences: double then int, and i64 then pointer. */
varargs_markers[5] = (u32)mixed_di(0, 2.5, 7);
varargs_markers[6] = (u32)mixed_llp(0, 0x1122334455667788LL,
(char *)0xCAFEUL);
/* va_copy: ap reads 4 then 5; aq still reads 4 independently. */
varargs_markers[7] = (u32)vcopy(0, 4, 5, 6);
/* A callee forwarding its va_list to vsum_walk. */
varargs_markers[8] = (u32)vforward(3, 7, 8, 9);
/* No fixed argument: the first pushed word is the first va_arg. */
varargs_markers[9] = (u32)vnoargs(11);
/* A double last fixed argument (two slots) before the variadic area. */
varargs_markers[10] = (u32)vlastd(1.5, 77);
/* An f32 va_arg: one GSP word (the C caller cannot pass a promoted
* float, so call_vf32 is the hand-written IR caller). */
varargs_markers[13] = (u32)call_vf32();
/* The %d path with a negative value, then the %d %s %f output. */
varargs_markers[11] = (u32)myfmt("n=%d", -7);
varargs_markers[12] = (u32)myfmt("v=%d s=%s d=%f", 42, "hello", 3.25);
}
+51
View File
@@ -0,0 +1,51 @@
; cinit-entry.asm -- M7.2 `.cinit` gate entry, linked at bit 018A0000.
;
; The `.cinit` loop is byte-for-byte the termtris `_start` loop from
; vendor/vt1200-termtris/apps/termtris/src/vt1200/entry.asm:
;
; movi cinit,a9
; move *a9+,count ; u16 data-word count
; jrz done
; move *a9+,dest,1 ; u32 destination (a TMS34010 bit address)
; move *a9+,*dest+ ; copy `count` words
;
; The public `cinit` symbol is defined at offset 0 of this object's empty
; `.cinit` section (the termtris cinit.asm shape), so the linker places it at
; the `.cinit` origin and the C table (concatenated after this zero-size input
; section) is the record the loop reads. GSPA emits this object's sections in
; the order .text/.data/.bss/.cinit; tms-link accepts that GSPA order as well
; as the llc .text/.data/.cinit/.bss order.
;
; After the copy loop the entry calls cinit_probe(), which returns the sum of
; the three copied words; that value is the 018A8000 marker.
.ref _cinit_probe
.text
.globl _start
_start:
setf 32,0,1
movi _cstack,a14
move a14,a13
movi cinit,a9
ci_loop:
setf 16,0,0
move *a9+,a11
jrz ci_done
move *a9+,a10,1
ci_copy:
move *a9+,*a10+
dsjs a11,ci_copy
jruc ci_loop
ci_done:
setf 32,0,1
move a13,a14
calla _cinit_probe
move a8,@018A8000h,1
rets
.sect ".cinit"
.globl cinit
cinit:
.bss _cstack,32768,16
.end
+51
View File
@@ -0,0 +1,51 @@
/* M7.2 `.cinit` gate table: the TI init-record format in C.
*
* The TI format is a sequence of records:
*
* packed struct {
* unsigned short count; // data word count
* unsigned long destination; // TMS34010 *bit* address
* unsigned short data[count];
* };
*
* terminated by a zero count. `cinit-entry.asm` defines the public `cinit`
* symbol at the start of its own empty `.cinit` section (the termtris
* `cinit.asm` shape) and walks this table exactly like the termtris `_start`:
* `movi cinit,a9; move *a9+,count; move *a9+,dst,1; copy count words`.
*
* The destination is a pointer-typed union member rather than a plain
* `unsigned long` initialised with `(unsigned long)&cinit_target`. Both are
* the same packed 32-bit field at byte offset 2, but the object writer emits a
* relocation only for a pointer constant; casting the address to an integer
* produces an LLVM `ptrtoint` constant expression that the `.data`/.cinit
* emitter deliberately rejects as unsupported. The pointer value *is* the
* TMS34010 bit address in this ABI, so the linked field is the resolved bit
* address the entry loop needs. The record header is packed, so the 32-bit
* destination sits at bit offset 16 and the linker resolves it as an ordinary
* R-RELLONG field (the CPU copy loop is bit-addressed).
*/
unsigned short cinit_target[4];
struct __attribute__((packed)) cinit_record {
unsigned short count;
union {
unsigned long destination;
unsigned short *address;
} target;
unsigned short data[3];
unsigned short end;
};
/* The table lives in `.cinit`; the entry object contributes the `cinit`
* symbol at offset 0 of the concatenated section. */
__attribute__((section(".cinit")))
const struct cinit_record cinit_table = {
3, { .address = cinit_target }, { 0x1111, 0x2222, 0x3333 }, 0
};
/* Called by the entry after the copy loop; returns the sum of the copied
* words (0x1111 + 0x2222 + 0x3333 = 0x6666). */
int cinit_probe(void) {
return cinit_target[0] + cinit_target[1] + cinit_target[2];
}
+29
View File
@@ -0,0 +1,29 @@
; debug-entry.asm -- M7.2 debug-info gate entry, linked at bit 018A0000.
;
; debug.c is linked first so debug_mul is the text-origin function and its
; DWARF low PC is the expected 0x314000 (text origin 018A0000 / 8). This
; entry calls debug_mul(), debug_add() and debug_ptr() and stores their
; results, 43, 14 and 30, at 018A8000, 018A8020 and 018A8040.
;
; debug_ptr() takes no argument: it uses the .data debug_index (2) for the
; pointer update, so the entry needs no argument-pushing sequence.
.ref _debug_mul
.ref _debug_add
.ref _debug_ptr
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _debug_mul
move a8,@018A8000h,1
calla _debug_add
move a8,@018A8020h,1
calla _debug_ptr
move a8,@018A8040h,1
rets
.bss _cstack,32768,16
.end
+37
View File
@@ -0,0 +1,37 @@
int debug_mul(void) {
int product = 42;
return product + 1;
}
int debug_add(void) {
int sum = 7;
return sum + 7;
}
int debug_array[4] = {10, 20, 30, 40};
int debug_index = 2;
int debug_ptr(void) {
int *p = debug_array;
p += debug_index;
return *p;
}
/* M7.2 debug-info gate driver.
*
* Three functions, so the linked `.debug_info` has three subprograms and the
* second/third `.text` offsets are nonzero. debug_mul returns 43,
* debug_add returns 14 and debug_ptr returns debug_array[2] = 30; the entry
* stores them at 018A8000/018A8020/018A8040 after the stripped link is loaded
* in MAME.
*
* debug_ptr is the bit-pointer barrier coverage: `p += debug_index` is a
* runtime `getelementptr` that --bitptr rewrites, so the -O0 gate proves the
* line row survives that rewrite; debug.sh also builds this TU at -O2 -g to
* exercise opt/--scale/--lower-bitptr/instcombine.
*
* The declarations are on lines 1, 6 and 14; the first local-variable /
* pointer-update lines are 2, 7, 15 and 16; debug.sh asserts those
* `.debug_line` rows and the DW_AT_decl_line values. The comment is
* deliberately after the code so the line numbers stay stable.
*/
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Wrap linked TI-COFF `.debug_*` sections in a minimal ELF32 container.
The TMS34010 native path is TI-COFF end to end; `llvm-dwarfdump` reads ELF,
Mach-O and Wasm, not the 1987 TI COFF variant. This test-only helper extracts
the non-allocated `.debug_*` sections from a `tms-link --keep-debug` image and
writes an ELF32 little-endian relocatable container with section headers and a
`.shstrtab` but no program headers or symbol table.
No addresses or relocations are rewritten: `tms-link` has already resolved the
DWARF byte addresses (for example `.debug_addr` holds 0x314000 for text origin
0x018A0000), and DWARF section-internal offsets are section-relative.
Usage:
elf-debug-wrap.py -o OUT.elf LINKED.coff [SECTION ...]
With no SECTION arguments every `.debug_*` section is wrapped. The input is
parsed directly (the helper has no project dependencies) so the debug gate can
assert the linked TI-COFF and the ELF wrapper independently.
"""
from __future__ import annotations
import argparse
import struct
import sys
MAGIC = 0x0090
class WrapError(Exception):
pass
def _u16(data, off):
return struct.unpack_from("<H", data, off)[0]
def _u32(data, off):
return struct.unpack_from("<I", data, off)[0]
def _string_at(table, offset, what):
if offset < 4:
raise WrapError("%s string-table offset %d is inside the 4-byte size "
"field" % (what, offset))
end = table.find(b"\0", offset)
if end < 0:
raise WrapError("%s string-table entry at %d is not terminated"
% (what, offset))
return table[offset:end].decode("latin1")
def read_coff(path):
with open(path, "rb") as fh:
data = fh.read()
if len(data) < 20:
raise WrapError("%s: shorter than a COFF file header" % path)
machine, nscns, _timdat, symptr, nsyms, opthdr, _flags = \
struct.unpack_from("<HHIIIHH", data, 0)
if machine != MAGIC:
raise WrapError("%s: machine %#06x, expected %#06x"
% (path, machine, MAGIC))
if nscns == 0:
raise WrapError("%s: no sections" % path)
string_table = b""
if nsyms:
string_base = symptr + nsyms * 18
if string_base + 4 > len(data):
raise WrapError("%s: symbol/string table runs past EOF" % path)
size = _u32(data, string_base)
if size < 4 or string_base + size > len(data):
raise WrapError("%s: implausible string-table size %d"
% (path, size))
string_table = data[string_base:string_base + size]
sections = []
base = 20 + opthdr
for i in range(nscns):
off = base + i * 40
if off + 40 > len(data):
raise WrapError("%s: section header %d past EOF" % (path, i))
raw_name = data[off:off + 8]
if raw_name.startswith(b"/"):
digits = raw_name[1:].split(b"\0", 1)[0]
if not digits.isdigit():
raise WrapError("%s: bad long section name %r"
% (path, raw_name))
name = _string_at(string_table, int(digits),
"%s: section %d" % (path, i + 1))
else:
name = raw_name.split(b"\0", 1)[0].decode("latin1")
paddr, vaddr, size, scnptr, relptr, _lnnoptr, nreloc, _nlnno, flags = \
struct.unpack_from("<IIIIIIHHI", data, off + 8)
if size % 8:
raise WrapError("%s: section %r size %d bits is not whole bytes"
% (path, name, size))
blob = b""
if size and name != ".bss":
if scnptr + size // 8 > len(data):
raise WrapError("%s: section %r raw data runs past EOF"
% (path, name))
blob = data[scnptr:scnptr + size // 8]
sections.append(dict(name=name, paddr=paddr, vaddr=vaddr, size=size,
flags=flags, nreloc=nreloc, raw=blob))
by_name = {s["name"]: s for s in sections}
if len(by_name) != len(sections):
raise WrapError("%s: duplicate section names" % path)
return sections
def build_elf(sections):
# Only the section-header table and the section payloads exist; the DWARF
# data is already absolute, so no symbol table or relocations are needed.
shstr = bytearray(b"\0")
name_off = {}
for sec in sections:
name_off[sec["name"]] = len(shstr)
shstr.extend(sec["name"].encode("latin1"))
shstr.append(0)
shstr_name = len(shstr)
shstr.extend(b".shstrtab\0")
shnum = len(sections) + 2 # null section + payload sections + shstrtab
shoff = 52
cursor = (shoff + shnum * 40 + 3) & ~3
payload_off = []
for sec in sections:
payload_off.append(cursor)
cursor += len(sec["raw"])
cursor = (cursor + 3) & ~3
shstr_off = cursor
cursor += len(shstr)
total = (cursor + 3) & ~3
out = bytearray(total)
e_ident = b"\x7fELF" + bytes([1, 1, 1, 0]) + bytes(8) # 32-bit LE v1
struct.pack_into("<16sHHIIIIIHHHHHH", out, 0, e_ident,
1, # e_type ET_REL
# EM_386 keeps llvm-dwarfdump from warning about an
# unknown machine (there is no standard TMS34010 EM_*).
3, # e_machine EM_386
1, # e_version
0, # e_entry
0, # e_phoff (no program headers)
shoff, # e_shoff
0, # e_flags
52, # e_ehsize
0, 0, # e_phentsize, e_phnum
40, # e_shentsize
shnum, # e_shnum
shnum - 1) # e_shstrndx
for i, sec in enumerate(sections, start=1):
off = shoff + i * 40
struct.pack_into("<IIIIIIIIII", out, off,
name_off[sec["name"]],
1, # SHT_PROGBITS
0, # no sh_flags
0, # sh_addr (DWARF is absolute)
payload_off[i - 1],
len(sec["raw"]),
0, 0, # sh_link, sh_info
1, # sh_addralign
0) # sh_entsize
out[payload_off[i - 1]:payload_off[i - 1] + len(sec["raw"])] = \
sec["raw"]
off = shoff + (shnum - 1) * 40
struct.pack_into("<IIIIIIIIII", out, off, shstr_name, 3, 0, 0,
shstr_off, len(shstr), 0, 0, 1, 0)
out[shstr_off:shstr_off + len(shstr)] = shstr
return bytes(out)
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("-o", "--output", required=True, metavar="OUT.elf",
help="ELF32 output container")
p.add_argument("coff", metavar="LINKED.coff",
help="linked TI-COFF with --keep-debug")
p.add_argument("sections", nargs="*", metavar="SECTION",
help="debug section names to include (default: all "
".debug_*)")
args = p.parse_args(argv)
try:
all_sections = read_coff(args.coff)
by_name = {s["name"]: s for s in all_sections}
if args.sections:
missing = [n for n in args.sections if n not in by_name]
if missing:
raise WrapError("%s: missing section(s): %s"
% (args.coff, ", ".join(missing)))
chosen = [by_name[n] for n in args.sections]
else:
chosen = [s for s in all_sections
if s["name"].startswith(".debug_")]
if not chosen:
raise WrapError("%s: no .debug_* sections to wrap" % args.coff)
for sec in chosen:
if not sec["name"].startswith(".debug_"):
raise WrapError("%s: %r is not a .debug_* section"
% (args.coff, sec["name"]))
if sec["paddr"] != 0 or sec["vaddr"] != 0:
raise WrapError("%s: debug section %r has paddr/vaddr "
"%#x/%#x, expected 0/0"
% (args.coff, sec["name"], sec["paddr"],
sec["vaddr"]))
elf = build_elf(chosen)
with open(args.output, "wb") as fh:
fh.write(elf)
print("elf-debug-wrap: %s <- %s (%s)"
% (args.output, args.coff,
" ".join("%s=%dB" % (s["name"], len(s["raw"]))
for s in chosen)))
return 0
except (WrapError, OSError) as exc:
print("elf-debug-wrap: error: %s" % exc, file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+111
View File
@@ -0,0 +1,111 @@
-- hw-check.lua -- M7.3 real-hardware marker gate, MAME-equivalent acceptance.
--
-- Loads the same COFF that hostload.py sends to the real unit
-- (scripts/m7/hwmark.c, linked at .text 018C0000 / .data 018D0000 /
-- .bss 018D8000) through vendor/vt1200/dwt/loader/loader.lua, then requires
-- exactly what hostload.py's verify_markers() requires:
--
-- 018E0000 start == the loader result block's entry (018C0000)
-- 018E0020 data == 0xDEADBEEF (copied .data)
-- 018E0040 data2 == 0x12345678 (copied .data)
-- 018E0060 bss == 0 (zeroed .bss; loader pre-fills A5A5)
-- 018E0080 count advances (the child is scheduled, not jumped)
--
-- and that the loader result status is 0. LOADER_AT/LOADER_END come from the
-- M4-style environment; the counter is sampled after the child has run, then
-- again one frame before the loader exits.
dofile(os.getenv("M4_LOADER_LUA"))
local AT = tonumber(os.getenv("LOADER_AT") or "2500")
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local RESULT = 0x01882D00
local CELLS = {
{ 0x018E0000, "start" },
{ 0x018E0020, "data" },
{ 0x018E0040, "data2" },
{ 0x018E0060, "bss" },
{ 0x018E0080, "count" },
}
-- First sample: a few frames after injection, so the child has started.
-- Second sample: the last frame before loader.lua inspects and exits.
local SAMPLE0 = math.max(AT + 5, ENDF - 11)
local SAMPLE1 = ENDF - 1
local frames = 0
local first_count = nil
local checked = false
local function r32(prog, addr)
local ok, v = pcall(function() return prog:read_u32(addr) end)
if ok then return v end
return nil
end
emu.register_frame_done(function()
frames = frames + 1
if frames == SAMPLE0 and first_count == nil then
local prog = manager.machine.devices[':maincpu'].spaces['program']
first_count = r32(prog, 0x018E0080)
end
if frames == SAMPLE1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local v = {}
for _, cell in ipairs(CELLS) do
v[cell[2]] = r32(prog, cell[1])
end
local status = r32(prog, RESULT + 0x000)
local entry = r32(prog, RESULT + 0x020)
local count0 = first_count or 0
local count1 = v.count or 0
print(string.format(
"M7 HW: start=0x%08X data=0x%08X data2=0x%08X bss=0x%08X count=%d->%d status=%d entry=0x%08X",
v.start or 0, v.data or 0, v.data2 or 0, v.bss or 0,
count0, count1, status or -1, entry or 0))
local problems = {}
if status ~= 0 then
problems[#problems + 1] = string.format("loader status=%s, want 0",
tostring(status))
end
if entry ~= 0x018C0000 then
problems[#problems + 1] = string.format(
"loader entry=0x%08X, want 0x018C0000", entry or 0)
end
if v.start ~= entry then
problems[#problems + 1] = string.format(
"start=0x%08X, want the entry 0x%08X", v.start or 0, entry or 0)
end
if v.data ~= 0xDEADBEEF then
problems[#problems + 1] = string.format("data=0x%08X, want 0xDEADBEEF",
v.data or 0)
end
if v.data2 ~= 0x12345678 then
problems[#problems + 1] = string.format(
"data2=0x%08X, want 0x12345678", v.data2 or 0)
end
if v.bss ~= 0 then
problems[#problems + 1] = string.format("bss=0x%08X, want 0",
v.bss or 0)
end
if count0 <= 0 or count1 <= count0 then
problems[#problems + 1] = string.format(
"count did not advance (%d -> %d)", count0, count1)
end
if #problems == 0 then
print("M7 HW MAME: PASS")
else
for _, p in ipairs(problems) do
print("M7 HW: FAIL: " .. p)
end
print("M7 HW MAME: FAIL")
end
end
end, "m7-hw-check")
+76
View File
@@ -0,0 +1,76 @@
/*
* hwmark.c -- M7.3 real-hardware marker client, built at the proven VT1200
* hardware origins:
*
* .text 018C0000h
* .data 018D0000h
* .bss 018D8000h
*
* This is the COFF image that dwt/loader/hostload.py pokes and that
* dwt/loader/loader.asm places through create_process. The marker cells are
* the ones hostload.py's MARKER_CELLS names (all TMS34010 *bit* addresses):
*
* 018E0000 _start address at run time (must equal the loader entry)
* 018E0020 d_magic read from .data (must be DEADBEEF)
* 018E0040 d_two read from .data (must be 12345678)
* 018E0060 b_zero read from .bss (must be 0)
* 018E0080 b_counter, a live counter (must advance)
*
* The M7.3 brief prefers a C-only entry when the compiler can express it, so
* `start` is an ordinary C function and the COFF entry point is `_start`.
* create_process() supplies the process stack (the firmware allocates it; the
* xhello trace records a valid entry A14). The MAME run proves the generated
* prologue did not fault and the markers/counter are correct, not that A14/SP
* point at the create_process stack; the real-unit run (VT1200_HOST) is the
* hardware confirmation. The `.data` pointer
* initializer below is supported as an ordinary pointer relocation, so no
* `ptrtoint` constant initializer and no assembly entry are needed.
*
* The loader zeroes .bss after the harness has pre-filled it with A5A5, so a
* zero at 018E0060 is the loader's work, not fresh RAM. The delay loop is
* marker.asm's 2000h `dsjs` delay: the child stays scheduled but does not burn
* the cooperative scheduler with an unbroken hot loop.
*/
#define MARK(n) (*(volatile unsigned int *)(0x018E0000u + (n) * 0x20u))
/* Initialised .data: the loader must copy these bytes from the COFF. */
unsigned int d_magic = 0xDEADBEEFu;
unsigned int d_two = 0x12345678u;
/* Uninitialised .bss: the loader must zero these. */
unsigned int b_zero;
unsigned int b_counter;
void start(void);
/*
* The entry address as a relocated pointer, not a ptrtoint constant. The
* loader's result block reports the same `_start` bit address as the COFF
* entry point, so the runtime start cell proves placement, not a guess.
*/
void (*const start_address)(void) = start;
/* A volatile .bss sink keeps the delay loop from being folded away. */
static volatile unsigned int delay_sink;
void start(void) {
unsigned int count = 0;
MARK(0) = (unsigned int)start_address;
MARK(1) = d_magic;
MARK(2) = d_two;
MARK(3) = b_zero;
for (;;) {
unsigned int spin;
count++;
b_counter = count;
MARK(4) = count;
for (spin = 0; spin < 0x2000u; spin++) {
delay_sink = spin;
}
}
}
+16
View File
@@ -0,0 +1,16 @@
-a
-o M4.OUT
-m M4.MAP
-e _start
M4.obj
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Assert the M7.4 i64div perf marker cells are outside every linked section.
Usage:
i64div-map-check.py MAP MARKER_HEX [PROG_ORIGIN PROG_LEN RAM_ORIGIN RAM_LEN]
MAP is a GSPLNK 2.00 map (the SECTION ALLOCATION MAP has origin/length in
bits) or a tms-link map (the symbol addresses give .text/etext,
.data/edata, .bss/end). MARKER_HEX is the marker base bit address; the gate
uses up to 16 cells 0x20 bits apart. The optional region arguments are also
in hex (bits) and bound .text/.data to prog and .bss/the markers to ram.
Exit status: 0 = every check passed, 1 = overlap/out-of-region, 2 = the map
could not be parsed.
"""
import re
import sys
def parse_sections(lines):
"""Return {name: (start, end)} for .text/.data/.bss."""
sections = {}
# GSPLNK allocation lines: name page origin length [attributes]
for line in lines:
m = re.match(
r"^\s*(\.\w+)\s+\d+\s+([0-9A-Fa-f]+)\s+([0-9A-Fa-f]+)\b",
line)
if not m:
continue
origin = int(m.group(2), 16)
length = int(m.group(3), 16)
sections[m.group(1)] = (origin, origin + length)
if sections:
return sections
# tms-link map: "ADDR .text" / "ADDR etext" style symbol addresses.
starts, ends = {}, {}
for line in lines:
m = re.match(
r"^\s*([0-9A-Fa-f]+)\s+(\.\w+|etext|edata|end)\s*$", line)
if not m:
continue
addr = int(m.group(1), 16)
name = m.group(2)
if name in (".text", ".data", ".bss"):
starts[name] = addr
else:
ends[name] = addr
for name, endname in ((".text", "etext"), (".data", "edata"),
(".bss", "end")):
if name in starts and endname in ends:
sections[name] = (starts[name], ends[endname])
return sections
def main():
if len(sys.argv) not in (3, 7):
print(__doc__, file=sys.stderr)
return 2
map_path = sys.argv[1]
marker = int(sys.argv[2], 16)
marker_end = marker + 16 * 0x20
regions = None
if len(sys.argv) == 7:
prog_origin, prog_len, ram_origin, ram_len = (
int(v, 16) for v in sys.argv[3:7])
regions = (prog_origin, prog_origin + prog_len,
ram_origin, ram_origin + ram_len)
with open(map_path, encoding="ascii", errors="replace") as f:
sections = parse_sections(f.read().splitlines())
missing = [s for s in (".text", ".data", ".bss") if s not in sections]
if missing:
print(
"i64div perf map: cannot find %s in %s"
% (", ".join(missing), map_path),
file=sys.stderr)
return 2
ok = True
for name in (".text", ".data", ".bss"):
lo, hi = sections[name]
if marker < hi and marker_end > lo:
print(
"i64div perf map: markers 0x%08X..0x%08X overlap %s "
"0x%08X..0x%08X" % (marker, marker_end, name, lo, hi),
file=sys.stderr)
ok = False
if regions is not None:
prog_lo, prog_hi, ram_lo, ram_hi = regions
for name in (".text", ".data"):
lo, hi = sections[name]
if lo < prog_lo or hi > prog_hi:
print(
"i64div perf map: %s 0x%08X..0x%08X is outside prog "
"0x%08X..0x%08X" % (name, lo, hi, prog_lo, prog_hi),
file=sys.stderr)
ok = False
lo, hi = sections[".bss"]
if lo < ram_lo or hi > ram_hi:
print(
"i64div perf map: .bss 0x%08X..0x%08X is outside ram "
"0x%08X..0x%08X" % (lo, hi, ram_lo, ram_hi),
file=sys.stderr)
ok = False
if marker < ram_lo or marker_end > ram_hi:
print(
"i64div perf map: markers 0x%08X..0x%08X are outside ram "
"0x%08X..0x%08X" % (marker, marker_end, ram_lo, ram_hi),
file=sys.stderr)
ok = False
if not ok:
return 1
extents = ", ".join(
"%s 0x%08X..0x%08X" % (name, sections[name][0], sections[name][1])
for name in (".text", ".data", ".bss"))
print(
"i64div perf map: %s; markers 0x%08X..0x%08X outside every section"
% (extents, marker, marker_end))
if regions is not None:
print(
"i64div perf map: markers inside ram 0x%08X..0x%08X"
% (regions[2], regions[3]))
return 0
if __name__ == "__main__":
sys.exit(main())
+181
View File
@@ -0,0 +1,181 @@
-- i64div-perf-check.lua -- measure the M7.4 i64 divide/remainder fast path in
-- MAME.
--
-- Loads the gate COFF with vendor/vt1200/dwt/loader/loader.lua (through the
-- M4_LOADER_LUA variable scripts/m4/run.sh exports) and polls the marker
-- words once per frame. A MAME frame is a fixed number of emulated 50 MHz
-- cycles, so the number of frames between the start marker and each phase's
-- completion marker is a reproducible cycle proxy for the equal-iteration
-- workloads in scripts/m7/i64div-perf.c:
--
-- fast phase: 16384 iterations, every divide fits 32 bits -> one DIVU each;
-- slow phase: 16384 iterations, both high words nonzero -> the 64-step loop;
-- wide phase: 16384 iterations, nonzero dividend high word, 32-bit divisor
-- and hi(N) >= D -> two even-destination DIVUs (the M8.3 64/32
-- path, quotient needs 33+ bits);
-- div32 phase: 16384 iterations, nonzero dividend high word, 32-bit divisor
-- and hi(N) < D -> one even-destination DIVU plus the low-word
-- N - q*D reconstruction (the M9.3 64/32 path).
--
-- The gate requires the fast phase to complete in materially fewer frames
-- (slow_frames >= 8 * max(fast_frames, 1)) and the slow phase to be long
-- enough to measure (>= 20 frames). A sub-frame fast phase is reported as
-- fast_frames=0 and compared as one frame, which can only make the check
-- harder. The wide phase must also be materially faster than the loop
-- (slow_frames >= 4 * max(wide_frames, 1)) and measurable (>= 2 frames).
-- The div32 phase must be measurable and materially faster than the M8.3
-- two-DIVU wide phase: wide_frames*4 >= div32_frames*5 (1.25x).
--
-- All four phase checksums are required to equal the deterministic values
-- below. They were computed from the same LCG/arithmetic with an independent
-- host implementation of scripts/m7/i64div-perf.c (see the header comment
-- there):
-- fast = 0x000000011E6F9AB4, slow = 0x00000000007512AE,
-- wide = 0xF56810CFEDA9D656, div32 = 0x00002C61C63842EE.
-- The in-image self-check (marker 7) also covers large 32-bit magnitudes
-- (0xFFFFFFFF/7, -123/7 and INT32_MIN/3) plus the 64/32 shapes with hi >= d,
-- hi == d, hi < d, INT64_MIN (both the small-divisor two-step case and the
-- 0xFFFFFFFF single-DIVU case, signed and unsigned magnitude) and the M9.3
-- single-DIVU cases (0x1_00000000/3, 0x1_FFFFFFFF/0x10000, -2^32/3 and
-- 2^32/-3), so a wrong quotient or remainder fails before the timing
-- comparison.
--
-- Markers at 01A20000h, 0x20 bits apart (free RAM above the 4 KiB entry stack;
-- scripts/m7/i64div-map-check.py asserts they are outside .text/.data/.bss):
-- 0 start 0x51A47A11 | 1/2 fast checksum | 3 fast done 0xFA57D01E
-- 4/5 slow checksum | 6 slow done 0x5104D0E5 | 7 status 0x600D600D
-- 8 wide done 0x81DE0D0E | 9/10 wide checksum
-- 11 div32 done 0x6432D0E5 | 12/13 div32 checksum
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "5000")
local BASE = 0x01A20000
local START = 0x51A47A11
local FAST_DONE = 0xFA57D01E
local SLOW_DONE = 0x5104D0E5
local WIDE_DONE = 0x81DE0D0E
local DIV32_DONE = 0x6432D0E5
local STATUS_OK = 0x600D600D
local FAST_HI, FAST_LO = 0x00000001, 0x1E6F9AB4
local SLOW_HI, SLOW_LO = 0x00000000, 0x007512AE
local WIDE_HI, WIDE_LO = 0xF56810CF, 0xEDA9D656
local DIV32_HI, DIV32_LO = 0x00002C61, 0xC63842EE
local frames = 0
local start_f, fast_f, slow_f, wide_f, div32_f
local reported = false
local function rd(n)
local prog = manager.machine.devices[':maincpu'].spaces['program']
return prog:read_u32(BASE + n * 0x20)
end
emu.register_frame_done(function()
frames = frames + 1
if start_f == nil and rd(0) == START then
start_f = frames
end
if start_f ~= nil and fast_f == nil and rd(3) == FAST_DONE then
fast_f = frames
end
if fast_f ~= nil and slow_f == nil and rd(6) == SLOW_DONE then
slow_f = frames
end
if slow_f ~= nil and wide_f == nil and rd(8) == WIDE_DONE then
wide_f = frames
end
if wide_f ~= nil and div32_f == nil and rd(11) == DIV32_DONE then
div32_f = frames
end
if div32_f ~= nil and not reported then
reported = true
local fast_frames = fast_f - start_f
local slow_frames = slow_f - fast_f
local wide_frames = wide_f - slow_f
local div32_frames = div32_f - wide_f
local basis = fast_frames
if basis < 1 then
basis = 1
end
local wide_basis = wide_frames
if wide_basis < 1 then
wide_basis = 1
end
local div32_basis = div32_frames
if div32_basis < 1 then
div32_basis = 1
end
local status = rd(7)
local cs_fast_hi, cs_fast_lo = rd(2), rd(1)
local cs_slow_hi, cs_slow_lo = rd(5), rd(4)
local cs_wide_hi, cs_wide_lo = rd(10), rd(9)
local cs_div32_hi, cs_div32_lo = rd(13), rd(12)
local ratio = slow_frames / basis
local wide_ratio = slow_frames / wide_basis
local div32_ratio = wide_frames / div32_basis
local cs_ok = cs_fast_hi == FAST_HI and cs_fast_lo == FAST_LO
and cs_slow_hi == SLOW_HI and cs_slow_lo == SLOW_LO
and cs_wide_hi == WIDE_HI and cs_wide_lo == WIDE_LO
and cs_div32_hi == DIV32_HI and cs_div32_lo == DIV32_LO
local ok = status == STATUS_OK and cs_ok
and slow_frames >= 20
and slow_frames >= 8 * basis
and wide_frames >= 2
and slow_frames >= 4 * wide_basis
and div32_frames >= 2
and wide_frames * 4 >= div32_basis * 5
print(string.format(
"M7: i64div perf: start=%d fast_done=%d slow_done=%d "
.. "wide_done=%d div32_done=%d fast_frames=%d "
.. "slow_frames=%d wide_frames=%d div32_frames=%d "
.. "ratio=%.1f wide_ratio=%.1f div32_ratio=%.1f "
.. "status=%08X cs_fast=%08X%08X cs_slow=%08X%08X "
.. "cs_wide=%08X%08X cs_div32=%08X%08X "
.. "cs_expected=%08X%08X/%08X%08X/%08X%08X/%08X%08X cs=%s",
start_f, fast_f, slow_f, wide_f, div32_f, fast_frames,
slow_frames, wide_frames, div32_frames, ratio, wide_ratio,
div32_ratio,
status, cs_fast_hi, cs_fast_lo, cs_slow_hi, cs_slow_lo,
cs_wide_hi, cs_wide_lo, cs_div32_hi, cs_div32_lo,
FAST_HI, FAST_LO, SLOW_HI, SLOW_LO, WIDE_HI, WIDE_LO,
DIV32_HI, DIV32_LO,
cs_ok and "ok" or "BAD"))
if ok then
print("M7 MAME: PASS")
else
print(string.format(
"M7 MAME: FAIL (status=%08X checksums=%s "
.. "fast_frames=%d slow_frames=%d wide_frames=%d "
.. "div32_frames=%d; "
.. "want status %08X, fast %08X%08X, slow %08X%08X, "
.. "wide %08X%08X, div32 %08X%08X, "
.. "slow_frames >= 20 and >= 8*max(fast_frames,1), "
.. "wide_frames >= 2 and "
.. "slow_frames >= 4*max(wide_frames,1), "
.. "div32_frames >= 2 and "
.. "4*wide_frames >= 5*max(div32_frames,1))",
status, cs_ok and "ok" or "BAD",
fast_frames, slow_frames, wide_frames, div32_frames,
STATUS_OK,
FAST_HI, FAST_LO, SLOW_HI, SLOW_LO,
WIDE_HI, WIDE_LO, DIV32_HI, DIV32_LO))
end
elseif frames == ENDF - 1 and not reported then
reported = true
local seen = string.format(
"start=%s fast_done=%s slow_done=%s wide_done=%s "
.. "div32_done=%s",
tostring(start_f), tostring(fast_f), tostring(slow_f),
tostring(wide_f), tostring(div32_f))
print(string.format(
"M7: i64div perf: incomplete at frame %d at marker 0x%08X",
frames, BASE))
print("M7 MAME: FAIL (timed out: " .. seen .. ")")
end
end, "i64div-perf-check")
+19
View File
@@ -0,0 +1,19 @@
; i64div-perf-entry.asm -- M7.4 i64 divide/remainder performance gate entry,
; linked at bit 018A0000 by scripts/tests/m7/i64div.sh through
; scripts/m4/run.sh.
;
; Sets the TI C field sizes, points STK/FP at the gate stack and calls
; i64div_perf_run(), which writes the phase markers and returns. The loader
; harness inspects the markers at LOADER_END-1, so no post-return sentinel is
; needed; the program's last marker write is the slow-phase completion flag.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _i64div_perf_run
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+354
View File
@@ -0,0 +1,354 @@
/* M7.4/M8.3/M9.3 i64 divide/remainder fast-path performance driver.
*
* Four equal-iteration workloads exercise the paths of
* TMS34010LowerI64::lowerDivRem:
*
* fast phase: both operands fit 32 bits after the signed magnitude
* normalization, so the compiler emits one 32-bit DIVU (plus
* the div/mul/sub remainder reconstruction) instead of the
* 64-step restoring loop;
* slow phase: both operands have nonzero high words, so the 64-step loop
* runs for each of the four i64 div/rem forms;
* wide phase: the dividend has a nonzero high word but the divisor fits
* 32 bits and the quotient needs 33+ bits (hi(N) >= D), so
* the M8.3 64/32 path emits two even-destination DIVUs (q1/r1
* then q0/r0) instead of the 64-step loop;
* div32 phase: the dividend has a nonzero high word but the quotient fits
* 32 bits (hi(N) < D), so the M9.3 path emits one
* even-destination DIVU plus the low-word N - q*D remainder
* reconstruction.
*
* The loop bodies are driven by a volatile iteration count and volatile
* seeds, and every result feeds a volatile accumulator that is published in
* the marker words, so neither phase can be constant-folded or discarded.
*
* Markers (0x20 bits apart at 01A20000h, the free RAM area above the 4 KiB
* entry stack at 01A00000h; outside .text/.data/.bss, see
* scripts/m7/i64div-map-check.py):
* 0 start 0x51A47A11
* 1 fast checksum low (printed evidence)
* 2 fast checksum high
* 3 fast phase done 0xFA57D01E
* 4 slow checksum low (printed evidence)
* 5 slow checksum high
* 6 slow phase done 0x5104D0E5
* 7 self-check status 0x600D600D on success
* 8 wide phase done 0x81DE0D0E
* 9 wide checksum low (printed evidence)
* 10 wide checksum high
* 11 div32 phase done 0x6432D0E5
* 12 div32 checksum low (printed evidence)
* 13 div32 checksum high
*
* The self-check runs known i64 divisions first (fast and slow, unsigned and
* signed, including full-width low words and the INT32_MIN magnitude), so the
* timing comparison is between two correct paths rather than between a
* fast-but-wrong path and the loop. scripts/m7/i64div-perf-check.lua polls
* the markers once per MAME frame, turns the frame numbers into the gate's
* cycle proxy, and requires the exact phase checksums. With the 16384
* iterations above the deterministic LCG workloads produce
* fast = 0x000000011E6F9AB4, slow = 0x00000000007512AE,
* wide = 0xF56810CFEDA9D656, div32 = 0x00002C61C63842EE
* (checked against an independent host implementation of this file; the
* target compiler must produce the same integer results).
*/
typedef unsigned int u32;
typedef int s32;
typedef unsigned long long u64;
typedef long long s64;
#define MARK(n) (*(volatile u32 *)(0x01A20000u + (u32)(n) * 0x20u))
#define PERF_START 0x51A47A11u
#define PERF_FAST_DONE 0xFA57D01Eu
#define PERF_SLOW_DONE 0x5104D0E5u
#define PERF_WIDE_DONE 0x81DE0D0Eu
#define PERF_DIV32_DONE 0x6432D0E5u
#define PERF_STATUS_OK 0x600D600Du
#define PERF_STATUS_BAD 0xBAD0BAD0u
/* 16384 iterations put the fast phase at a few frames and the slow phase at a
* few hundred frames on the emulated 50 MHz part, with a wide margin under
* the gate-local loader budget (5000 frames by default). The count is volatile so the optimizer keeps
* a real loop and does not unroll it into a folded constant. */
static volatile u32 perf_iters = 16384u;
/* Seeds are volatile for the same reason: the divisions must really execute. */
static volatile u64 seed_a = 0x0000000012345678ull;
static volatile u64 seed_b = 0x000000009ABCDEF1ull;
/* Known-value inputs (values pinned by the M6 i64 gate). */
static volatile u64 sc_n1 = 0x123456789ABCDEF0ull;
static volatile u64 sc_d1 = 0x0000000000001234ull;
static volatile u64 sc_d2 = 0x0000000123456789ull;
static volatile s64 sc_n3 = -1000000000000ll;
static volatile s64 sc_d3 = 7ll;
static volatile s64 sc_n4 = 123ll;
static volatile s64 sc_d4 = -7ll;
/* Fast-path cases with large low words: the high word is zero (or the value
* is a negative 32-bit value whose magnitude still fits), so the quotient and
* remainder must come from the 32-bit DIVU, not the loop. */
static volatile u64 sc_max32 = 0xFFFFFFFFull;
static volatile u64 sc_seven = 7ull;
static volatile s64 sc_neg123 = -123ll;
static volatile s64 sc_int32min = -2147483648ll;
static volatile s64 sc_three = 3ll;
static volatile s64 sc_three_neg = -3ll;
/* M8.3/M9.3 64/32-path cases: nonzero dividend high word, 32-bit divisor.
* The first, second and unsigned INT64_MIN-magnitude cases exercise the
* two-step form where the quotient needs 33+ bits (hi >= d), so q1 is nonzero
* and both even-destination divides run. The third has hi < d and takes the
* M9.3 single-DIVU path. INT64_MIN never fits 32 bits (magnitude high word
* 0x80000000): divisors <= 2^31 keep it on the two-step helper, while a
* divisor in (2^31, 2^32), e.g. 0xFFFFFFFF, has hi(|N|) < d and takes the
* single-DIVU path; the self-check below covers both. */
static volatile u64 sc_wide1 = 0xFEDCBA9876543210ull;
static volatile u64 sc_wide_d1 = 0x12345678ull;
static volatile u64 sc_wide2 = 0xFFFFFFFFFFFFFFFFull;
static volatile u64 sc_wide_d2 = 0xFFFFFFFFull;
static volatile u64 sc_wide3 = 0x00000001FFFFFFFFull;
static volatile u64 sc_wide4 = 0x8000000000000000ull;
static volatile s64 sc_int64min = -9223372036854775807ll - 1ll;
/* M9.3 single-DIVU 64/32 cases: a nonzero dividend high word with hi < d so
* the whole quotient fits 32 bits. 0x1_00000000 / 3 is the canonical
* q = 0x55555555, r = 1 case; the negative form exercises the shared signed
* fixup on the new path. */
static volatile u64 sc_div32_n = 0x0000000100000000ull;
static volatile u64 sc_div32_d = 3ull;
static volatile u64 sc_div32_n2 = 0x00000001FFFFFFFFull;
static volatile u64 sc_div32_d2 = 0x0000000000010000ull;
static volatile s64 sc_div32_neg = -4294967296ll;
static u32 lcg(u32 x)
{
return x * 1103515245u + 12345u;
}
/* Known-value checks for both paths, unsigned and signed, including the
* full-width low words and INT32_MIN. */
static u32 selfcheck(void)
{
u64 q, r;
s64 sq, sr;
u32 ok = 1;
q = sc_n1 / sc_d1;
r = sc_n1 % sc_d1;
ok &= (q == 0x00010004C016906Bull) && (r == 0x334ull);
/* Divisor above 32 bits: the restoring loop. */
q = sc_n1 / sc_d2;
r = sc_n1 % sc_d2;
ok &= (q == 0x0000000010000000ull) && (r == 0x0ABCDEF0ull);
/* Both signed values fit after normalization: the signed fast path. */
sq = sc_n4 / sc_d4;
sr = sc_n4 % sc_d4;
ok &= (sq == -17ll) && (sr == 4ll);
/* Fast paths with large low words. A wrong 32-bit quotient/remainder
* for a full-width magnitude (or for INT32_MIN's magnitude 2^31) must
* fail here before the timing comparison. */
q = sc_max32 / sc_seven;
r = sc_max32 % sc_seven;
ok &= (q == 0x0000000024924924ull) && (r == 3ull);
/* sc_d3 is the signed 7: sc_seven is u64, so mixing it with a negative
* s64 would make the comparison unsigned (the same C conversion the
* target performs). */
sq = sc_neg123 / sc_d3;
sr = sc_neg123 % sc_d3;
ok &= (sq == -17ll) && (sr == -4ll);
sq = sc_int32min / sc_three;
sr = sc_int32min % sc_three;
ok &= (sq == -715827882ll) && (sr == -2ll);
/* A large signed dividend: the signed wide path (32-bit divisor 7). */
sq = sc_n3 / sc_d3;
sr = sc_n3 % sc_d3;
ok &= (sq == -142857142857ll) && (sr == -1ll);
/* M8.3 64/32 path with hi >= d: the quotient needs 36 bits. */
q = sc_wide1 / sc_wide_d1;
r = sc_wide1 % sc_wide_d1;
ok &= (q == 0x0000000E00000077ull) && (r == 0x48ull);
/* M8.3 64/32 path with hi == d: the quotient needs 33 bits. */
q = sc_wide2 / sc_wide_d2;
r = sc_wide2 % sc_wide_d2;
ok &= (q == 0x0000000100000001ull) && (r == 0ull);
/* M8.3 64/32 path with hi < d: it now takes the M9.3 single divide. */
q = sc_wide3 / sc_wide_d2;
r = sc_wide3 % sc_wide_d2;
ok &= (q == 2ull) && (r == 1ull);
/* M9.3 single-DIVU 64/32 path: hi < d (0x1 < 3 and 0x1 < 0x10000). */
q = sc_div32_n / sc_div32_d;
r = sc_div32_n % sc_div32_d;
ok &= (q == 0x55555555ull) && (r == 1ull);
q = sc_div32_n2 / sc_div32_d2;
r = sc_div32_n2 % sc_div32_d2;
ok &= (q == 0x1FFFFull) && (r == 0xFFFFull);
sq = sc_div32_neg / sc_three;
sr = sc_div32_neg % sc_three;
ok &= (sq == -1431655765ll) && (sr == -1ll);
/* M8.3 unsigned INT64_MIN magnitude and signed INT64_MIN / 3. */
q = sc_wide4 / sc_three;
r = sc_wide4 % sc_three;
ok &= (q == 0x2AAAAAAAAAAAAAAAull) && (r == 2ull);
sq = sc_int64min / sc_three;
sr = sc_int64min % sc_three;
ok &= (sq == -3074457345618258602ll) && (sr == -2ll);
/* INT64_MIN magnitude with a divisor above 2^31: hi(|N|) = 0x80000000
* < 0xFFFFFFFF, so it takes the M9.3 single-DIVU path (unsigned and
* signed). q = r = 2^31 in magnitude; the signed remainder keeps the
* dividend's sign. */
q = sc_wide4 / sc_max32;
r = sc_wide4 % sc_max32;
ok &= (q == 0x80000000ull) && (r == 0x80000000ull);
sq = sc_int64min / (s64)sc_max32;
sr = sc_int64min % (s64)sc_max32;
ok &= (sq == -2147483648ll) && (sr == -2147483648ll);
/* M9.3 single-DIVU 64/32 path with a negative 32-bit-magnitude divisor:
* 2^32 / -3 = -1431655765 r 1 (the quotient sign is the sign XOR, the
* remainder follows the dividend). */
sq = (s64)sc_div32_n / (s64)sc_three_neg;
sr = (s64)sc_div32_n % (s64)sc_three_neg;
ok &= (sq == -1431655765ll) && (sr == 1ll);
return ok ? PERF_STATUS_OK : PERF_STATUS_BAD;
}
/* Small operands: the high words are zero, so the four divisions take the
* 32-bit fast path. The signed forms cast a 32-bit value to i64; a negative
* value still has a 32-bit magnitude, so it also takes the fast path. */
static void run_fast(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = (u64)(lcg((u32)a) & 0x7FFFFFFFu) + 1u;
b = (u64)(lcg((u32)b) & 0x0000FFFFu) + 1u;
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)(s32)a / (s64)(s32)b);
acc ^= (u64)((s64)(s32)a % (s64)(s32)b);
}
MARK(1) = (u32)acc;
MARK(2) = (u32)(acc >> 32);
MARK(3) = PERF_FAST_DONE;
}
/* Nonzero high words in both operands: all four forms take the 64-step
* restoring loop. The same iteration count as the fast phase makes the frame
* counts directly comparable. */
static void run_slow(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = ((u64)(1u + (lcg((u32)(a >> 32)) & 0xFFFFu)) << 32)
| (u64)(lcg((u32)a) | 1u);
b = ((u64)(1u + (lcg((u32)(b >> 32)) & 0x00FFu)) << 32)
| (u64)(lcg((u32)b) | 1u);
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)a / (s64)b);
acc ^= (u64)((s64)a % (s64)b);
}
MARK(4) = (u32)acc;
MARK(5) = (u32)(acc >> 32);
MARK(6) = PERF_SLOW_DONE;
}
/* Nonzero dividend high word, 32-bit divisor, hi(N) >= D: all four forms take
* the M8.3 two-step 64/32 path (two even-destination DIVUs) instead of the
* 64-step loop. The high word mask 0x80000000|(lcg & 0x7FFEFFFF) keeps
* hi(N) in [0x80000000, 0xFFFEFFFF] and the divisor at most 0x10000, so the
* unsigned high word is at least 0x10000. For the signed forms the
* magnitude's high word is 0xFFFFFFFF - hi(N), i.e. in [0x10000, 0x7FFFFFFF],
* so the negated magnitude is also >= 2^32 and every signed division takes
* the same two-step helper. */
static void run_wide(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = ((u64)(0x80000000u
| (lcg((u32)(a >> 32)) & 0x7FFEFFFFu)) << 32)
| (u64)(lcg((u32)a) | 1u);
b = (u64)(1u + (lcg((u32)b) & 0x0000FFFFu));
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)a / (s64)b);
acc ^= (u64)((s64)a % (s64)b);
}
MARK(9) = (u32)acc;
MARK(10) = (u32)(acc >> 32);
MARK(8) = PERF_WIDE_DONE;
}
/* Nonzero dividend high word, 32-bit divisor, hi(N) < D: all four forms take
* the M9.3 single-even-destination-DIVU path. The dividend high word is at
* most 0x10000 and the divisor is at least 0x10001, so the quotient always
* fits 32 bits and the single divide produces it. */
static void run_div32(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = ((u64)(1u + (lcg((u32)(a >> 32)) & 0xFFFFu)) << 32)
| (u64)(lcg((u32)a) | 1u);
b = (u64)(0x10001u + (lcg((u32)b) & 0x0000FFFFu));
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)a / (s64)b);
acc ^= (u64)((s64)a % (s64)b);
}
MARK(12) = (u32)acc;
MARK(13) = (u32)(acc >> 32);
MARK(11) = PERF_DIV32_DONE;
}
void i64div_perf_run(void)
{
MARK(7) = selfcheck();
MARK(0) = PERF_START;
run_fast();
run_slow();
run_wide();
run_div32();
}
+11
View File
@@ -0,0 +1,11 @@
/* M7.2 long-public-name gate, TU A.
*
* The public function name is 44 characters (45 with the C `_` prefix),
* longer than GSPA 2.00's 31-character symbol limit. The object path keeps it
* intact; tms-link resolves the cross-TU reference from longname-b.c and writes
* the full name into its map.
*/
int tms34010_public_function_name_longer_than_31(void) {
return 42;
}
+12
View File
@@ -0,0 +1,12 @@
/* M7.2 long-public-name gate, TU B.
*
* Declares and calls the 44-character public function from longname-a.c. The
* call is a normal undefined-external R-RELLONG in this object; tms-link
* resolves it to TU A's definition without truncating either name.
*/
int tms34010_public_function_name_longer_than_31(void);
int longname_call(void) {
return tms34010_public_function_name_longer_than_31() + 1;
}
+21
View File
@@ -0,0 +1,21 @@
; longname-entry.asm -- M7.2 long-public-name gate entry, linked at 018A0000.
;
; Calls the short-named TU B wrapper (which calls the 44-character public
; function in TU A) and stores its result, 43, at 018A8000. GSPA never sees
; the long name: it only assembles the short `_longname_call` reference, so
; the gate exercises tms-link's long-name symbol resolution rather than GSPA's
; 31-character truncation.
.ref _longname_call
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _longname_call
move a8,@018A8000h,1
rets
.bss _cstack,32768,16
.end
+149
View File
@@ -0,0 +1,149 @@
-- xmore-check.lua -- load the M7.3 wider-Xlib COFF with dwt/loader/loader.lua,
-- then prove the markers and the window pixels.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame (default 3400)
--
-- Markers (0x20 bits apart, read at LOADER_END-1):
-- 018A8000 parent Window id, nonzero
-- 018A8020 child Window id, nonzero
-- 018A8040 gc GC pointer, nonzero
-- 018A8060 atom XInternAtom("WM_NAME"): nonzero atom, or
-- 0xFFFFFFFF documented skip (the ROM _XSend path
-- that carries the name does not complete here)
-- 018A8080 property 1 after the XChangeProperty call site ran (no
-- server read-back; zero X errors is the only
-- runtime check)
-- 018A80A0 configure client-computed (child width << 16) | height
-- (0x00C80096); the move is pixel-proven, the size
-- is not read back
-- 018A80C0 font XLoadFont("fixed"), nonzero
-- 018A80E0 image (pixel << 8) | flags (0x13F when the full
-- XCreateImage/XGetImage/XPutImage/XDestroyImage
-- round trip worked: pixel=1 and flags=0x3F)
-- 018A8100 errors X protocol error count (0)
-- 018A8120 stage 14 = InternAtom attempted (skip), 15 = returned
-- 018A8140 attrs 1 after the XChangeWindowAttributes call site ran;
-- the real proof is the black CWBackPixel margin
-- (the ROM builder does not set A8)
-- 018A8160 gcchange XChangeGC source call count (2); runtime entry is
-- not proven, and the ROM entry is a cache flush
-- 018A8180 text set pixels in the XDrawString band (0,126) 64x16
-- 018A81A0 display Display pointer stored just before XInternAtom
-- 018A81C0 fill (FILL_W << 16) | FILL_H (0xA00078), pins the
-- margin sample's fill geometry
--
-- Geometry: parent at screen (100,100) 400x300 (the WM leaves a top-level
-- client window at its requested origin, as the M4 xshow gate proves), child
-- configured to (20,20) 200x150. The child is created with background 1
-- (white), then CWBackPixel=0 (black). The 160x120 black fill leaves a
-- right/bottom margin; screen (300,240) is in that margin, so it is black only
-- because of the window attribute (without it the child background is white).
-- The white rectangle is at child (0,0) 32x32 (screen 120,120), the heap image
-- at child (40,32) (screen 160,152; 32-bit aligned) and the XGetImage result
-- put back at child (104,32) (screen 224,152). The text is drawn at baseline
-- child (4,140) on the black margin, and the XGetImage band (child 0,126 64x16)
-- counts its white glyph pixels.
--
-- The printed "parent(...)" coordinate is screen minus the parent origin
-- (100,100), i.e. parent-relative, not child-relative (the child is at 20,20
-- inside the parent).
--
-- Pixel sampling reads the exact VRAM bit address (VR319: 2048-bit rows,
-- LSB-first), not a whole unaligned word. If XConfigureWindow did not move the
-- child from its created (40,40), the p_rect sample (screen 128,128) is outside
-- the child and p_back (screen 240,160) maps outside the put-back image; p_img
-- alone would still be white (it would land inside the 32x32 rectangle).
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local VRAM_BASE = 0x04000000
local VRAM_PITCH = 2048
local WIN_X, WIN_Y = 100, 100
local frames = 0
local checked = false
local function read_bit(prog, sx, sy)
local bit = VRAM_BASE + sy * VRAM_PITCH + sx
return prog:read_u16(bit) % 2, bit
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local m = {}
for i = 0, 14 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M7: window=0x%X child=0x%X gc=0x%X atom=0x%X property_called=%d configure=0x%X font=0x%X image=0x%X errors=%d stage=%d attrs_called=%d gcchange=%d text=%d display=0x%X fill=0x%X",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
m[10], m[11], m[12], m[13], m[14]))
local function sample(sx, sy, want)
local b, bit = read_bit(prog, sx, sy)
print(string.format(
"M7: pixel screen(%d,%d) parent(%d,%d) bit=0x%08X value=%d %s",
sx, sy, sx - WIN_X, sy - WIN_Y, bit, b,
b == 1 and "white" or "black"))
return b == want
end
-- (screen x, screen y, expected); parent-relative coordinates.
local p_rect = sample(128, 128, 1) -- parent (28,28): XFillRectangle
local p_img = sample(170, 162, 1) -- parent (70,62): heap XPutImage
local p_back = sample(240, 160, 1) -- parent (140,60): put back
local p_bg = sample(300, 240, 0) -- parent (200,140): CWBackPixel margin
local configure_want = 200 * 65536 + 150
local image_want = 0x13F
local atom_skip = (m[3] == 0xFFFFFFFF)
local atom_ok = (m[3] ~= 0 and m[3] ~= 0xFFFFFFFF
and m[3] ~= 0xFFFFFFFE)
local stage_ok = (atom_skip and m[9] == 14)
or (atom_ok and m[9] == 15)
local text_want_max = 64 * 16
local ok = m[0] ~= 0 and m[1] ~= 0 and m[2] ~= 0
and (atom_skip or atom_ok)
and m[4] == 1 and m[5] == configure_want and m[6] ~= 0
and m[7] == image_want and m[8] == 0 and stage_ok
and m[10] == 1 and m[11] == 2
and m[12] > 0 and m[12] < text_want_max
and m[13] ~= 0 and m[14] == 0xA00078
and p_rect and p_img and p_back and p_bg
print(string.format(
"M7: text band child(0,126) 64x16 set_pixels=%d (%s); "
.. "gcchange=%d (source call sites; runtime entry not proven); "
.. "attrs_called=%d; property_called=%d (call site ran, no "
.. "server read-back)",
m[12], (m[12] > 0 and m[12] < text_want_max) and "ok" or "BAD",
m[11], m[10], m[4]))
if atom_skip then
print("M7: internatom=SKIP (ROM _XSend scatter path blocks; "
.. "WM_NAME written with predefined atom 39; the display "
.. "marker only proves the connection was live before the "
.. "call; the isolated probe is narrative entry evidence)")
elseif atom_ok then
print(string.format("M7: internatom=0x%X", m[3]))
end
if ok then
print("M7 MAME: PASS")
else
print(string.format(
"M7 MAME: FAIL (window=0x%X child=0x%X gc=0x%X atom=0x%X property_called=%d configure=0x%X font=0x%X image=0x%X errors=%d stage=%d attrs_called=%d gcchange=%d text=%d display=0x%X fill=0x%X; pixels rect=%s image=%s putback=%s margin=%s)",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
m[10], m[11], m[12], m[13], m[14],
tostring(p_rect), tostring(p_img), tostring(p_back),
tostring(p_bg)))
end
end
end, "xmore-check")
+25
View File
@@ -0,0 +1,25 @@
; xmore-entry.asm -- M7.3 wider-Xlib client entry, linked at bit 018A0000.
;
; Installs the TI all-stack ABI fields and the 4 KiB stack, then calls the
; compiled xmore() client. Markers (0x20 bits apart):
; 018A8000 parent nonzero
; 018A8020 child nonzero
; 018A8040 gc nonzero
; 018A8060 atom WM_NAME atom, or 0xFFFFFFFF documented skip
; 018A8080 property post-call flag, 1 (no server read-back)
; 018A80A0 configure (width << 16) | height (client-computed; move pixel-proven)
; 018A80C0 font XLoadFont("fixed") handle
; 018A80E0 image (pixel << 8) | round-trip flags
; 018A8100 errors 0
; 018A8120 stage last completed step (14 skip, 15 atom returned)
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _xmore
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+456
View File
@@ -0,0 +1,456 @@
/*
* xmore.c -- the M7.3 wider VT1200 Xlib surface client.
*
* The client opens the ROM X display, builds one parent window and one child
* window, maps the children with XMapSubwindows, moves/resizes the child with
* the ROM's fixed-mask XConfigureWindow builder, writes the parent's WM_NAME
* property (XChangeProperty), changes the child's background with
* XChangeWindowAttributes, changes the GC foreground with XChangeGC, loads a
* font and draws text (XLoadFont + XDrawString) and a rectangle, and performs
* a heap image round trip: XCreateImage with malloc'd bytes, XPutImage,
* XGetImage of the same region, a second XPutImage of the returned image, then
* XDestroyImage on both. XInternAtom("WM_NAME") is the last surface call.
*
* The child is created with background 1 (white) and then given
* CWBackPixel=0 (black); the 160x120 black fill leaves a right/bottom margin
* that only the window attribute can make black. The text is drawn on that
* margin and its pixels are counted from an XGetImage band.
*
* Markers live at 0x018A8000 + n*0x20 (bit addresses):
* 0 parent Window id (nonzero)
* 1 child Window id (nonzero; the XMapSubwindows child)
* 2 gc GC pointer (nonzero)
* 3 atom XInternAtom("WM_NAME") result:
* nonzero the call returned the atom
* 0xFFFFFFFF the call was attempted but blocked; the
* surface is kept and the skip is explicit
* 0xFFFFFFFE the call returned None
* 4 property 1 after the XChangeProperty call site ran (no server
* read-back; the zero X-error count is the only runtime
* check)
* 5 configure client-computed (child width << 16) | child height; the
* move is pixel-proven, the size is not read back
* 6 font XLoadFont("fixed") handle (nonzero; the GC uses the
* server default font, see the CreateGC note below)
* 7 image (get_pixel << 8) | flags:
* 0x01 XCreateImage, 0x02 XGetImage returned an image,
* 0x04 the XGetImage pixel word was all white,
* 0x08 XPutImage of the returned image,
* 0x10 XDestroyImage both images,
* 0x20 XGetImage was usable (not skipped)
* all six flags plus a white pixel is 0x13F
* 8 errors X protocol error count (0)
* 9 stage last completed step (14 = XInternAtom attempted after
* everything else; 15 = it returned and the property was
* rewritten with that atom)
* 10 attrs 1 after the XChangeWindowAttributes call site ran; the
* real proof is the black CWBackPixel margin sampled by the
* gate (the ROM builder does not set A8)
* 11 gcchange count of XChangeGC source call sites (2). The ROM entry is
* the 2-arg GC-cache flush; this counts the calls in source,
* not their runtime entry.
* 12 text set pixels counted in the XDrawString band (64x16 at
* child 0,126) after XGetImage; must be > 0 and below the
* band size
* 13 display Display pointer stored just before XInternAtom; proves the
* connection was live at the pre-call marker, not that the
* call was entered
* 14 fill (FILL_W << 16) | FILL_H, so the hard-coded margin sample
* cannot silently become vacuous if the fill changes
*
* The image marker distinguishes a usable XGetImage (0x13F) from a failed or
* skipped one; a failed call clears IMG_USABLE and the gate names it.
*
* XInternAtom is deliberately last. The ROM's _XSend (0x3F9B44C0) is the
* scatter/service-write path used for InternAtom's name bytes (and for
* XPutImage's direct-send path); the M4 xshow client already records that
* this path does not make progress in the loader harness. The call is kept in
* the surface, and marker 3 records the documented skip instead of dropping
* it. The WM_NAME property is therefore written first with the predefined
* X11R4 atom XA_WM_NAME (39), which the server knows without an InternAtom.
* If XInternAtom does return (the real unit), the client rewrites the property
* with the returned atom and advances to stage 15.
*
* Two ROM/Xlib details matter:
* - XChangeProperty copies the value bytes with the ROM blitter entry
* blit_copy (0x3FB44400), just as _XPutImage does. A loader child starts
* with a zeroed blitter context, so prime it once before the property.
* - The ROM XChangeGC entry is (display, gc): it serializes the GC value
* cache that XSetForeground/XSetFont marked dirty. The drawing
* primitives call the same serializer, but the explicit call is what the
* gate exercises.
*/
#include "x11m4.h"
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
#define PARENT_X 100
#define PARENT_Y 100
#define PARENT_W 400
#define PARENT_H 300
/* Created at (40,40) 240x160, then configured to (20,20) 200x150. */
#define CHILD_X 20
#define CHILD_Y 20
#define CHILD_W 200
#define CHILD_H 150
#define IMG_W 64
#define IMG_H 64
#define IMG_BPL (IMG_W / 8)
/* The black fill leaves a margin so the CWBackPixel background is visible. */
#define FILL_W 160
#define FILL_H 120
/* XDrawString("xmore") at baseline (4,140), on the black bottom margin. */
#define TEXT_X 4
#define TEXT_Y 140
#define TEXT_LEN 5
#define TEXT_BAND_X 0
#define TEXT_BAND_Y 126
#define TEXT_BAND_W 64
#define TEXT_BAND_H 16
#define XA_STRING 31
#define XA_WM_NAME 39
#define PropModeReplace 0
#define INTERNATOM_SKIPPED 0xFFFFFFFFu
#define INTERNATOM_NONE 0xFFFFFFFEu
/*
* The wider-surface ABI, pinned here so a header edit cannot silently change
* the offsets the ROM request builders read (X11R4 32-bit structs: 4-byte
* fields). XWindowChanges.width=8; XSetWindowAttributes.background_pixel=4
* (CWBackPixel); XGCValues.font=60 (GCFont; the ROM walker reads byte 60).
*/
_Static_assert(__builtin_offsetof(XWindowChanges, width) == 8,
"XWindowChanges.width must be at byte 8");
_Static_assert(__builtin_offsetof(XSetWindowAttributes, background_pixel) == 4,
"XSetWindowAttributes.background_pixel must be at byte 4");
_Static_assert(__builtin_offsetof(XGCValues, font) == 60,
"XGCValues.font must be at byte 60");
#define IMG_CREATED 0x01
#define IMG_GOT 0x02
#define IMG_PIXEL 0x04
#define IMG_PUT 0x08
#define IMG_DESTROYED 0x10
#define IMG_USABLE 0x20
/* The ROM allocator (symbols/vt1200-v22.syms: malloc/free). */
extern void *malloc(unsigned int size);
extern void free(void *p);
static int xerrors;
/* The two explicit XChangeGC call sites (marker 11). */
static unsigned int gc_changes;
static int on_error(Display *d, XErrorEvent *e) {
(void)d;
(void)e;
xerrors++;
return 0;
}
/* The ROM sleep through a function pointer, as the M4 client does. */
static int (*volatile vt_sleep)(int) = sleep;
/* XImage.data is heap memory here, so the ROM destructor may free it. */
static XImage *heap_image;
/*
* The blitter is process-global and starts zeroed in a loader child. Prime
* it with a four-byte self-copy before XChangeProperty's value copy.
*/
static void prime_blitter(void) {
static unsigned int word;
blit_copy(&word, &word, 4);
}
static void clear_black(Display *d, Window w, GC gc) {
XSetForeground(d, gc, 0);
XChangeGC(d, gc);
gc_changes++;
/* Leave the child's right/bottom margin to the CWBackPixel background. */
XFillRectangle(d, w, gc, 0, 0, FILL_W, FILL_H);
}
static void draw_white(Display *d, Window w, GC gc) {
XSetForeground(d, gc, 1);
XChangeGC(d, gc);
gc_changes++;
/* The drawing call and the text call, both after the GC change. The
* text sits on the black CWBackPixel margin so its pixels are countable. */
XFillRectangle(d, w, gc, 0, 0, 32, 32);
XDrawString(d, w, gc, TEXT_X, TEXT_Y, "xmore", TEXT_LEN);
}
/*
* Prove XDrawString with pixels: XGetImage the text band and count set bits.
* The band is black CWBackPixel background; white glyphs make the count
* nonzero. A solid white count (>= the band size) would mean the band was not
* contrasting, so the gate also requires it below the band size.
*/
static void text_pixels(Display *d, Window w) {
XImage *im = XGetImage(d, w, TEXT_BAND_X, TEXT_BAND_Y, TEXT_BAND_W,
TEXT_BAND_H, ~0L, XYPixmap);
unsigned int count = 0;
int y, x;
if (!im) {
MARK(12) = 0;
return;
}
if (im->data) {
for (y = 0; y < TEXT_BAND_H; y++) {
unsigned int *row = (unsigned int *)(void *)(im->data +
y * im->bytes_per_line);
for (x = 0; x < (TEXT_BAND_W / 8) / 4; x++) {
unsigned int v = row[x];
while (v) {
count += v & 1u;
v >>= 1;
}
}
}
}
MARK(12) = count;
XDestroyImage(im);
}
static void image_roundtrip(Display *d, Window w, GC gc) {
char *bytes;
XImage *got;
unsigned int flags = 0;
unsigned int pixel = 0;
int i;
int destroyed = 0;
bytes = (char *)malloc(IMG_BPL * IMG_H);
if (bytes) {
unsigned int *words = (unsigned int *)bytes;
for (i = 0; i < (IMG_BPL * IMG_H) / 4; i++)
words[i] = 0xFFFFFFFFu;
}
heap_image = XCreateImage(d, 0, 1, XYBitmap, 0, bytes, IMG_W, IMG_H, 32,
IMG_BPL);
if (!heap_image) {
if (bytes)
free(bytes);
MARK(7) = 0;
return;
}
flags |= IMG_CREATED;
heap_image->byte_order = LSBFirst;
heap_image->bitmap_bit_order = LSBFirst;
/* A 32-bit-aligned destination x (screen 100+20+40 = 160) is required by
* the server's 1-bit bitmap copy path, as the M4 xshow client found. */
if (XPutImage(d, w, gc, heap_image, 0, 0, 40, 32, IMG_W, IMG_H))
flags |= IMG_PUT;
XSync(d, 0);
got = XGetImage(d, w, 40, 32, IMG_W, IMG_H, ~0L, XYPixmap);
if (!got) {
/* The call ran and failed. Destroy our half of the surface and leave
* the caller's stage at 12 (the text-pixel step), so the check names
* XGetImage. */
if (XDestroyImage(heap_image))
flags |= IMG_DESTROYED;
heap_image = 0;
MARK(7) = flags;
return;
}
flags |= IMG_GOT | IMG_USABLE;
/* The region is all white: the first 32 bits of row 0 are all ones. */
if (got->data && *(unsigned int *)(void *)got->data == 0xFFFFFFFFu) {
flags |= IMG_PIXEL;
pixel = 1;
}
/* Put the returned heap image back at child x=104 (screen 224). */
if (XPutImage(d, w, gc, got, 0, 0, 104, 32, IMG_W, IMG_H))
flags |= IMG_PUT;
if (XDestroyImage(got))
destroyed++;
if (XDestroyImage(heap_image))
destroyed++;
heap_image = 0;
if (destroyed == 2)
flags |= IMG_DESTROYED;
MARK(7) = (pixel << 8) | flags;
}
int xmore(void) {
Display *d;
Window root;
Window parent;
Window child;
GC gc;
Font font;
XSetWindowAttributes attrs = {0};
XWindowChanges wc;
int tries;
int i;
for (i = 0; i <= 14; i++)
MARK(i) = 0;
if (!vt_install_xg())
return -1;
d = 0;
for (tries = 0; tries < 40; tries++) {
d = XOpenDisplay("0::0");
if (d)
break;
vt_sleep(50);
}
if (!d)
return -1;
MARK(9) = 1;
XSetErrorHandler(on_error);
prime_blitter();
root = vt_root(d);
parent = XCreateSimpleWindow(d, root, PARENT_X, PARENT_Y, PARENT_W,
PARENT_H, 0, 0, 0);
MARK(0) = (unsigned)parent;
/* Background 1 (white) at creation: CWBackPixel must make it black. */
child = XCreateSimpleWindow(d, parent, 40, 40, 240, 160, 0, 0, 1);
MARK(1) = (unsigned)child;
MARK(9) = 2;
/* opcode 9: map both the parent's children (the child above). */
XMapSubwindows(d, parent);
MARK(9) = 3;
/*
* opcode 12 with the ROM's fixed CWX|CWY|CWWidth|CWHeight mask. The
* XWindowChanges record holds the same four values; the X11R4 client
* API's mask is implied by the entry.
*/
wc.x = CHILD_X;
wc.y = CHILD_Y;
wc.width = CHILD_W;
wc.height = CHILD_H;
wc.border_width = 0;
wc.sibling = 0;
wc.stack_mode = 0;
XConfigureWindow(d, child, wc.x, wc.y, (unsigned int)wc.width,
(unsigned int)wc.height);
/*
* The configure marker is client-computed: it records the four values
* passed to the ROM builder. The move is pixel-proven below; the size is
* not read back from the server.
*/
MARK(5) = ((unsigned int)wc.width << 16) | (unsigned int)wc.height;
MARK(9) = 4;
/*
* The property value first goes through the predefined XA_WM_NAME atom,
* so the XChangeProperty surface is exercised even if XInternAtom cannot
* complete below. Marker 4 is a plain post-call flag: the ROM builder
* never sets A8, so there is no return value or server read-back; zero X
* errors is the only runtime check.
*/
XChangeProperty(d, parent, XA_WM_NAME, XA_STRING, 8, PropModeReplace,
(const unsigned char *)"xmore", 5);
MARK(4) = 1;
MARK(9) = 5;
/* The struct was zero-initialized at its declaration; only
* CWBackPixel's byte 4 is selected here. */
attrs.background_pixel = 0;
XChangeWindowAttributes(d, child, CWBackPixel, &attrs);
/* Post-call flag only; the black margin is the real attribute proof. */
MARK(10) = 1;
MARK(9) = 6;
/*
* Map the top-level parent after the child is mapped, then let the WM
* frame it before drawing: an X11 map fills the background and would
* erase anything drawn while the window is still unmapped.
*/
XMapWindow(d, parent);
XSync(d, 0);
vt_sleep(300);
MARK(9) = 7;
font = XLoadFont(d, "fixed");
MARK(6) = (unsigned)font;
MARK(9) = 8;
/*
* The GC uses the server's default font. XLoadFont is still exercised
* above (marker 6); its returned value is a ROM font handle, not the
* server font XID, so passing it as GCFont makes CreateGC fail BadFont.
* The default GC font is the 6x13 cell the termtris client documents.
*/
gc = XCreateGC(d, child, 0, 0);
MARK(2) = (unsigned)gc;
MARK(9) = 9;
clear_black(d, child, gc);
MARK(9) = 10;
draw_white(d, child, gc);
MARK(9) = 11;
/* XGetImage the text band and count its white pixels (marker 12). */
text_pixels(d, child);
MARK(9) = 12;
image_roundtrip(d, child, gc);
/* Only a usable XGetImage advances the image stage. */
if ((MARK(7) & IMG_USABLE) != 0) {
XSync(d, 0);
MARK(8) = (unsigned)xerrors;
MARK(9) = 13;
} else {
MARK(8) = (unsigned)xerrors;
}
/*
* Last: the InternAtom surface. The skip marker and the live Display
* pointer are written before the call so a blocked _XSend still leaves
* the documented state behind. The marker proves only that the
* connection was live before the call; entry into the ROM function is
* not proven by it (the report's isolated probe is narrative evidence).
*/
MARK(13) = (unsigned)d;
MARK(11) = gc_changes;
MARK(14) = ((unsigned)FILL_W << 16) | (unsigned)FILL_H;
MARK(3) = INTERNATOM_SKIPPED;
MARK(9) = 14;
{
Atom a = XInternAtom(d, "WM_NAME", False);
if (a) {
MARK(3) = (unsigned)a;
XChangeProperty(d, parent, a, XA_STRING, 8, PropModeReplace,
(const unsigned char *)"xmore", 5);
MARK(4) = 1;
MARK(9) = 15;
} else {
MARK(3) = INTERNATOM_NONE;
}
}
/*
* Do not return: returning tears the process (and its windows) down before
* the harness reads the markers and VRAM. Keep the connection drained and
* hold the last completed stage so a failed call stays visible.
*/
for (;;) {
MARK(8) = (unsigned)xerrors;
MARK(11) = gc_changes;
XFlush(d);
vt_sleep(5);
}
}
+20
View File
@@ -0,0 +1,20 @@
int debug_a_base = 3;
int debug_a_mul(void) {
int product = debug_a_base * 7;
return product + 1;
}
int debug_a_add(void) {
int sum = debug_a_base + 4;
return sum * 2;
}
/* M8.2 multi-TU debug gate, first translation unit.
*
* Two functions with distinct source lines; debug_a_mul returns 22 and
* debug_a_add returns 14. debug-b.c is the second debug-bearing TU, and
* debug-entry.asm calls all four functions so the linked image exercises both
* units at runtime. The comment is after the code so the line numbers used by
* dwarf-multi.sh stay stable.
*/
+19
View File
@@ -0,0 +1,19 @@
int debug_b_base = 5;
int debug_b_sub(void) {
int diff = debug_b_base - 2;
return diff * 3;
}
int debug_b_mul(void) {
int factor = debug_b_base + 1;
return factor * factor;
}
/* M8.2 multi-TU debug gate, second translation unit.
*
* debug_b_sub returns 9 and debug_b_mul returns 36. The TU's `.text` is
* concatenated after debug-a.c's, so its functions and DWARF addresses are at
* nonzero text offsets; dwarf-multi.sh asserts the rehomed CU/section bases
* and the linked low PCs.
*/
+31
View File
@@ -0,0 +1,31 @@
; debug-entry.asm -- M8.2 multi-TU debug gate entry, linked at bit 018A0000.
;
; debug-a.o is linked first and debug-b.o second, so debug_a_mul is the text
; origin function (DWARF low PC 0x314000), debug-b's functions are at nonzero
; text offsets, and _start follows both TUs. The entry calls all four
; functions and stores their results (22, 14, 9, 36) at 018A8000, 018A8020,
; 018A8040 and 018A8060; debug-multi-check.lua reads them after the stripped
; image loads.
.ref _debug_a_mul
.ref _debug_a_add
.ref _debug_b_sub
.ref _debug_b_mul
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _debug_a_mul
move a8,@018A8000h,1
calla _debug_a_add
move a8,@018A8020h,1
calla _debug_b_sub
move a8,@018A8040h,1
calla _debug_b_mul
move a8,@018A8060h,1
rets
.bss _cstack,32768,16
.end
+19
View File
@@ -0,0 +1,19 @@
dofile(os.getenv("M4_LOADER_LUA"))
local frames = 0
emu.register_frame_done(function()
frames = frames + 1
if frames == tonumber(os.getenv("LOADER_END") or "2700") - 1 then
local prog = manager.machine.devices[':maincpu'].spaces['program']
local a_mul = prog:read_u32(0x018A8000)
local a_add = prog:read_u32(0x018A8020)
local b_sub = prog:read_u32(0x018A8040)
local b_mul = prog:read_u32(0x018A8060)
print(string.format("DEBUG MULTI: a_mul=%d a_add=%d b_sub=%d b_mul=%d",
a_mul, a_add, b_sub, b_mul))
if a_mul == 22 and a_add == 14 and b_sub == 9 and b_mul == 36 then
print("DEBUG MULTI MAME: PASS")
else
print("DEBUG MULTI MAME: FAIL (want 22/14/9/36)")
end
end
end, "debug-multi-check")
+34
View File
@@ -0,0 +1,34 @@
-- lib-check.lua -- read the M8 native-library gate marker words.
--
-- The driver writes five words at 018A8000 + n*0x20:
-- 0: (int)(1.5 + 2.5) == 4 (flib FD$ADD + FD$DTOI)
-- 1: (int)(1.5 * 2.5) == 3 (flib FD$MUL + FD$DTOI)
-- 2: isascii('A') != 0 (rts.lib _isascii)
-- 3: isascii(0xC8) == 0 (rts.lib _isascii)
-- 4: 0x4C494231 ("LIB1" sentinel)
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local frames = 0
local checked = false
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
for i = 0, 4 do
got[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format("M8 LIB: sum=%d product=%d asciiA=%d asciiC8=%d sentinel=%08X",
got[0], got[1], got[2], got[3], got[4]))
if got[0] == 4 and got[1] == 3 and got[2] ~= 0 and
got[3] == 0 and got[4] == 0x4C494231 then
print("M8 LIB MAME: PASS")
else
print("M8 LIB MAME: FAIL (want 4 3 nonzero 0 4C494231)")
end
end
end, "m8-lib-check")
+16
View File
@@ -0,0 +1,16 @@
; lib-entry.asm -- M8 native-library gate entry, linked at bit 018A0000.
;
; Calls the compiled driver libcheck_test(), which uses flib.lib doubles and
; rts.lib _isascii. Marker words live at 018A8000 + n*0x20 and are checked by
; lib-check.lua.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _libcheck_test
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+26
View File
@@ -0,0 +1,26 @@
/* M8 native-library gate driver.
*
* The double operations lower to flib.lib's FD$ADD/FD$MUL and the fptosi
* conversions to FD$DTOI; isascii is the rts.lib member. The markers are
* fixed bit addresses in the prog region because the linker map's symbol
* values are not needed by this tiny check.
*/
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
extern int isascii(int);
static volatile double fa = 1.5;
static volatile double fb = 2.5;
int libcheck_test(void)
{
double sum = fa + fb;
double product = fa * fb;
MARK(0) = (unsigned)(int)sum; /* 4: FD$ADD + FD$DTOI */
MARK(1) = (unsigned)(int)product; /* 3: FD$MUL + FD$DTOI */
MARK(2) = (unsigned)isascii('A'); /* 1: rts.lib _isascii */
MARK(3) = (unsigned)isascii(0xC8); /* 0: rts.lib _isascii */
MARK(4) = 0x4C494231u; /* "LIB1" sentinel */
return 0;
}
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# os2-toolchain.sh -- run the 1990 TI r5.01 OS/2 tools under 2ine/qemu-i386.
#
# Sourced by scripts/m4/run.sh when M4_OS2=1. The 1990 tools are 16-bit OS/2
# 1.x NE programs; the patched 2ine loader runs them on a 64-bit Linux host
# via qemu-i386 (the plain lx_loader needs a kernel with 16-bit LDT support).
#
# Environment:
# M4_OS2=1 enable this path
# M4_OS2_2INE=PATH 2ine checkout (default /home/arti/os2-work/2ine-tms34010)
# M4_OS2_LX=PATH lx_loader (default $2ine/build/lx_loader; the
# build-qemu wrapper is the fallback)
# M4_OS2_SDK=PATH extracted r5.01 tree with bin/ and lib/
# M4_OS2_ROOT=PATH parent of the default 2ine/os2-501 (default /home/arti/os2-work)
#
# The functions expect run.sh globals: WORK, SDK, fail, NATIVE_OBJS,
# NATIVE_LIBS. Outputs are copied back with the uppercase names run.sh uses.
os2_init() {
OS2_2INE=${M4_OS2_2INE:-${M4_OS2_ROOT:-/home/arti/os2-work}/2ine-tms34010}
OS2_LX=${M4_OS2_LX:-$OS2_2INE/build/lx_loader}
if [ ! -x "$OS2_LX" ] && [ -x "$OS2_2INE/build-qemu/lx_loader" ]; then
OS2_LX=$OS2_2INE/build-qemu/lx_loader
fi
OS2_SDK=${M4_OS2_SDK:-${M4_OS2_ROOT:-/home/arti/os2-work}/os2-501}
[ -x "$OS2_LX" ] || fail "M4_OS2=1: missing 2ine lx_loader: $OS2_LX (run scripts/m8/setup-os2.sh)"
[ -f "$OS2_SDK/bin/gspa.exe" ] \
|| fail "M4_OS2=1: missing OS/2 gspa.exe under $OS2_SDK/bin (run scripts/m8/setup-os2.sh)"
case $OS2_LX in
*/build-qemu/*)
command -v qemu-i386 >/dev/null 2>&1 \
|| fail "M4_OS2=1: qemu-i386 is required for the build-qemu wrapper" ;;
esac
OS2_QEMU=$OS2_2INE/build-qemu/lx_loader
OS2_DIR=$WORK/os2
rm -rf "$OS2_DIR"
mkdir -p "$OS2_DIR"
# 2ine loads its OS/2 import modules from the working directory.
for so in "$OS2_2INE"/build/lib*.so; do
[ -e "$so" ] && ln -sf "$so" "$OS2_DIR/"
done
cp "$OS2_SDK/bin/gspa.exe" "$OS2_DIR/"
cp "$OS2_SDK/bin/gsplnk.exe" "$OS2_DIR/"
cp "$OS2_SDK/lib/rts.lib" "$OS2_SDK/lib/flib.lib" "$OS2_DIR/" 2>/dev/null || true
}
os2_gspa() { # os2_gspa NAME (M4 or M4EXT)
_name=$1
[ -f "$SDK/$_name.ASM" ] || fail "M4_OS2: missing $SDK/$_name.ASM"
cp "$SDK/$_name.ASM" "$OS2_DIR/$_name.ASM"
_gspa() { # _gspa LX
( cd "$OS2_DIR" && \
"$1" ./gspa.exe "$_name.ASM" "$_name.obj" "$_name.lst" -l \
) > "$OS2_DIR/$_name.gspa.log" 2>&1 || true
}
rm -f "$OS2_DIR/$_name.lst" "$OS2_DIR/$_name.obj"
_gspa "$OS2_LX"
if ! grep -q 'No Errors' "$OS2_DIR/$_name.lst" 2>/dev/null; then
# The direct 2ine loader can hit its segment assertion on some large
# inputs; qemu-i386 is the reliable fallback.
if [ -x "$OS2_QEMU" ] && [ "$OS2_LX" != "$OS2_QEMU" ]; then
echo " note: direct 2ine gspa failed; retrying under qemu" >&2
_gspa "$OS2_QEMU"
fi
fi
grep -q 'No Errors' "$OS2_DIR/$_name.lst" 2>/dev/null || {
cat "$OS2_DIR/$_name.gspa.log" >&2
fail "OS/2 gspa failed for $_name"
}
cp "$OS2_DIR/$_name.obj" "$SDK/$_name.OBJ"
cp "$OS2_DIR/$_name.lst" "$SDK/$_name.LST"
}
os2_gsplnk() {
# Copy every object the linker command may reference, plus the lowercase
# library names the 5.01 command file uses.
for obj in "$SDK"/*.OBJ "$SDK"/*.obj; do
[ -e "$obj" ] && cp "$obj" "$OS2_DIR/"
done
# Copy every library the command file may reference; the 1987/1990 files
# are uppercase on disk while the linker command uses lowercase names.
for lib in "$SDK"/*.LIB "$SDK"/*.lib; do
[ -e "$lib" ] || continue
_low=$(basename "$lib" | tr '[:upper:]' '[:lower:]')
cp "$lib" "$OS2_DIR/$_low"
done
cp "$SDK/M4.CMD" "$OS2_DIR/M4.CMD"
rm -f "$OS2_DIR/M4.OUT" "$OS2_DIR/M4.MAP"
_gsplnk() {
( cd "$OS2_DIR" && "$1" ./gsplnk.exe M4.CMD ) \
> "$OS2_DIR/M4.gsplnk.log" 2>&1 || true
}
_gsplnk "$OS2_LX"
if [ ! -f "$OS2_DIR/M4.OUT" ] && [ -x "$OS2_QEMU" ] \
&& [ "$OS2_LX" != "$OS2_QEMU" ]; then
echo " note: direct 2ine gsplnk failed; retrying under qemu" >&2
_gsplnk "$OS2_QEMU"
fi
[ -f "$OS2_DIR/M4.OUT" ] || {
cat "$OS2_DIR/M4.gsplnk.log" >&2
fail "OS/2 gsplnk failed"
}
cp "$OS2_DIR/M4.OUT" "$SDK/M4.OUT"
cp "$OS2_DIR/M4.MAP" "$SDK/M4.MAP"
}
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# setup-os2.sh -- provision the 1990 TI r5.01 OS/2 toolchain for the harness.
#
# The r5.01 tools are 16-bit OS/2 1.x NE console programs. They run on a
# 64-bit Linux host through the patched 2ine loader under qemu-i386 (the plain
# lx_loader needs a kernel with 16-bit LDT support; qemu-i386 provides it).
#
# scripts/m8/setup-os2.sh
#
# Environment:
# M4_OS2_ROOT install root (default $HOME/os2-work)
# M4_OS2_2INE 2ine checkout (default $M4_OS2_ROOT/2ine-tms34010)
# M4_OS2_SDK extracted r5.01 tree (default $M4_OS2_ROOT/os2-501)
#
# Then run gates with M4_OS2=1 (and optionally M4_LINKER=tms-link). The
# default harness remains the 1987 DOSBox GSPA/GSPLNK oracle.
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
OS2_ROOT=${M4_OS2_ROOT:-$HOME/os2-work}
TWOINE=${M4_OS2_2INE:-$OS2_ROOT/2ine-tms34010}
SDK=${M4_OS2_SDK:-$OS2_ROOT/os2-501}
SDK_SRC="$ROOT/vendor/vt1200/tools/tms34010-sdk/1990-11 TMS340 Family SDK"
fail() { echo "setup-os2: FAIL: $*" >&2; exit 1; }
command -v git >/dev/null 2>&1 || fail "git is required"
command -v cmake >/dev/null 2>&1 || fail "cmake is required"
command -v unzip >/dev/null 2>&1 || fail "unzip is required"
# The direct loader is preferred; qemu-i386 is only needed as a fallback on
# kernels without 16-bit LDT support.
if [ ! -x "$TWOINE/build/lx_loader" ]; then
echo "== clone and build 2ine-tms34010 into $TWOINE"
mkdir -p "$(dirname "$TWOINE")"
[ -d "$TWOINE/.git" ] || \
git clone https://git.wut.ee/opencode.energia.arti.ee/2ine-tms34010.git "$TWOINE"
cmake -S "$TWOINE" -B "$TWOINE/build" -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_POLICY_VERSION_MINIMUM=3.5
cmake --build "$TWOINE/build" -j"${JOBS:-$(nproc)}"
fi
LX=${M4_OS2_LX:-$TWOINE/build/lx_loader}
if [ ! -x "$LX" ]; then
# Kernel fallback: wrap the loader in qemu-i386 (which provides 16-bit LDT
# support even when CONFIG_X86_16BIT is off).
command -v qemu-i386 >/dev/null 2>&1 \
|| fail "lx_loader is missing and qemu-i386 is unavailable"
mkdir -p "$TWOINE/build-qemu"
cat > "$TWOINE/build-qemu/lx_loader" <<EOF
#!/bin/sh
exec qemu-i386 "$TWOINE/build/lx_loader" "\$@"
EOF
chmod +x "$TWOINE/build-qemu/lx_loader"
LX=$TWOINE/build-qemu/lx_loader
fi
if [ ! -f "$SDK/bin/gspa.exe" ]; then
echo "== extract the r5.01 tools into $SDK"
[ -f "$SDK_SRC/1990-11-19 TMS340 Family Code Generation Tools (1 of 2) r5.01 rev2564062-1641.zip" ] \
|| fail "missing the r5.01 tools zip under $SDK_SRC"
mkdir -p "$SDK/bin" "$SDK/lib" "$SDK/work"
unzip -oq "$SDK_SRC/1990-11-19 TMS340 Family Code Generation Tools (1 of 2) r5.01 rev2564062-1641.zip" -d "$SDK/bin"
unzip -oq "$SDK_SRC/1990-11-19 TMS340 Family Code Generation Tools (2 of 2) r5.01 rev2564062-1641.zip" -d "$SDK/lib"
fi
[ -f "$SDK/bin/gspa.exe" ] || fail "gspa.exe missing after extraction"
[ -x "$LX" ] || fail "lx_loader missing: $LX"
# Smoke test: assemble an empty source in a throw-away work dir.
TMP=$(mktemp -d "$OS2_ROOT/os2-smoke.XXXXXX")
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
for so in "$TWOINE"/build/lib*.so; do [ -e "$so" ] && ln -sf "$so" "$TMP/"; done
cp "$SDK/bin/gspa.exe" "$TMP/"
: > "$TMP/t.asm"
( cd "$TMP" && "$LX" ./gspa.exe t.asm > gspa.log 2>&1 ) || true
if ! grep -q 'No Errors' "$TMP/gspa.log"; then
# Retry through qemu if the direct loader cannot allocate 16-bit LDTs.
if [ "$LX" = "$TWOINE/build/lx_loader" ] && command -v qemu-i386 >/dev/null 2>&1; then
mkdir -p "$TWOINE/build-qemu"
cat > "$TWOINE/build-qemu/lx_loader" <<EOF
#!/bin/sh
exec qemu-i386 "$TWOINE/build/lx_loader" "\$@"
EOF
chmod +x "$TWOINE/build-qemu/lx_loader"
LX=$TWOINE/build-qemu/lx_loader
( cd "$TMP" && "$LX" ./gspa.exe t.asm > gspa.log 2>&1 ) || true
fi
grep -q 'No Errors' "$TMP/gspa.log" \
|| { cat "$TMP/gspa.log" >&2; fail "gspa smoke test failed"; }
fi
cat <<EOF
OS/2 r5.01 toolchain ready:
M4_OS2_ROOT=$OS2_ROOT
M4_OS2_2INE=$TWOINE
M4_OS2_LX=$LX
M4_OS2_SDK=$SDK
Use it with:
M4_OS2=1 scripts/tests/m7/full-suite.sh --corpus all --work build/m8-os2-full
M4_OS2=1 M4_LINKER=tms-link scripts/tests/m5/c-torture.sh
M4_OS2=1 scripts/m4/run.sh # asm path: OS/2 gspa + OS/2 gsplnk
The default harness still uses the 1987 DOSBox GSPA/GSPLNK oracle.
EOF
+24
View File
@@ -0,0 +1,24 @@
/* M9.2 range-list fixture A: -O2 -g loop/inlining shape that makes LLVM emit
* a non-contiguous DW_TAG_inlined_subroutine and therefore .debug_rnglists.
* Compiled by scripts/tests/m9/dwarf-ranges.sh; not a runtime test. */
static inline __attribute__((always_inline)) int m9_inc(int x) {
if (x & 1)
return x + 1;
return x + 3;
}
int m9_range_one(int a) {
int sum = 0;
int i;
for (i = 0; i < a; i++)
sum += m9_inc(i);
return sum;
}
static int m9_helper(int q) {
return q * 5;
}
int m9_range_two(int a) {
return m9_helper(a) + m9_range_one(a);
}
+18
View File
@@ -0,0 +1,18 @@
/* M9.2 range-list fixture B: a second TU with the same loop/inlining shape so
* the multi-TU merge has two .debug_rnglists contributions to rehome. */
static inline __attribute__((always_inline)) int m9_dec(int x) {
if (x & 2)
return x - 1;
return x - 3;
}
int m9_range_three(int a) {
int sum = 1;
for (int i = 0; i < a; i++)
sum += m9_dec(i);
return sum;
}
int m9_range_four(int a) {
return m9_range_three(a) * 3;
}
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env python3
"""Write two TI-COFF objects that actually emit DWARF v5 `.debug_rnglists`.
The M8 fixtures (-O0 and a straight-line -O2 shape) never emitted a range list,
so the merge's `.debug_rnglists` whitelist was untested. This helper emits the
section directly: a well-formed CU per object with
* ``DW_AT_rnglists_base`` (``DW_FORM_sec_offset`` into .debug_rnglists),
* ``DW_AT_addr_base`` (``DW_FORM_sec_offset`` into .debug_addr),
* ``DW_AT_ranges`` (``DW_FORM_rnglistx`` index 0),
* a range list with one ``DW_RLE_start_end`` (absolute, relocated .text
addresses) and one ``DW_RLE_startx_length`` (index into .debug_addr),
* a subprogram DIE with a relocated ``DW_FORM_addr`` low PC.
Every section-relative field carries an R-RELLONG relocation, so the objects
also pass the form-aware input gate. ``scripts/tests/m9/dwarf-ranges.sh``
links them, wraps the result in the M7 ELF container and validates the ranges
with ``llvm-dwarfdump``. The same gate also has a real `-O2 -g` producer case
(loop/inline shapes can make LLVM emit non-contiguous inlined ranges); this
synthetic fixture keeps the `start_end`/`startx_length` and offset-rehoming
forms deterministic.
Usage: dwarf-ranges-fixture.py OUTDIR [--tag AB]
"""
from __future__ import annotations
import argparse
import os
import struct
import sys
MAGIC = 0x0090
R_RELLONG = 0x11
S_TEXT = 0x20
S_DATA = 0x40
S_BSS = 0x80
C_EXT = 2
C_STAT = 3
TEXT_ORIGIN = 0x018A0000
TEXT_BYTES = 16
def uleb(value):
out = bytearray()
while True:
byte = value & 0x7F
value >>= 7
if value:
out.append(byte | 0x80)
else:
out.append(byte)
return bytes(out)
class Section:
def __init__(self, name, flags, data=b"", bits=None):
self.name = name
self.flags = flags
self.data = bytearray(data)
self.bits = len(self.data) * 8 if bits is None else bits
self.relocs = [] # (byte offset, symbol name)
def reloc(self, offset, symbol):
self.relocs.append((offset, symbol))
return offset
def debug_abbrev():
return (
b"\x01\x11\x01" # 1: DW_TAG_compile_unit, children
b"\x03\x0e" # DW_AT_name, DW_FORM_strp
b"\x73\x17" # DW_AT_addr_base, DW_FORM_sec_offset
b"\x74\x17" # DW_AT_rnglists_base, sec_offset
b"\x55\x23" # DW_AT_ranges, DW_FORM_rnglistx
b"\x00\x00"
b"\x02\x2e\x00" # 2: DW_TAG_subprogram, no children
b"\x03\x0e" # DW_AT_name, DW_FORM_strp
b"\x11\x01" # DW_AT_low_pc, DW_FORM_addr
b"\x12\x06" # DW_AT_high_pc, DW_FORM_data4
b"\x00\x00"
b"\x00")
def build(tag):
"""One object whose single function sits at .text offset 0."""
cu_name = ("rng-%s.c" % tag).encode("ascii")
fn_name = ("rng_" + tag).encode("ascii")
strings = cu_name + b"\0" + fn_name + b"\0"
cu_off = 0
fn_off = len(cu_name) + 1
sections = [
Section(".text", S_TEXT, b"\0" * TEXT_BYTES),
Section(".data", S_DATA),
Section(".bss", S_BSS, bits=0),
]
abbrev = Section(".debug_abbrev", 0, debug_abbrev())
sections.append(abbrev)
# .debug_info: v5 CU header + root DIE (code 1) + subprogram (2).
info_section = Section(".debug_info", 0, b"\0\0\0\0")
info = info_section.data
info += struct.pack("<HBB", 5, 1, 4) # version, DW_UT_compile, addrsize
info += b"\0\0\0\0" # abbrev offset (relocated)
info_section.reloc(8, ".debug_abbrev")
info += b"\x01" # root DIE
info += struct.pack("<I", cu_off) # DW_AT_name -> .debug_str
info_section.reloc(len(info) - 4, ".debug_str")
info += struct.pack("<I", 8) # DW_AT_addr_base -> .debug_addr
info_section.reloc(len(info) - 4, ".debug_addr")
info += struct.pack("<I", 12) # DW_AT_rnglists_base -> header end
info_section.reloc(len(info) - 4, ".debug_rnglists")
info += uleb(0) # DW_AT_ranges, rnglistx index 0
info += b"\x02" # subprogram DIE
info += struct.pack("<I", fn_off) # DW_AT_name
info_section.reloc(len(info) - 4, ".debug_str")
info += struct.pack("<I", 0) # DW_AT_low_pc, linked .text
info_section.reloc(len(info) - 4, ".text")
info += struct.pack("<I", 4) # DW_AT_high_pc (byte size)
info += b"\x00" # end of the root's children
struct.pack_into("<I", info, 0, len(info) - 4)
sections.append(info_section)
sections.append(Section(".debug_str", 0, strings))
# .debug_addr: unit header + two 4-byte addresses (text+8, text+12).
addr_section = Section(".debug_addr", 0, b"\0\0\0\0")
addr = addr_section.data
addr += struct.pack("<HBB", 5, 4, 0)
for value in (8, 12):
addr += struct.pack("<I", value)
addr_section.reloc(len(addr) - 4, ".text")
struct.pack_into("<I", addr, 0, len(addr) - 4)
sections.append(addr_section)
# .debug_rnglists: header (12 bytes) + one offset entry (base = 12).
rng_section = Section(".debug_rnglists", 0, b"\0\0\0\0")
rng = rng_section.data
rng += struct.pack("<HBB", 5, 4, 0)
rng += struct.pack("<I", 1) # offset_entry_count
rng += struct.pack("<I", 4) # offset[0]: list at base + 4
assert len(rng) == 16, len(rng)
rng += b"\x06" # DW_RLE_start_end
rng += struct.pack("<I", 0) # start = text + 0
rng_section.reloc(len(rng) - 4, ".text")
rng += struct.pack("<I", 4) # end = text + 4
rng_section.reloc(len(rng) - 4, ".text")
rng += b"\x03" + uleb(0) + uleb(4) # DW_RLE_startx_length: addr[0] .. +4
rng += b"\x00" # DW_RLE_end_of_list
struct.pack_into("<I", rng, 0, len(rng) - 4)
sections.append(rng_section)
# Section sizes were captured at construction; the unit builders above
# append to the byte arrays afterwards.
for sec in sections:
if sec.name != ".bss":
sec.bits = len(sec.data) * 8
return sections
def short_name(name):
return len(name.encode("latin1")) <= 8
def write_object(path, sections, tag):
"""Serialise one relocatable TI-COFF object.
Relocation targets are section symbols (matching the LLVM producer), plus
an external ``_rng_<tag>`` in .text so the linked image names the function.
"""
section_symbols = {}
symbols = [] # (name, value, secno, class, naux, aux)
record = 0
for index, sec in enumerate(sections, start=1):
section_symbols[sec.name] = record
aux = struct.pack("<III", sec.bits, 0, 0).ljust(18, b"\0")
symbols.append((sec.name, 0, index, C_STAT, 1, aux))
record += 2 # main record + one aux record
symbols.append(("_rng_" + tag, 0, 1, C_EXT, 0, b""))
record += 1
string_table = bytearray(b"\0\0\0\0")
sec_name_offsets = {}
for sec in sections:
if not short_name(sec.name):
sec_name_offsets[sec.name] = len(string_table)
string_table.extend(sec.name.encode("latin1") + b"\0")
sym_name_offsets = {}
for name, _value, _secno, _class, _naux, _aux in symbols:
if not short_name(name):
sym_name_offsets[name] = len(string_table)
string_table.extend(name.encode("latin1") + b"\0")
struct.pack_into("<I", string_table, 0, len(string_table))
nsyms = sum(1 + naux for _n, _v, _s, _c, naux, _a in symbols)
if nsyms != record:
raise SystemExit("internal: symbol record count mismatch")
header_size = 20 + 40 * len(sections)
cursor = header_size
payload = []
for sec in sections:
if sec.bits and sec.name != ".bss":
payload.append(cursor)
cursor += len(sec.data)
else:
payload.append(0)
relptr = []
for sec in sections:
if sec.relocs:
relptr.append(cursor)
cursor += 10 * len(sec.relocs)
else:
relptr.append(0)
symptr = cursor
cursor += nsyms * 18 + len(string_table)
out = bytearray()
out.extend(struct.pack("<HHIIIHH", MAGIC, len(sections), 0, symptr,
nsyms, 0, 0))
for sec, ptr, rptr in zip(sections, payload, relptr):
if short_name(sec.name):
raw_name = sec.name.encode("latin1").ljust(8, b"\0")
else:
raw_name = ("/%d" % sec_name_offsets[sec.name]).encode("ascii")
out.extend(raw_name.ljust(8, b"\0"))
out.extend(struct.pack("<IIIIIIHHI", 0, 0, sec.bits, ptr, rptr, 0,
len(sec.relocs), 0, sec.flags))
for sec, ptr in zip(sections, payload):
if ptr:
out.extend(sec.data)
for sec, rptr in zip(sections, relptr):
if not rptr:
continue
for offset, name in sec.relocs:
out.extend(struct.pack("<IIH", offset * 8,
section_symbols[name], R_RELLONG))
for name, value, secno, sclass, naux, aux in symbols:
if short_name(name):
raw_name = name.encode("latin1").ljust(8, b"\0")
else:
raw_name = b"\0\0\0\0" + struct.pack("<I", sym_name_offsets[name])
out.extend(raw_name)
out.extend(struct.pack("<IhHBB", value, secno, 0, sclass, naux))
out.extend(aux)
out.extend(string_table)
if len(out) != cursor:
raise SystemExit("internal: %s size %d != planned %d"
% (path, len(out), cursor))
with open(path, "wb") as fh:
fh.write(out)
return len(out)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("outdir", metavar="OUTDIR")
parser.add_argument("--tag", default="ab",
help="the two single-letter tags")
args = parser.parse_args(argv)
if len(args.tag) != 2:
parser.error("--tag must be two characters (one per object)")
os.makedirs(args.outdir, exist_ok=True)
for tag in args.tag:
path = os.path.join(args.outdir, "rng-%s.o" % tag)
size = write_object(path, build(tag), tag)
print("dwarf-ranges-fixture: %s (%d bytes, .text %d bits)"
% (path, size, TEXT_BYTES * 8))
return 0
if __name__ == "__main__":
sys.exit(main())
+6
View File
@@ -3,3 +3,9 @@ int int_diff4(int *p) { return (int)(p + 1) - (int)p; }
long pd_char(char *a, char *b) { return a - b; }
long pd_int(int *a, int *b) { return a - b; }
int late(char *p, char *q) { return (char *)((unsigned)p + 24) == q; }
int late64(char *p, char *q) {
return (char *)((unsigned long long)(unsigned)p + 24) == q;
}
int late64s(char *p, char *q) {
return (char *)((long long)(int)p + 24) == q;
}
+35 -3
View File
@@ -13,14 +13,46 @@ grep -A2 'define.*@int_diff(' "$OUT/pdiff.ll" | grep -q 'ret i32 8'
grep -A2 'define.*@int_diff4' "$OUT/pdiff.ll" | grep -q 'ret i32 32'
grep -A6 'define.*@pd_char' "$OUT/pdiff.ll" | grep -Eq 'sdiv|ashr|udiv'
grep -A6 'define.*@pd_int' "$OUT/pdiff.ll" | grep -Eq 'sdiv|ashr|udiv'
grep -Eq 'add i32 %bit.base[0-9]*, 24' "$OUT/pdiff.ll"
# The final instcombine canonicalizes the lowered `inttoptr(add(ptrtoint, 24))`
# into `getelementptr i8, %p, 24`; llc treats a GEP index as a bit offset, so
# either shape carries the M0 24-bit addend. Scope the positive to `late`
# itself (the identical `late64` line must not satisfy it); keep the 192
# rejection file-wide.
grep -A6 'define.*@late(' "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 24|getelementptr i8, ptr %p, i32 24'
if grep -Eq 'add i32 %bit\.base[0-9]*, 192|getelementptr i8, ptr %p, i32 192' \
"$OUT/pdiff.ll"; then
echo "M0 pipeline: FAIL: late GEP was scaled twice (192)" >&2
exit 1
fi
# The 64-bit pointer-int shapes (`(unsigned long long)(unsigned)p + 24` and
# `(long long)(int)p + 24`) must take the same 24-bit low word, not 192.
for fn in late64 late64s; do
grep -A6 "define.*@$fn(" "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 24|getelementptr i8, ptr %p, i32 24'
if grep -A6 "define.*@$fn(" "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 192|getelementptr i8, ptr %p, i32 192'; then
echo "M0 pipeline: FAIL: $fn over-scaled to 192" >&2
exit 1
fi
done
"$TMS_OPT" -passes=verify -disable-output "$OUT/pdiff.ll"
"$ROOT/scripts/tms-clang" -O2 -I "$ROOT/spike" -o "$OUT/xclient.ll" "$ROOT/spike/xclient.c"
test "$(grep -c getelementptr "$OUT/xclient.ll")" -eq 0
# The M7.1 barrier is gone after lowering, and any GEP the final instcombine
# creates from a lowered inttoptr is the `i8` bit-index form. A typed GEP here
# would mean a byte offset escaped the post-opt --scale.
if grep -q '__tms_bitptr' "$OUT/xclient.ll"; then
echo "M0 pipeline: FAIL: __tms_bitptr was not lowered" >&2
exit 1
fi
if grep 'getelementptr' "$OUT/xclient.ll" | grep -qv 'getelementptr i8'; then
echo "M0 pipeline: FAIL: a typed (byte) GEP escaped the post-opt scale" >&2
exit 1
fi
grep -Eq 'add i32 %bit.base[0-9]*, 1056' "$OUT/xclient.ll"
grep -Eq 'mul i32 [^,]+, 640' "$OUT/xclient.ll"
grep -Eq 'add i32 %bit.addr[0-9]*, 320' "$OUT/xclient.ll"
grep -Eq 'add i32 %bit\.(base|addr)[0-9]*, 320' "$OUT/xclient.ll"
"$TMS_OPT" -passes=verify -disable-output "$OUT/xclient.ll"
"$ROOT/scripts/tms-clang" -O0 -o "$OUT/pdiff.o0.ll" "$ROOT/scripts/tests/m0/ptrdiff.c"
+1 -1
View File
@@ -31,7 +31,7 @@ if git -C "$VENDOR" rev-parse --git-dir >/dev/null 2>&1; then
fi
# The optimizer's switch-to-lookup-table transform creates a late byte-offset
# GEP. tms-bitaddr --normalize recognizes the `switch.table.*` base and
# GEP. tms-bitaddr --scale recognizes the `switch.table.*` base and
# shifts its index into bits; a dense char switch is the regression probe.
# The termtris init_game/runesc switches are the real instances.
TMP=$(mktemp -d "${TMPDIR:-/tmp}/tt-switch.XXXXXX")
+36 -7
View File
@@ -1,12 +1,14 @@
# M5 c-testsuite `single-exec` output subset.
# M6 c-testsuite `single-exec` output subset.
#
# Curated list seeded by Task 12. One test name per line (no .c suffix); the
# `.c`, `.c.expected` and `.tags` live under the pinned
# Curated list seeded by the M5 Task 12 list and expanded by M6 Task 8 with
# the float/double, long long, bitfield, varargs and aggregate tests the M6
# language/runtime work made runnable. One test name per line (no .c
# suffix); the `.c`, `.c.expected` and `.tags` live under the pinned
# vendor/conformance/c-testsuite/tests/single-exec tree. Every listed test is
# portable C89/C99 using only integer/pointer/struct/array/string language
# features and, where it prints, the shim's printf conversions. Each test
# must return 0 and its captured output must equal `<name>.c.expected` byte
# for byte. Unsupported tests live in c-testsuite.skip, never here.
# portable C89/C99 using only language features and shim conversions the M6
# path supports. Each test must return 0 and its captured output must equal
# `<name>.c.expected` byte for byte, including the `%f` and `%lld` output.
# Unsupported tests live in c-testsuite.skip, never here.
#
# Core language: integer arithmetic, control flow, pointers, arrays, structs,
# strings (expected output is empty; the status is 0).
@@ -41,3 +43,30 @@
00213
00214
00215
#
# M6 floats/doubles: float/double arithmetic, globals, struct members, %f and
# double sizeof. 00175 and 00195 compare the exact printed output.
00113
00119
00123
00175
00178
00195
#
# M6 64-bit integers: long long arithmetic/constants/conversions, int64_t,
# pointer-width interactions and the exact %lld/%llx-style output.
00081
00082
00104
00128
00135
00200
00203
00212
00217
00219
#
# M6 varargs, bitfields, aggregates, and sprintf output.
00140
00218
00186
+5
View File
@@ -29,6 +29,11 @@
# M5_C_TESTSUITE_WORK M5_CONFORMANCE_DIR M5_CONFORMANCE_MODE
set -eu
# The curated gates are the full-loader acceptance tier; the bare tier is
# exercised by scripts/tests/m7/full-suite.sh.
M5_CONFORMANCE_BARE=${M5_CONFORMANCE_BARE:-0}
export M5_CONFORMANCE_BARE
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$HERE/conformance}
+16 -33
View File
@@ -1,10 +1,12 @@
# M5 c-testsuite `single-exec` skips.
# M6 c-testsuite `single-exec` skips.
#
# Every single-exec test that is not in c-testsuite.list is accounted for here
# as `<name><TAB><feature>: <reason>`, so no pinned test is silently dropped.
# A skipped test is never a pass. Classifier-rejected tests carry the
# classifier's exact `feature: reason` text; classifier-supported tests that
# are outside this subset are marked `unselected:` or an explicit shim gap
# A skipped test is never a pass. M6 Task 8 removed the float/long-long/
# bitfield skip rows for the tests that moved into the list; the remainder are
# either classifier-rejected (exact `feature: reason` text) or
# classifier-supported tests outside the curated output subset
# (`unselected:`) or an explicit shim gap
# (`libc:`/`stderr:`/`shim-format:`/`runtime:`).
00002 unselected: classifier-supported; outside the curated output subset
00003 unselected: classifier-supported; outside the curated output subset
@@ -68,8 +70,6 @@
00078 unselected: classifier-supported; outside the curated output subset
00079 unselected: classifier-supported; outside the curated output subset
00080 unselected: classifier-supported; outside the curated output subset
00081 long-long: 64-bit integers (long long/int64) are deferred to M6
00082 long-long: 64-bit integers (long long/int64) are deferred to M6
00083 unselected: classifier-supported; outside the curated output subset
00084 unselected: classifier-supported; outside the curated output subset
00085 unselected: classifier-supported; outside the curated output subset
@@ -85,13 +85,12 @@
00095 unselected: classifier-supported; outside the curated output subset
00096 unselected: classifier-supported; outside the curated output subset
00097 unselected: classifier-supported; outside the curated output subset
00098 wide-char: wide characters are deferred to M6
00098 wide-char: wide characters are unsupported
00099 unselected: classifier-supported; outside the curated output subset
00100 unselected: classifier-supported; outside the curated output subset
00101 unselected: classifier-supported; outside the curated output subset
00102 unselected: classifier-supported; outside the curated output subset
00103 unselected: classifier-supported; outside the curated output subset
00104 long-long: 64-bit integers (long long/int64) are deferred to M6
00105 unselected: classifier-supported; outside the curated output subset
00106 unselected: classifier-supported; outside the curated output subset
00107 unselected: classifier-supported; outside the curated output subset
@@ -100,36 +99,30 @@
00110 unselected: classifier-supported; outside the curated output subset
00111 unselected: classifier-supported; outside the curated output subset
00112 unselected: classifier-supported; outside the curated output subset
00113 float: floats and doubles are deferred to M6
00114 unselected: classifier-supported; outside the curated output subset
00115 unselected: classifier-supported; outside the curated output subset
00116 unselected: classifier-supported; outside the curated output subset
00117 unselected: classifier-supported; outside the curated output subset
00118 unselected: classifier-supported; outside the curated output subset
00119 float: floats and doubles are deferred to M6
00120 unselected: classifier-supported; outside the curated output subset
00121 unselected: classifier-supported; outside the curated output subset
00122 unselected: classifier-supported; outside the curated output subset
00123 float: floats and doubles are deferred to M6
00124 unselected: classifier-supported; outside the curated output subset
00126 unselected: classifier-supported; outside the curated output subset
00127 unselected: classifier-supported; outside the curated output subset
00128 long-long: 64-bit integers (long long/int64) are deferred to M6
00129 unselected: classifier-supported; outside the curated output subset
00130 unselected: classifier-supported; outside the curated output subset
00131 unselected: classifier-supported; outside the curated output subset
00133 unselected: classifier-supported; outside the curated output subset
00134 unselected: classifier-supported; outside the curated output subset
00135 long-long: 64-bit integers (long long/int64) are deferred to M6
00136 unselected: classifier-supported; outside the curated output subset
00137 unselected: classifier-supported; outside the curated output subset
00138 unselected: classifier-supported; outside the curated output subset
00139 unselected: classifier-supported; outside the curated output subset
00140 float: floats and doubles are deferred to M6
00141 unselected: classifier-supported; outside the curated output subset
00142 unselected: classifier-supported; outside the curated output subset
00143 unselected: classifier-supported; outside the curated output subset
00144 bitfield: bitfields are deferred to M6
00144 unselected: classifier-supported; outside the curated output subset
00145 unselected: classifier-supported; outside the curated output subset
00146 unselected: classifier-supported; outside the curated output subset
00147 unselected: classifier-supported; outside the curated output subset
@@ -153,19 +146,16 @@
00169 unselected: classifier-supported; outside the curated output subset
00171 unselected: classifier-supported; outside the curated output subset
00172 unselected: classifier-supported; outside the curated output subset
00174 float: floats and doubles are deferred to M6
00175 float: floats and doubles are deferred to M6
00174 libc: sin() is not implemented by the conformance shim
00176 unselected: classifier-supported; outside the curated output subset
00177 unselected: classifier-supported; outside the curated output subset
00178 float: floats and doubles are deferred to M6
00179 wide-char: wide characters are deferred to M6
00179 wide-char: wide characters are unsupported
00180 unselected: classifier-supported; outside the curated output subset
00181 unselected: classifier-supported; outside the curated output subset
00182 long-long-format: %ll/%L need 64-bit formatting
00182 file-io: stdio/POSIX file I/O is unavailable under the bare loader
00183 unselected: classifier-supported; outside the curated output subset
00184 unselected: classifier-supported; outside the curated output subset
00185 unselected: classifier-supported; outside the curated output subset
00186 libc: sprintf is not implemented by the conformance shim
00187 file-io: stdio/POSIX file I/O is unavailable under the bare loader
00188 unselected: classifier-supported; outside the curated output subset
00189 file-io: stdio/POSIX file I/O is unavailable under the bare loader
@@ -174,26 +164,19 @@
00192 unselected: classifier-supported; outside the curated output subset
00193 unselected: classifier-supported; outside the curated output subset
00194 unselected: classifier-supported; outside the curated output subset
00195 float: floats and doubles are deferred to M6
00196 unselected: classifier-supported; outside the curated output subset
00197 unselected: classifier-supported; outside the curated output subset
00198 unselected: classifier-supported; outside the curated output subset
00199 unselected: classifier-supported; outside the curated output subset
00200 long-long: 64-bit integers (long long/int64) are deferred to M6
00201 unselected: classifier-supported; outside the curated output subset
00202 unselected: classifier-supported; outside the curated output subset
00203 long-long: 64-bit integers (long long/int64) are deferred to M6
00204 float: floats and doubles are deferred to M6
00205 runtime: M2 .data supports only integer, pointer and byte-array initializers (host compile fails)
00204 format-unsupported: printf %n, positional $, %e/%g/%a/%F, %j, long-double %L/%F and wide %ls/%lc are not implemented by the shim
00205 unselected: curated list not re-evaluated after the M7.1 .data extension
00206 unselected: classifier-supported; outside the curated output subset
00207 unselected: classifier-supported; outside the curated output subset
00208 wide-char: wide characters are deferred to M6
00208 wide-char: wide characters are unsupported
00209 unselected: classifier-supported; outside the curated output subset
00210 unselected: classifier-supported; outside the curated output subset
00211 unselected: classifier-supported; outside the curated output subset
00212 long-long: 64-bit integers (long long/int64) are deferred to M6
00216 runtime: M2 .data supports only integer, pointer and byte-array initializers (host compile fails)
00217 long-long: 64-bit integers (long long/int64) are deferred to M6
00218 bitfield: bitfields are deferred to M6
00219 long-long: 64-bit integers (long long/int64) are deferred to M6
00220 wide-char: wide characters are deferred to M6
00216 unselected: curated list not re-evaluated after the M7.1 .data extension
00220 wide-char: wide characters are unsupported
+50 -6
View File
@@ -1,12 +1,22 @@
# M5 c-torture `execute` subset.
# M6 c-torture `execute` subset.
#
# One test name per line (no .c suffix), selected from
# vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute.
# The gate runs each name at -O0 and -O2 through the Task 9 conformance
# harness and requires main to return 0 in MAME. Keep this list to the
# integer/control/array/pointer subset: no floats, 64-bit integers, bitfields,
# general varargs, aggregates by value, setjmp, signals, wide
# characters, or file I/O. Seeded by Task 11.
# The M6 gate runs each name at -O0 and a bounded subset at -O2 through the
# conformance harness and requires main to return 0 in MAME.
#
# M6 Task 8 removed the M5 "integer/control only" restriction: the list now
# includes the float/double, long long, bitfield, general-varargs and
# aggregate-by-value tests the M6 compiler/runtime made runnable. It is 79
# tests (59 M5 legacy + 20 M6 additions); the 40-60 curated target is a soft
# bound for this one-time expansion, and the 19 legacy tests that a first cut
# dropped are restored so no previously gated shape loses coverage. The full
# corpus classifier report (`c-torture.sh --scan`) is the selection report, not
# this gate.
#
# Test selection is runtime-verified, not classifier-only: several
# classifier-supported tests still hit the M2 `.data` initializer limit
# (aggregate/bitfield globals) or the 300/600 frame budget and are not listed.
#
# Integer arithmetic, conversions, and bit operations
20000313-1
@@ -72,3 +82,37 @@
951115-1
960419-2
991227-1
#
# M6 floats/doubles: arithmetic, comparisons, struct/union members, globals,
# floats passed by value, and a double function pointer.
20000603-1
20000605-1
20020213-1
920501-8
930614-1
930614-2
#
# M6 64-bit integers: constants, add/sub/mul, shifts, divide/remainder and
# conversions through int.
20000402-1
20000523-1
20001108-1
20110418-1
20141125-1
#
# M6 general varargs: va_list passes through a second function, mixed
# int/double/long walks, many stack arguments and a va_list copy.
20000519-1
stdarg-4
va-arg-1
multi-ix
#
# M6 bitfields: packed struct fields, bitfield arithmetic and bitfield stores.
20000113-1
20001101
20040629-1
#
# M6 aggregates: struct/union passed and returned by value, including a
# float/char-array struct checked with memcmp.
20081103-1
921112-1
+5
View File
@@ -31,6 +31,11 @@
# M5_CONFORMANCE_CLANG_OPT M5_CONFORMANCE_LLC_OPT (per pass)
set -eu
# The curated gates are the full-loader acceptance tier; the bare tier is
# exercised by scripts/tests/m7/full-suite.sh.
M5_CONFORMANCE_BARE=${M5_CONFORMANCE_BARE:-0}
export M5_CONFORMANCE_BARE
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$HERE/conformance}
+174
View File
@@ -0,0 +1,174 @@
-- bare-check.lua -- run a freestanding conformance COFF on the VT1200 CPU
-- without booting the firmware or using the COFF loader.
--
-- The test harness maps the image itself: each section is copied to its COFF
-- paddr, .bss is zeroed, the result block is cleared, and PC/SP are set. This
-- is the fast tier for codegen/semantics tests; the full loader/X11/runtime
-- tiers still use loader.lua.
--
-- Required env: BARE_COFF, BARE_ENTRY, BARE_SP (bit addresses), CONF_RESULT.
-- Optional: BARE_END (frame budget, default 1000).
local machine = manager.machine
local cpu = machine.devices[':maincpu']
local prog = cpu.spaces['program']
local COFF = os.getenv("BARE_COFF") or ""
local ENTRY = tonumber(os.getenv("BARE_ENTRY") or "0", 16)
local SP = tonumber(os.getenv("BARE_SP") or "0", 16)
local ENDF = tonumber(os.getenv("BARE_END") or "1000")
local RESULT = os.getenv("CONF_RESULT") or "conformance-result.txt"
local STATUS = 0x01B00000
local LEN = 0x01B00020
local MAGIC = 0x01B00040
local ERRLEN = 0x01B00060
local OUT = 0x01B10000
local ERR = 0x01B30000
local CAP = 16384
local MAGIC_VAL = 0x434F4E46
local ST_IE = 0x200000
local function slurp(path)
local f = io.open(path, "rb")
if not f then error("cannot open " .. path) end
local d = f:read("*a")
f:close()
return d
end
local function u16(d, o) return string.unpack("<I2", d, o + 1) end
local function u32(d, o) return string.unpack("<I4", d, o + 1) end
local function parse_coff(d)
local c = {}
c.magic = u16(d, 0)
c.nscns = u16(d, 2)
c.opthdr = u16(d, 16)
c.entry = c.opthdr ~= 0 and u32(d, 20 + 16) or 0
c.sections = {}
local base = 20 + c.opthdr
for i = 0, c.nscns - 1 do
local o = base + i * 40
local name = d:sub(o + 1, o + 8):gsub("%z", "")
c.sections[#c.sections + 1] = {
name = name,
paddr = u32(d, o + 8),
size = u32(d, o + 16),
scnptr = u32(d, o + 20),
flags = u32(d, o + 36),
}
end
return c
end
local function poke_bytes(bitaddr, data)
local n = math.floor((#data + 1) / 2)
for i = 0, n - 1 do
local lo = data:byte(i * 2 + 1) or 0
local hi = data:byte(i * 2 + 2) or 0
prog:write_u16(bitaddr + i * 16, lo + hi * 256)
end
return n
end
local function zero_bytes(bitaddr, nbytes)
for i = 0, math.floor((nbytes + 1) / 2) - 1 do
prog:write_u16(bitaddr + i * 16, 0)
end
end
local function rd32(a)
local ok, v = pcall(function() return prog:read_u32(a) end)
if ok then return v end
return 0xDEADBEEF
end
local function rd8(a)
local ok, v = pcall(function() return prog:read_u8(a) end)
if ok then return v end
return 0
end
local function dump(tag)
local status = rd32(STATUS)
local raw_len = rd32(LEN)
local magic = rd32(MAGIC)
local raw_errlen = rd32(ERRLEN)
local bytes, n = {}, 0
local nread = (raw_len >= 0 and raw_len <= CAP) and raw_len or 0
for i = 0, nread - 1 do
bytes[#bytes + 1] = string.format("%02X", rd8(OUT + i * 8))
n = n + 1
end
local errbytes = {}
local erread = (raw_errlen >= 0 and raw_errlen <= CAP) and raw_errlen or 0
for i = 0, erread - 1 do
errbytes[#errbytes + 1] = string.format("%02X", rd8(ERR + i * 8))
end
print(string.format(
"CONF: %s status=%08X len=%d magic=%08X loader=%08X out=%s errlen=%d err=%s",
tag, status, raw_len, magic, 0, table.concat(bytes),
raw_errlen, table.concat(errbytes)))
local f = io.open(RESULT, "w")
if f then
f:write(string.format("status=%08X\n", status))
f:write(string.format("len=%d\n", raw_len))
f:write(string.format("magic=%08X\n", magic))
f:write("loader=00000000\n")
f:write("out=" .. table.concat(bytes) .. "\n")
f:write(string.format("errlen=%d\n", raw_errlen))
f:write("err=" .. table.concat(errbytes) .. "\n")
f:close()
end
if magic == MAGIC_VAL then
print("BARE MAME: PASS")
else
print("BARE MAME: FAIL")
end
end
local frames = 0
local started = false
local done = false
local function setup()
local d = slurp(COFF)
local c = parse_coff(d)
if c.magic ~= 0x0090 then
print(string.format("BARE: bad COFF magic %04X", c.magic))
machine:exit()
return
end
for _, s in ipairs(c.sections) do
if s.name == ".bss" then
zero_bytes(s.paddr, math.floor((s.size + 7) / 8))
elseif s.size > 0 then
local nb = math.floor((s.size + 7) / 8)
poke_bytes(s.paddr, d:sub(s.scnptr + 1, s.scnptr + nb))
end
end
-- Clear the result block; the entry also does it, but this is idempotent.
prog:write_u32(STATUS, 0); prog:write_u32(LEN, 0)
prog:write_u32(MAGIC, 0); prog:write_u32(ERRLEN, 0)
cpu.state['SP'].value = SP
local st = cpu.state['ST'].value
cpu.state['ST'].value = st & ~ST_IE
cpu.state['PC'].value = (ENTRY ~= 0) and ENTRY or c.entry
print(string.format("BARE: entry=%08X sp=%08X sections=%d", cpu.state['PC'].value, SP, c.nscns))
end
emu.register_frame_done(function()
frames = frames + 1
if not started then
started = true
setup()
return
end
if done then return end
if rd32(MAGIC) == MAGIC_VAL or frames >= ENDF then
done = true
dump(frames >= ENDF and "timeout" or "result")
machine:exit()
end
end, "m5-bare-check")
+9 -3
View File
@@ -40,6 +40,8 @@ pass=0
skip=0
failed=0
total=0
ONE_LOG=$(mktemp "${TMPDIR:-/tmp}/c-testsuite.XXXXXX")
trap 'rm -f "$ONE_LOG"' EXIT HUP INT TERM
while IFS= read -r name; do
case $name in
@@ -53,15 +55,19 @@ while IFS= read -r name; do
[ -f "$src" ] || fail "missing c-testsuite source: $src"
[ -f "$expected" ] || fail "missing c-testsuite expected output: $expected"
if "$RUN" --id "c-testsuite/$base" --classify --mode native \
--expect-status 0 --expect-output-file "$expected" "$src"; then
--expect-status 0 --expect-output-file "$expected" "$src" \
> "$ONE_LOG" 2>&1; then
cat "$ONE_LOG"
pass=$((pass + 1))
else
rc=$?
if [ "$rc" -eq 2 ]; then
cat "$ONE_LOG"
# Exit 2 is a skip only with a real SKIP row (see c-torture.sh).
if [ "$rc" -eq 2 ] && grep -q '^CONFORMANCE: SKIP ' "$ONE_LOG"; then
skip=$((skip + 1))
else
failed=$((failed + 1))
echo "c-testsuite: FAIL $base" >&2
echo "c-testsuite: FAIL $base (runner exit $rc, no SKIP row)" >&2
fi
fi
done < "$LIST"
+10 -3
View File
@@ -38,6 +38,8 @@ pass=0
skip=0
failed=0
total=0
ONE_LOG=$(mktemp "${TMPDIR:-/tmp}/c-torture.XXXXXX")
trap 'rm -f "$ONE_LOG"' EXIT HUP INT TERM
while IFS= read -r name; do
case $name in
@@ -47,15 +49,20 @@ while IFS= read -r name; do
src=$SUITE_DIR/$name.c
[ -f "$src" ] || fail "missing c-torture source: $src"
if "$RUN" --id "c-torture/$name" --classify \
--expect-status 0 --ignore-output "$src"; then
--expect-status 0 --ignore-output "$src" > "$ONE_LOG" 2>&1; then
cat "$ONE_LOG"
pass=$((pass + 1))
else
rc=$?
if [ "$rc" -eq 2 ]; then
cat "$ONE_LOG"
# Exit 2 is a skip only when the runner printed a real SKIP row.
# run.sh also uses 2 for a native-COFF loader rejection; treating a
# bare 2 as a skip would turn a genuine failure into a pass-like row.
if [ "$rc" -eq 2 ] && grep -q '^CONFORMANCE: SKIP ' "$ONE_LOG"; then
skip=$((skip + 1))
else
failed=$((failed + 1))
echo "c-torture: FAIL $name" >&2
echo "c-torture: FAIL $name (runner exit $rc, no SKIP row)" >&2
fi
fi
done < "$LIST"
+34 -16
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# Classify a C source for features the M5 conformance path cannot run.
# Classify a C source for features the M6 conformance path cannot run.
#
# classify.sh FILE
#
@@ -9,9 +9,14 @@
# real skip apart from a classifier failure. The reasons come from skip.tsv
# so the manifest, suite runners and reports agree.
#
# This is deliberately conservative: a false positive skips a test (and says
# why), while a false negative could turn an unsupported test into a fake
# pass. Comments and string literals are scanned too.
# M6 implements floats/doubles, 64-bit integers, bitfields, general varargs
# and aggregates, so those are no longer skipped. The remaining skips are
# genuine M6 non-goals: 128-bit integers, non-local jumps, signals, wide
# characters, stdio/POSIX file I/O and the printf conversions the shim does
# not implement. This is deliberately conservative: a false positive skips a
# test (and says why), while a false negative could turn an unsupported test
# into a fake pass. Comments are scanned; printf conversions are checked
# inside string literals only.
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
@@ -38,9 +43,21 @@ match() {
return 0
}
match_cs() {
# A printf conversion is only meaningful inside a string literal. Scan the
# double-quoted literals instead of the whole source so a C modulo expression
# (`x % e`, `0 % a++`, `(c || b) % g`) is not mistaken for a conversion.
# Escaped quotes are split so a conversion after \" is still seen.
match_formats() {
[ -z "$feature" ] || return 0
if grep -Eq -- "$2" "$SRC"; then
set +e
literals=$(sed 's/\\"/""/g' "$SRC" | grep -o '"[^"]*"')
st=$?
set -e
[ "$st" -le 1 ] || {
echo "classify: string-literal scan failed (status $st) on $SRC" >&2
exit 2
}
if printf '%s\n' "$literals" | grep -Eq -- "$2"; then
feature=$1
else
st=$?
@@ -53,20 +70,21 @@ match_cs() {
}
# Order is only cosmetic; the first match names the primary blocker. Most
# matches are case-insensitive so macro spellings (INT64_MAX, UINT64_C,
# intmax_t) are not missed. The %ll/%L length check stays case-sensitive
# because %ld is supported while %Ld is a long-double format.
match float '(^|[^A-Za-z0-9_])(float|double)([^A-Za-z0-9_]|$)'
match long-long 'long[[:space:]]+long|(^|[^A-Za-z0-9_])(u?int64(_t)?|intmax_t|uintmax_t|__int64(_t)?|int64_max|int64_c|uint64_max|uint64_c)([^A-Za-z0-9_]|$)'
# matches are case-insensitive so macro spellings are not missed. The
# format-unsupported scan is case-sensitive because %L/%e/%g/%a/%F are
# distinct conversions and %ld/%lld/%lf are supported; the regex spells out
# the uppercase forms it does match.
match int128 '__int128|__uint128|__int128_t|__uint128_t'
match bitfield '[A-Za-z_][A-Za-z0-9_]*[[:space:]]*:[[:space:]]*[0-9]+[[:space:]]*;'
match varargs '(^|[^A-Za-z0-9_])(va_list|va_start|va_arg|va_end|va_copy)([^A-Za-z0-9_]|$)'
match setjmp '(^|[^A-Za-z0-9_])(setjmp|longjmp|sigsetjmp|siglongjmp)([^A-Za-z0-9_]|$)'
match signal '(^|[^A-Za-z0-9_])(signal|sigaction|sigemptyset|sigaddset|sigprocmask)([^A-Za-z0-9_]|$)'
match wide-char '(^|[^A-Za-z0-9_])(wchar|wchar_t|wint_t|wprintf|wscanf)([^A-Za-z0-9_]|$)|L"|L'"'"''
match float-format '%[-+ #0-9.*]*[fFeEgGaA]'
match_cs long-long-format '%[-+ #0-9.*]*ll|%[-+ #0-9.*]*LL|%[-+ #0-9.*]*L'
match format-unsupported '%[-+ #0-9.*]*n|%[-+ #0-9.]*\*|%[-+ #0-9]*\.[0-9*]*[diouxXcspn]'
# %n (also %hhn/%lln), positional arguments, the floating conversions without
# shim support (%e/%g/%a/%F, including %lF), %j (intmax_t is 64-bit here while
# the shim reads 32), long double and wide strings are genuinely unsupported.
# %z/%t are supported: size_t is unsigned int and ptrdiff_t is int on this
# target, so the shim's 32-bit read is correct. Field width, precision, * and
# %lld/%llu/%f are implemented and must not be skipped.
match_formats format-unsupported '%[-+ #0-9.*]*\$|%[-+ #0-9.*]*l?[eEgGaAF]|%[-+ #0-9.*]*j[diouxX]|%[-+ #0-9.*]*(hh|h|ll|l)?n|%[-+ #0-9.*]*L[diouxXeEfgGaAF]|%[-+ #0-9.*]*l[sc]'
match file-io '(^|[^A-Za-z0-9_])(FILE|fopen|fclose|fread|fwrite|fprintf|freopen|fflush|fseek|ftell|fgetc|fputc|fgets|fputs|remove|rename|tmpfile|tmpnam)([^A-Za-z0-9_]|$)|(^|[^A-Za-z0-9_])(open|creat)[[:space:]]*\('
[ -n "$feature" ] || exit 0
@@ -6,11 +6,14 @@
-- 01B00000 status
-- 01B00020 out_len
-- 01B00040 magic 0x434F4E46
-- 01B10000 output bytes (bit addresses, 8 bits apart)
-- 01B00060 err_len
-- 01B10000 output bytes (bit addresses, 8 bits apart; 16 KiB ends at
-- 01B2FFFF, so it cannot reach stderr)
-- 01B30000 stderr bytes (bit addresses, 8 bits apart; 16 KiB)
--
-- The block is above the linker-managed .bss region (01A00000..01A80000), so
-- test globals cannot overwrite it. The runner rejects len >= the 16 KiB cap
-- because the shim truncates there.
-- (or errlen >= the cap) because the shim truncates there.
--
-- The result is written to CONF_RESULT in a stable, shell-readable form:
-- status=<8 hex>
@@ -18,6 +21,8 @@
-- magic=<8 hex>
-- loader=<8 hex> (loader result block status at 01882D00)
-- out=<uppercase hex bytes>
-- errlen=<decimal>
-- err=<uppercase hex bytes>
--
-- The runner compares this file against the manifest/expected result. A
-- missing magic is a failure, never a pass.
@@ -35,7 +40,9 @@ local RESULT = os.getenv("CONF_RESULT") or "conformance-result.txt"
local STATUS = 0x01B00000
local LEN = 0x01B00020
local MAGIC = 0x01B00040
local ERRLEN = 0x01B00060
local OUT = 0x01B10000
local ERR = 0x01B30000
local CAP = 16384
local MAGIC_VAL = 0x434F4E46
local LOADER_STATUS = 0x01882D00
@@ -55,38 +62,46 @@ local function rd8(a)
return 0
end
local function dump(tag)
local status = rd32(STATUS)
local raw_len = rd32(LEN)
local magic = rd32(MAGIC)
local loader = rd32(LOADER_STATUS)
-- Read raw_len bytes at bit address `base` (8 bits apart). Keep the raw
-- length for the runner (it rejects len >= CAP), but never loop over an
-- implausible value. Returns the full hex dump and its 128-byte preview.
local function dump_bytes(base, raw_len)
local bytes = {}
local shown = {}
local n = 0
local nread = raw_len
-- Keep the raw length for the runner (it rejects len >= CAP), but never
-- loop over an implausible value.
if nread < 0 or nread > CAP then
nread = 0
end
for i = 0, nread - 1 do
local b = rd8(OUT + i * 8)
local b = rd8(base + i * 8)
bytes[#bytes + 1] = string.format("%02X", b)
if i < 128 then
shown[#shown + 1] = string.format("%02X", b)
end
n = n + 1
end
local outhex = table.concat(bytes)
local shownhex = table.concat(shown)
if n > 128 then
shownhex = shownhex .. "..."
end
return table.concat(bytes), shownhex
end
local function dump(tag)
local status = rd32(STATUS)
local raw_len = rd32(LEN)
local raw_errlen = rd32(ERRLEN)
local magic = rd32(MAGIC)
local loader = rd32(LOADER_STATUS)
local outhex, shownhex = dump_bytes(OUT, raw_len)
local errhex, errshownhex = dump_bytes(ERR, raw_errlen)
print(string.format(
"CONF: %s status=%08X len=%d magic=%08X loader=%08X out=%s",
tag, status, raw_len, magic, loader, shownhex))
"CONF: %s status=%08X len=%d magic=%08X loader=%08X out=%s errlen=%d err=%s",
tag, status, raw_len, magic, loader, shownhex,
raw_errlen, errshownhex))
local f, err = io.open(RESULT, "w")
if not f then
@@ -100,6 +115,8 @@ local function dump(tag)
f:write(string.format("magic=%08X\n", magic))
f:write(string.format("loader=%08X\n", loader))
f:write("out=" .. outhex .. "\n")
f:write(string.format("errlen=%d\n", raw_errlen))
f:write("err=" .. errhex .. "\n")
f:close()
if magic == MAGIC_VAL and loader == 0 then
+5 -1
View File
@@ -6,7 +6,9 @@
; 01B00000 status main's return value
; 01B00020 out_len maintained by shim.c
; 01B00040 magic 0x434F4E46 after main returns
; 01B10000 output shim.c's 16 KiB output buffer
; 01B00060 err_len maintained by shim.c
; 01B10000 output shim.c's 16 KiB output buffer (ends at 01B2FFFF)
; 01B30000 error shim.c's 16 KiB stderr buffer
;
; The result block is above the linker-managed RAM region
; (01A00000..01A80000), so a test's .bss cannot overwrite it. That region is
@@ -30,6 +32,8 @@ _start:
move a0, *a1, 1
movi 01B00040h, a1
move a0, *a1, 1
movi 01B00060h, a1
move a0, *a1, 1
movi _cstack, a14
move a14, a13
+57
View File
@@ -0,0 +1,57 @@
/*
* heap.c -- optional bounded allocator for the conformance shim.
*
* This object is linked only for tests whose source references
* malloc/calloc/free, so adding the allocator does not shift the hot shim
* code that the shipped 300/600-frame gates time. The arena is the 64 KiB gap
* between the linker RAM region (01A00000..01A80000) and the result block
* (01B00000); it lies outside every loaded section. free() is a no-op because
* each conformance test is a single short-lived process.
*/
#include <stddef.h>
#define CONF_HEAP_START 0x01A80000UL
#define CONF_HEAP_END 0x01B00000UL
static unsigned int heap_next;
/* Sizes are bytes; the target's pointers are bit addresses, so advance the
* cursor by 8 bits per byte. Align to a 16-bit word. */
void *malloc(size_t n)
{
unsigned int p;
n = (n + 1) & ~(size_t)1;
if (n == 0)
n = 2;
if (heap_next == 0)
heap_next = CONF_HEAP_START;
if (n > (CONF_HEAP_END - heap_next) / 8)
return 0;
p = heap_next;
heap_next += n * 8;
return (void *)p;
}
void *calloc(size_t nmemb, size_t size)
{
size_t total;
char *p;
size_t i;
if (nmemb != 0 && size > (size_t)~0 / nmemb)
return 0;
total = nmemb * size;
p = (char *)malloc(total);
if (!p)
return 0;
for (i = 0; i < total; i++)
p[i] = 0;
return p;
}
void free(void *ptr)
{
(void)ptr;
}
@@ -0,0 +1,14 @@
#ifndef CONFORMANCE_ASSERT_H
#define CONFORMANCE_ASSERT_H
/* The freestanding conformance runtime has no libc assert; abort() publishes
* the terminal status, so a failed assertion is an honest nonzero result. */
void abort(void);
#ifdef NDEBUG
#define assert(expr) ((void)0)
#else
#define assert(expr) ((expr) ? (void)0 : abort())
#endif
#endif
@@ -0,0 +1,40 @@
#ifndef CONFORMANCE_MATH_H
#define CONFORMANCE_MATH_H
/* Minimal <math.h> for the freestanding corpus. There is no libm in the bare
* loader, so transcendental functions are only declared (a test that calls
* sin/pow/floor and expects a value is curated as a libm skip); the useful
* classification macros and fabs* are compiler builtins and do not link. */
#define HUGE_VAL (__builtin_huge_val())
#define HUGE_VALF (__builtin_huge_valf())
#define INFINITY (__builtin_inff())
#define NAN (__builtin_nanf(""))
#define M_PI 3.14159265358979323846
#define isfinite(x) __builtin_isfinite(x)
#define isinf(x) __builtin_isinf(x)
#define isnan(x) __builtin_isnan(x)
#define signbit(x) __builtin_signbit(x)
#define fabs(x) __builtin_fabs(x)
#define fabsf(x) __builtin_fabsf(x)
double acos(double);
double asin(double);
double atan(double);
double atan2(double, double);
double ceil(double);
double cos(double);
double cosh(double);
double exp(double);
double floor(double);
double fmod(double, double);
double log(double);
double log10(double);
double pow(double, double);
double sin(double);
double sinh(double);
double sqrt(double);
double tan(double);
double tanh(double);
#endif
@@ -0,0 +1,17 @@
#ifndef CONFORMANCE_STDARG_H
#define CONFORMANCE_STDARG_H
/* M6 general varargs: the target's va_list is the compiler's built-in
* downward stack walk (see scripts/m6/varargs-main.c). Keep these macros
* thin wrappers over the clang builtins so the va_arg type/ABI rules come
* from the target lowering, not from a header layout guess. */
typedef __builtin_va_list va_list;
#define va_start(ap, last) __builtin_va_start(ap, last)
#define va_arg(ap, type) __builtin_va_arg(ap, type)
#define va_end(ap) __builtin_va_end(ap)
#define va_copy(dst, src) __builtin_va_copy(dst, src)
#define __va_copy(dst, src) __builtin_va_copy(dst, src)
#endif
@@ -0,0 +1,12 @@
#ifndef CONFORMANCE_STDBOOL_H
#define CONFORMANCE_STDBOOL_H
/* C99 <stdbool.h> for the freestanding C99-and-older corpus. clang accepts
* _Bool in its gnu89 mode as a GNU extension; the c-torture sweep uses gnu89
* for the K&R-era files but still compiles the few files that include this. */
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
@@ -7,8 +7,12 @@ typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
typedef int intptr_t;
typedef unsigned int uintptr_t;
typedef long long intmax_t;
typedef unsigned long long uintmax_t;
#define INT8_MIN (-128)
#define INT8_MAX 127
@@ -19,8 +23,14 @@ typedef unsigned int uintptr_t;
#define INT32_MIN (-2147483647 - 1)
#define INT32_MAX 2147483647
#define UINT32_MAX 4294967295U
#define INT64_MIN (-9223372036854775807LL - 1)
#define INT64_MAX 9223372036854775807LL
#define UINT64_MAX 18446744073709551615ULL
#define INTPTR_MIN INT32_MIN
#define INTPTR_MAX INT32_MAX
#define UINTPTR_MAX UINT32_MAX
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
#define UINTMAX_MAX UINT64_MAX
#endif
@@ -2,11 +2,31 @@
#define CONFORMANCE_STDIO_H
#include <stddef.h>
#include <stdarg.h>
#define EOF (-1)
/* stdout and stderr are distinct sink descriptors: stdout writes the fixed
* CONF_OUT stream (01B10000/01B00020), stderr the CONF_ERR stream
* (01B30000/01B00060). 16 KiB of bytes is 0x20000 bit address units, so
* stdout ends at 01B2FFFF and does not alias stderr. Both cap at 16 KiB; the
* runner rejects a full buffer
* as truncated. fprintf/vfprintf return the untruncated formatted length;
* fputs/fwrite return the untruncated byte/item count; fputc returns the
* character written. */
typedef struct conf_file FILE;
extern FILE *stdout;
extern FILE *stderr;
int printf(const char *fmt, ...);
int sprintf(char *buf, const char *fmt, ...);
int fprintf(FILE *stream, const char *fmt, ...);
int vfprintf(FILE *stream, const char *fmt, va_list ap);
int putchar(int c);
int puts(const char *s);
int fputc(int c, FILE *stream);
int fputs(const char *s, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
#endif
@@ -13,4 +13,10 @@ void abort(void);
int atoi(const char *s);
int abs(int v);
/* Bounded allocator in the 64 KiB gap between the linker RAM region and the
* result block (see shim.c); free is a no-op. */
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void free(void *ptr);
#endif
+2
View File
@@ -3,6 +3,8 @@
-m M4.MAP
-e _start
M4.obj
-l m6flib.lib
-l m6rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 58000h
+2 -1
View File
@@ -2,8 +2,9 @@
#
# test_id<TAB>suite<TAB>expected<TAB>features<TAB>skip_reason
#
# expected: status=<decimal> or status=<decimal>;stdout=<escaped text>
# expected: status=<decimal>[;stdout=<escaped text>][;stderr=<escaped text>]
# escapes: \n \t \r \\ (interpreted with printf %b)
# stderr defaults to empty when the field is absent
# features: space-separated classifier tags (int-control, print, ...)
# skip_reason: empty for a runnable row; a non-empty reason is reported as a
# SKIP and is never counted as a pass.
1 # M5 conformance manifest
2 #
3 # test_id<TAB>suite<TAB>expected<TAB>features<TAB>skip_reason
4 #
5 # expected: status=<decimal> or status=<decimal>;stdout=<escaped text> # expected: status=<decimal>[;stdout=<escaped text>][;stderr=<escaped text>]
6 # escapes: \n \t \r \\ (interpreted with printf %b)
7 # stderr defaults to empty when the field is absent
8 # features: space-separated classifier tags (int-control, print, ...)
9 # skip_reason: empty for a runnable row; a non-empty reason is reported as a
10 # SKIP and is never counted as a pass.
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more