mirror of
https://github.com/Ed94/pikuma_ps1.git
synced 2026-08-25 10:30:32 +00:00
Compare commits
39
Commits
1a5b618484
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
159ead625e | ||
|
|
52888015de | ||
|
|
a37ffe6f58 | ||
|
|
b61610d819 | ||
|
|
1b950ab5b5 | ||
|
|
b2858b3c73 | ||
|
|
f1801343e2 | ||
|
|
85b2205603 | ||
|
|
2d754650c9 | ||
|
|
e2ffe538b6 | ||
|
|
223d1832eb | ||
|
|
de13bc3ce9 | ||
|
|
2a087f735e | ||
|
|
449216967b | ||
|
|
c226e8a7d3 | ||
|
|
81f37e0098 | ||
|
|
bde829bf59 | ||
|
|
cf78cfa120 | ||
|
|
3440c9b59e | ||
|
|
1cbddc6708 | ||
|
|
b345ccd60e | ||
|
|
bbda5efaea | ||
|
|
290bb0e07a | ||
|
|
86fe189b4e | ||
|
|
da007d342e | ||
|
|
5a4bfb1224 | ||
|
|
d4795cf9de | ||
|
|
e79c364b40 | ||
|
|
18b1d5a04b | ||
|
|
581b00b960 | ||
|
|
3faccfc283 | ||
|
|
1a0d417649 | ||
|
|
3301826f5c | ||
|
|
d9b9241e2c | ||
|
|
a16c727db2 | ||
|
|
8a825a59c7 | ||
|
|
f8b28be02e | ||
|
|
ffc66052f8 | ||
|
|
7764612325 |
Vendored
+43
@@ -0,0 +1,43 @@
|
|||||||
|
# Package and install the local VS Code Insiders extensions under .vscode/.
|
||||||
|
# Usage:
|
||||||
|
# .\install_extensions.ps1
|
||||||
|
# .\install_extensions.ps1 -SkipPackage
|
||||||
|
|
||||||
|
param([switch] $SkipPackage)
|
||||||
|
|
||||||
|
$path_vscode = $PSScriptRoot
|
||||||
|
$code_insiders = "C:\apps\Microsoft VS Code Insiders\bin\code-insiders.cmd"
|
||||||
|
if (-not (test-path -literalpath $code_insiders)) {
|
||||||
|
$found = get-command code-insiders -erroraction silentlycontinue
|
||||||
|
if ($found) { $code_insiders = $found.source }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (test-path -literalpath $code_insiders)) { throw "code-insiders not found. Install VS Code Insiders or add it to PATH." }
|
||||||
|
|
||||||
|
$extensions = @(
|
||||||
|
(join-path $path_vscode "tape-atom-syntax"),
|
||||||
|
(join-path $path_vscode "cozy-and-windy")
|
||||||
|
)
|
||||||
|
|
||||||
|
foreach ($extension in $extensions) {
|
||||||
|
$package_json = join-path $extension "package.json"
|
||||||
|
if (-not (test-path -literalpath $package_json)) { throw "missing $package_json" }
|
||||||
|
|
||||||
|
$manifest = get-content -literalpath $package_json -raw | convertfrom-json
|
||||||
|
$vsix = join-path $extension ("{0}-{1}.vsix" -f $manifest.name, $manifest.version)
|
||||||
|
|
||||||
|
if (-not $SkipPackage) {
|
||||||
|
if (-not $manifest.scripts.package) { throw "$package_json has no scripts.package" }
|
||||||
|
write-host "packaging $($manifest.displayName) ($($manifest.name)@$($manifest.version))"
|
||||||
|
& npm --prefix $extension run package
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "npm run package failed for $extension" }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (test-path -literalpath $vsix)) { throw "missing $vsix" }
|
||||||
|
|
||||||
|
write-host "installing $vsix"
|
||||||
|
& $code_insiders --install-extension $vsix --force
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "install failed for $vsix" }
|
||||||
|
}
|
||||||
|
|
||||||
|
write-host "done. reload the Insiders window (Developer: Reload Window)."
|
||||||
BIN
Binary file not shown.
+3
-3
@@ -21,7 +21,7 @@ const TOKEN_TYPES = [
|
|||||||
"tapeGprRegister",
|
"tapeGprRegister",
|
||||||
"tapeCop2Register",
|
"tapeCop2Register",
|
||||||
"tapeDuffleType",
|
"tapeDuffleType",
|
||||||
"tapeAttribute",
|
"tapeAt__ibute",
|
||||||
"keyword",
|
"keyword",
|
||||||
"macro",
|
"macro",
|
||||||
];
|
];
|
||||||
@@ -43,13 +43,13 @@ const DSL_KEYWORDS = new Set([
|
|||||||
"Slice_", "TypeR_", "TypeV_", "align_", "internal", "local_persist", "global",
|
"Slice_", "TypeR_", "TypeV_", "align_", "internal", "local_persist", "global",
|
||||||
"RO_", "LP_", "gknown", "expect_", "cexpr_",
|
"RO_", "LP_", "gknown", "expect_", "cexpr_",
|
||||||
"asm", "asm_words", "asm_rpins", "asm_clobber",
|
"asm", "asm_words", "asm_rpins", "asm_clobber",
|
||||||
"O_", "S_", "C_", "T_", "tmpl", "glue", "r_", "v_", "tr_", "tv_",
|
"O_", "S_", "C_", "T_", "tmpl", "glue", "r_", "v_", "rt_", "vt_",
|
||||||
"rgcc", "r_use", "r_set", "r_mod", "r_imm", "r_mem",
|
"rgcc", "r_use", "r_set", "r_mod", "r_imm", "r_mem",
|
||||||
"u1_", "u2_", "u4_", "u8_", "s1_", "s2_", "s4_", "s8_",
|
"u1_", "u2_", "u4_", "u8_", "s1_", "s2_", "s4_", "s8_",
|
||||||
"u1_r", "u2_r", "u4_r", "u8_r", "u1_v", "u2_v", "u4_v", "u8_v",
|
"u1_r", "u2_r", "u4_r", "u8_r", "u1_v", "u2_v", "u4_v", "u8_v",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const DELAY_SLOT_KEYWORDS = new Set(["LdSlot_", "BdSlot_"]);
|
const DELAY_SLOT_KEYWORDS = new Set(["LdSlot_", "BdSlot_", "DmaSlot_", "GteDelay_"]);
|
||||||
|
|
||||||
const CONTROL_FLOW_PREFIXES = /^(?:branch_|jump_|call_)/;
|
const CONTROL_FLOW_PREFIXES = /^(?:branch_|jump_|call_)/;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -19,7 +19,7 @@ const BASE_ATTRIBUTES = [
|
|||||||
"Slice_", "TypeR_", "TypeV_", "align_", "internal", "local_persist", "global",
|
"Slice_", "TypeR_", "TypeV_", "align_", "internal", "local_persist", "global",
|
||||||
"RO_", "LP_", "gknown", "expect_", "cexpr_",
|
"RO_", "LP_", "gknown", "expect_", "cexpr_",
|
||||||
"asm", "asm_words", "asm_rpins", "asm_clobber",
|
"asm", "asm_words", "asm_rpins", "asm_clobber",
|
||||||
"O_", "S_", "C_", "T_", "tmpl", "glue", "r_", "v_", "tr_", "tv_",
|
"O_", "S_", "C_", "T_", "tmpl", "glue", "r_", "v_", "rt_", "vt_",
|
||||||
"rgcc", "r_use", "r_set", "r_mod", "r_imm", "r_mem",
|
"rgcc", "r_use", "r_set", "r_mod", "r_imm", "r_mem",
|
||||||
"u1_", "u2_", "u4_", "u8_", "s1_", "s2_", "s4_", "s8_",
|
"u1_", "u2_", "u4_", "u8_", "s1_", "s2_", "s4_", "s8_",
|
||||||
"u1_r", "u2_r", "u4_r", "u8_r", "u1_v", "u2_v", "u4_v", "u8_v",
|
"u1_r", "u2_r", "u4_r", "u8_r", "u1_v", "u2_v", "u4_v", "u8_v",
|
||||||
|
|||||||
@@ -56,7 +56,7 @@
|
|||||||
"name": "support.function.duffle.annotation"
|
"name": "support.function.duffle.annotation"
|
||||||
},
|
},
|
||||||
"delay-slots": {
|
"delay-slots": {
|
||||||
"match": "\\b(LdSlot_|BdSlot_)\\b",
|
"match": "\\b(LdSlot_|BdSlot_|DmaSlot_|GteDelay_)\\b",
|
||||||
"name": "keyword.operator.duffle.delayslot"
|
"name": "keyword.operator.duffle.delayslot"
|
||||||
},
|
},
|
||||||
"types": {
|
"types": {
|
||||||
|
|||||||
@@ -105,6 +105,16 @@ test("document-local declarations override an empty workspace index", () => {
|
|||||||
assert.equal(byText(result, "mac_new_component")[0].type, "tapeComponentInstruction");
|
assert.equal(byText(result, "mac_new_component")[0].type, "tapeComponentInstruction");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("delay slot markers share the tapeDelaySlot token", () => {
|
||||||
|
const source = "LdSlot_ nop, BdSlot_ nop, DmaSlot_ nop2, GteDelay_ nop";
|
||||||
|
const result = classifyDocument(source, "C:/x/code/duffle/gte.atom.c", createIndex());
|
||||||
|
|
||||||
|
assert.equal(byText(result, "LdSlot_")[0].type, "tapeDelaySlot");
|
||||||
|
assert.equal(byText(result, "BdSlot_")[0].type, "tapeDelaySlot");
|
||||||
|
assert.equal(byText(result, "DmaSlot_")[0].type, "tapeDelaySlot");
|
||||||
|
assert.equal(byText(result, "GteDelay_")[0].type, "tapeDelaySlot");
|
||||||
|
});
|
||||||
|
|
||||||
test("classifier returns ordered non-overlapping spans and partial malformed output", () => {
|
test("classifier returns ordered non-overlapping spans and partial malformed output", () => {
|
||||||
const source = "atom_reads(R_A /* broken";
|
const source = "atom_reads(R_A /* broken";
|
||||||
const result = classifyDocument(source, "C:/x/code/test.atom.c", createIndex());
|
const result = classifyDocument(source, "C:/x/code/test.atom.c", createIndex());
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#ifdef INTELLISENSE_DIRECTIVES
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
# pragma once
|
# pragma once
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
enum {
|
enum {
|
||||||
bios_init_pad_2 = 0x12,
|
bios_init_pad_2 = 0x12,
|
||||||
bios_start_pad_2 = 0x13,
|
bios_start_pad_2 = 0x13,
|
||||||
|
|||||||
@@ -44,7 +44,7 @@
|
|||||||
*
|
*
|
||||||
* Annotation rules
|
* Annotation rules
|
||||||
* ----------------
|
* ----------------
|
||||||
* 1. atom_info(...) is OPTIONAL. Atoms without atom_info are silently skipped by the metaprogram.
|
* 1. atom_info(...) is optional. Atoms without atom_info are silently skipped by the metaprogram.
|
||||||
* 2. If present, atom_info takes up to three sub-calls, all order-independent within the arg list:
|
* 2. If present, atom_info takes up to three sub-calls, all order-independent within the arg list:
|
||||||
* - atom_bind(Binds_X)
|
* - atom_bind(Binds_X)
|
||||||
* - atom_reads(...)
|
* - atom_reads(...)
|
||||||
@@ -160,6 +160,8 @@
|
|||||||
* ----------------------------------------------------------------------------*/
|
* ----------------------------------------------------------------------------*/
|
||||||
#define atom_bind(binds_struct) /* atom_bind(binds_struct) */
|
#define atom_bind(binds_struct) /* atom_bind(binds_struct) */
|
||||||
|
|
||||||
|
#define Binds_(type) (tmpl(Binds,type)) // TODO(Ed): Do we want to use this?
|
||||||
|
|
||||||
/* ============================================================================
|
/* ============================================================================
|
||||||
* atom_label / atom_offset — branch target machinery
|
* atom_label / atom_offset — branch target machinery
|
||||||
*
|
*
|
||||||
|
|||||||
+6
-4
@@ -29,7 +29,7 @@
|
|||||||
|
|
||||||
#define asm __asm__
|
#define asm __asm__
|
||||||
|
|
||||||
#define A_(data) (& data)
|
#define A_(data) (& (data))
|
||||||
#define align_(value) __attribute__((aligned (value))) // for easy alignment
|
#define align_(value) __attribute__((aligned (value))) // for easy alignment
|
||||||
#define align_(value) __attribute__((aligned (value))) // for easy alignment
|
#define align_(value) __attribute__((aligned (value))) // for easy alignment
|
||||||
#define C_(type,data) ((type)(data)) // for enforced precedence
|
#define C_(type,data) ((type)(data)) // for enforced precedence
|
||||||
@@ -45,7 +45,8 @@
|
|||||||
#define R_ restrict
|
#define R_ restrict
|
||||||
#define V_ volatile
|
#define V_ volatile
|
||||||
|
|
||||||
#pragma region Fictional //, used for intiution
|
#pragma region Fictional
|
||||||
|
//, used for intiution
|
||||||
|
|
||||||
#define EUB_ restrict // Execute Unit Bound: Data is siloed in the ALU Register File. The Load/Store Unit is bypassed. (Route to Execution Unit. Keep in registers)
|
#define EUB_ restrict // Execute Unit Bound: Data is siloed in the ALU Register File. The Load/Store Unit is bypassed. (Route to Execution Unit. Keep in registers)
|
||||||
#define ISO_ restrict // Isolated Provenance: Alternative to Exu_. Guarantees electrical memory isolation,
|
#define ISO_ restrict // Isolated Provenance: Alternative to Exu_. Guarantees electrical memory isolation,
|
||||||
@@ -83,8 +84,8 @@
|
|||||||
|
|
||||||
#define r_(ptr) C_(T_(ptr[0])*R_, ptr) // Constrain pointer to restrict
|
#define r_(ptr) C_(T_(ptr[0])*R_, ptr) // Constrain pointer to restrict
|
||||||
#define v_(ptr) C_(T_(ptr[0])V_*, ptr) //
|
#define v_(ptr) C_(T_(ptr[0])V_*, ptr) //
|
||||||
#define tr_(type, ptr) C_(type *R_, ptr)
|
#define rt_(type, ptr) C_(type *R_, ptr)
|
||||||
#define tv_(type, ptr) C_(type V_*, ptr)
|
#define vt_(type, ptr) C_(type V_*, ptr)
|
||||||
|
|
||||||
#define TypeR_(type) type *R_ type ## _R // type *restrict type_R
|
#define TypeR_(type) type *R_ type ## _R // type *restrict type_R
|
||||||
#define TypeV_(type) type V_* type ## _V // type volatile* type_V
|
#define TypeV_(type) type V_* type ## _V // type volatile* type_V
|
||||||
@@ -148,6 +149,7 @@ typedef void Proc_(VoidFn) (void);
|
|||||||
#define null C_(U4, 0)
|
#define null C_(U4, 0)
|
||||||
#define nullptr C_(void*, 0)
|
#define nullptr C_(void*, 0)
|
||||||
#define O_(type, field) C_(U4, & C_(type*,0)->field)
|
#define O_(type, field) C_(U4, & C_(type*,0)->field)
|
||||||
|
#define OA_(type, aexpr) C_(U4, & C_(type*,0) aexpr)
|
||||||
#define OT_(field) O_(typeof_ptr(& field), field))
|
#define OT_(field) O_(typeof_ptr(& field), field))
|
||||||
#define S_(data) C_(U4, sizeof(data))
|
#define S_(data) C_(U4, sizeof(data))
|
||||||
|
|
||||||
|
|||||||
@@ -79,14 +79,6 @@
|
|||||||
* Why bundle the `__asm__()` wrapper?
|
* Why bundle the `__asm__()` wrapper?
|
||||||
* - The integer R_T4 (= 12, via R_T4_Code) already indicates the register.
|
* - The integer R_T4 (= 12, via R_T4_Code) already indicates the register.
|
||||||
* - The string "$12" is derived from it via reg_str, so they cannot drift apart.
|
* - The string "$12" is derived from it via reg_str, so they cannot drift apart.
|
||||||
* - Spelling `__asm__(reg_str(R_T4_Code))` at every call site is noise.
|
|
||||||
*
|
|
||||||
* tmpl defined in dsl.h (token-paste glue).
|
|
||||||
* rgcc define here (gcc_asm.h) because the `__asm__` keyword is GCC-specific.
|
|
||||||
* Anyone porting to a different compiler's asm dialect overrides rgcc,
|
|
||||||
* and the integer→string derivation in rlit can be retargeted in one place.
|
|
||||||
*
|
|
||||||
* For clobber lists and asm-template strings, use the bare `rlit(R_T4_Code)`.
|
|
||||||
* ------------------------------------------------------------------------ */
|
* ------------------------------------------------------------------------ */
|
||||||
#define rgcc(n) __asm__(rlit(n))
|
#define rgcc(n) __asm__(rlit(n))
|
||||||
|
|
||||||
|
|||||||
+164
-64
@@ -17,9 +17,9 @@
|
|||||||
// source: C:\projects\Pikuma\ps1\code\duffle\bios.h
|
// source: C:\projects\Pikuma\ps1\code\duffle\bios.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.h
|
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\pad.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\pad.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\math.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\math.atom.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\mips.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\mips.atom.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\gte.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\gte.atom.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\gp.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\gp.atom.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\pad.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\pad.atom.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.atom.c
|
||||||
@@ -35,15 +35,12 @@
|
|||||||
* These do NOT yield. They are expanded inline inside Tape Atoms.
|
* These do NOT yield. They are expanded inline inside Tape Atoms.
|
||||||
* ---------------------------------------------------------------------------*/
|
* ---------------------------------------------------------------------------*/
|
||||||
// The 'Yield' sequence for Tape Atoms (mac_yield).
|
// The 'Yield' sequence for Tape Atoms (mac_yield).
|
||||||
// - mac_yield() is the safe default for atom-endings: 4 words, BD-slot of jr is mandatory nop.
|
|
||||||
// - mac_yield_load() + mac_yield_tail():
|
|
||||||
// - unconditional branch: mac_yield_load fills the branch's BD-slot (replaces a nop);
|
|
||||||
// - mac_yield_tail runs at the branch target (does NOT re-load R_AtomJmp).
|
|
||||||
#define mac_yield(...) \
|
#define mac_yield(...) \
|
||||||
load_word(R_AtomJmp, R_TapePtr, 0) \
|
load_word(R_AtomJmp, R_TapePtr, 0) \
|
||||||
|
LdSlot_ \
|
||||||
, add_ui_self( R_TapePtr, S_(MipsCode)) \
|
, add_ui_self( R_TapePtr, S_(MipsCode)) \
|
||||||
, jump_reg( R_AtomJmp) \
|
, jump_reg( R_AtomJmp) \
|
||||||
, nop
|
, BdSlot_ nop
|
||||||
WORD_COUNT(mac_yield, 4)
|
WORD_COUNT(mac_yield, 4)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
@@ -55,13 +52,24 @@ WORD_COUNT(mac_yield_load, 1)
|
|||||||
#define mac_yield_tail(...) \
|
#define mac_yield_tail(...) \
|
||||||
add_ui_self(R_TapePtr, S_(MipsCode)) \
|
add_ui_self(R_TapePtr, S_(MipsCode)) \
|
||||||
, jump_reg( R_AtomJmp) \
|
, jump_reg( R_AtomJmp) \
|
||||||
, nop
|
, BdSlot_ nop
|
||||||
WORD_COUNT(mac_yield_tail, 3)
|
WORD_COUNT(mac_yield_tail, 3)
|
||||||
|
|
||||||
|
/* atom_dbg_skip */
|
||||||
|
#define mac_load_half_v3(tx, ty, tz, base, offset) \
|
||||||
|
load_half(tx, base, offset + OA_(U2,[0])) \
|
||||||
|
, load_half(ty, base, offset + OA_(U2,[1])) \
|
||||||
|
, load_half(tz, base, offset + OA_(U2,[2]))
|
||||||
|
WORD_COUNT(mac_load_half_v3, 3)
|
||||||
|
|
||||||
|
#define mac_load_v3s2(transfer, base, offset) \
|
||||||
|
mac_load_half_v3(transfer.x, transfer.y, transfer.z, base, offset)
|
||||||
|
WORD_COUNT(mac_load_v3s2, 3)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_load_v2s2(rs_x, rs_y, r_base, offset) \
|
#define mac_load_v2s2(rs_x, rs_y, r_base, offset) \
|
||||||
load_half( rs_x, r_base, offset + O_(V3_S2,x)) \
|
load_half(rs_x, r_base, offset + O_(V3_S2,x)) \
|
||||||
, load_half( rs_y, r_base, offset + O_(V3_S2,y))
|
, load_half(rs_y, r_base, offset + O_(V3_S2,y))
|
||||||
WORD_COUNT(mac_load_v2s2, 2)
|
WORD_COUNT(mac_load_v2s2, 2)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
@@ -71,26 +79,75 @@ WORD_COUNT(mac_load_v2s2, 2)
|
|||||||
WORD_COUNT(mac_store_v2s2, 2)
|
WORD_COUNT(mac_store_v2s2, 2)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_load_v3s4(rs_x, rs_y, rs_z, r_base, offset) \
|
#define mac_load_word_v3(tx, ty, tz, base, offset) \
|
||||||
load_word( rs_x, r_base, offset + O_(V3_S4,x)) \
|
load_word(tx, base, offset + OA_(U4,[0])) \
|
||||||
, load_word( rs_y, r_base, offset + O_(V3_S4,y)) \
|
, load_word(ty, base, offset + OA_(U4,[1])) \
|
||||||
, load_word( rs_z, r_base, offset + O_(V3_S4,z))
|
, load_word(tz, base, offset + OA_(U4,[2]))
|
||||||
|
WORD_COUNT(mac_load_word_v3, 3)
|
||||||
|
|
||||||
|
#define mac_load_v3s4(transfer, base, offset) \
|
||||||
|
mac_load_word_v3(transfer.x, transfer.y, transfer.z, base, offset)
|
||||||
WORD_COUNT(mac_load_v3s4, 3)
|
WORD_COUNT(mac_load_v3s4, 3)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
#define mac_load_p3s4(transfer, base, offset) \
|
||||||
#define mac_store_v3s4(rt_x, rt_y, rt_z, base, offset) \
|
mac_load_word_v3(transfer.x, transfer.y, transfer.z, base, offset)
|
||||||
store_word(rt_x, base, offset + O_(V3_S4,x)) \
|
WORD_COUNT(mac_load_p3s4, 3)
|
||||||
, store_word(rt_y, base, offset + O_(V3_S4,y)) \
|
|
||||||
, store_word(rt_z, base, offset + O_(V3_S4,z))
|
|
||||||
WORD_COUNT(mac_store_v3s4, 3)
|
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_sub_v3s4(rds_x, rds_y, rds_z, rt_x, rt_y, rt_z) \
|
#define mac_store_half_v3(tx, ty, tz, base, offset) \
|
||||||
sub_s(rds_x, rds_x, rt_x) \
|
store_half(tx, base, offset + OA_(U2,[0])) \
|
||||||
, sub_s(rds_y, rds_y, rt_y) \
|
, store_half(ty, base, offset + OA_(U2,[1])) \
|
||||||
, sub_s(rds_z, rds_z, rt_z)
|
, store_half(tz, base, offset + OA_(U2,[2]))
|
||||||
|
WORD_COUNT(mac_store_half_v3, 3)
|
||||||
|
|
||||||
|
#define mac_store_v3s2(transfer, base, offset) \
|
||||||
|
mac_store_half_v3(transfer.x, transfer.y, transfer.z, base, offset)
|
||||||
|
WORD_COUNT(mac_store_v3s2, 3)
|
||||||
|
|
||||||
|
/* atom_dbg_skip */
|
||||||
|
#define mac_store_word_v3(tx, ty, tz, base, offset) \
|
||||||
|
store_word(tx, base, offset + OA_(U4,[0])) \
|
||||||
|
, store_word(ty, base, offset + OA_(U4,[1])) \
|
||||||
|
, store_word(tz, base, offset + OA_(U4,[2]))
|
||||||
|
WORD_COUNT(mac_store_word_v3, 3)
|
||||||
|
|
||||||
|
#define mac_store_v3s4(transfer, base, offset) \
|
||||||
|
mac_store_word_v3(transfer.x, transfer.y, transfer.z, base, offset)
|
||||||
|
WORD_COUNT(mac_store_v3s4, 3)
|
||||||
|
|
||||||
|
#define mac_store_p3s4(transfer, base, offset) \
|
||||||
|
mac_store_word_v3(transfer.x, transfer.y, transfer.z, base, offset)
|
||||||
|
WORD_COUNT(mac_store_p3s4, 3)
|
||||||
|
|
||||||
|
/* atom_dbg_skip */
|
||||||
|
#define mac_add_si_v3s4(rt_x, rt_y, rt_z, base, offset) \
|
||||||
|
add_si(rt_x, base, O_(V3_S4,x)) \
|
||||||
|
, add_si(rt_y, base, O_(V3_S4,y)) \
|
||||||
|
, add_si(rt_z, base, O_(V3_S4,z))
|
||||||
|
WORD_COUNT(mac_add_si_v3s4, 3)
|
||||||
|
|
||||||
|
/* atom_dbg_skip */
|
||||||
|
#define mac_sub_s_v3(dx, dy, dz, sx, sy, sz, tx, ty, tz) \
|
||||||
|
sub_s(dx, sx, tx) \
|
||||||
|
, sub_s(dy, sy, ty) \
|
||||||
|
, sub_s(dz, sz, tz)
|
||||||
|
WORD_COUNT(mac_sub_s_v3, 3)
|
||||||
|
|
||||||
|
#define mac_sub_v3s4(d, s, t) \
|
||||||
|
mac_sub_s_v3(d.x, d.y, d.z, s.x, s.y, s.z, t.x, t.y, t.z)
|
||||||
WORD_COUNT(mac_sub_v3s4, 3)
|
WORD_COUNT(mac_sub_v3s4, 3)
|
||||||
|
|
||||||
|
/* atom_dbg_skip */
|
||||||
|
#define mac_sub_s_v3_self(ds_x, ds_y, ds_z, tx, ty, tz) \
|
||||||
|
sub_s(ds_x, ds_x, tx) \
|
||||||
|
, sub_s(ds_y, ds_y, ty) \
|
||||||
|
, sub_s(ds_z, ds_z, tz)
|
||||||
|
WORD_COUNT(mac_sub_s_v3_self, 3)
|
||||||
|
|
||||||
|
#define mac_sub_v3s4_self(ds, t) \
|
||||||
|
mac_sub_s_v3_self(ds.x, ds.y, ds.z, t.x, t.y, t.z)
|
||||||
|
WORD_COUNT(mac_sub_v3s4_self, 3)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_store_rects2(rt_x, rt_y, rt_width, rt_height, base, offset) \
|
#define mac_store_rects2(rt_x, rt_y, rt_width, rt_height, base, offset) \
|
||||||
store_half(rt_x, base, offset + O_(Rect_S2,x)) \
|
store_half(rt_x, base, offset + O_(Rect_S2,x)) \
|
||||||
@@ -105,6 +162,33 @@ WORD_COUNT(mac_store_rects2, 4)
|
|||||||
, or_i_self( dst, u4_lo(imm))
|
, or_i_self( dst, u4_lo(imm))
|
||||||
WORD_COUNT(mac_load_word_imm, 2)
|
WORD_COUNT(mac_load_word_imm, 2)
|
||||||
|
|
||||||
|
#define mac_shift_aright_v3_self(dt_x, dt_y, dt_z, shift_amount) \
|
||||||
|
shift_aright(dt_x, dt_x, shift_amount) \
|
||||||
|
, shift_aright(dt_y, dt_y, shift_amount) \
|
||||||
|
, shift_aright(dt_z, dt_z, shift_amount)
|
||||||
|
WORD_COUNT(mac_shift_aright_v3_self, 3)
|
||||||
|
|
||||||
|
#define mac_shift_aright_v3s4_self(dt, shift) \
|
||||||
|
mac_shift_aright_v3_self(dt.x, dt.y, dt.z, shift)
|
||||||
|
WORD_COUNT(mac_shift_aright_v3s4_self, 3)
|
||||||
|
|
||||||
|
#define mac_shift_aright_var_v3(rd_v0, rd_v1, rd_v2, rs_v0, rs_v1, rs_v2, r_shift) \
|
||||||
|
shift_aright_var(rd_v0, rs_v0, r_shift) \
|
||||||
|
, shift_aright_var(rd_v1, rs_v1, r_shift) \
|
||||||
|
, shift_aright_var(rd_v2, rs_v2, r_shift)
|
||||||
|
WORD_COUNT(mac_shift_aright_var_v3, 3)
|
||||||
|
|
||||||
|
/* atom_dbg_skip */
|
||||||
|
#define mac_shift_aright_var_v3_self(rds_v0, rds_v1, rds_v2, r_shift) \
|
||||||
|
shift_aright_var(rds_v0, rds_v0, r_shift) \
|
||||||
|
, shift_aright_var(rds_v1, rds_v1, r_shift) \
|
||||||
|
, shift_aright_var(rds_v2, rds_v2, r_shift)
|
||||||
|
WORD_COUNT(mac_shift_aright_var_v3_self, 3)
|
||||||
|
|
||||||
|
#define mac_shift_aright_var_v3s4_self(ds, shift) \
|
||||||
|
mac_shift_aright_var_v3_self(ds.x, ds.y, ds.z, shift)
|
||||||
|
WORD_COUNT(mac_shift_aright_var_v3s4_self, 3)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_load_tri_indices(r_face_cusor, r_i0, r_i1, r_i2) \
|
#define mac_load_tri_indices(r_face_cusor, r_i0, r_i1, r_i2) \
|
||||||
load_half_u(r_i0, r_face_cusor, 0 * S_(S2)) \
|
load_half_u(r_i0, r_face_cusor, 0 * S_(S2)) \
|
||||||
@@ -112,6 +196,30 @@ WORD_COUNT(mac_load_word_imm, 2)
|
|||||||
, load_half_u(r_i2, r_face_cusor, 2 * S_(S2))
|
, load_half_u(r_i2, r_face_cusor, 2 * S_(S2))
|
||||||
WORD_COUNT(mac_load_tri_indices, 3)
|
WORD_COUNT(mac_load_tri_indices, 3)
|
||||||
|
|
||||||
|
#define mac_gte_mv_to_cr_diag_v3s4(v) \
|
||||||
|
gte_mv_to_ctrl_r(v.y, gte_cr_RT13) \
|
||||||
|
, gte_mv_to_ctrl_r(v.z, gte_cr_RT22) \
|
||||||
|
, gte_mv_to_ctrl_r(v.x, gte_cr_RT11)
|
||||||
|
WORD_COUNT(mac_gte_mv_to_cr_diag_v3s4, 3)
|
||||||
|
|
||||||
|
#define mac_gte_ld_ir123_v3s4(v) \
|
||||||
|
gte_mv_to_data_r(v.x, C2_IR1) \
|
||||||
|
, gte_mv_to_data_r(v.y, C2_IR2) \
|
||||||
|
, gte_mv_to_data_r(v.z, C2_IR3)
|
||||||
|
WORD_COUNT(mac_gte_ld_ir123_v3s4, 3)
|
||||||
|
|
||||||
|
/* atom_dbg_skip */
|
||||||
|
#define mac_gte_op_cross_v3s4(a, b) \
|
||||||
|
mac_gte_mv_to_cr_diag_v3s4(a) \
|
||||||
|
GteDelay_ /* RT diagonal: D1 = a.x, D2 = a.y, D3 = a.z */ \
|
||||||
|
, mac_gte_ld_ir123_v3s4(b) \
|
||||||
|
GteDelay_ /* IR: second operand (b.xyz) */ \
|
||||||
|
, gte_cmdw_cross /* OP: MAC1/2/3 = a × b (S12.20) */ \
|
||||||
|
, mac_gte_mv_from_mac123_v3s4(a) \
|
||||||
|
GteDelay_ /* Read MAC1/2/3 → a.xyz (overwrites source-A's load targets) */ \
|
||||||
|
, mac_shift_aright_v3s4_self(a, 12) /* Right-shift MAC by 12 (S12.20 → S12.0 OuterProduct12) */
|
||||||
|
WORD_COUNT(mac_gte_op_cross_v3s4, 13)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_gte_store_f3(r_primitive_cursor) \
|
#define mac_gte_store_f3(r_primitive_cursor) \
|
||||||
gte_sw(C2_SXY0, r_primitive_cursor, O_(Poly_F3,p0)) \
|
gte_sw(C2_SXY0, r_primitive_cursor, O_(Poly_F3,p0)) \
|
||||||
@@ -120,24 +228,24 @@ WORD_COUNT(mac_load_tri_indices, 3)
|
|||||||
WORD_COUNT(mac_gte_store_f3, 3)
|
WORD_COUNT(mac_gte_store_f3, 3)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_gte_load_tri_verts(r_vert_base, r_v0, r_v1, r_v2) \
|
#define mac_gte_load_tri_verts(vbase, v0, v1, v2) \
|
||||||
shift_lleft(R_AT, r_v0, v3s2_byteoff) \
|
shift_lleft(R_AT, v0, v3s2_byteoff) \
|
||||||
, add_u_self(R_AT, r_vert_base) \
|
, add_u_self(R_AT, vbase) \
|
||||||
, load_word(R_V0, R_AT, O_(V3_S2,x)) \
|
, load_word(R_V0, R_AT, O_(V3_S2,x)) \
|
||||||
, load_word(R_V1, R_AT, O_(V3_S2,z)) \
|
, load_word(R_V1, R_AT, O_(V3_S2,z)) \
|
||||||
, gte_mv_to_data_r(R_V0, C2_VXY0) \
|
, LdSlot_ gte_mv_to_data_r(R_V0, C2_VXY0) \
|
||||||
, gte_mv_to_data_r(R_V1, C2_VZ0) \
|
, gte_mv_to_data_r(R_V1, C2_VZ0) \
|
||||||
, shift_lleft(R_AT, r_v1, v3s2_byteoff) \
|
, shift_lleft(R_AT, v1, v3s2_byteoff) \
|
||||||
, add_u_self(R_AT, r_vert_base) \
|
, add_u_self(R_AT, vbase) \
|
||||||
, load_word(R_V0, R_AT, O_(V3_S2,x)) \
|
, load_word(R_V0, R_AT, O_(V3_S2,x)) \
|
||||||
, load_word(R_V1, R_AT, O_(V3_S2,z)) \
|
, load_word(R_V1, R_AT, O_(V3_S2,z)) \
|
||||||
, gte_mv_to_data_r(R_V0, C2_VXY1) \
|
, LdSlot_ gte_mv_to_data_r(R_V0, C2_VXY1) \
|
||||||
, gte_mv_to_data_r(R_V1, C2_VZ1) \
|
, gte_mv_to_data_r(R_V1, C2_VZ1) \
|
||||||
, shift_lleft(R_AT, r_v2, v3s2_byteoff) \
|
, shift_lleft(R_AT, v2, v3s2_byteoff) \
|
||||||
, add_u_self(R_AT, r_vert_base) \
|
, add_u_self(R_AT, vbase) \
|
||||||
, load_word(R_V0, R_AT, O_(V3_S2,x)) \
|
, load_word(R_V0, R_AT, O_(V3_S2,x)) \
|
||||||
, load_word(R_V1, R_AT, O_(V3_S2,z)) \
|
, load_word(R_V1, R_AT, O_(V3_S2,z)) \
|
||||||
, gte_mv_to_data_r(R_V0, C2_VXY2) \
|
, LdSlot_ gte_mv_to_data_r(R_V0, C2_VXY2) \
|
||||||
, gte_mv_to_data_r(R_V1, C2_VZ2)
|
, gte_mv_to_data_r(R_V1, C2_VZ2)
|
||||||
WORD_COUNT(mac_gte_load_tri_verts, 18)
|
WORD_COUNT(mac_gte_load_tri_verts, 18)
|
||||||
|
|
||||||
@@ -162,11 +270,11 @@ WORD_COUNT(mac_gte_store_g4_p3, 1)
|
|||||||
WORD_COUNT(mac_gte_sqr_v3, 8)
|
WORD_COUNT(mac_gte_sqr_v3, 8)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_gte_sqr_v3s4(r_sx, r_sy, r_sz, nop_slot) \
|
#define mac_gte_sqr_v3s4(sx, sy, sz, delay_slot) \
|
||||||
gte_mv_to_data_r(r_sx, C2_IR1) \
|
gte_mv_to_data_r(sx, C2_IR1) \
|
||||||
, gte_mv_to_data_r(r_sy, C2_IR2) \
|
, gte_mv_to_data_r(sy, C2_IR2) \
|
||||||
, gte_mv_to_data_r(r_sz, C2_IR3) \
|
, gte_mv_to_data_r(sz, C2_IR3) \
|
||||||
, nop_slot \
|
, delay_slot \
|
||||||
, gte_cmdw_sqr
|
, gte_cmdw_sqr
|
||||||
WORD_COUNT(mac_gte_sqr_v3s4, 5)
|
WORD_COUNT(mac_gte_sqr_v3s4, 5)
|
||||||
|
|
||||||
@@ -176,7 +284,7 @@ WORD_COUNT(mac_gte_sqr_v3s4, 5)
|
|||||||
, gte_mv_to_data_r(r_sx, C2_IR1) \
|
, gte_mv_to_data_r(r_sx, C2_IR1) \
|
||||||
, gte_mv_to_data_r(r_sy, C2_IR2) \
|
, gte_mv_to_data_r(r_sy, C2_IR2) \
|
||||||
, gte_mv_to_data_r(r_sz, C2_IR3) \
|
, gte_mv_to_data_r(r_sz, C2_IR3) \
|
||||||
, nop2 /* retire IR0..IR3 → GPF input pre-fill (matches libgte 0x80016134..0x80016138) */ \
|
, GteDelay_ nop2 /* retire IR0..IR3 → GPF input pre-fill (matches libgte 0x80016134..0x80016138) */ \
|
||||||
, gte_cmdw_gpf \
|
, gte_cmdw_gpf \
|
||||||
, gte_mv_from_data_r(r_dx, C2_MAC1) \
|
, gte_mv_from_data_r(r_dx, C2_MAC1) \
|
||||||
, gte_mv_from_data_r(r_dy, C2_MAC2) \
|
, gte_mv_from_data_r(r_dy, C2_MAC2) \
|
||||||
@@ -187,42 +295,30 @@ WORD_COUNT(mac_gte_sqr_v3s4, 5)
|
|||||||
WORD_COUNT(mac_gte_gpf_scale, 13)
|
WORD_COUNT(mac_gte_gpf_scale, 13)
|
||||||
|
|
||||||
#define mac_trans_mt3s3s4(r_mtx, r_off, r_t0, r_t1, r_t2) \
|
#define mac_trans_mt3s3s4(r_mtx, r_off, r_t0, r_t1, r_t2) \
|
||||||
load_word(r_t0, r_off, O_(V3_S4,x)) \
|
load_word( r_t0, r_off, O_(V3_S4,x)) \
|
||||||
, load_word(r_t1, r_off, O_(V3_S4,y)) \
|
, load_word( r_t1, r_off, O_(V3_S4,y)) \
|
||||||
, load_word(r_t2, r_off, O_(V3_S4,z)) \
|
, load_word( r_t2, r_off, O_(V3_S4,z)) \
|
||||||
, store_word(r_t0, r_mtx, O_(MT3_S2S4,t[0])) \
|
, store_word(r_t0, r_mtx, O_(MT3_S2S4,t[0])) \
|
||||||
, store_word(r_t1, r_mtx, O_(MT3_S2S4,t[1])) \
|
, store_word(r_t1, r_mtx, O_(MT3_S2S4,t[1])) \
|
||||||
, store_word(r_t2, r_mtx, O_(MT3_S2S4,t[2]))
|
, store_word(r_t2, r_mtx, O_(MT3_S2S4,t[2]))
|
||||||
WORD_COUNT(mac_trans_mt3s3s4, 6)
|
WORD_COUNT(mac_trans_mt3s3s4, 6)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_lzcr_round_even_half_shift(r_shift, r_mag_sq, r_mag_sq_copy) \
|
#define mac_lzcr_round_even_half_shift(shift, mag_sq, mag_sq_copy) \
|
||||||
and_i(r_shift, r_shift, gte_lzcr_even_mask) \
|
and_i(shift, shift, gte_lzcr_even_mask) \
|
||||||
, or_u(r_mag_sq_copy, r_mag_sq, 0) \
|
, or_u(mag_sq_copy, mag_sq, 0) \
|
||||||
, li_s(r_mag_sq, 31) \
|
, li_s( mag_sq, 31) \
|
||||||
, sub_s(r_mag_sq, r_mag_sq, r_shift) \
|
, sub_s( mag_sq, mag_sq, shift) \
|
||||||
, shift_aright(r_mag_sq, r_mag_sq, 1)
|
, shift_aright(mag_sq, mag_sq, 1)
|
||||||
WORD_COUNT(mac_lzcr_round_even_half_shift, 5)
|
WORD_COUNT(mac_lzcr_round_even_half_shift, 5)
|
||||||
|
|
||||||
#define mac_shift_aright_var_v3(rd_v0, rd_v1, rd_v2, rs_v0, rs_v1, rs_v2, r_shift) \
|
|
||||||
shift_aright_var(rd_v0, rs_v0, r_shift) \
|
|
||||||
, shift_aright_var(rd_v1, rs_v1, r_shift) \
|
|
||||||
, shift_aright_var(rd_v2, rs_v2, r_shift)
|
|
||||||
WORD_COUNT(mac_shift_aright_var_v3, 3)
|
|
||||||
|
|
||||||
#define mac_shift_aright_var_v3_self(rds_v0, rds_v1, rds_v2, r_shift) \
|
|
||||||
shift_aright_var(rds_v0, rds_v0, r_shift) \
|
|
||||||
, shift_aright_var(rds_v1, rds_v1, r_shift) \
|
|
||||||
, shift_aright_var(rds_v2, rds_v2, r_shift)
|
|
||||||
WORD_COUNT(mac_shift_aright_var_v3_self, 3)
|
|
||||||
|
|
||||||
#define mac_gte_general_purpose_interopolation(to_ir0, to_ir1, to_ir2, to_ir3, fr_mac1, fr_mac2, fr_mac3, nop_slot1, nop_slot2) \
|
#define mac_gte_general_purpose_interopolation(to_ir0, to_ir1, to_ir2, to_ir3, fr_mac1, fr_mac2, fr_mac3, nop_slot1, nop_slot2) \
|
||||||
gte_mv_to_data_r(to_ir0, C2_IR0) \
|
gte_mv_to_data_r(to_ir0, C2_IR0) \
|
||||||
, gte_mv_to_data_r(to_ir1, C2_IR1) /* IR1 = src.x (preserved in r_tmp — r_mac2_scratch was clobbered to MAC2 in stage 1.5) */ \
|
, gte_mv_to_data_r(to_ir1, C2_IR1) /* IR1 = src.x (preserved in r_tmp — r_mac2_scratch was clobbered to MAC2 in stage 1.5) */ \
|
||||||
, gte_mv_to_data_r(to_ir2, C2_IR2) \
|
, gte_mv_to_data_r(to_ir2, C2_IR2) \
|
||||||
, gte_mv_to_data_r(to_ir3, C2_IR3) /* IR3 = src.z (reloaded) */ \
|
, gte_mv_to_data_r(to_ir3, C2_IR3) /* IR3 = src.z (reloaded) */ \
|
||||||
, LdSlot_ nop_slot1 \
|
, GteDelay_ nop_slot1 \
|
||||||
, LdSlot_ nop_slot2 \
|
, GteDelay_ nop_slot2 \
|
||||||
, gte_cmdw_gpf \
|
, gte_cmdw_gpf \
|
||||||
, gte_mv_from_data_r(fr_mac1, C2_MAC1) \
|
, gte_mv_from_data_r(fr_mac1, C2_MAC1) \
|
||||||
, gte_mv_from_data_r(fr_mac2, C2_MAC2) \
|
, gte_mv_from_data_r(fr_mac2, C2_MAC2) \
|
||||||
@@ -235,6 +331,10 @@ WORD_COUNT(mac_gte_general_purpose_interopolation, 10)
|
|||||||
, gte_mv_from_data_r(fr_mac3, C2_MAC3)
|
, gte_mv_from_data_r(fr_mac3, C2_MAC3)
|
||||||
WORD_COUNT(mac_gte_mv_from_data_r_mac123, 3)
|
WORD_COUNT(mac_gte_mv_from_data_r_mac123, 3)
|
||||||
|
|
||||||
|
#define mac_gte_mv_from_mac123_v3s4(v) \
|
||||||
|
mac_gte_mv_from_data_r_mac123(v.x, v.y, v.z)
|
||||||
|
WORD_COUNT(mac_gte_mv_from_mac123_v3s4, 3)
|
||||||
|
|
||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_gcmd_push(cmd, reg_transfer, reg_base, port) \
|
#define mac_gcmd_push(cmd, reg_transfer, reg_base, port) \
|
||||||
mac_load_word_imm(reg_transfer, cmd) \
|
mac_load_word_imm(reg_transfer, cmd) \
|
||||||
@@ -303,6 +403,6 @@ WORD_COUNT(mac_pad_set_status, 2)
|
|||||||
/* atom_dbg_skip */
|
/* atom_dbg_skip */
|
||||||
#define mac_pad_store_inverted_buttons(r_buttons, r_pad_state) \
|
#define mac_pad_store_inverted_buttons(r_buttons, r_pad_state) \
|
||||||
nor_u( r_buttons, r_buttons, R_0) \
|
nor_u( r_buttons, r_buttons, R_0) \
|
||||||
, store_half( r_buttons, r_pad_state, O_(PadState,buttons))
|
, store_half(r_buttons, r_pad_state, O_(PadState,buttons))
|
||||||
WORD_COUNT(mac_pad_store_inverted_buttons, 2)
|
WORD_COUNT(mac_pad_store_inverted_buttons, 2)
|
||||||
|
|
||||||
|
|||||||
@@ -14,9 +14,9 @@
|
|||||||
// source: C:\projects\Pikuma\ps1\code\duffle\bios.h
|
// source: C:\projects\Pikuma\ps1\code\duffle\bios.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.h
|
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\pad.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\pad.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\math.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\math.atom.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\mips.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\mips.atom.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\gte.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\gte.atom.h
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\gp.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\gp.atom.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\pad.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\pad.atom.c
|
||||||
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.atom.c
|
// source: C:\projects\Pikuma\ps1\code\duffle\psyq.atom.c
|
||||||
@@ -25,7 +25,15 @@
|
|||||||
#pragma region duffle
|
#pragma region duffle
|
||||||
|
|
||||||
|
|
||||||
// --- atom: normalize_v3s4 (47 words) ---
|
// --- atom: example_atom_proc (10 words) ---
|
||||||
|
|
||||||
|
#define _atom_offset_example_atom_proc_skip 2
|
||||||
|
|
||||||
|
enum {
|
||||||
|
atom_offset_example_atom_proc_skip = _atom_offset_example_atom_proc_skip,
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- atom: normalize_v3s4 (62 words) ---
|
||||||
|
|
||||||
#define _atom_offset_aligned_done_srav_path 3
|
#define _atom_offset_aligned_done_srav_path 3
|
||||||
#define _atom_offset_srav_path_aligned_done 4
|
#define _atom_offset_srav_path_aligned_done 4
|
||||||
|
|||||||
@@ -44,7 +44,8 @@ atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|||||||
})
|
})
|
||||||
|
|
||||||
/* Words: 11; Correctly inserts a primitive into the Ordering Table linked list. */
|
/* Words: 11; Correctly inserts a primitive into the Ordering Table linked list. */
|
||||||
I_ Slice_MipsCode ac_insert_ot_tag(AtomBuilder_R ab, U4 r_ot_base, U4 r_prim_cursor, U4 poly_size) MipsAtomComp_Proc_(ab, {
|
// TODO(Ed): Expose R_T1 as a r_t0, r_V0 as r_t2
|
||||||
|
I_ Slice_MipsCode ac_insert_ot_tag(AtomBuilder_R ab, Reg r_ot_base, Reg r_prim_cursor, U2 poly_size) MipsAtomComp_Proc_(ab, {
|
||||||
shift_lleft( R_T1, R_T1, S_(U4)/2), // T1 = otz * S_(U4) (otz arg is implicit R_T1)
|
shift_lleft( R_T1, R_T1, S_(U4)/2), // T1 = otz * S_(U4) (otz arg is implicit R_T1)
|
||||||
add_u_self( R_T1, r_ot_base), // T1 = & OrderingTable[OTZ]
|
add_u_self( R_T1, r_ot_base), // T1 = & OrderingTable[OTZ]
|
||||||
load_word( R_AT, R_T1, O_(PolyTag,code)), // AT = old_ot_head
|
load_word( R_AT, R_T1, O_(PolyTag,code)), // AT = old_ot_head
|
||||||
|
|||||||
+57
-74
@@ -6,26 +6,13 @@
|
|||||||
* Primitive commands: gp0_cmd_poly_f3 = 0x20 (byte opcode)
|
* Primitive commands: gp0_cmd_poly_f3 = 0x20 (byte opcode)
|
||||||
* Packed 32-bit cmd: gp0_word_poly_f3(r, g, b) (32-bit, shifted)
|
* Packed 32-bit cmd: gp0_word_poly_f3(r, g, b) (32-bit, shifted)
|
||||||
*
|
*
|
||||||
* Type ordering: domain?_(direction)?_action_target_modifier_type?
|
|
||||||
* Examples: add_ui (add + unsigned + immediate)
|
|
||||||
* add_s (add + signed, R-type implicit)
|
|
||||||
* shift_lleft (shift + logical + left)
|
|
||||||
* shift_aright (shift + arithmetic + right)
|
|
||||||
* call_reg(rs) (call + register, $ra implicit)
|
|
||||||
* gte_mv_to_data_r (gte + mv + to + data + register)
|
|
||||||
* gte_lw_v0_xy(base) (gte + lw + v0 + xy)
|
|
||||||
* load_upper_i (load-upper + immediate, unique verb)
|
|
||||||
*
|
|
||||||
* --- GPU-domain layer cake ---
|
* --- GPU-domain layer cake ---
|
||||||
* Every gp.h macro follows the same 4-layer composition as mips.h and gte.h:
|
* Every gp.h macro follows the same 4-layer composition as mips.h and gte.h:
|
||||||
* 4. Semantic encoders gp0_word_poly_f3(r,g,b)
|
* 4. Semantic encoders gp0_word_poly_f3(r,g,b)
|
||||||
* 3. Composite encoders enc_color_word(cmd, r, g, b)
|
* 3. Composite encoders enc_color_word(cmd, r, g, b)
|
||||||
* 2. Per-field encoders enc_gp0_color_r(r), enc_gp0_color_g(g), ...
|
* 2. Per-field encoders enc_gp0_color_r(r), enc_gp0_color_g(g), ...
|
||||||
* 1. Bitfield layout consts gp0_color_red_shift = 0, gp0_color_red_width = 8
|
* 1. Bitfield layout consts gp0_color_red_pos = 0, gp0_color_red_width = 8
|
||||||
* 0. Opcode IDs gp0_cmd_poly_f3 = 0x20
|
* 0. Opcode IDs gp0_cmd_poly_f3 = 0x20
|
||||||
*
|
|
||||||
* Vendor mnemonics (gte_mtc2, gte_mfc2, etc.) are NOT in this header.
|
|
||||||
* They live in the opt-in `gp_vendor_sym.h` for users who prefer the PSYQ-style names.
|
|
||||||
* ============================================================================ */
|
* ============================================================================ */
|
||||||
|
|
||||||
#ifdef INTELLISENSE_DIRECTIVES
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
@@ -68,13 +55,14 @@ enum {
|
|||||||
|
|
||||||
#define gp0_send(word) (HW_GP0[0] = (word))
|
#define gp0_send(word) (HW_GP0[0] = (word))
|
||||||
#define gp1_send(word) (HW_GP1[0] = (word))
|
#define gp1_send(word) (HW_GP1[0] = (word))
|
||||||
|
#define DmaSlot_ // Annotate an instruction as filling a CPU <-> Command DMA delay slot/s
|
||||||
|
|
||||||
/* ============================================================================
|
/* ============================================================================
|
||||||
* GP0 command byte constants + Layer 1 (GPU bitfield shifts)
|
* GP0 command byte constants + Layer 1 (GPU bitfield shifts)
|
||||||
* ============================================================================
|
* ============================================================================
|
||||||
* 8-bit GP0 opcodes (the upper byte of a primitive's first word). These are the BYTE only.
|
* 8-bit GP0 opcodes (the upper byte of a primitive's first word). These are the BYTE only.
|
||||||
* NO macro body past this point uses a raw shift or raw mask.
|
* NO macro body past this point uses a raw shift or raw mask.
|
||||||
* Mirrors the OPCODE_SHIFT / RS_SHIFT convention from mips.h.
|
* Mirrors the OPCODE_POS / RS_POS convention from mips.h.
|
||||||
* ============================================================================ */
|
* ============================================================================ */
|
||||||
enum {
|
enum {
|
||||||
gp0_cmd_Nop = 0x00,
|
gp0_cmd_Nop = 0x00,
|
||||||
@@ -116,9 +104,9 @@ enum {
|
|||||||
gp0_cmd_SetDrawOffset = 0xE5,
|
gp0_cmd_SetDrawOffset = 0xE5,
|
||||||
gp0_cmd_SetMaskBit = 0xE6,
|
gp0_cmd_SetMaskBit = 0xE6,
|
||||||
|
|
||||||
/* bitfield shifts / widths ----
|
/* bitfield offset pos / widths ----
|
||||||
* Generic GP0/GP1 command byte (upper 8 bits of every word sent to either port). */
|
* Generic GP0/GP1 command byte (upper 8 bits of every word sent to either port). */
|
||||||
gp0_cmd_shift = 24,
|
gp0_cmd_pos = 24,
|
||||||
gp0_cmd_width = 8,
|
gp0_cmd_width = 8,
|
||||||
|
|
||||||
/* Color word layout (lives in Poly_F3.color, Poly_G4.c0..c3, etc.):
|
/* Color word layout (lives in Poly_F3.color, Poly_G4.c0..c3, etc.):
|
||||||
@@ -126,10 +114,10 @@ enum {
|
|||||||
* bits 23..16 = BLUE
|
* bits 23..16 = BLUE
|
||||||
* bits 15..08 = GREEN
|
* bits 15..08 = GREEN
|
||||||
* bits 07..00 = RED (PSX GPU is BGR, NOT RGB) */
|
* bits 07..00 = RED (PSX GPU is BGR, NOT RGB) */
|
||||||
gp0_color_cmd_shift = 24, gp0_color_cmd_width = 8,
|
gp0_color_cmd_pos = 24, gp0_color_cmd_width = 8,
|
||||||
gp0_color_blue_shift = 16, gp0_color_blue_width = 8,
|
gp0_color_blue_pos = 16, gp0_color_blue_width = 8,
|
||||||
gp0_color_green_shift = 8, gp0_color_green_width = 8,
|
gp0_color_green_pos = 8, gp0_color_green_width = 8,
|
||||||
gp0_color_red_shift = 0, gp0_color_red_width = 8,
|
gp0_color_red_pos = 0, gp0_color_red_width = 8,
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ============================================================================
|
/* ============================================================================
|
||||||
@@ -142,12 +130,12 @@ enum {
|
|||||||
* ============================================================================ */
|
* ============================================================================ */
|
||||||
|
|
||||||
/* ---- Layer 1.5: per-field encoders ---- */
|
/* ---- Layer 1.5: per-field encoders ---- */
|
||||||
#define enc_gp0_cmd(cmd) ((cmd) << gp0_cmd_shift)
|
#define enc_gp0_cmd(cmd) ((cmd) << gp0_cmd_pos)
|
||||||
|
|
||||||
#define enc_gp0_color_cmd(cmd) ((cmd) << gp0_color_cmd_shift)
|
#define enc_gp0_color_cmd(cmd) ((cmd) << gp0_color_cmd_pos)
|
||||||
#define enc_gp0_color_r(r) ((r) << gp0_color_red_shift)
|
#define enc_gp0_color_r(r) ((r) << gp0_color_red_pos)
|
||||||
#define enc_gp0_color_g(g) ((g) << gp0_color_green_shift)
|
#define enc_gp0_color_g(g) ((g) << gp0_color_green_pos)
|
||||||
#define enc_gp0_color_b(b) ((b) << gp0_color_blue_shift)
|
#define enc_gp0_color_b(b) ((b) << gp0_color_blue_pos)
|
||||||
|
|
||||||
/* ---- Layer 2: composite encoders ---- */
|
/* ---- Layer 2: composite encoders ---- */
|
||||||
#define enc_color_word(cmd, r, g, b) (enc_gp0_color_cmd(cmd) | enc_gp0_color_r(r) | enc_gp0_color_g(g) | enc_gp0_color_b(b))
|
#define enc_color_word(cmd, r, g, b) (enc_gp0_color_cmd(cmd) | enc_gp0_color_r(r) | enc_gp0_color_g(g) | enc_gp0_color_b(b))
|
||||||
@@ -211,37 +199,37 @@ enum {
|
|||||||
gp1_disp_VInterlace = 0x1,
|
gp1_disp_VInterlace = 0x1,
|
||||||
|
|
||||||
/* ---- Layer 1: GP1 display-mode + range + draw-area shifts/widths ---- */
|
/* ---- Layer 1: GP1 display-mode + range + draw-area shifts/widths ---- */
|
||||||
gp1_disp_hres_shift = 0, gp1_disp_hres_width = 2,
|
gp1_disp_hres_pos = 0, gp1_disp_hres_width = 2,
|
||||||
gp1_disp_vres_shift = 2, gp1_disp_vres_width = 1,
|
gp1_disp_vres_pos = 2, gp1_disp_vres_width = 1,
|
||||||
gp1_disp_color_shift = 4, gp1_disp_color_width = 1,
|
gp1_disp_color_pos = 4, gp1_disp_color_width = 1,
|
||||||
gp1_disp_interlace_shift = 5, gp1_disp_interlace_width = 1,
|
gp1_disp_interlace_pos = 5, gp1_disp_interlace_width = 1,
|
||||||
|
|
||||||
/* GP1 horizontal display range: bits 0..11 = X2, bits 12..23 = X1 */
|
/* GP1 horizontal display range: bits 0..11 = X2, bits 12..23 = X1 */
|
||||||
gp1_hrange_x1_shift = 12, gp1_hrange_x1_width = 12,
|
gp1_hrange_x1_pos = 12, gp1_hrange_x1_width = 12,
|
||||||
gp1_hrange_x2_shift = 0, gp1_hrange_x2_width = 12,
|
gp1_hrange_x2_pos = 0, gp1_hrange_x2_width = 12,
|
||||||
|
|
||||||
/* GP1 vertical display range: bits 0..9 = Y2, bits 10..19 = Y1 */
|
/* GP1 vertical display range: bits 0..9 = Y2, bits 10..19 = Y1 */
|
||||||
gp1_vrange_y1_shift = 10, gp1_vrange_y1_width = 10,
|
gp1_vrange_y1_pos = 10, gp1_vrange_y1_width = 10,
|
||||||
gp1_vrange_y2_shift = 0, gp1_vrange_y2_width = 10,
|
gp1_vrange_y2_pos = 0, gp1_vrange_y2_width = 10,
|
||||||
|
|
||||||
/* GP1 draw area (top-left or bottom-right): bits 0..9 = X, bits 10..19 = Y
|
/* GP1 draw area (top-left or bottom-right): bits 0..9 = X, bits 10..19 = Y
|
||||||
* (10-bit signed — caller pre-signs) */
|
* (10-bit signed — caller pre-signs) */
|
||||||
gp1_draw_x_shift = 0, gp1_draw_x_width = 10,
|
gp1_draw_x_pos = 0, gp1_draw_x_width = 10,
|
||||||
gp1_draw_y_shift = 10, gp1_draw_y_width = 10,
|
gp1_draw_y_pos = 10, gp1_draw_y_width = 10,
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ---- Layer 1.5: GP1 per-field encoders ---- */
|
/* ---- Layer 1.5: GP1 per-field encoders ---- */
|
||||||
#define enc_gp1_disp_hres(h) ((h) << gp1_disp_hres_shift)
|
#define enc_gp1_disp_hres(h) ((h) << gp1_disp_hres_pos)
|
||||||
#define enc_gp1_disp_vres(v) ((v) << gp1_disp_vres_shift)
|
#define enc_gp1_disp_vres(v) ((v) << gp1_disp_vres_pos)
|
||||||
#define enc_gp1_disp_color(c) ((c) << gp1_disp_color_shift)
|
#define enc_gp1_disp_color(c) ((c) << gp1_disp_color_pos)
|
||||||
#define enc_gp1_disp_interlace(i) ((i) << gp1_disp_interlace_shift)
|
#define enc_gp1_disp_interlace(i) ((i) << gp1_disp_interlace_pos)
|
||||||
|
|
||||||
#define enc_gp1_hrange_x1(x1) ((x1) << gp1_hrange_x1_shift)
|
#define enc_gp1_hrange_x1(x1) ((x1) << gp1_hrange_x1_pos)
|
||||||
#define enc_gp1_hrange_x2(x2) ((x2) << gp1_hrange_x2_shift)
|
#define enc_gp1_hrange_x2(x2) ((x2) << gp1_hrange_x2_pos)
|
||||||
#define enc_gp1_vrange_y1(y1) ((y1) << gp1_vrange_y1_shift)
|
#define enc_gp1_vrange_y1(y1) ((y1) << gp1_vrange_y1_pos)
|
||||||
#define enc_gp1_vrange_y2(y2) ((y2) << gp1_vrange_y2_shift)
|
#define enc_gp1_vrange_y2(y2) ((y2) << gp1_vrange_y2_pos)
|
||||||
#define enc_gp1_draw_x(x) ((x) << gp1_draw_x_shift)
|
#define enc_gp1_draw_x(x) ((x) << gp1_draw_x_pos)
|
||||||
#define enc_gp1_draw_y(y) ((y) << gp1_draw_y_shift)
|
#define enc_gp1_draw_y(y) ((y) << gp1_draw_y_pos)
|
||||||
|
|
||||||
/* ---- Layer 2: GP1 composite encoders ---- */
|
/* ---- Layer 2: GP1 composite encoders ---- */
|
||||||
#define enc_gp1_disp_mode_word(h, v, c, i) (enc_gp0_cmd(gp1_cmd_DisplayMode) | enc_gp1_disp_hres(h) | enc_gp1_disp_vres(v) | enc_gp1_disp_color(c) | enc_gp1_disp_interlace(i))
|
#define enc_gp1_disp_mode_word(h, v, c, i) (enc_gp0_cmd(gp1_cmd_DisplayMode) | enc_gp1_disp_hres(h) | enc_gp1_disp_vres(v) | enc_gp1_disp_color(c) | enc_gp1_disp_interlace(i))
|
||||||
@@ -390,10 +378,8 @@ enum {
|
|||||||
* Primitive structs (8 polygon variants + tag)
|
* Primitive structs (8 polygon variants + tag)
|
||||||
* ============================================================================
|
* ============================================================================
|
||||||
* Each struct follows the GPU-documented memory layout for the corresponding primitive command.
|
* Each struct follows the GPU-documented memory layout for the corresponding primitive command.
|
||||||
* The PolyTag is the OT-link header; the rest of the struct is the primitive's body.
|
* PolyTag is an OT-link header. Rest of the struct is the primitive's body.
|
||||||
*
|
*
|
||||||
* The current working layouts match the existing demo
|
|
||||||
* (floor_tri uses Poly_F3; cube_tri uses Poly_G4).
|
|
||||||
* They are NOT necessarily byte-identical to the PSX-SPX reference layout.
|
* They are NOT necessarily byte-identical to the PSX-SPX reference layout.
|
||||||
* The demo layout uses color+vertex interleaving that doesn't match the standard PSX SDK file format.
|
* The demo layout uses color+vertex interleaving that doesn't match the standard PSX SDK file format.
|
||||||
* For PSX-SDK file compatibility, the textured variants (FT*, GT*) would need layout adjustments.
|
* For PSX-SDK file compatibility, the textured variants (FT*, GT*) would need layout adjustments.
|
||||||
@@ -418,14 +404,11 @@ typedef Struct_(PolyTag) {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
/* DSL cast convention: every cast uses `C_()`, every pointer qualifier is `R_` (restrict) or `V_` (volatile).
|
|
||||||
* No raw C-style casts. RHS values are assumed to be `U4` — caller passes a `U4` directly. */
|
|
||||||
#define set_len(tag,v) (C_(PolyTag_R,tag)->len = u4_(v))
|
#define set_len(tag,v) (C_(PolyTag_R,tag)->len = u4_(v))
|
||||||
#define set_addr(tag,v) (C_(PolyTag_R,tag)->addr = u4_(v))
|
#define set_addr(tag,v) (C_(PolyTag_R,tag)->addr = u4_(v))
|
||||||
/* `set_code` is no longer in the new PolyTag design — the code byte lives in the primitive body
|
/* `set_code` is no longer in the new PolyTag design
|
||||||
* (e.g. `((Poly_F3*)(p))->code`), not in the tag.
|
* (e.g. `((Poly_F3*)(p))->code`), not in the tag.
|
||||||
* Use the typed primitive structs (Poly_F3, Poly_G4, etc.) and the `set_poly_*` setters,
|
* Use the typed primitive structs (Poly_F3, Poly_G4, etc.) and the `set_poly_*` setters, which set both the tag's length and the code. */
|
||||||
* which set both the tag's length and the code. */
|
|
||||||
#define get_len(tag) C_(U4,C_(PolyTag_R,tag)->len)
|
#define get_len(tag) C_(U4,C_(PolyTag_R,tag)->len)
|
||||||
#define get_addr(tag) C_(U4,C_(PolyTag_R,tag)->addr)
|
#define get_addr(tag) C_(U4,C_(PolyTag_R,tag)->addr)
|
||||||
|
|
||||||
@@ -555,16 +538,16 @@ typedef Struct_(Poly_GT4) {
|
|||||||
* ============================================================================ */
|
* ============================================================================ */
|
||||||
enum {
|
enum {
|
||||||
/* ---- Layer 1: TPage bitfield shifts / widths ---- */
|
/* ---- Layer 1: TPage bitfield shifts / widths ---- */
|
||||||
gp0_tpage_x_shift = 0, gp0_tpage_x_width = 4,
|
gp0_tpage_x_pos = 0, gp0_tpage_x_width = 4,
|
||||||
gp0_tpage_y_shift = 4, gp0_tpage_y_width = 1,
|
gp0_tpage_y_pos = 4, gp0_tpage_y_width = 1,
|
||||||
gp0_tpage_semi_trans_shift = 5, gp0_tpage_semi_trans_width = 2,
|
gp0_tpage_semi_trans_pos = 5, gp0_tpage_semi_trans_width = 2,
|
||||||
gp0_tpage_color_depth_shift = 7, gp0_tpage_color_depth_width = 2,
|
gp0_tpage_color_depth_pos = 7, gp0_tpage_color_depth_width = 2,
|
||||||
gp0_tpage_dither_shift = 9, gp0_tpage_dither_width = 1,
|
gp0_tpage_dither_pos = 9, gp0_tpage_dither_width = 1,
|
||||||
gp0_tpage_draw_to_disp_shift = 10, gp0_tpage_draw_to_disp_width = 1,
|
gp0_tpage_draw_to_disp_pos = 10, gp0_tpage_draw_to_disp_width = 1,
|
||||||
gp0_tpage_tex_disable_shift = 11, gp0_tpage_tex_disable_width = 1,
|
gp0_tpage_tex_disable_pos = 11, gp0_tpage_tex_disable_width = 1,
|
||||||
|
|
||||||
/* TPage color-depth payload values (NOT bit positions — these go in
|
/* TPage color-depth payload values (NOT bit positions — these go in
|
||||||
* the 2-bit field at gp0_tpage_color_depth_shift). */
|
* the 2-bit field at gp0_tpage_color_depth_pos). */
|
||||||
gp0_tpage_color_4bpp = 0x0,
|
gp0_tpage_color_4bpp = 0x0,
|
||||||
gp0_tpage_color_8bpp = 0x1,
|
gp0_tpage_color_8bpp = 0x1,
|
||||||
gp0_tpage_color_16bpp = 0x2,
|
gp0_tpage_color_16bpp = 0x2,
|
||||||
@@ -572,7 +555,7 @@ enum {
|
|||||||
/* Default TPage value libpsyx's SetDefDrawEnv writes (matches the `li v1, 10; sh v1, 20(v0)` sequence at C11_only.elf:0x8001273C). */
|
/* Default TPage value libpsyx's SetDefDrawEnv writes (matches the `li v1, 10; sh v1, 20(v0)` sequence at C11_only.elf:0x8001273C). */
|
||||||
gp0_tpage_default = 10,
|
gp0_tpage_default = 10,
|
||||||
|
|
||||||
/* TPage semi-transparency mode payload values (NOT bit positions). */
|
/* TPage semi-transparency mode payload values. */
|
||||||
gp0_tpage_semi_trans_none = 0x0,
|
gp0_tpage_semi_trans_none = 0x0,
|
||||||
gp0_tpage_semi_trans_alpha = 0x1,
|
gp0_tpage_semi_trans_alpha = 0x1,
|
||||||
gp0_tpage_semi_trans_add = 0x2,
|
gp0_tpage_semi_trans_add = 0x2,
|
||||||
@@ -580,13 +563,13 @@ enum {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/* ---- Layer 1.5: TPage per-field encoders. Mirrors enc_gte_sf/mx/v in gte.h. ---- */
|
/* ---- Layer 1.5: TPage per-field encoders. Mirrors enc_gte_sf/mx/v in gte.h. ---- */
|
||||||
#define enc_gp0_tpage_x(x) ((x) << gp0_tpage_x_shift)
|
#define enc_gp0_tpage_x(x) ((x) << gp0_tpage_x_pos)
|
||||||
#define enc_gp0_tpage_y(y) ((y) << gp0_tpage_y_shift)
|
#define enc_gp0_tpage_y(y) ((y) << gp0_tpage_y_pos)
|
||||||
#define enc_gp0_tpage_semi_trans(s) ((s) << gp0_tpage_semi_trans_shift)
|
#define enc_gp0_tpage_semi_trans(s) ((s) << gp0_tpage_semi_trans_pos)
|
||||||
#define enc_gp0_tpage_color_depth(c) ((c) << gp0_tpage_color_depth_shift)
|
#define enc_gp0_tpage_color_depth(c) ((c) << gp0_tpage_color_depth_pos)
|
||||||
#define enc_gp0_tpage_dither(d) ((d) << gp0_tpage_dither_shift)
|
#define enc_gp0_tpage_dither(d) ((d) << gp0_tpage_dither_pos)
|
||||||
#define enc_gp0_tpage_draw_to_disp(d) ((d) << gp0_tpage_draw_to_disp_shift)
|
#define enc_gp0_tpage_draw_to_disp(d) ((d) << gp0_tpage_draw_to_disp_pos)
|
||||||
#define enc_gp0_tpage_tex_disable(t) ((t) << gp0_tpage_tex_disable_shift)
|
#define enc_gp0_tpage_tex_disable(t) ((t) << gp0_tpage_tex_disable_pos)
|
||||||
|
|
||||||
/* ---- Layer 2: TPage composite encoder. Mirrors enc_gte_cmdw in gte.h ---- */
|
/* ---- Layer 2: TPage composite encoder. Mirrors enc_gte_cmdw in gte.h ---- */
|
||||||
#define enc_gp0_tpage_word(x, y, semi_trans, color_depth, dither, draw_to_disp, tex_disable) \
|
#define enc_gp0_tpage_word(x, y, semi_trans, color_depth, dither, draw_to_disp, tex_disable) \
|
||||||
@@ -617,16 +600,16 @@ typedef Struct_(TexturePage) { U4 raw; };
|
|||||||
* ============================================================================ */
|
* ============================================================================ */
|
||||||
enum {
|
enum {
|
||||||
/* ---- Layer 1: CLUT bitfield shifts / widths ---- */
|
/* ---- Layer 1: CLUT bitfield shifts / widths ---- */
|
||||||
gp0_clut_y_shift = 0, gp0_clut_y_width = 6,
|
gp0_clut_y_pos = 0, gp0_clut_y_width = 6,
|
||||||
gp0_clut_x_shift = 6, gp0_clut_x_width = 9,
|
gp0_clut_x_pos = 6, gp0_clut_x_width = 9,
|
||||||
/* CLUT-load cmd-byte variants — the upper byte of the GP0 word. */
|
/* CLUT-load cmd-byte variants — the upper byte of the GP0 word. */
|
||||||
gp0_clut_cmd_Load4bpp = 0x20,
|
gp0_clut_cmd_Load4bpp = 0x20,
|
||||||
gp0_clut_cmd_Load8bpp = 0x25,
|
gp0_clut_cmd_Load8bpp = 0x25,
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ---- Layer 1.5: CLUT per-field encoders ---- */
|
/* ---- Layer 1.5: CLUT per-field encoders ---- */
|
||||||
#define enc_gp0_clut_x(x) ((x) << gp0_clut_x_shift)
|
#define enc_gp0_clut_x(x) ((x) << gp0_clut_x_pos)
|
||||||
#define enc_gp0_clut_y(y) ((y) << gp0_clut_y_shift)
|
#define enc_gp0_clut_y(y) ((y) << gp0_clut_y_pos)
|
||||||
|
|
||||||
/* ---- Layer 2: CLUT composite encoder ---- */
|
/* ---- Layer 2: CLUT composite encoder ---- */
|
||||||
#define enc_gp0_clut_word(cmd, x, y) (enc_gp0_cmd(cmd) | enc_gp0_clut_x(x) | enc_gp0_clut_y(y))
|
#define enc_gp0_clut_word(cmd, x, y) (enc_gp0_cmd(cmd) | enc_gp0_clut_x(x) | enc_gp0_clut_y(y))
|
||||||
|
|||||||
@@ -18,6 +18,42 @@ atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|||||||
load_half_u(r_i2, r_face_cusor, 2 * S_(S2)),
|
load_half_u(r_i2, r_face_cusor, 2 * S_(S2)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_gte_mv_to_cr_diag_v3s4(AtomBuilder_R ab, Reg_(V3_S4) v) MipsAtomComp_Proc_(ab, {
|
||||||
|
gte_mv_to_ctrl_r(v.y, gte_cr_RT13),
|
||||||
|
gte_mv_to_ctrl_r(v.z, gte_cr_RT22),
|
||||||
|
gte_mv_to_ctrl_r(v.x, gte_cr_RT11),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_gte_ld_ir123_v3s4(AtomBuilder_R ab, Reg_(V3_S4) v) MipsAtomComp_Proc_(ab, {
|
||||||
|
gte_mv_to_data_r(v.x, C2_IR1),
|
||||||
|
gte_mv_to_data_r(v.y, C2_IR2),
|
||||||
|
gte_mv_to_data_r(v.z, C2_IR3),
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ─── GTE OP cross product (a × b → a) ───
|
||||||
|
* Sets up RT diagonal from a.xyz, IR1/2/3 from b.xyz, fires OP,
|
||||||
|
* reads MAC1/2/3, shifts right 12 (S12.20 → S12.0 OuterProduct12), writes back to a.xyz.
|
||||||
|
* Composes the three sub-primitives (RT-load, IR-load, OP, MAC-read, shift)
|
||||||
|
* into one component for use by atoms that need the cross product inline.
|
||||||
|
*
|
||||||
|
* Output gpr (a) aliases source-A gpr; MAC read clobbers source-A's load targets,
|
||||||
|
* but by that point the RT load is complete and source A is dead.
|
||||||
|
* Pipeline: clobbers IR1..3, MAC1..3, RT11..33.
|
||||||
|
*
|
||||||
|
* The CPU→COP2 transfer chains (3 ctc2, 3 mtc2) require a 2-slot retirement gap,
|
||||||
|
* and the MFC2→GPR chain (3 mfc2) requires a 1-slot retirement gap, before the GPR can be read.
|
||||||
|
* The hazard nops are inlined below — same convention as ac_gte_gpf_scale — so any atom body inlining this component inherits them.
|
||||||
|
*
|
||||||
|
* Words: 18 (3 ctc2 + 2 nop + 3 mtc2 + 2 nop + 1 op + 3 mfc2 + 1 nop + 3 sra).
|
||||||
|
*/
|
||||||
|
FI_ Slice_MipsCode ac_gte_op_cross_v3s4(AtomBuilder_R ab, Reg_(V3_S4) a, Reg_(V3_S4) b) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
mac_gte_mv_to_cr_diag_v3s4(a), GteDelay_ /* RT diagonal: D1 = a.x, D2 = a.y, D3 = a.z */
|
||||||
|
mac_gte_ld_ir123_v3s4(b), GteDelay_ /* IR: second operand (b.xyz) */
|
||||||
|
gte_cmdw_cross, /* OP: MAC1/2/3 = a × b (S12.20) */
|
||||||
|
mac_gte_mv_from_mac123_v3s4(a), GteDelay_ /* Read MAC1/2/3 → a.xyz (overwrites source-A's load targets) */
|
||||||
|
mac_shift_aright_v3s4_self(a, 12), /* Right-shift MAC by 12 (S12.20 → S12.0 OuterProduct12) */
|
||||||
|
})
|
||||||
|
|
||||||
/* Words: 3; Stores the 3 transformed (V2_S2 screen) vertices to the F3.
|
/* Words: 3; Stores the 3 transformed (V2_S2 screen) vertices to the F3.
|
||||||
* PIPELINE: post-RTPT (SXY0=v0.screen, SXY1=v1.screen, SXY2=v2.screen). */
|
* PIPELINE: post-RTPT (SXY0=v0.screen, SXY1=v1.screen, SXY2=v2.screen). */
|
||||||
FI_ Slice_MipsCode ac_gte_store_f3(AtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
FI_ Slice_MipsCode ac_gte_store_f3(AtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
@@ -27,10 +63,10 @@ FI_ Slice_MipsCode ac_gte_store_f3(AtomBuilder_R ab, U4 r_primitive_cursor) atom
|
|||||||
})
|
})
|
||||||
|
|
||||||
/* Words: 18; Translates indices to vertex addresses and pushes them to GTE */
|
/* Words: 18; Translates indices to vertex addresses and pushes them to GTE */
|
||||||
I_ Slice_MipsCode ac_gte_load_tri_verts(AtomBuilder_R ab, U4 r_vert_base, U4 r_v0, U4 r_v1, U4 r_v2) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
I_ Slice_MipsCode ac_gte_load_tri_verts(AtomBuilder_R ab, Reg vbase, Reg v0, Reg v1, Reg v2) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
shift_lleft(R_AT, r_v0, v3s2_byteoff), add_u_self(R_AT, r_vert_base), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY0), gte_mv_to_data_r(R_V1, C2_VZ0),
|
shift_lleft(R_AT, v0, v3s2_byteoff), add_u_self(R_AT, vbase), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), LdSlot_ gte_mv_to_data_r(R_V0, C2_VXY0), gte_mv_to_data_r(R_V1, C2_VZ0),
|
||||||
shift_lleft(R_AT, r_v1, v3s2_byteoff), add_u_self(R_AT, r_vert_base), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY1), gte_mv_to_data_r(R_V1, C2_VZ1),
|
shift_lleft(R_AT, v1, v3s2_byteoff), add_u_self(R_AT, vbase), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), LdSlot_ gte_mv_to_data_r(R_V0, C2_VXY1), gte_mv_to_data_r(R_V1, C2_VZ1),
|
||||||
shift_lleft(R_AT, r_v2, v3s2_byteoff), add_u_self(R_AT, r_vert_base), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY2), gte_mv_to_data_r(R_V1, C2_VZ2),
|
shift_lleft(R_AT, v2, v3s2_byteoff), add_u_self(R_AT, vbase), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), LdSlot_ gte_mv_to_data_r(R_V0, C2_VXY2), gte_mv_to_data_r(R_V1, C2_VZ2),
|
||||||
})
|
})
|
||||||
|
|
||||||
/* Words: 3; Stores the 3 transformed (V2_S2 screen) vertices of the
|
/* Words: 3; Stores the 3 transformed (V2_S2 screen) vertices of the
|
||||||
@@ -38,7 +74,7 @@ I_ Slice_MipsCode ac_gte_load_tri_verts(AtomBuilder_R ab, U4 r_vert_base, U4 r_v
|
|||||||
* PIPELINE: post-RTPT, pre-RTPS (SXY0=v0.screen, SXY1=v1.screen, SXY2=v2.screen).
|
* PIPELINE: post-RTPT, pre-RTPS (SXY0=v0.screen, SXY1=v1.screen, SXY2=v2.screen).
|
||||||
* MUST be called BEFORE V3-RTPS, otherwise SXY0/1/2 get overwritten with v3
|
* MUST be called BEFORE V3-RTPS, otherwise SXY0/1/2 get overwritten with v3
|
||||||
* (RTPS writes only to SXY2, but to keep the three registers aligned with v0/v1/v2 you must store before RTPS). */
|
* (RTPS writes only to SXY2, but to keep the three registers aligned with v0/v1/v2 you must store before RTPS). */
|
||||||
FI_ Slice_MipsCode ac_gte_store_g4_p012(AtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
FI_ Slice_MipsCode ac_gte_store_g4_p012(AtomBuilder_R ab, Reg r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
gte_sw(C2_SXY0, r_primitive_cursor, O_(Poly_G4,p0)),
|
gte_sw(C2_SXY0, r_primitive_cursor, O_(Poly_G4,p0)),
|
||||||
gte_sw(C2_SXY1, r_primitive_cursor, O_(Poly_G4,p1)),
|
gte_sw(C2_SXY1, r_primitive_cursor, O_(Poly_G4,p1)),
|
||||||
gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_G4,p2)),
|
gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_G4,p2)),
|
||||||
@@ -51,9 +87,7 @@ FI_ Slice_MipsCode ac_gte_store_g4_p012(AtomBuilder_R ab, U4 r_primitive_cursor)
|
|||||||
FI_ Slice_MipsCode ac_gte_store_g4_p3(AtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ab, { gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_G4,p3)) })
|
FI_ Slice_MipsCode ac_gte_store_g4_p3(AtomBuilder_R ab, U4 r_primitive_cursor) atom_dbg_skip MipsAtomComp_Proc_(ab, { gte_sw(C2_SXY2, r_primitive_cursor, O_(Poly_G4,p3)) })
|
||||||
|
|
||||||
/* ─── STAGE 1 of normalize: SQR + mfc2 MAC1/2/3 ───
|
/* ─── STAGE 1 of normalize: SQR + mfc2 MAC1/2/3 ───
|
||||||
* Emits squared magnitude per component (in MAC1/2/3) into caller-provided scratch regs.
|
* Emits squared magnitude per component (in MAC1/2/3) into caller-provided scratch regs. */
|
||||||
* Stage 2 of normalize consumes these directly.
|
|
||||||
* Words: 8. Clobbers: IR1/2/3, MAC1/2/3. Uses gte_cmdw_sqr (sf=0, lm=1). */
|
|
||||||
FI_ Slice_MipsCode ac_gte_sqr_v3(AtomBuilder_R ab, U4 r_sx, U4 r_sy, U4 r_sz, U4 r_sq_x, U4 r_sq_y, U4 r_sq_z) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
FI_ Slice_MipsCode ac_gte_sqr_v3(AtomBuilder_R ab, U4 r_sx, U4 r_sy, U4 r_sz, U4 r_sq_x, U4 r_sq_y, U4 r_sq_z) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
mac_gte_sqr_v3s4(r_sx, r_sy, r_sz, nop),
|
mac_gte_sqr_v3s4(r_sx, r_sy, r_sz, nop),
|
||||||
gte_mv_from_data_r(r_sq_x, C2_MAC1),
|
gte_mv_from_data_r(r_sq_x, C2_MAC1),
|
||||||
@@ -61,16 +95,13 @@ FI_ Slice_MipsCode ac_gte_sqr_v3(AtomBuilder_R ab, U4 r_sx, U4 r_sy, U4 r_sz, U4
|
|||||||
gte_mv_from_data_r(r_sq_z, C2_MAC3),
|
gte_mv_from_data_r(r_sq_z, C2_MAC3),
|
||||||
})
|
})
|
||||||
|
|
||||||
/* ─── SQR FIRE — mtc2 3 GPRs into IR1/IR2/IR3, then fire SQR. ───
|
/* ─── SQR FIRE — mtc2 3 GPRs into IR1/IR2/IR3, then fire SQR. ─── */
|
||||||
* The SQR command always squares IR1/IR2/IR3 — those C2 registers are fixed.
|
FI_ Slice_MipsCode ac_gte_sqr_v3s4(AtomBuilder_R ab, Reg sx, Reg sy, Reg sz, MipsCode delay_slot)
|
||||||
* The GPRs holding the source vector are caller-determined.
|
|
||||||
* Words: 5 (3 mtc2 + 1 nop hazard + 1 cmd). */
|
|
||||||
FI_ Slice_MipsCode ac_gte_sqr_v3s4(AtomBuilder_R ab, Reg r_sx, Reg r_sy, Reg r_sz, MipsCode nop_slot)
|
|
||||||
atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
gte_mv_to_data_r(r_sx, C2_IR1),
|
gte_mv_to_data_r(sx, C2_IR1),
|
||||||
gte_mv_to_data_r(r_sy, C2_IR2),
|
gte_mv_to_data_r(sy, C2_IR2),
|
||||||
gte_mv_to_data_r(r_sz, C2_IR3),
|
gte_mv_to_data_r(sz, C2_IR3),
|
||||||
nop_slot, gte_cmdw_sqr,
|
delay_slot, gte_cmdw_sqr,
|
||||||
})
|
})
|
||||||
|
|
||||||
/* ─── STAGE 4 of normalize: mtc2 IR0..3 + GPF + mfc2 MAC + srav finalize ───
|
/* ─── STAGE 4 of normalize: mtc2 IR0..3 + GPF + mfc2 MAC + srav finalize ───
|
||||||
@@ -87,7 +118,7 @@ atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|||||||
gte_mv_to_data_r(r_sx, C2_IR1),
|
gte_mv_to_data_r(r_sx, C2_IR1),
|
||||||
gte_mv_to_data_r(r_sy, C2_IR2),
|
gte_mv_to_data_r(r_sy, C2_IR2),
|
||||||
gte_mv_to_data_r(r_sz, C2_IR3),
|
gte_mv_to_data_r(r_sz, C2_IR3),
|
||||||
nop2, /* retire IR0..IR3 → GPF input pre-fill (matches libgte 0x80016134..0x80016138) */
|
GteDelay_ nop2, /* retire IR0..IR3 → GPF input pre-fill (matches libgte 0x80016134..0x80016138) */
|
||||||
gte_cmdw_gpf,
|
gte_cmdw_gpf,
|
||||||
gte_mv_from_data_r(r_dx, C2_MAC1),
|
gte_mv_from_data_r(r_dx, C2_MAC1),
|
||||||
gte_mv_from_data_r(r_dy, C2_MAC2),
|
gte_mv_from_data_r(r_dy, C2_MAC2),
|
||||||
@@ -106,59 +137,33 @@ FI_ Slice_MipsCode ac_trans_mt3s3s4(AtomBuilder_R ab
|
|||||||
, U4 r_mtx, U4 r_off
|
, U4 r_mtx, U4 r_off
|
||||||
, U4 r_t0, U4 r_t1, U4 r_t2
|
, U4 r_t0, U4 r_t1, U4 r_t2
|
||||||
) MipsAtomComp_Proc_(ab, {
|
) MipsAtomComp_Proc_(ab, {
|
||||||
load_word(r_t0, r_off, O_(V3_S4,x)),
|
load_word( r_t0, r_off, O_(V3_S4,x)),
|
||||||
load_word(r_t1, r_off, O_(V3_S4,y)),
|
load_word( r_t1, r_off, O_(V3_S4,y)),
|
||||||
load_word(r_t2, r_off, O_(V3_S4,z)),
|
load_word( r_t2, r_off, O_(V3_S4,z)),
|
||||||
store_word(r_t0, r_mtx, O_(MT3_S2S4,t[0])),
|
store_word(r_t0, r_mtx, O_(MT3_S2S4,t[0])),
|
||||||
store_word(r_t1, r_mtx, O_(MT3_S2S4,t[1])),
|
store_word(r_t1, r_mtx, O_(MT3_S2S4,t[1])),
|
||||||
store_word(r_t2, r_mtx, O_(MT3_S2S4,t[2])),
|
store_word(r_t2, r_mtx, O_(MT3_S2S4,t[2])),
|
||||||
})
|
})
|
||||||
|
|
||||||
/* ─── LZCR ROUND EVEN + HALF-SHIFT ───
|
/* ─── LZCR ROUND EVEN + HALF-SHIFT ───
|
||||||
* Takes the raw LZCR leading-zero/ones count (from mfc2 C2_LZCR, range 1..32
|
* Takes the raw LZCR leading-zero/ones count (from mfc2 C2_LZCR, range 1..32 per PSX-SPX cop2r31) and the |v|² sum (in r_mag_sq from the MAC1+MAC2+MAC3 add).
|
||||||
* per PSX-SPX cop2r31) and the |v|² sum (in r_mag_sq from the MAC1+MAC2+MAC3
|
* Produces:
|
||||||
* add). Produces:
|
|
||||||
* r_shift ← LZCR rounded down to even (clear bit 0)
|
* r_shift ← LZCR rounded down to even (clear bit 0)
|
||||||
* r_mag_sq_copy ← |v|² sum (moved out of r_mag_sq before it's overwritten)
|
* r_mag_sq_copy ← |v|² sum (moved out of r_mag_sq before it's overwritten)
|
||||||
* r_mag_sq ← (31 - even_LZCR) / 2 = the final srav/GPF shift amount
|
* r_mag_sq ← (31 - even_LZCR) / 2 = the final srav/GPF shift amount
|
||||||
*
|
*
|
||||||
* Rounding to even ensures (31 - LZCR) is always odd, so the >> 1 division
|
* Rounding to even ensures (31 - LZCR) is always odd, so the >> 1 division is consistent — no 0.5 loss.
|
||||||
* is consistent — no 0.5 loss. The caller branches on LZCR < 24 to decide
|
* The caller branches on LZCR < 24 to decide left-shift vs right-shift of r_mag_sq_copy, then saves the shift count.
|
||||||
* left-shift vs right-shift of r_mag_sq_copy, then saves the shift count.
|
|
||||||
*
|
*
|
||||||
* Note: C2_LZCR (cop2r31) is a fixed read-only C2 data register — the caller
|
* Note: C2_LZCR (cop2r31) is a fixed read-only C2 data register — the caller must read it via mfc2 from C2_LZCR;
|
||||||
* must read it via mfc2 from C2_LZCR; there is no register choice at the
|
* there is no register choice at the hardware level. Only the GPR that holds the result is caller-determined. */
|
||||||
* hardware level. Only the GPR that holds the result is caller-determined. */
|
FI_ Slice_MipsCode ac_lzcr_round_even_half_shift(AtomBuilder_R ab, Reg shift, Reg mag_sq, Reg mag_sq_copy)
|
||||||
FI_ Slice_MipsCode ac_lzcr_round_even_half_shift(AtomBuilder_R ab,
|
|
||||||
U4 r_shift,
|
|
||||||
U4 r_mag_sq,
|
|
||||||
U4 r_mag_sq_copy
|
|
||||||
)
|
|
||||||
atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
and_i(r_shift, r_shift, gte_lzcr_even_mask),
|
and_i(shift, shift, gte_lzcr_even_mask),
|
||||||
or_u(r_mag_sq_copy, r_mag_sq, 0),
|
or_u(mag_sq_copy, mag_sq, 0),
|
||||||
li_s(r_mag_sq, 31),
|
li_s( mag_sq, 31),
|
||||||
sub_s(r_mag_sq, r_mag_sq, r_shift),
|
sub_s( mag_sq, mag_sq, shift),
|
||||||
shift_aright(r_mag_sq, r_mag_sq, 1),
|
shift_aright(mag_sq, mag_sq, 1),
|
||||||
})
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_shift_aright_var_v3(AtomBuilder_R ab
|
|
||||||
, Reg rd_v0, Reg rd_v1, Reg rd_v2
|
|
||||||
, Reg rs_v0, Reg rs_v1, Reg rs_v2
|
|
||||||
, Reg r_shift)
|
|
||||||
MipsAtomComp_Proc_(ab, {
|
|
||||||
shift_aright_var(rd_v0, rs_v0, r_shift),
|
|
||||||
shift_aright_var(rd_v1, rs_v1, r_shift),
|
|
||||||
shift_aright_var(rd_v2, rs_v2, r_shift),
|
|
||||||
})
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_shift_aright_var_v3_self(AtomBuilder_R ab
|
|
||||||
, Reg rds_v0, Reg rds_v1, Reg rds_v2
|
|
||||||
, Reg r_shift)
|
|
||||||
MipsAtomComp_Proc_(ab, {
|
|
||||||
shift_aright_var(rds_v0, rds_v0, r_shift),
|
|
||||||
shift_aright_var(rds_v1, rds_v1, r_shift),
|
|
||||||
shift_aright_var(rds_v2, rds_v2, r_shift),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_gte_general_purpose_interopolation(AtomBuilder_R ab
|
FI_ Slice_MipsCode ac_gte_general_purpose_interopolation(AtomBuilder_R ab
|
||||||
@@ -170,31 +175,32 @@ MipsAtomComp_Proc_(ab, {
|
|||||||
gte_mv_to_data_r(to_ir1, C2_IR1), /* IR1 = src.x (preserved in r_tmp — r_mac2_scratch was clobbered to MAC2 in stage 1.5) */
|
gte_mv_to_data_r(to_ir1, C2_IR1), /* IR1 = src.x (preserved in r_tmp — r_mac2_scratch was clobbered to MAC2 in stage 1.5) */
|
||||||
gte_mv_to_data_r(to_ir2, C2_IR2),
|
gte_mv_to_data_r(to_ir2, C2_IR2),
|
||||||
gte_mv_to_data_r(to_ir3, C2_IR3), /* IR3 = src.z (reloaded) */
|
gte_mv_to_data_r(to_ir3, C2_IR3), /* IR3 = src.z (reloaded) */
|
||||||
LdSlot_ nop_slot1,
|
GteDelay_ nop_slot1,
|
||||||
LdSlot_ nop_slot2,
|
GteDelay_ nop_slot2,
|
||||||
gte_cmdw_gpf,
|
gte_cmdw_gpf,
|
||||||
gte_mv_from_data_r(fr_mac1, C2_MAC1),
|
gte_mv_from_data_r(fr_mac1, C2_MAC1),
|
||||||
gte_mv_from_data_r(fr_mac2, C2_MAC2),
|
gte_mv_from_data_r(fr_mac2, C2_MAC2),
|
||||||
gte_mv_from_data_r(fr_mac3, C2_MAC3),
|
gte_mv_from_data_r(fr_mac3, C2_MAC3),
|
||||||
})
|
})
|
||||||
|
|
||||||
FI_ Slice_MipsCode gte_mv_from_data_r_mac123(AtomBuilder_R ab
|
FI_ Slice_MipsCode ac_gte_mv_from_data_r_mac123(AtomBuilder_R ab
|
||||||
, Reg fr_mac1, Reg fr_mac2, Reg fr_mac3
|
, Reg fr_mac1, Reg fr_mac2, Reg fr_mac3)
|
||||||
)
|
|
||||||
MipsAtomComp_Proc_(ab, {
|
MipsAtomComp_Proc_(ab, {
|
||||||
gte_mv_from_data_r(fr_mac1, C2_MAC1),
|
gte_mv_from_data_r(fr_mac1, C2_MAC1),
|
||||||
gte_mv_from_data_r(fr_mac2, C2_MAC2),
|
gte_mv_from_data_r(fr_mac2, C2_MAC2),
|
||||||
gte_mv_from_data_r(fr_mac3, C2_MAC3),
|
gte_mv_from_data_r(fr_mac3, C2_MAC3),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_gte_mv_from_mac123_v3s4(AtomBuilder_R ab, Reg_(V3_S4) v) MipsAtomComp_ProcMap_(ab, mac_gte_mv_from_data_r_mac123(v.x, v.y, v.z))
|
||||||
|
|
||||||
#pragma endregion MACs (Mips Atom Components)
|
#pragma endregion MACs (Mips Atom Components)
|
||||||
|
|
||||||
#pragma region Atom Procs
|
#pragma region Atom Procs
|
||||||
|
|
||||||
/* ─── Local copy of PSYQ's sqrtbl (1/sqrt lookup table for VectorNormal). ───
|
/* ─── Local copy of PSYQ's sqrtbl (1/sqrt lookup table for VectorNormal). ───
|
||||||
* Source: PSYQ 4.7 libgte sqrtbl at 0x800185B4 in hello_camera.elf.
|
* Source: PSYQ 4.7 libgte sqrtbl at 0x800185B4 in hello_camera.elf.
|
||||||
* objdump -s --start-address=0x800185B4 --stop-address=0x800185F4 hello_camera.elf
|
* objdump -s --start-address=0x800185B4 --stop-address=0x800185F4 hello_camera.elf → 192 entries × 16-bit signed, in 1.12 fixed-point (max value 0x1000 = 1.0).
|
||||||
* → 192 entries × 16-bit signed, in 1.12 fixed-point (max value 0x1000 = 1.0).
|
|
||||||
*
|
*
|
||||||
* Data is identical to the libgte original (byte-for-byte verified).
|
* Data is identical to the libgte original (byte-for-byte verified).
|
||||||
*
|
*
|
||||||
@@ -229,7 +235,8 @@ MipsAtomComp_Proc_(ab, {
|
|||||||
* and the load upper_halves of the table bracket the input range.
|
* and the load upper_halves of the table bracket the input range.
|
||||||
* The later 64 entries (octaves 2-3) are the `srav` branch when the magnitude's top bit is well above bit 24.
|
* The later 64 entries (octaves 2-3) are the `srav` branch when the magnitude's top bit is well above bit 24.
|
||||||
*
|
*
|
||||||
* 192-entry table is reproduced verbatim from libgte (verified against libpsn00b/psxgte/vector.s:100-123 — 24 rows × 8 halfwords, last entry 0x0804). */
|
* Reproduced verbatim from libgte (verified against libpsn00b/psxgte/vector.s:100-123 — 24 rows × 8 halfwords, last entry 0x0804).
|
||||||
|
* */
|
||||||
internal S2 const gte_normalize_sqr_tbl[192] align_(2) = {
|
internal S2 const gte_normalize_sqr_tbl[192] align_(2) = {
|
||||||
0x1000, 0x0fe0, 0x0fc1, 0x0fa3, 0x0f85, 0x0f68, 0x0f4c, 0x0f30,
|
0x1000, 0x0fe0, 0x0fc1, 0x0fa3, 0x0f85, 0x0f68, 0x0f4c, 0x0f30,
|
||||||
0x0f15, 0x0efb, 0x0ee1, 0x0ec7, 0x0eae, 0x0e96, 0x0e7e, 0x0e66,
|
0x0f15, 0x0efb, 0x0ee1, 0x0ec7, 0x0eae, 0x0e96, 0x0e7e, 0x0e66,
|
||||||
@@ -257,110 +264,96 @@ internal S2 const gte_normalize_sqr_tbl[192] align_(2) = {
|
|||||||
0x0820, 0x081c, 0x0818, 0x0814, 0x0810, 0x080c, 0x0808, 0x0804,
|
0x0820, 0x081c, 0x0818, 0x0814, 0x0810, 0x080c, 0x0808, 0x0804,
|
||||||
};
|
};
|
||||||
|
|
||||||
#define RegUse_(proc_name) (tmpl(RegUse,proc_name))
|
typedef Struct_(Binds_normalize_v3s4) {
|
||||||
typedef Struct_(RegUse_normalize_v3s4_proc) {
|
U2 src_offset; /* offset of src V3_S4 within the BIOS scratchpad */
|
||||||
Reg scratch; // Scratch base carrier.
|
U2 dst_offset; /* offset of dst V3_S4 within the BIOS scratchpad */
|
||||||
Reg src_ptr;
|
};
|
||||||
Reg dst_ptr;
|
typedef Struct_(RegUse_normalize_v3s4) {
|
||||||
Reg recip_est; // |v|² sum + shift-input + sqrtbl[index]
|
union { Reg_(V3_S4) res, src; };
|
||||||
Reg norm; Reg shift;
|
union { Reg r0, src_ptr, mac2; };
|
||||||
Reg src_x;
|
union { Reg r1, dst_ptr; };
|
||||||
union { Reg mac1_scratch; } t3;
|
union { Reg r2, dst_offset, mac1, v_sqr_aligned; };
|
||||||
union { Reg mac2_scratch; } t4;
|
union { Reg r3, src_offset, btarget, shift_count, sqrtbl_index; };
|
||||||
union { Reg shift_count, btarget, lookup_addr, src_z; } t5;
|
union { Reg r4, mac3, v_sqr_sum, scale_exp, srav_shift; };
|
||||||
|
union { Reg r5, lzcr, inv_len; };
|
||||||
};
|
};
|
||||||
/* ─── Full normalize (all 4 stages inline) ───
|
/* ─── Full normalize (all 4 stages inline) ───
|
||||||
* Generic 4-stage GTE normalize (SQR → sum+LZCR → align+sqrtbl → GPF+srav).
|
* Generic 4-stage GTE normalize (SQR → sum+LZCR → align+sqrtbl → GPF+srav). */
|
||||||
*
|
internal MipsAtom* normalize_v3s4(AtomArena_R aa, RegUse_normalize_v3s4 r)
|
||||||
* Parameterized by caller-provided scratch base + src/dst offsets.
|
|
||||||
* The caller passes r_src_offset and r_dst_offset as compile-time constants
|
|
||||||
* (typically derived from O_ macros in the caller's struct schema, e.g., `O_(CallerBundleScratch, fwd)`).
|
|
||||||
*
|
|
||||||
* This design lets any caller (with a scratch base + struct schema) use `normalize_v3s4_proc`
|
|
||||||
* without putting magic offsets in the C-side bundle helper — the offsets come from O_ macros at the call site.
|
|
||||||
*
|
|
||||||
* Body uses 9 GPRs (r_src_ptr..r_branch_tmp):
|
|
||||||
* r_src_ptr, r_dst_ptr : src/dst pointers (computed from r_scratch + caller offsets)
|
|
||||||
* r_tmp : src.x PRESERVED across stages 1-2 (NOT clobbered by mfc2 MAC2) → fed to IR1 in stage 4
|
|
||||||
* r_mac1_scratch : MAC1 result scratch (also holds aligned |v|² in stage 3)
|
|
||||||
* r_mac2_scratch : MAC2 result scratch → result.x after stage 4 sra
|
|
||||||
* r_recip_est : src.y PRESERVED across stages 1-2 → fed to IR2 in stage 4 → result.y
|
|
||||||
* r_norm : |v|² sum (stage 2) → half-shift (stage 3) → 1/|v| (stage 4 IR0)
|
|
||||||
* r_shift : shift count SAVED in stage 3 → consumed by stage 4 srav
|
|
||||||
* r_branch_tmp : src.z PRESERVED across stages 1-2 → fed to IR3 in stage 4 → result.z (also sqrtbl base addr)
|
|
||||||
*
|
|
||||||
* Atom_labels are srav_path / aligned_done
|
|
||||||
* (NOT namespaced — they're internal to this proc;
|
|
||||||
* the metaprogram's per-atom-name enum emission handles any collision across different atoms/files that share the same labels).
|
|
||||||
*
|
|
||||||
* Pool cost: 11 GPRs (well within the 9-10 caller-trash GPR budget when r_scratch is a wave-context carrier).
|
|
||||||
*
|
|
||||||
* Direct port of PSYQ libgte msc02.rel.text VectorNormal disassembly (0x800160a0..0x8001615c).
|
|
||||||
* Words: ~59 (matches libgte 0x800160a0..0x8001615c at +/- 0-2 words for BD-slot reshuffling).
|
|
||||||
* Sqrtbl: hardcoded to 0x800185B4 (libgte msc02.rel.data). Note: swapped to local.
|
|
||||||
* Pipeline: clobbers IR0..3, MAC1..3, LZCS, LZCR.
|
|
||||||
*/
|
|
||||||
internal MipsAtom* normalize_v3s4_proc(AtomArena_R aa, U2 src_offset, U2 dst_offset, RegUse_normalize_v3s4_proc r)
|
|
||||||
MipsAtom_Proc_(aa, {
|
MipsAtom_Proc_(aa, {
|
||||||
add_si(r.src_ptr, r.scratch, src_offset), /* r_src_ptr = &src */
|
load_half(r.src_offset, R_TapePtr, O_(Binds_normalize_v3s4, src_offset)),
|
||||||
|
load_half(r.dst_offset, R_TapePtr, O_(Binds_normalize_v3s4, dst_offset)),
|
||||||
|
LdSlot_ add_u(r.src_ptr, R_ScratchBase, r.src_offset),
|
||||||
|
LdSlot_ add_u(r.dst_ptr, R_ScratchBase, r.dst_offset),
|
||||||
|
LdSlot_ add_ui_self(R_TapePtr, S_(Binds_normalize_v3s4)),
|
||||||
|
|
||||||
/* Load src.x/y/z from r_src_ptr (caller-determined address) into r_tmp/r_recip_est/r_branch_tmp.
|
mac_load_v3s4(r.src, r.src_ptr, 0),
|
||||||
* r.rt1_src_x holds src.x throughout stages 1-2 — r_mac2_scratch is clobbered to MAC2 in stage 1.5 (line below). */
|
|
||||||
mac_load_v3s4(r.src_x, r.recip_est, r.t5.lookup_addr, r.src_ptr, 0),
|
|
||||||
|
|
||||||
/* Stage 1: mtc2 src → IR1/2/3, SQR fires. */
|
/* Stage 1: mtc2 src → IR1/2/3, SQR fires. */
|
||||||
LdSlot_ mac_gte_sqr_v3s4(r.src_x, r.recip_est, r.t5.src_z, LdSlot_ nop),
|
LdSlot_ mac_gte_sqr_v3s4(r.src.x, r.src.y, r.src.z, LdSlot_ nop),
|
||||||
|
|
||||||
/* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS. */
|
/* Stage 2: mfc2 MAC1/2/3, sum, mtc2 LZCS. src_ptr is dead; reuse as mac2. */
|
||||||
mac_gte_mv_from_data_r_mac123(r.t3.mac1_scratch, r.t4.mac2_scratch, r.norm), LdSlot_ nop,
|
mac_gte_mv_from_data_r_mac123(r.mac1, r.mac2, r.mac3), LdSlot_ nop,
|
||||||
add_u_self( r.norm, r.t3.mac1_scratch),
|
add_u_self( r.v_sqr_sum, r.mac1),
|
||||||
add_u_self( r.norm, r.t4.mac2_scratch),
|
add_u_self( r.v_sqr_sum, r.mac2),
|
||||||
gte_mv_to_data_r( r.norm, C2_LZCS), LdSlot_ nop2,
|
gte_mv_to_data_r( r.v_sqr_sum, C2_LZCS), GteDelay_ nop2,
|
||||||
gte_mv_from_data_r(r.shift, C2_LZCR), LdSlot_ nop,
|
gte_mv_from_data_r(r.lzcr, C2_LZCR), GteDelay_ nop,
|
||||||
|
|
||||||
/* Stage 3: round LZCR to even, compute half-shift, align |v|² to bit 24.
|
/* Stage 3: even(LZCR), half-shift, align |v|² to bit 24. */
|
||||||
* r_norm holds |v|² sum; r_shift holds the LZCR count from mfc2.
|
mac_lzcr_round_even_half_shift(r.lzcr, r.v_sqr_sum, r.v_sqr_aligned),
|
||||||
* After the component: r_shift = even(LZCR), r_norm = half-shift, r_mac1_scratch = |v|². */
|
add_si( r.btarget, r.lzcr, -24),
|
||||||
mac_lzcr_round_even_half_shift(r.shift, r.norm, r.t3.mac1_scratch),
|
branch_lt_zero(r.btarget, atom_offset(aligned_done, srav_path)), BdSlot_ nop, /* bltz → srav_path (LZCR < 24 path) */
|
||||||
/* r_branch_tmp = LZCR - 24 (overwrites r_branch_tmp; src.z no longer needed after SQR) */
|
|
||||||
add_si( r.t5.btarget, r.shift, -24),
|
|
||||||
branch_lt_zero(r.t5.btarget, atom_offset(aligned_done, srav_path)), BdSlot_ nop, /* bltz → srav_path (LZCR < 24 path) */
|
|
||||||
jump_rel(atom_offset(srav_path, aligned_done)), /* b → aligned_done (LZCR >= 24 path) */
|
jump_rel(atom_offset(srav_path, aligned_done)), /* b → aligned_done (LZCR >= 24 path) */
|
||||||
BdSlot_ shift_lleft_var(r.t3.mac1_scratch, r.t3.mac1_scratch, r.t5.btarget), /* src=sum (r_mac1_scratch), dst=same */
|
BdSlot_ shift_lleft_var(r.v_sqr_aligned, r.v_sqr_aligned, r.btarget),
|
||||||
atom_label(srav_path)
|
atom_label(srav_path)
|
||||||
li_s( r.t5.shift_count, 24),
|
li_s( r.shift_count, 24),
|
||||||
sub_s(r.t5.shift_count, r.t5.shift_count, r.shift),
|
sub_s(r.shift_count, r.shift_count, r.lzcr),
|
||||||
shift_aright_var(r.t3.mac1_scratch, r.t3.mac1_scratch, r.t5.shift_count), /* src=sum (r_mac1_scratch), dst=same */
|
shift_aright_var(r.v_sqr_aligned, r.v_sqr_aligned, r.shift_count),
|
||||||
atom_label(aligned_done)
|
atom_label(aligned_done)
|
||||||
// Save the shift count to r_shift before the next 5 instructions overwrite r_norm (the sqrtbl lookup loads 1/|v| into r_norm, which becomes IR0 in stage 4).
|
add_si( r.v_sqr_aligned, r.v_sqr_aligned, -64),
|
||||||
or_u(r.shift, r.norm, 0), /* r_shift ← shift count (preserved through stage 4) */
|
shift_lleft(r.v_sqr_aligned, r.v_sqr_aligned, 1),
|
||||||
/* r_mac1_scratch holds |v|² aligned (top bit at bit 7). */
|
mac_load_word_imm(r.sqrtbl_index, & gte_normalize_sqr_tbl), add_u_self(r.sqrtbl_index, r.v_sqr_aligned),
|
||||||
add_si( r.t3.mac1_scratch, r.t3.mac1_scratch, -64),
|
load_half(r.inv_len, r.sqrtbl_index, 0),
|
||||||
shift_lleft(r.t3.mac1_scratch, r.t3.mac1_scratch, 1),
|
LdSlot_ nop,
|
||||||
mac_load_word_imm(r.t5.lookup_addr, & gte_normalize_sqr_tbl), add_u_self(r.t5.lookup_addr, r.t3.mac1_scratch),
|
|
||||||
load_half(r.norm, r.t5.lookup_addr, 0), /* r_norm = sqrtbl[aligned-64] = 1/|v| (IR0 in stage 4) */
|
|
||||||
|
|
||||||
/* r_branch_tmp held the sqrtbl base+index, NOT src.z. Reload src.z from scratch now that r_branch_tmp is free. */
|
mac_gte_general_purpose_interopolation(r.inv_len,
|
||||||
LdSlot_ load_word(r.t5.src_z, r.src_ptr, O_(V3_S4,z)), /* r_branch_tmp = src.z (for IR3 in stage 4) */
|
r.src.x, r.src.y, r.src.z,
|
||||||
|
r.res.x, r.res.y, r.res.z,
|
||||||
/* Stage 4: GPF + srav finalize (r_shift = shift count, r_norm = 1/|v|). */
|
GteDelay_ load_word(R_AtomJmp, R_TapePtr, 0), LdSlot_ // ac_yield: word 1
|
||||||
LdSlot_ mac_gte_general_purpose_interopolation(
|
GteDelay_ add_ui_self( R_TapePtr, S_(MipsCode)) // ac_yield: word 2
|
||||||
r.norm,
|
|
||||||
r.src_x, /* IR1 = src.x (preserved in r_tmp — r_mac2_scratch was clobbered to MAC2 in stage 1.5) */
|
|
||||||
r.recip_est,
|
|
||||||
r.t5.src_z, /* IR3 = src.z (reloaded) */
|
|
||||||
r.t4.mac2_scratch, r.recip_est, r.t5.src_z,
|
|
||||||
LdSlot_ add_si(r.dst_ptr, r.scratch, dst_offset), // pre-laoding destination to register here.
|
|
||||||
LdSlot_ nop
|
|
||||||
),
|
),
|
||||||
/* sra by r_shift = (31-LZCR)/2 (saved before sqrtbl lookup) */
|
mac_shift_aright_var_v3s4_self(r.res, r.srav_shift),
|
||||||
mac_shift_aright_var_v3_self(r.t4.mac2_scratch, r.recip_est, r.t5.src_z, r.shift),
|
mac_store_v3s4(r.res, r.dst_ptr, 0),
|
||||||
/* Store result.x/y/z to r_dst_ptr (caller-determined dst address). */
|
|
||||||
mac_store_v3s4(r.t4.mac2_scratch, r.recip_est, r.t5.src_z, r.dst_ptr, 0),
|
jump_reg(R_AtomJmp), BdSlot_ nop // ac_yield: word 3-4
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
/* ─── GTE OP cross product (a × b → out) ───
|
||||||
|
* Generalized V3_S4 cross product via GTE OP (OuterProduct12 libpsyx convention).
|
||||||
|
* The >> 12 shift converts S12.20 → S12.0 OuterProduct12. */
|
||||||
|
typedef Struct_(Binds_gte_cross_v3s4) { V3_S4* src_a; V3_S4* src_b; V3_S4* out; };
|
||||||
|
typedef Struct_(RegUse_gte_cross_v3s4) {
|
||||||
|
Reg_(V3_S4) a;
|
||||||
|
Reg_(V3_S4) b;
|
||||||
|
Reg out;
|
||||||
|
Reg src_a;
|
||||||
|
Reg src_b;
|
||||||
|
};
|
||||||
|
internal MipsAtom* gte_cross_v3s4(AtomArena_R aa, RegUse_gte_cross_v3s4 r)
|
||||||
|
atom_info(atom_bind(Binds_gte_cross_v3s4)) MipsAtom_Proc_(aa, {
|
||||||
|
load_word(r.src_a, R_TapePtr, O_(Binds_gte_cross_v3s4,src_a)),
|
||||||
|
load_word(r.src_b, R_TapePtr, O_(Binds_gte_cross_v3s4,src_b)),
|
||||||
|
load_word(r.out, R_TapePtr, O_(Binds_gte_cross_v3s4,out)),
|
||||||
|
LdSlot_ add_ui_self(R_TapePtr, S_(Binds_gte_cross_v3s4)),
|
||||||
|
|
||||||
|
mac_load_v3s4(r.a, r.src_a, 0), LdSlot_
|
||||||
|
mac_load_v3s4(r.b, r.src_b, 0), LdSlot_
|
||||||
|
mac_gte_op_cross_v3s4(r.a, r.b), /* RT diagonal + IR + OP + MAC read + shift */
|
||||||
|
mac_store_v3s4(r.a, r.out, 0),
|
||||||
|
|
||||||
mac_yield()
|
mac_yield()
|
||||||
})
|
})
|
||||||
|
|
||||||
#pragma endregion Atom Procs
|
#pragma endregion Atom Procs
|
||||||
|
|
||||||
#pragma region Baked Atoms
|
#pragma region Baked Atoms
|
||||||
@@ -376,12 +369,22 @@ internal MipsAtom_(set_gte_mt3s2s4) atom_info(
|
|||||||
load_word(R_T3, R_TapePtr, O_(Binds_SetGteMT3S2S4,transform)),
|
load_word(R_T3, R_TapePtr, O_(Binds_SetGteMT3S2S4,transform)),
|
||||||
add_ui_self( R_TapePtr, S_(Binds_SetGteMT3S2S4)),
|
add_ui_self( R_TapePtr, S_(Binds_SetGteMT3S2S4)),
|
||||||
/* Load 3x3 Rotation + 3x1 Translation from R_T3 into GTE CONTROL Regs (ctc2) */
|
/* Load 3x3 Rotation + 3x1 Translation from R_T3 into GTE CONTROL Regs (ctc2) */
|
||||||
load_word(R_T0, R_T3, 0), load_word(R_T1, R_T3, 4),
|
load_word(R_T0, R_T3, 0),
|
||||||
gte_mv_to_ctrl_r(R_T0, gte_cr_RT11), gte_mv_to_ctrl_r(R_T1, gte_cr_RT12),
|
load_word(R_T1, R_T3, 4),
|
||||||
load_word(R_T0, R_T3, 8), load_word(R_T1, R_T3, 12), load_word(R_T2, R_T3, 16),
|
gte_mv_to_ctrl_r(R_T0, gte_cr_RT11),
|
||||||
gte_mv_to_ctrl_r(R_T0, gte_cr_RT13), gte_mv_to_ctrl_r(R_T1, gte_cr_RT21), gte_mv_to_ctrl_r(R_T2, gte_cr_RT22),
|
gte_mv_to_ctrl_r(R_T1, gte_cr_RT12),
|
||||||
load_word(R_T0, R_T3, 20), load_word(R_T1, R_T3, 24), load_word(R_T2, R_T3, 28),
|
load_word(R_T0, R_T3, 8),
|
||||||
gte_mv_to_ctrl_r(R_T0, gte_cr_TRX), gte_mv_to_ctrl_r(R_T1, gte_cr_TRY), gte_mv_to_ctrl_r(R_T2, gte_cr_TRZ),
|
load_word(R_T1, R_T3, 12),
|
||||||
|
load_word(R_T2, R_T3, 16),
|
||||||
|
gte_mv_to_ctrl_r(R_T0, gte_cr_RT13),
|
||||||
|
gte_mv_to_ctrl_r(R_T1, gte_cr_RT21),
|
||||||
|
gte_mv_to_ctrl_r(R_T2, gte_cr_RT22),
|
||||||
|
load_word(R_T0, R_T3, 20),
|
||||||
|
load_word(R_T1, R_T3, 24),
|
||||||
|
load_word(R_T2, R_T3, 28),
|
||||||
|
gte_mv_to_ctrl_r(R_T0, gte_cr_TRX),
|
||||||
|
gte_mv_to_ctrl_r(R_T1, gte_cr_TRY),
|
||||||
|
gte_mv_to_ctrl_r(R_T2, gte_cr_TRZ),
|
||||||
mac_yield()
|
mac_yield()
|
||||||
};
|
};
|
||||||
|
|
||||||
+54
-92
@@ -1,24 +1,10 @@
|
|||||||
/* ============================================================================
|
/* ============================================================================
|
||||||
* duffle DSL Suffix Conventions
|
* duffle DSL Suffix Conventions
|
||||||
* ============================================================================
|
* ============================================================================
|
||||||
*
|
|
||||||
* Every mnemonic in this header follows the same suffix grammar:
|
* Every mnemonic in this header follows the same suffix grammar:
|
||||||
*
|
*
|
||||||
* Primitive commands: gp0_cmd_poly_f3 = 0x20 (byte opcode)
|
* Primitive commands: gp0_cmd_poly_f3 = 0x20 (byte opcode)
|
||||||
* Packed 32-bit cmd: gp0_word_poly_f3(r, g, b) (32-bit, shifted)
|
* Packed 32-bit cmd: gp0_word_poly_f3(r, g, b) (32-bit, shifted)
|
||||||
*
|
|
||||||
* Type ordering: domain?_(direction)?_action_target_modifier_type?
|
|
||||||
* Examples: add_ui (add + unsigned + immediate)
|
|
||||||
* add_s (add + signed, R-type implicit)
|
|
||||||
* shift_lleft (shift + logical + left)
|
|
||||||
* shift_aright (shift + arithmetic + right)
|
|
||||||
* call_reg(rs) (call + register, $ra implicit)
|
|
||||||
* gte_mv_to_data_r (gte + mv + to + data + register)
|
|
||||||
* gte_lw_v0_xy(base) (gte + lw + v0 + xy)
|
|
||||||
* load_upper_i (load-upper + immediate, unique verb)
|
|
||||||
*
|
|
||||||
* Vendor mnemonics (gte_mtc2, gte_mfc2, gte_lwc2, gte_swc2, etc.) are NOT in this header.
|
|
||||||
* They are in the opt-in `gte_vendor_sym.h` for users who prefer the textbook MIPS assembly mnemonics.
|
|
||||||
* ============================================================================ */
|
* ============================================================================ */
|
||||||
|
|
||||||
#ifdef INTELLISENSE_DIRECTIVES
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
@@ -32,21 +18,7 @@
|
|||||||
/* ============================================================================
|
/* ============================================================================
|
||||||
* gte.h — Geometry Transformation Engine (COP2) for the PS1
|
* gte.h — Geometry Transformation Engine (COP2) for the PS1
|
||||||
* ============================================================================
|
* ============================================================================
|
||||||
*
|
* DSL for emitting GTE/MIPS instruction words from C.
|
||||||
* Hand-rolled DSL for emitting GTE/MIPS instruction words as raw `.word` constants from C.
|
|
||||||
* No GCC inline-assembly string syntax in the code body.
|
|
||||||
*
|
|
||||||
* STYLE NOTES
|
|
||||||
* -----------
|
|
||||||
* - Per-field encoders are named `enc_gte_<field>(value)` and each one self-masks its argument before shifting.
|
|
||||||
* Mirrors the `enc_op / enc_rs / enc_rt / ...` family in mips.h.
|
|
||||||
* - The composite `enc_gte_cmdw(sf, mx, v, cv, lm, cmd)` is a flat OR of the per-field encoders, plus the COP2/CO base.
|
|
||||||
* - Pre-baked shortcuts (`gte_cmd_rtpt`, `gte_cmd_rtps`, …) are defined for the common cases so call sites read like assembly source.
|
|
||||||
* - All register/field values are enums (not `#define`s) so they show up in debugger symbol tables and IDE autocomplete.
|
|
||||||
*
|
|
||||||
* SEE ALSO
|
|
||||||
* --------
|
|
||||||
* - mips.h: The MIPS encoder layer this builds on.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* C2 data registers */
|
/* C2 data registers */
|
||||||
@@ -101,20 +73,20 @@ enum {
|
|||||||
|
|
||||||
/* Semantic Aliases for GTE Data Registers */
|
/* Semantic Aliases for GTE Data Registers */
|
||||||
enum {
|
enum {
|
||||||
gte_in_v0_xy = C2_VXY0, /* Input Vector 0 (X, Y) */
|
C2_InV0_XY = C2_VXY0, /* Input Vector 0 (X, Y) */
|
||||||
gte_in_v0_z = C2_VZ0, /* Input Vector 0 (Z) */
|
C2_InV0_Z = C2_VZ0, /* Input Vector 0 (Z) */
|
||||||
gte_in_v1_xy = C2_VXY1, /* Input Vector 1 (X, Y) */
|
C2_InV1_XY = C2_VXY1, /* Input Vector 1 (X, Y) */
|
||||||
gte_in_v1_z = C2_VZ1, /* Input Vector 1 (Z) */
|
C2_InV1_Z = C2_VZ1, /* Input Vector 1 (Z) */
|
||||||
gte_in_v2_xy = C2_VXY2, /* Input Vector 2 (X, Y) */
|
C2_InV2_XY = C2_VXY2, /* Input Vector 2 (X, Y) */
|
||||||
gte_in_v2_z = C2_VZ2, /* Input Vector 2 (Z) */
|
C2_InV2_Z = C2_VZ2, /* Input Vector 2 (Z) */
|
||||||
gte_in_rgb = C2_RGB, /* Input Color (R, G, B, MipsCode) */
|
C2_In_RGB = C2_RGB, /* Input Color (R, G, B, MipsCode) */
|
||||||
gte_out_scr_xy0 = C2_SXY0, /* Output Screen Coord 0 (X, Y) */
|
C2_OutSrc_XY0 = C2_SXY0, /* Output Screen Coord 0 (X, Y) */
|
||||||
gte_out_scr_xy1 = C2_SXY1, /* Output Screen Coord 1 (X, Y) */
|
C2_OutSrc_XY1 = C2_SXY1, /* Output Screen Coord 1 (X, Y) */
|
||||||
gte_out_scr_xy2 = C2_SXY2, /* Output Screen Coord 2 (X, Y) */
|
C2_OutSrc_XY2 = C2_SXY2, /* Output Screen Coord 2 (X, Y) */
|
||||||
gte_out_depth = C2_OTZ, /* Output Ordering Table Z (Depth) */
|
C2_OutDepth = C2_OTZ, /* Output Ordering Table Z (Depth) */
|
||||||
gte_math_accum0 = C2_MAC0, /* Math Accumulator 0 */
|
C2_MathAccu0 = C2_MAC0, /* Math Accumulator 0 */
|
||||||
gte_math_accum1 = C2_MAC1, /* Math Accumulator 1 */
|
C2_MathAccu1 = C2_MAC1, /* Math Accumulator 1 */
|
||||||
gte_math_accum2 = C2_MAC2, /* Math Accumulator 2 */
|
C2_MathAccu2 = C2_MAC2, /* Math Accumulator 2 */
|
||||||
};
|
};
|
||||||
|
|
||||||
/* --- GTE Command Semantics (The Bitfield Meanings) ---
|
/* --- GTE Command Semantics (The Bitfield Meanings) ---
|
||||||
@@ -173,45 +145,40 @@ enum {
|
|||||||
* +------------+--+-----+------+------+------+------+---+--------+----------+
|
* +------------+--+-----+------+------+------+------+---+--------+----------+
|
||||||
* \_____ GTE_PAYLOAD _____/ \__ GTE_CMD __/
|
* \_____ GTE_PAYLOAD _____/ \__ GTE_CMD __/
|
||||||
*
|
*
|
||||||
* Shifts/masks below are the *bit positions* and *bit widths* of each configurable field, used by the ENC_GTE_CMD encoder.
|
* Offset position & masks below are the *bit positions* and *bit widths* of each configurable field, used by the ENC_GTE_CMD encoder.
|
||||||
* Mirrors the OPCODE_SHIFT / RS_SHIFT convention used in mips.h.
|
* Mirrors the OPCODE_POS / RS_POS convention used in mips.h.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
gte_shift_sf = 19, gte_width_sf = 1,
|
gte_pos_sf = 19, gte_width_sf = 1,
|
||||||
gte_shift_mx = 17, gte_width_mx = 2,
|
gte_pos_mx = 17, gte_width_mx = 2,
|
||||||
gte_shift_v = 15, gte_width_v = 2,
|
gte_pos_v = 15, gte_width_v = 2,
|
||||||
gte_shift_cv = 13, gte_width_cv = 2,
|
gte_pos_cv = 13, gte_width_cv = 2,
|
||||||
gte_shift_lm = 10, gte_width_lm = 1,
|
gte_pos_lm = 10, gte_width_lm = 1,
|
||||||
gte_shift_cmd = 0, gte_width_cmd = 6,
|
gte_pos_cmd = 0, gte_width_cmd = 6,
|
||||||
|
|
||||||
/* Fake command number (bits 24-20) — IGNORED by the GTE hardware per PSX-SPX `geometrytransformationenginegte.md` line 48.
|
/* Fake command number (bits 24-20) — IGNORED by the GTE hardware per PSX-SPX `geometrytransformationenginegte.md` line 48.
|
||||||
* libgte's compiler emits non-zero values in this field as a disassembly signature. */
|
* libgte's compiler emits non-zero values in this field as a disassembly signature. */
|
||||||
gte_shift_fake_cmd = 20,
|
gte_pos_fake_cmd = 20,
|
||||||
gte_width_fake_cmd = 5,
|
gte_width_fake_cmd = 5,
|
||||||
};
|
};
|
||||||
|
|
||||||
/* --- GTE Control Register Aliases (Pitfall 1) ---
|
/* --- GTE Control Register Aliases (Pitfall 1) ---
|
||||||
* Three pairs of aliases map to the SAME C2 control-register slot on real silicon:
|
* Three pairs of aliases map to the C2 control-register slot:
|
||||||
* C2[24] = gte_cr_RBK (background R) | gte_cr_OFX (screen offset X)
|
* C2[24] = gte_cr_RBK (background R) | gte_cr_OFX (screen offset X)
|
||||||
* C2[25] = gte_cr_GBK (background G) | gte_cr_OFY (screen offset Y)
|
* C2[25] = gte_cr_GBK (background G) | gte_cr_OFY (screen offset Y)
|
||||||
* C2[26] = gte_cr_BBK (background B) | gte_cr_H (projection plane distance H)
|
* C2[26] = gte_cr_BBK (background B) | gte_cr_H (projection plane distance H)
|
||||||
* Cross-alias writes inside one atom body, or across the wave-context boundary,
|
* Cross-alias writes inside one atom body, or across the wave-context boundary, silently clobber each other.
|
||||||
* silently clobber each other. The metaprogram's check_gte_cr_alias_writes
|
* The metaprogram's check_gte_cr_alias_writes (CHECK_RULES row) warns about each pair per source.
|
||||||
* (CHECK_RULES row) warns about each pair per source. See
|
* See psx-spx docs/gte_reference.md §"Control-register alias table" for the silicon rationale and the libgte outer-product convention.
|
||||||
* docs/gte_reference.md §"Control-register alias table" for the silicon
|
|
||||||
* rationale and the libgte outer-product convention.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* --- RT-matrix packed-slot convention (Pitfall 4) ---
|
/* --- RT-matrix packed-slot convention (Pitfall 4) ---
|
||||||
* The silicon packs two 16-bit RT elements per 32-bit C2 slot:
|
* The silicon packs two 16-bit RT elements per 32-bit C2 slot:
|
||||||
* C2[2] = (RT22 << 16) | RT13 (gte_cr_RT13 writes the low half, gte_cr_RT22 writes the high half)
|
* C2[2] = (RT22 << 16) | RT13 (gte_cr_RT13 writes the low half, gte_cr_RT22 writes the high half)
|
||||||
* C2[4] = (RT33 << 16) | RT22 (gte_cr_RT22 writes the low half — clobbers prior RT22 value if RT13 was also written)
|
* C2[4] = (RT33 << 16) | RT22 (gte_cr_RT22 writes the low half — clobbers prior RT22 value if RT13 was also written)
|
||||||
* OP and MVMVA read D1/D2/D3 from these packed slots. The libgte outer-product
|
* OP and MVMVA read D1/D2/D3 from these packed slots.
|
||||||
* convention (see ac_apply_matrix_lv at gte.atom.c:108-122) writes C2[2] then
|
* The libgte outer-product convention (see ac_apply_matrix_lv at gte.atom.c:108-122) writes C2[2] then C2[4] in sequence;
|
||||||
* C2[4] in sequence; the SECOND write's low half is RT22, not RT13. An agent
|
* the SECOND write's low half is RT22, not RT13.
|
||||||
* who writes gte_cr_RT13 then gte_cr_RT22 to the SAME source GPR clobbers the
|
|
||||||
* RT13 value. See docs/gte_reference.md §"RT-matrix packed-slot convention"
|
|
||||||
* for the canonical write pattern.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* --- GTE Control Register Indices (for ctc2/cfc2) ---
|
/* --- GTE Control Register Indices (for ctc2/cfc2) ---
|
||||||
@@ -300,8 +267,7 @@ enum { _C2_TX_SUBS_ = 0
|
|||||||
// #define gte_mv_from_data_r(rt, rd) enc_gte_tx(cop_mf, (rt), (rd)) /* Move GTE Control Register (rd) to GPR (rt) */
|
// #define gte_mv_from_data_r(rt, rd) enc_gte_tx(cop_mf, (rt), (rd)) /* Move GTE Control Register (rd) to GPR (rt) */
|
||||||
|
|
||||||
/* GTE Data vs Control Register Transfers
|
/* GTE Data vs Control Register Transfers
|
||||||
*
|
* Each macro emits a single instruction for one of MFC2/CFC2/MTC2/CTC2.
|
||||||
* Each macro emits a single .word constant for one of MFC2/CFC2/MTC2/CTC2.
|
|
||||||
*
|
*
|
||||||
* `rd` is the C2 register index in the file the sub-opcode names:
|
* `rd` is the C2 register index in the file the sub-opcode names:
|
||||||
* gte_mv_from_data_r / gte_mv_to_data_r → C2 data register file
|
* gte_mv_from_data_r / gte_mv_to_data_r → C2 data register file
|
||||||
@@ -316,14 +282,14 @@ enum { _C2_TX_SUBS_ = 0
|
|||||||
#define gte_mv_from_ctrl_r(rt, rd) enc_gte_tx(sub_cfc2, (rt), (rd)) /* Copy From ctrl reg */
|
#define gte_mv_from_ctrl_r(rt, rd) enc_gte_tx(sub_cfc2, (rt), (rd)) /* Copy From ctrl reg */
|
||||||
#define gte_mv_to_data_r(rt, rd) enc_gte_tx(sub_mtc2, (rt), (rd)) /* Move To data reg */
|
#define gte_mv_to_data_r(rt, rd) enc_gte_tx(sub_mtc2, (rt), (rd)) /* Move To data reg */
|
||||||
#define gte_mv_to_ctrl_r(rt, rd) enc_gte_tx(sub_ctc2, (rt), (rd)) /* Copy To ctrl reg */
|
#define gte_mv_to_ctrl_r(rt, rd) enc_gte_tx(sub_ctc2, (rt), (rd)) /* Copy To ctrl reg */
|
||||||
|
#define GteDelay_ // Annotate an instruction as filling a CPU <-> GTE DMA delay slot/s
|
||||||
|
|
||||||
/* COP2 Data Load (lwc2): `lwc2 rt, off(rs)`
|
/* COP2 Data Load (lwc2): `lwc2 rt, off(rs)`
|
||||||
* Layout: [op_lwc2:6][rs:5][rt:5][imm:16]
|
* Layout: [op_lwc2:6][rs:5][rt:5][imm:16]
|
||||||
* - rs: GPR base address
|
* - rs: GPR base address
|
||||||
* - rt: COP2 data register index (0..31)
|
* - rt: COP2 data register index (0..31)
|
||||||
* - imm: signed 16-bit offset
|
* - imm: signed 16-bit offset
|
||||||
* NOTE: When `rs` is a runtime register, the encoding cannot be pre-baked
|
* NOTE: When `rs` is a runtime register, the encoding cannot be pre-baked into a .word — use the string-style `gte_load_v0` macro below instead. */
|
||||||
* into a .word — use the string-style `gte_load_v0` macro below instead. */
|
|
||||||
#define enc_gte_lw(rt, base, off) enc_i(op_lwc2, (base), (rt), (off))
|
#define enc_gte_lw(rt, base, off) enc_i(op_lwc2, (base), (rt), (off))
|
||||||
/* Store Word */
|
/* Store Word */
|
||||||
#define enc_gte_sw(rt, base, off) enc_i(op_swc2, (base), (rt), (off))
|
#define enc_gte_sw(rt, base, off) enc_i(op_swc2, (base), (rt), (off))
|
||||||
@@ -332,8 +298,7 @@ enum { _C2_TX_SUBS_ = 0
|
|||||||
* `swc2` is redundant when we're already inside the `gte_` namespace.
|
* `swc2` is redundant when we're already inside the `gte_` namespace.
|
||||||
* gte_lw rt, base, off → lwc2 rt, off(base)
|
* gte_lw rt, base, off → lwc2 rt, off(base)
|
||||||
* gte_sw rt, base, off → swc2 rt, off(base)
|
* gte_sw rt, base, off → swc2 rt, off(base)
|
||||||
* For the typical user-facing vector-level load (xy + z as two instructions),
|
* For the typical user-facing vector-level load (xy + z as two instructions), use the higher-level `gte_load_vN` macros below. */
|
||||||
* use the higher-level `gte_load_vN` macros below. */
|
|
||||||
#define gte_lw(rt, base, off) enc_gte_lw(rt, base, off)
|
#define gte_lw(rt, base, off) enc_gte_lw(rt, base, off)
|
||||||
#define gte_sw(rt, base, off) enc_gte_sw(rt, base, off)
|
#define gte_sw(rt, base, off) enc_gte_sw(rt, base, off)
|
||||||
|
|
||||||
@@ -350,13 +315,13 @@ enum { _C2_TX_SUBS_ = 0
|
|||||||
#define gte_cmd_base (enc_op(op_cop2) | (1 << 25))
|
#define gte_cmd_base (enc_op(op_cop2) | (1 << 25))
|
||||||
|
|
||||||
/* Per-field encoders. Each one does (value & mask) << shift on its own. */
|
/* Per-field encoders. Each one does (value & mask) << shift on its own. */
|
||||||
#define enc_gte_sf(sf) ((sf) << gte_shift_sf )
|
#define enc_gte_sf(sf) ((sf) << gte_pos_sf )
|
||||||
#define enc_gte_mx(mx) ((mx) << gte_shift_mx )
|
#define enc_gte_mx(mx) ((mx) << gte_pos_mx )
|
||||||
#define enc_gte_v(v) ((v) << gte_shift_v )
|
#define enc_gte_v(v) ((v) << gte_pos_v )
|
||||||
#define enc_gte_cv(cv) ((cv) << gte_shift_cv )
|
#define enc_gte_cv(cv) ((cv) << gte_pos_cv )
|
||||||
#define enc_gte_lm(lm) ((lm) << gte_shift_lm )
|
#define enc_gte_lm(lm) ((lm) << gte_pos_lm )
|
||||||
#define enc_gte_cmd(cmd) ((cmd) << gte_shift_cmd )
|
#define enc_gte_cmd(cmd) ((cmd) << gte_pos_cmd )
|
||||||
#define enc_gte_fake_cmd(x) ((x) << gte_shift_fake_cmd)
|
#define enc_gte_fake_cmd(x) ((x) << gte_pos_fake_cmd)
|
||||||
|
|
||||||
/* Composite: all six GTE fields + the COP2/CO base. */
|
/* Composite: all six GTE fields + the COP2/CO base. */
|
||||||
#define enc_gte_cmdw(sf, mx, v, cv, lm, cmd) ( \
|
#define enc_gte_cmdw(sf, mx, v, cv, lm, cmd) ( \
|
||||||
@@ -408,10 +373,11 @@ enum { _C2_TX_SUBS_ = 0
|
|||||||
#define gte_cmdw_rtpt (gte_cmd_base | enc_gte_cmd(gte_cmd_rtpt ) | gte_cmdw_psyq_compat)
|
#define gte_cmdw_rtpt (gte_cmd_base | enc_gte_cmd(gte_cmd_rtpt ) | gte_cmdw_psyq_compat)
|
||||||
#define gte_cmdw_nclip (gte_cmd_base | enc_gte_cmd(gte_cmd_nclip))
|
#define gte_cmdw_nclip (gte_cmd_base | enc_gte_cmd(gte_cmd_nclip))
|
||||||
#define gte_cmdw_op (gte_cmd_base | enc_gte_cmd(gte_cmd_op ))
|
#define gte_cmdw_op (gte_cmd_base | enc_gte_cmd(gte_cmd_op ))
|
||||||
#define gte_cmdw_outer_product gte_cmdw_op /* "outer product" -- NOCASH/Sdk terminology */
|
#define gte_cmdw_outer_product gte_cmdw_op /* "outer product" -- PSY-Q terminology */
|
||||||
#define gte_cmdw_wedge gte_cmdw_op /* "wedge product" -- geometric-algebra terminology.
|
#define gte_cmdw_wedge gte_cmdw_op /* "wedge product" -- geometric-algebra terminology. */
|
||||||
* RGA(Lengyel): the GTE OP is a 3D signed-16-bit D x IR cross, not a generic RGA exterior product.
|
#define gte_cmdw_cross gte_cmdw_op /* "cross product" -- geometric-algebra terminology.
|
||||||
* The wedge alias is the 3D complement interpretation of the same 3 scalars (MAC1..MAC3). */
|
* RGA(Lengyel): The GTE OP is a 3D signed-16-bit D x IR cross, not a generic RGA exterior product.
|
||||||
|
* The wedge alias is a 3D complement interpretation of the same 3 scalars (MAC1..MAC3). */
|
||||||
#define gte_cmdw_mvmva (gte_cmd_base | enc_gte_cmd(gte_cmd_mvmva))
|
#define gte_cmdw_mvmva (gte_cmd_base | enc_gte_cmd(gte_cmd_mvmva))
|
||||||
|
|
||||||
/* MVMVA with sf=0 (no shift, full-integer), cv=3 (no translation), v=3 (IR vector input).
|
/* MVMVA with sf=0 (no shift, full-integer), cv=3 (no translation), v=3 (IR vector input).
|
||||||
@@ -448,9 +414,8 @@ enum { _C2_TX_SUBS_ = 0
|
|||||||
/* MVMVA: sf=1 (>>12), mx=0 (RT matrix), v=0 (V0), cv=3 (no TR). */
|
/* MVMVA: sf=1 (>>12), mx=0 (RT matrix), v=0 (V0), cv=3 (no TR). */
|
||||||
#define gte_cmdw_mvmva_sf1_mx0_v0_cv3 (gte_cmd_base | enc_gte_sf(1) | enc_gte_cv(3) | enc_gte_v(0) | enc_gte_mx(0) | enc_gte_cmd(gte_cmd_mvmva))
|
#define gte_cmdw_mvmva_sf1_mx0_v0_cv3 (gte_cmd_base | enc_gte_sf(1) | enc_gte_cv(3) | enc_gte_v(0) | enc_gte_mx(0) | enc_gte_cmd(gte_cmd_mvmva))
|
||||||
|
|
||||||
/* RTPS with sf=1 (12-bit shift, no translation): matches the output of libgte's
|
/* RTPS with sf=1 (12-bit shift, no translation): matches the output of libgte's ApplyMatrixLV when the GTE pipeline expects R*pos >> 12.
|
||||||
* ApplyMatrixLV when the GTE pipeline expects R*pos >> 12. The shift produces
|
* The shift produces values like (-270, 710, 1713) which match the C11 reference path. */
|
||||||
* values like (-270, 710, 1713) which match the C11 reference path. */
|
|
||||||
#define gte_cmdw_rtps_sf1 (gte_cmd_base | enc_gte_sf(1) | enc_gte_cv(3) | enc_gte_cmd(gte_cmd_rtps))
|
#define gte_cmdw_rtps_sf1 (gte_cmd_base | enc_gte_sf(1) | enc_gte_cv(3) | enc_gte_cmd(gte_cmd_rtps))
|
||||||
|
|
||||||
/* SQR / GPF cosmetic-bits compat helpers.
|
/* SQR / GPF cosmetic-bits compat helpers.
|
||||||
@@ -483,10 +448,8 @@ enum { _C2_TX_SUBS_ = 0
|
|||||||
* bits 24-20 = 0x19 (libgte "nonsense SDK command number" signature) */
|
* bits 24-20 = 0x19 (libgte "nonsense SDK command number" signature) */
|
||||||
#define gte_cmdw_gpf (gte_cmd_base | enc_gte_cmd(gte_cmd_gpf) | gte_cmdw_gpf_fake_sig)
|
#define gte_cmdw_gpf (gte_cmd_base | enc_gte_cmd(gte_cmd_gpf) | gte_cmdw_gpf_fake_sig)
|
||||||
|
|
||||||
/* Mask to round LZCR (leading-zero/ones count, range 1..32 per PSX-SPX cop2r31)
|
/* Mask to round LZCR (leading-zero/ones count, range 1..32 per PSX-SPX cop2r31) down to even.
|
||||||
* down to even. The normalize_v3s4 half-shift logic computes (31 - LZCR) >> 1;
|
* The normalize_v3s4 half-shift logic computes (31 - LZCR) >> 1; clearing bit 0 ensures the subtraction result is always odd, so the >> 1 division is consistent (no 0.5 loss). */
|
||||||
* clearing bit 0 ensures the subtraction result is always odd,
|
|
||||||
* so the >> 1 division is consistent (no 0.5 loss). */
|
|
||||||
enum {
|
enum {
|
||||||
gte_lzcr_even_mask = 0xFFFE, /* all bits except bit 0 */
|
gte_lzcr_even_mask = 0xFFFE, /* all bits except bit 0 */
|
||||||
};
|
};
|
||||||
@@ -593,8 +556,8 @@ enum {
|
|||||||
|
|
||||||
/* gte_load_v0v1v2(p0, p1, p2, b0, b1, b2) — prelude to gte_cmd_rtpt.
|
/* gte_load_v0v1v2(p0, p1, p2, b0, b1, b2) — prelude to gte_cmd_rtpt.
|
||||||
*
|
*
|
||||||
* Loads all three GTE input vectors (6 words) from three separate pointers, one per GTE vector register,
|
* Loads all three GTE input vectors (6 words) from three separate pointers, one per GTE vector register, each loaded from its own base GPR.
|
||||||
* each loaded from its own base GPR. Caller must bind each `pN` to `bN` via a register variable.
|
* Caller must bind each `pN` to `bN` via a register variable.
|
||||||
* register V3_S2* p0 rgcc(R_T4) = verts[0].ptr; // → __asm__("$12")
|
* register V3_S2* p0 rgcc(R_T4) = verts[0].ptr; // → __asm__("$12")
|
||||||
* register V3_S2* p1 rgcc(R_T5) = verts[1].ptr; // → __asm__("$13")
|
* register V3_S2* p1 rgcc(R_T5) = verts[1].ptr; // → __asm__("$13")
|
||||||
* register V3_S2* p2 rgcc(R_T6) = verts[2].ptr; // → __asm__("$14")
|
* register V3_S2* p2 rgcc(R_T6) = verts[2].ptr; // → __asm__("$14")
|
||||||
@@ -688,8 +651,7 @@ enum {
|
|||||||
* Loads the 3x3 rotation matrix at `r0` into the GTE's rotation-matrix control registers (RT11..RT22, indices 0..4) via ctc2.
|
* Loads the 3x3 rotation matrix at `r0` into the GTE's rotation-matrix control registers (RT11..RT22, indices 0..4) via ctc2.
|
||||||
*
|
*
|
||||||
* Memory layout at r0: five contiguous 32-bit words (offsets 0..16), each holding two packed 16-bit matrix elements.
|
* Memory layout at r0: five contiguous 32-bit words (offsets 0..16), each holding two packed 16-bit matrix elements.
|
||||||
* The first 1.5 rows of a standard PSX SDK MATRIX struct (where each row is laid out as
|
* The first 1.5 rows of a standard PSX SDK MATRIX struct (where each row is laid out as [RT_xx, RT_xy] | [RT_xz, pad] | ...).
|
||||||
* [RT_xx, RT_xy] | [RT_xz, pad] | ...).
|
|
||||||
*
|
*
|
||||||
* Generated MIPS (mirrors the source macro):
|
* Generated MIPS (mirrors the source macro):
|
||||||
* lw $12, 0( %0 ) ; word 0
|
* lw $12, 0( %0 ) ; word 0
|
||||||
|
|||||||
+160
-91
@@ -66,51 +66,68 @@
|
|||||||
* */
|
* */
|
||||||
/* Register Allocation Info */
|
/* Register Allocation Info */
|
||||||
enum {
|
enum {
|
||||||
R_AtomJmp = R_T8 atom_reg, /* debug-visible; tape yield handshake scratch */
|
R_ScratchBase = R_SP atom_reg, /* Scratchpad base address (host frame top) */
|
||||||
R_TapePtr = R_T9 atom_reg, /* The Instruction Stream Pointer */
|
R_AtomJmp = R_FP atom_reg, /* Next atom target (yield handshake scratch) */
|
||||||
|
R_TapePtr = R_RA atom_reg, /* The Instruction Stream Pointer */
|
||||||
/* Stringification codes for the GCC inline assembler clobber lists. */
|
/* Stringification codes for the GCC inline assembler clobber lists. */
|
||||||
#define R_AtomJmp_Code R_T8_Code
|
#define R_ScratchBase_Code R_SP_Code
|
||||||
#define R_TapePtr_Code R_T9_Code
|
#define R_AtomJmp_Code R_FP_Code
|
||||||
|
#define R_TapePtr_Code R_RA_Code
|
||||||
|
|
||||||
// R_InCursor = R_T4,
|
// R_InCursor = R_T4,
|
||||||
// #define R_InCursor_Code R_T4_Code
|
// #define R_InCursor_Code R_T4_Code
|
||||||
|
|
||||||
// Reserved Registers (Callee-saved):
|
// Reserved Registers (Callee-saved across the host ABI transition):
|
||||||
// - R_T9: Holds the Tape Ptr which we need to increment
|
// - R_SP: Holds the scratchpad base while tape code executes.
|
||||||
// If we hit a wall with register allocations we can clobber V0 & V1 (return values), defering as opt-in by user.
|
// - R_FP: Holds the next atom target.
|
||||||
// - R_RA: Not sure??
|
// - R_RA: Holds the tape cursor.
|
||||||
// Needed by ac_yield but can be used as atom scratch:
|
// All atom-body allocations must stay out of these.
|
||||||
// - R_T8: Will be used as the atom jump register.
|
// Atom bodies may freely use R2-R25.
|
||||||
|
|
||||||
// All allocatable registers for mips atoms:
|
// All allocatable registers for atom bodies (R2-R25, 24 registers):
|
||||||
R_TScratchVolatile = R_AT, // This one is reserved for psuedo instructions, but you can technically use it.
|
|
||||||
R_TScratch0 = R_T0,
|
R_PsuedoVolatile = R_AT, // Assembler temporary; never allocate.
|
||||||
R_TScratch1 = R_T1,
|
|
||||||
R_TScratch2 = R_T2,
|
// Atom Allocation Pool
|
||||||
R_TScratch3 = R_T3,
|
R_Atom0 = R_T0,
|
||||||
R_TScratch4 = R_T4,
|
R_Atom1 = R_T1,
|
||||||
R_TScratch5 = R_T5,
|
R_Atom2 = R_T2,
|
||||||
R_TScratch6 = R_T6,
|
R_Atom3 = R_T3,
|
||||||
R_TScratch7 = R_T7,
|
R_Atom4 = R_T4,
|
||||||
R_TScratch8 = R_T8,
|
R_Atom5 = R_T5,
|
||||||
R_TScratch10 = R_V0, // Tend to be used with gte DMAs
|
R_Atom6 = R_T6,
|
||||||
R_TScratch11 = R_V1, // Tend to be used with gte DMAs
|
R_Atom7 = R_T7,
|
||||||
// Note(Ed): We can technically clobber these, but don't unless we hit a bottleneck.
|
R_Atom8 = R_T8,
|
||||||
// A 0-2
|
R_Atom9 = R_T9,
|
||||||
// S 0-7
|
R_Atom10 = R_V0, // Tend to be used with gte moves
|
||||||
|
R_Atom11 = R_V1, // Tend to be used with gte moves
|
||||||
|
R_Atom12 = R_A0,
|
||||||
|
R_Atom13 = R_A1,
|
||||||
|
R_Atom14 = R_A2,
|
||||||
|
R_Atom15 = R_A3,
|
||||||
|
R_Atom16 = R_S0,
|
||||||
|
R_Atom17 = R_S1,
|
||||||
|
R_Atom18 = R_S2,
|
||||||
|
R_Atom19 = R_S3,
|
||||||
|
R_Atom20 = R_S4,
|
||||||
|
R_Atom21 = R_S5,
|
||||||
|
R_Atom22 = R_S6,
|
||||||
|
R_Atom23 = R_S7,
|
||||||
};
|
};
|
||||||
|
|
||||||
typedef U2 Reg; // Register parameter used with atom or atom component procedures
|
typedef U2 Reg; // Register parameter used with atom or atom component procedures
|
||||||
|
#define Reg_(type) tmpl(Reg,type) // Just a way to template register allocations of C-struct types.
|
||||||
|
|
||||||
typedef U4 const MipsCode; // Underlying type to mips asm words.
|
typedef U4 const MipsCode; // Underlying type to mips asm words.
|
||||||
typedef Slice_(MipsCode);
|
typedef Slice_(MipsCode);
|
||||||
|
|
||||||
typedef U4 const MipsAtom;
|
typedef U4 const MipsAtom; // Underlying type to a mips atom defnition
|
||||||
typedef Slice_(MipsAtom);
|
typedef Slice_(MipsAtom);
|
||||||
|
|
||||||
// Sometimes a user will define a bundle of atoms that represent a procedure of work as:
|
// Sometimes a user will define a bundle of atoms that represent a procedure of work as:
|
||||||
// MipsAtom* <identifier>[...];
|
// MipsAtom* <identifier>[...];
|
||||||
// Unfortuantely if using slice_from_array it will make the slice's pointer: MipsAtom** so this enforce its defined as MipsAtom*
|
// Unfortuantely if using slice_from_array it will make the slice's pointer: MipsAtom** so this enforce its defined as MipsAtom*
|
||||||
// TODO(Ed): Alternatively we can make the MipsAtom an opaque pointer to the atom... so that the blow returns 'MipsAtom'.
|
// TODO(Ed): Alternatively we can make the MipsAtom an opaque pointer to the atom... so that the proc returns 'MipsAtom'.
|
||||||
#define atombundle_from_array(array) (Slice_MipsAtom){.ptr=array[0],.len=Array_len(array)}
|
#define atombundle_from_array(array) (Slice_MipsAtom){.ptr=array[0],.len=Array_len(array)}
|
||||||
|
|
||||||
// Underlying type to an ptr to an array of mips asm words that must terminate with an ac_yield.
|
// Underlying type to an ptr to an array of mips asm words that must terminate with an ac_yield.
|
||||||
@@ -143,57 +160,84 @@ typedef Slice_(MipsAtom);
|
|||||||
// Inline-only callers (the generated `mac_<name>` aliases) skip the `ab` arg via metaprogram filtering; escape callers (ac_<name> invoked as a function) pass a long-lived builder.
|
// Inline-only callers (the generated `mac_<name>` aliases) skip the `ab` arg via metaprogram filtering; escape callers (ac_<name> invoked as a function) pass a long-lived builder.
|
||||||
#define MipsAtomComp_Proc_(ab, ...) { MipsCode atom_comp_code[] align_(4) = __VA_ARGS__; atombuilder_push(ab, slice_from_array(MipsCode, atom_comp_code)); }
|
#define MipsAtomComp_Proc_(ab, ...) { MipsCode atom_comp_code[] align_(4) = __VA_ARGS__; atombuilder_push(ab, slice_from_array(MipsCode, atom_comp_code)); }
|
||||||
|
|
||||||
|
// Used for trivial mappings from one atom component proc to the command of a more baser (meant for type-mapping)
|
||||||
|
#define MipsAtomComp_ProcMap_(ab, base_command) atom_dbg_skip MipsAtomComp_Proc_(ab, {base_command })
|
||||||
|
|
||||||
|
// WIP: Atoms Assocated closely with each other to form a tape procedure. (Maybe also a phase in a procedure/pipeline?)
|
||||||
|
|
||||||
|
#define AtomBundle_(name) Struct_(tmpl(AtomBundle,name))
|
||||||
|
#define AtomBundle_Len(name) S_(tmpl(AtomBundle,name))/S_(MipsAtom*)
|
||||||
|
#define AtomBundleEntry_(bundle,entry) tmpl(bundle,entry)
|
||||||
|
|
||||||
/* Line-table anchor: gcc only adds a file to the .debug_line file table when the contains line-numbered content.
|
/* Line-table anchor: gcc only adds a file to the .debug_line file table when the contains line-numbered content.
|
||||||
Files containing only atoms and atom components.
|
Files containing only atoms and atom components.
|
||||||
Place `ATOM_FILE_LINE_MARKER();` once at file scope in any `.atom.c` that defines atoms.
|
Place `ATOM_FILE_LINE_MARKER();` once at file scope in any `.atom.c` that defines atoms.
|
||||||
Macro expands to a file-scope `internal U4 const` declaration keeps the file in the line table.
|
Macro expands to a file-scope `internal U4 const` declaration keeps the file in the line table.
|
||||||
The constant is in `.rodata` so the linker may eliminate it.
|
The constant is in `.rodata` so the linker may eliminate it. */
|
||||||
Two-level concat + `__LINE__` suffix makes the identifier unique per call site
|
|
||||||
(identifier embeds the source line, so duplicates across `#include`d files don't collide). */
|
|
||||||
#define ATOM_FILE_DEBUGGER_LINE_MARKER(file_name) internal U4 const tmpl(atom_file_debugger_line_marker,file_name) = 0
|
#define ATOM_FILE_DEBUGGER_LINE_MARKER(file_name) internal U4 const tmpl(atom_file_debugger_line_marker,file_name) = 0
|
||||||
|
|
||||||
typedef Slice_MipsAtom Tape;
|
typedef Slice_MipsAtom Tape;
|
||||||
|
|
||||||
/* The 'Exit' Atom */
|
typedef Struct_(TapeHostFrame) {
|
||||||
atom_dbg_skip MipsAtom_(tape_exit) { jump_reg(R_RA), nop };
|
U4 s0;
|
||||||
|
U4 s1;
|
||||||
|
U4 s2;
|
||||||
|
U4 s3;
|
||||||
|
U4 s4;
|
||||||
|
U4 s5;
|
||||||
|
U4 s6;
|
||||||
|
U4 s7;
|
||||||
|
U4 fp;
|
||||||
|
U4 sp;
|
||||||
|
U4 ra;
|
||||||
|
};
|
||||||
|
|
||||||
// TODO(Ed): When we have a substantial workload/throughput, profile each of these to see impact at ABI boundaries.
|
enum {
|
||||||
|
TapeHostFrame_Loc = Scratchpad_End - S_(TapeHostFrame),
|
||||||
|
TapeScratch_Len = TapeHostFrame_Loc - Scratchpad_Loc,
|
||||||
|
};
|
||||||
|
static_assert(S_(TapeHostFrame) == 11 * S_(U4));
|
||||||
|
static_assert(TapeHostFrame_Loc == 0x1F8003D4);
|
||||||
|
|
||||||
/* Tape Runner (Default) */
|
atom_dbg_skip MipsAtom_(tape_enter) {
|
||||||
FI_ void tape_run(Tape tape) { register U4* tape_ptr rgcc(R_TapePtr) = u4_r(tape.ptr); asm volatile(
|
mac_load_word_imm(R_V0, u4_(TapeHostFrame_Loc)),
|
||||||
asm_words(
|
store_word(R_S0, R_V0, O_(TapeHostFrame,s0)),
|
||||||
load_word( R_AtomJmp, R_TapePtr, 0) /* Bootstrap the first jump */
|
store_word(R_S1, R_V0, O_(TapeHostFrame,s1)),
|
||||||
, add_ui_self(R_TapePtr, S_(MipsAtom)) /* Advance tape */
|
store_word(R_S2, R_V0, O_(TapeHostFrame,s2)),
|
||||||
, call_reg( R_AtomJmp) /* jalr $t9 */
|
store_word(R_S3, R_V0, O_(TapeHostFrame,s3)),
|
||||||
, nop /* Branch delay slot */
|
store_word(R_S4, R_V0, O_(TapeHostFrame,s4)),
|
||||||
)
|
store_word(R_S5, R_V0, O_(TapeHostFrame,s5)),
|
||||||
asm_rpins, r_use(tape_ptr)
|
store_word(R_S6, R_V0, O_(TapeHostFrame,s6)),
|
||||||
asm_clobber:
|
store_word(R_S7, R_V0, O_(TapeHostFrame,s7)),
|
||||||
rlit(R_AT),
|
store_word(R_FP, R_V0, O_(TapeHostFrame,fp)),
|
||||||
rlit(R_V0), rlit(R_V1), // We clobber these for GTE ACs (that don't expose register selection, might expose them in the future...)
|
store_word(R_SP, R_V0, O_(TapeHostFrame,sp)),
|
||||||
rlit(R_T0), rlit(R_T1), rlit(R_T2), rlit(R_T3), rlit(R_T4),
|
store_word(R_RA, R_V0, O_(TapeHostFrame,ra)),
|
||||||
rlit(R_T5), rlit(R_T6), rlit(R_T7), rlit(R_T8),
|
add_ui(R_TapePtr, R_A0, 0),
|
||||||
clb_mem_drain
|
load_upper_i(R_ScratchBase, u4_hi(Scratchpad_Loc)),
|
||||||
); }
|
load_word(R_AtomJmp, R_TapePtr, 0),
|
||||||
|
add_ui_self( R_TapePtr, S_(MipsAtom)),
|
||||||
|
jump_reg(R_AtomJmp), BdSlot_ nop,
|
||||||
|
};
|
||||||
|
|
||||||
/* Tape Runner (Static and Arg Clobbers) */
|
atom_dbg_skip MipsAtom_(tape_exit) {
|
||||||
FI_ void tape_run_a02_s07(Tape tape) { register U4* tape_ptr rgcc(R_TapePtr) = u4_r(tape.ptr); asm volatile(
|
mac_load_word_imm(R_V0, u4_(TapeHostFrame_Loc)),
|
||||||
asm_words(
|
load_word(R_S0, R_V0, O_(TapeHostFrame,s0)),
|
||||||
load_word( R_AtomJmp, R_TapePtr, 0) /* Bootstrap the first jump */
|
load_word(R_S1, R_V0, O_(TapeHostFrame,s1)),
|
||||||
, add_ui_self(R_TapePtr, S_(MipsAtom)) /* Advance tape */
|
load_word(R_S2, R_V0, O_(TapeHostFrame,s2)),
|
||||||
, call_reg( R_AtomJmp) /* jalr $t9 */
|
load_word(R_S3, R_V0, O_(TapeHostFrame,s3)),
|
||||||
, nop /* Branch delay slot */
|
load_word(R_S4, R_V0, O_(TapeHostFrame,s4)),
|
||||||
)
|
load_word(R_S5, R_V0, O_(TapeHostFrame,s5)),
|
||||||
asm_rpins, r_use(tape_ptr)
|
load_word(R_S6, R_V0, O_(TapeHostFrame,s6)),
|
||||||
asm_clobber:
|
load_word(R_S7, R_V0, O_(TapeHostFrame,s7)),
|
||||||
rlit(R_AT),
|
load_word(R_RA, R_V0, O_(TapeHostFrame,ra)),
|
||||||
rlit(R_V0), rlit(R_V1), rlit(R_A0), rlit(R_A1), rlit(R_A2),
|
load_word(R_FP, R_V0, O_(TapeHostFrame,fp)),
|
||||||
rlit(R_T0), rlit(R_T1), rlit(R_T2), rlit(R_T3), rlit(R_T4),
|
load_word(R_SP, R_V0, O_(TapeHostFrame,sp)),
|
||||||
rlit(R_T5), rlit(R_T6), rlit(R_T7), rlit(R_T8),
|
jump_reg(R_RA), BdSlot_ nop,
|
||||||
rlit(R_S0), rlit(R_S1), rlit(R_S2), rlit(R_S3), rlit(R_S4),
|
};
|
||||||
rlit(R_S5), rlit(R_S6), rlit(R_S7),
|
|
||||||
clb_mem_drain
|
typedef void Proc_(TapeEntryFn)(MipsAtom* tape_ptr);
|
||||||
); }
|
|
||||||
|
FI_ void tape_run(Tape tape) { C_(TapeEntryFn*, tape_enter)(tape.ptr); }
|
||||||
|
|
||||||
// Procedural authoring of tapes:
|
// Procedural authoring of tapes:
|
||||||
typedef Relative_(FArena) Struct_(TapeBuilder) { U4 ptr; U4 capacity; U4 used; };
|
typedef Relative_(FArena) Struct_(TapeBuilder) { U4 ptr; U4 capacity; U4 used; };
|
||||||
@@ -204,9 +248,13 @@ FI_ TapeBuilder tb_make(Slice mem) { return (TapeBuilder){ u4_(mem.ptr), mem.len
|
|||||||
FI_ void tb_emit(TapeBuilder* tb, MipsAtom* atom) { u4_r(tb->ptr)[tb->used] = u4_(atom); ++ tb->used; }
|
FI_ void tb_emit(TapeBuilder* tb, MipsAtom* atom) { u4_r(tb->ptr)[tb->used] = u4_(atom); ++ tb->used; }
|
||||||
FI_ void tb_data(TapeBuilder* tb, U4 data) { u4_r(tb->ptr)[tb->used] = u4_(data); ++ tb->used; }
|
FI_ void tb_data(TapeBuilder* tb, U4 data) { u4_r(tb->ptr)[tb->used] = u4_(data); ++ tb->used; }
|
||||||
#define tb_emit_(atom) tb_emit(& tb, atom)
|
#define tb_emit_(atom) tb_emit(& tb, atom)
|
||||||
#define tb_data_(field, data) tb_data(& tb, u4_(data))
|
|
||||||
|
|
||||||
FI_ void tb_emit_bundle(TapeBuilder_R tb, Slice_MipsAtom atoms) { mem_copy(u4_(tb->ptr), u4_(atoms.ptr), S_slice(atoms)); tb->used += atoms.len; }
|
FI_ void tb_bind(TapeBuilder* tb, Slice data) { mem_copy(tb->ptr + tb->used * S_(MipsCode), u4_(data.ptr), data.len); tb->used += data.len / S_(MipsCode); }
|
||||||
|
#define tb_bind_(tb,type,...) tb_bind(tb, (Slice){ (B1*)(& (type){__VA_ARGS__}), S_(type) }); static_assert(S_(type) % S_(MipsCode) == 0)
|
||||||
|
|
||||||
|
// NOTE(Ed): Wip still ideating convention. Possibly will never use a composite.
|
||||||
|
#define tb_emit_wbind_(tb,atom,...) tb_emit(tb,atom); tb_bind_(tb,tmpl(Binds,atom),__VA_ARGS__)
|
||||||
|
#define tb_emit_wbind2_(tb,atom,type,...) tb_emit(tb,atom); tb_bind_(tb,type,__VA_ARGS__)
|
||||||
|
|
||||||
FI_ Tape tb_end (TapeBuilder* tb) { tb_emit(tb,tape_exit); return (Tape){ C_(U4*,tb->ptr), tb->used }; }
|
FI_ Tape tb_end (TapeBuilder* tb) { tb_emit(tb,tape_exit); return (Tape){ C_(U4*,tb->ptr), tb->used }; }
|
||||||
FI_ Tape tb_slice(TapeBuilder tb) { return (Tape){ C_(U4*,tb.ptr), tb.used }; }
|
FI_ Tape tb_slice(TapeBuilder tb) { return (Tape){ C_(U4*,tb.ptr), tb.used }; }
|
||||||
@@ -223,15 +271,11 @@ FI_ void tb_scope_run_end(TapeBuilder* tb) { tb_emit(tb,tape_exit); tape_run(tb_
|
|||||||
* ---------------------------------------------------------------------------*/
|
* ---------------------------------------------------------------------------*/
|
||||||
|
|
||||||
// The 'Yield' sequence for Tape Atoms (mac_yield).
|
// The 'Yield' sequence for Tape Atoms (mac_yield).
|
||||||
// - mac_yield() is the safe default for atom-endings: 4 words, BD-slot of jr is mandatory nop.
|
|
||||||
// - mac_yield_load() + mac_yield_tail():
|
|
||||||
// - unconditional branch: mac_yield_load fills the branch's BD-slot (replaces a nop);
|
|
||||||
// - mac_yield_tail runs at the branch target (does NOT re-load R_AtomJmp).
|
|
||||||
|
|
||||||
atom_dbg_skip MipsAtomComp_(ac_yield) {
|
atom_dbg_skip MipsAtomComp_(ac_yield) {
|
||||||
load_word(R_AtomJmp, R_TapePtr, 0),
|
load_word(R_AtomJmp, R_TapePtr, 0), LdSlot_
|
||||||
add_ui_self( R_TapePtr, S_(MipsCode)),
|
add_ui_self( R_TapePtr, S_(MipsCode)),
|
||||||
jump_reg( R_AtomJmp), nop,
|
jump_reg( R_AtomJmp), BdSlot_ nop,
|
||||||
};
|
};
|
||||||
|
|
||||||
atom_dbg_skip MipsAtomComp_(ac_yield_load) {
|
atom_dbg_skip MipsAtomComp_(ac_yield_load) {
|
||||||
@@ -240,16 +284,13 @@ atom_dbg_skip MipsAtomComp_(ac_yield_load) {
|
|||||||
|
|
||||||
atom_dbg_skip MipsAtomComp_(ac_yield_tail) {
|
atom_dbg_skip MipsAtomComp_(ac_yield_tail) {
|
||||||
add_ui_self(R_TapePtr, S_(MipsCode)),
|
add_ui_self(R_TapePtr, S_(MipsCode)),
|
||||||
jump_reg( R_AtomJmp), nop,
|
jump_reg( R_AtomJmp), BdSlot_ nop,
|
||||||
};
|
};
|
||||||
|
|
||||||
#pragma endregion Macro Atom Components
|
#pragma endregion Macro Atom Components
|
||||||
|
|
||||||
#pragma region Atom Builder
|
#pragma region Atom Builder
|
||||||
// This helps with runtime procedural authoring of mips atoms.
|
// This helps with runtime procedural authoring of mips atoms.
|
||||||
|
|
||||||
typedef Struct_(FMipsAtom512) { U4 data[512]; U4 used; };
|
|
||||||
|
|
||||||
// FArena Related
|
|
||||||
typedef Relative_(FArena) Struct_(AtomBuilder) { U4 start; U4 capacity; U4 used; };
|
typedef Relative_(FArena) Struct_(AtomBuilder) { U4 start; U4 capacity; U4 used; };
|
||||||
|
|
||||||
// Usual way to resolve an atom after the bulder is done.
|
// Usual way to resolve an atom after the bulder is done.
|
||||||
@@ -270,7 +311,6 @@ FI_ void tb_emit_atombuilder(TapeBuilder_R tb, AtomBuilder_R ab) { tb_emit(tb, a
|
|||||||
|
|
||||||
#pragma region Atom Arena
|
#pragma region Atom Arena
|
||||||
// Just a dedicated FArena that is meant to mem_copy and return atom definitions made with MipsAtom_Proc_
|
// Just a dedicated FArena that is meant to mem_copy and return atom definitions made with MipsAtom_Proc_
|
||||||
|
|
||||||
typedef Relative_(FArena) Struct_(AtomArena) { U4 start; U4 capacity; U4 used; };
|
typedef Relative_(FArena) Struct_(AtomArena) { U4 start; U4 capacity; U4 used; };
|
||||||
|
|
||||||
#define atomarena_unused_start(ab) ((ab).start + (ab).used)
|
#define atomarena_unused_start(ab) ((ab).start + (ab).used)
|
||||||
@@ -295,13 +335,24 @@ FI_ void atomarena_reset(AtomArena_R aa) { aa->used = 0; }
|
|||||||
// TODO(Ed): Technically we can do this at comp-time with the metaprogram, but we may have namespace conflicts.
|
// TODO(Ed): Technically we can do this at comp-time with the metaprogram, but we may have namespace conflicts.
|
||||||
// Unless we follow a convention for #define <Scope_Prefix> or something per register allocation boundary.
|
// Unless we follow a convention for #define <Scope_Prefix> or something per register allocation boundary.
|
||||||
|
|
||||||
/* ABI + tape reserves that are never handed out by alloc. */
|
/* ABI reserves that are never handed out by alloc.
|
||||||
|
* R_AT is the assembler temporary (per the MIPS O32 ABI).
|
||||||
|
* R_K0/K1 are kernel reserves.
|
||||||
|
* R_GP stays the host global pointer.
|
||||||
|
* R_SP/R_FP/R_RA are tape runtime carriers between tape_enter and tape_exit. */
|
||||||
U4 const regfile_abi_mask =
|
U4 const regfile_abi_mask =
|
||||||
(1u << R_0) | (1u << R_AT) |
|
(1u << R_0) | (1u << R_AT) |
|
||||||
(1u << R_K0) | (1u << R_K1) |
|
(1u << R_K0) | (1u << R_K1) |
|
||||||
(1u << R_GP) | (1u << R_SP) |
|
(1u << R_GP) | (1u << R_SP) |
|
||||||
(1u << R_FP) | (1u << R_RA) |
|
(1u << R_FP) | (1u << R_RA);
|
||||||
(1u << R_T8) | (1u << R_T9); /* AtomJmp + TapePtr */
|
|
||||||
|
internal Reg const regfile_alloc_order[] = {
|
||||||
|
R_V0, R_V1,
|
||||||
|
R_A0, R_A1, R_A2, R_A3,
|
||||||
|
R_T0, R_T1, R_T2, R_T3, R_T4, R_T5, R_T6, R_T7,
|
||||||
|
R_S0, R_S1, R_S2, R_S3, R_S4, R_S5, R_S6, R_S7,
|
||||||
|
R_T8, R_T9,
|
||||||
|
};
|
||||||
|
|
||||||
typedef Struct_(RegFile) {
|
typedef Struct_(RegFile) {
|
||||||
A2_U2 GPR;
|
A2_U2 GPR;
|
||||||
@@ -337,12 +388,11 @@ FI_ Reg regfile__alloc_helper(A2_U2 file, Reg r_id) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
I_ Reg regfile_alloc(RegFile_R rf) {
|
I_ Reg regfile_alloc(RegFile_R rf) {
|
||||||
U2 allocated = 0;
|
Reg allocated = 0;
|
||||||
for index_iter(Reg, r_id, R_T0, <=, R_T7) {
|
for index_iter(U4, r_id, R_V0, <, R_T9) {
|
||||||
allocated = regfile__alloc_helper(rf->GPR, r_id); Jmp_nZero_(allocated,resolved);
|
allocated = regfile__alloc_helper(rf->GPR, r_id);
|
||||||
|
Jmp_nZero_(allocated,resolved);
|
||||||
}
|
}
|
||||||
allocated = regfile__alloc_helper(rf->GPR, R_V0); Jmp_nZero_(allocated,resolved);
|
|
||||||
allocated = regfile__alloc_helper(rf->GPR, R_V1);
|
|
||||||
assert(allocated != 0);
|
assert(allocated != 0);
|
||||||
resolved: return allocated;
|
resolved: return allocated;
|
||||||
}
|
}
|
||||||
@@ -371,13 +421,32 @@ FI_ void regfile_reset(RegFile_R rf) {
|
|||||||
rf->GPR[0] = u4_lo(regfile_abi_mask);
|
rf->GPR[0] = u4_lo(regfile_abi_mask);
|
||||||
rf->GPR[1] = u4_hi(regfile_abi_mask);
|
rf->GPR[1] = u4_hi(regfile_abi_mask);
|
||||||
}
|
}
|
||||||
FI_ void regfile_reset_mask(RegFile_R rf, U4 mask) {
|
FI_ void regfile_reset_to_mask(RegFile_R rf, U4 mask) {
|
||||||
rf->GPR[0] = u4_lo(mask);
|
rf->GPR[0] = u4_lo(mask);
|
||||||
rf->GPR[1] = u4_hi(mask);
|
rf->GPR[1] = u4_hi(mask);
|
||||||
}
|
}
|
||||||
#pragma endregion RegFileArena (Register File Allocator)
|
#pragma endregion RegFileArena (Register File Allocator)
|
||||||
|
|
||||||
#pragma region Mips Atom Procs
|
#pragma region Mips Atom Procs
|
||||||
|
/* RegUse structs are a convention to organize register allocations for a mips atom procedure.
|
||||||
|
Unlike the usual enum-based declarations, they provide a namespaced scope and have view types via union declarations. */
|
||||||
|
#define RegUse_(proc_name) (tmpl(RegUse,proc_name))
|
||||||
|
|
||||||
|
typedef Struct_(RegUse_example_atom_proc) {
|
||||||
|
Reg const ro_register; // Scratch base carrier.
|
||||||
|
Reg usual_modifiable;
|
||||||
|
union { Reg view_1, view_2, view_3; } t1;
|
||||||
|
};
|
||||||
|
internal MipsAtom* example_atom_proc(AtomArena_R aa, U2 offset, RegUse_example_atom_proc r)
|
||||||
|
MipsAtom_Proc_(aa, {
|
||||||
|
add_si(r.usual_modifiable, r.ro_register, offset),
|
||||||
|
or_u(r.t1.view_1, r.ro_register, 0),
|
||||||
|
branch_lt_zero(r.t1.view_1, atom_offset(example_atom_proc, skip)), BdSlot_ nop,
|
||||||
|
li_s(r.t1.view_2, 100),
|
||||||
|
atom_label(skip)
|
||||||
|
add_si(r.t1.view_3, r.usual_modifiable, 10),
|
||||||
|
mac_yield(),
|
||||||
|
})
|
||||||
|
|
||||||
#pragma endregion Mips Atom Procs
|
#pragma endregion Mips Atom Procs
|
||||||
|
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
#ifdef INTELLISENSE_DIRECTIVES
|
|
||||||
# include "gen/macs.h"
|
|
||||||
# include "gen/offsets.h"
|
|
||||||
# include "math.h"
|
|
||||||
# include "lottes_tape.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
ATOM_FILE_DEBUGGER_LINE_MARKER(math_atom_c);
|
|
||||||
|
|
||||||
#pragma region MACs (Mips Atom Component)
|
|
||||||
|
|
||||||
// FI_ Slice_MipsCode ac_load_imm
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_load_v2s2(AtomBuilder_R ab, U4 rs_x, U4 rs_y, U4 r_base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|
||||||
load_half( rs_x, r_base, offset + O_(V3_S2,x)),
|
|
||||||
load_half( rs_y, r_base, offset + O_(V3_S2,y)),
|
|
||||||
})
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_store_v2s2(AtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|
||||||
store_half(rt_x, base, offset + O_(V2_S2,x)),
|
|
||||||
store_half(rt_y, base, offset + O_(V2_S2,y)),
|
|
||||||
})
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_load_v3s4(AtomBuilder_R ab, U4 rs_x, U4 rs_y, U4 rs_z, U4 r_base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|
||||||
load_word( rs_x, r_base, offset + O_(V3_S4,x)),
|
|
||||||
load_word( rs_y, r_base, offset + O_(V3_S4,y)),
|
|
||||||
load_word( rs_z, r_base, offset + O_(V3_S4,z)),
|
|
||||||
})
|
|
||||||
// TODO(Ed): we could generate these mappings properly..
|
|
||||||
#define ac_load_p3s4 ac_load_v3s4
|
|
||||||
#define mac_load_p3s4 mac_load_v3s4
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_store_v3s4(AtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 rt_z, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|
||||||
store_word(rt_x, base, offset + O_(V3_S4,x)),
|
|
||||||
store_word(rt_y, base, offset + O_(V3_S4,y)),
|
|
||||||
store_word(rt_z, base, offset + O_(V3_S4,z)),
|
|
||||||
})
|
|
||||||
// TODO(Ed): we could generate these mappings properly..
|
|
||||||
#define ac_store_p3s4 ac_store_v3s4
|
|
||||||
#define mac_store_p3s4 mac_store_v3s4
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_sub_v3s4(AtomBuilder_R ab, U4 rds_x, U4 rds_y, U4 rds_z, U4 rt_x, U4 rt_y, U4 rt_z) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|
||||||
sub_s(rds_x, rds_x, rt_x),
|
|
||||||
sub_s(rds_y, rds_y, rt_y),
|
|
||||||
sub_s(rds_z, rds_z, rt_z),
|
|
||||||
})
|
|
||||||
|
|
||||||
FI_ Slice_MipsCode ac_store_rects2(AtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 rt_width, U4 rt_height, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|
||||||
store_half(rt_x, base, offset + O_(Rect_S2,x)),
|
|
||||||
store_half(rt_y, base, offset + O_(Rect_S2,y)),
|
|
||||||
store_half(rt_width, base, offset + O_(Rect_S2,width)),
|
|
||||||
store_half(rt_height, base, offset + O_(Rect_S2,height)),
|
|
||||||
})
|
|
||||||
|
|
||||||
#pragma endregion MACs (Mips Atom Component)
|
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# include "gen/macs.h"
|
||||||
|
# include "gen/offsets.h"
|
||||||
|
# include "math.h"
|
||||||
|
# include "lottes_tape.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
ATOM_FILE_DEBUGGER_LINE_MARKER(math_atom_c);
|
||||||
|
|
||||||
|
#define v3s4_R_0() ((Reg_(V3_S4)){R_0,R_0,R_0})
|
||||||
|
|
||||||
|
typedef Struct_(Reg_V3_S2) { Reg x, y, z; };
|
||||||
|
typedef Struct_(Reg_V3_S4) { Reg x, y, z; }; // Register allocation of a V3_S4
|
||||||
|
typedef Struct_(Reg_P3_S4) { Reg x, y, z; }; // Register allocation of a P3_S4
|
||||||
|
|
||||||
|
#pragma region MACs (Mips Atom Component)
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_load_half_v3(AtomBuilder_R ab, Reg tx, Reg ty, Reg tz, Reg base, U2 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
load_half(tx, base, offset + OA_(U2,[0])),
|
||||||
|
load_half(ty, base, offset + OA_(U2,[1])),
|
||||||
|
load_half(tz, base, offset + OA_(U2,[2])),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_load_v3s2(AtomBuilder_R ab, Reg_(V3_S2) transfer, Reg base, U2 offset) MipsAtomComp_ProcMap_(ab, mac_load_half_v3(transfer.x, transfer.y, transfer.z, base, offset))
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_load_v2s2(AtomBuilder_R ab, U4 rs_x, U4 rs_y, U4 r_base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
load_half(rs_x, r_base, offset + O_(V3_S2,x)),
|
||||||
|
load_half(rs_y, r_base, offset + O_(V3_S2,y)),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_store_v2s2(AtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
store_half(rt_x, base, offset + O_(V2_S2,x)),
|
||||||
|
store_half(rt_y, base, offset + O_(V2_S2,y)),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_load_word_v3(AtomBuilder_R ab, Reg tx, Reg ty, Reg tz, Reg base, U2 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
load_word(tx, base, offset + OA_(U4,[0])),
|
||||||
|
load_word(ty, base, offset + OA_(U4,[1])),
|
||||||
|
load_word(tz, base, offset + OA_(U4,[2])),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_load_v3s4(AtomBuilder_R ab, Reg_(V3_S4) transfer, Reg base, U2 offset) MipsAtomComp_ProcMap_(ab, mac_load_word_v3(transfer.x, transfer.y, transfer.z, base, offset))
|
||||||
|
FI_ Slice_MipsCode ac_load_p3s4(AtomBuilder_R ab, Reg_(P3_S4) transfer, Reg base, U2 offset) MipsAtomComp_ProcMap_(ab, mac_load_word_v3(transfer.x, transfer.y, transfer.z, base, offset))
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_store_half_v3(AtomBuilder_R ab, Reg tx, Reg ty, Reg tz, Reg base, U2 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
store_half(tx, base, offset + OA_(U2,[0])),
|
||||||
|
store_half(ty, base, offset + OA_(U2,[1])),
|
||||||
|
store_half(tz, base, offset + OA_(U2,[2])),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_store_v3s2(AtomBuilder_R ab, Reg_(V3_S2) transfer, Reg base, U2 offset) MipsAtomComp_ProcMap_(ab, mac_store_half_v3(transfer.x, transfer.y, transfer.z, base, offset))
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_store_word_v3(AtomBuilder_R ab, Reg tx, Reg ty, Reg tz, Reg base, U2 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
store_word(tx, base, offset + OA_(U4,[0])),
|
||||||
|
store_word(ty, base, offset + OA_(U4,[1])),
|
||||||
|
store_word(tz, base, offset + OA_(U4,[2])),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_store_v3s4(AtomBuilder_R ab, Reg_(V3_S4) transfer, Reg base, U2 offset) MipsAtomComp_ProcMap_(ab, mac_store_word_v3(transfer.x, transfer.y, transfer.z, base, offset))
|
||||||
|
FI_ Slice_MipsCode ac_store_p3s4(AtomBuilder_R ab, Reg_(P3_S4) transfer, Reg base, U2 offset) MipsAtomComp_ProcMap_(ab, mac_store_word_v3(transfer.x, transfer.y, transfer.z, base, offset))
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_add_si_v3s4(AtomBuilder_R ab, Reg rt_x, Reg rt_y, Reg rt_z, Reg base, U2 offset)
|
||||||
|
atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
add_si(rt_x, base, O_(V3_S4,x)),
|
||||||
|
add_si(rt_y, base, O_(V3_S4,y)),
|
||||||
|
add_si(rt_z, base, O_(V3_S4,z)),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_sub_s_v3(AtomBuilder_R ab
|
||||||
|
, Reg dx, Reg dy, Reg dz
|
||||||
|
, Reg sx, Reg sy, Reg sz
|
||||||
|
, Reg tx, Reg ty, Reg tz
|
||||||
|
) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
sub_s(dx, sx, tx),
|
||||||
|
sub_s(dy, sy, ty),
|
||||||
|
sub_s(dz, sz, tz),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_sub_v3s4(AtomBuilder_R ab, Reg_(V3_S4) d, Reg_(V3_S4) s, Reg_(V3_S4) t) MipsAtomComp_ProcMap_(ab, mac_sub_s_v3(d.x, d.y, d.z, s.x, s.y, s.z, t.x, t.y, t.z))
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_sub_s_v3_self(AtomBuilder_R ab, Reg ds_x, Reg ds_y, Reg ds_z, Reg tx, Reg ty, Reg tz) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
sub_s(ds_x, ds_x, tx),
|
||||||
|
sub_s(ds_y, ds_y, ty),
|
||||||
|
sub_s(ds_z, ds_z, tz),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_sub_v3s4_self(AtomBuilder_R ab, Reg_(V3_S4) ds, Reg_(V3_S4) t) MipsAtomComp_ProcMap_(ab, mac_sub_s_v3_self(ds.x, ds.y, ds.z, t.x, t.y, t.z))
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_store_rects2(AtomBuilder_R ab, U4 rt_x, U4 rt_y, U4 rt_width, U4 rt_height, U4 base, U4 offset) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
store_half(rt_x, base, offset + O_(Rect_S2,x)),
|
||||||
|
store_half(rt_y, base, offset + O_(Rect_S2,y)),
|
||||||
|
store_half(rt_width, base, offset + O_(Rect_S2,width)),
|
||||||
|
store_half(rt_height, base, offset + O_(Rect_S2,height)),
|
||||||
|
})
|
||||||
|
|
||||||
|
#pragma endregion MACs (Mips Atom Component)
|
||||||
+13
-2
@@ -58,13 +58,13 @@ typedef Struct_(Str8) { UTF8* ptr; U4 len; };
|
|||||||
typedef Struct_(Slice_Str8) { Str8* ptr; U4 len; };
|
typedef Struct_(Slice_Str8) { Str8* ptr; U4 len; };
|
||||||
#define slit(string_literal) (Str8){ (UTF8*) string_literal, S_(string_literal) - 1 }
|
#define slit(string_literal) (Str8){ (UTF8*) string_literal, S_(string_literal) - 1 }
|
||||||
|
|
||||||
typedef Struct_(Slice) { B1* ptr; U4 len; }; // Untyped Slice (byte-addressable; .len in elements)
|
typedef Struct_(Slice) { B1* ptr; U4 len; };
|
||||||
FI_ Slice slice_ut_(U4 ptr, U4 len) { return (Slice){(B1*)ptr, len}; }
|
FI_ Slice slice_ut_(U4 ptr, U4 len) { return (Slice){(B1*)ptr, len}; }
|
||||||
|
|
||||||
#define Slice_(type) Struct_(tmpl(Slice,type)) { type* ptr; U4 len; }
|
#define Slice_(type) Struct_(tmpl(Slice,type)) { type* ptr; U4 len; }
|
||||||
typedef Slice_(B1);
|
typedef Slice_(B1);
|
||||||
#define slice_assert(s) do { assert((s).ptr != 0); assert((s).len > 0); } while(0)
|
#define slice_assert(s) do { assert((s).ptr != 0); assert((s).len > 0); } while(0)
|
||||||
#define slice_end(slice) ((slice).ptr + S_slice(slice) / S_(B1)) /* byte-ptr arithmetic; .len is in elements per slice convention */
|
#define slice_end(slice) ((slice).ptr + S_slice(slice) / S_(B1))
|
||||||
#define S_slice(s) ((s).len * S_((s).ptr[0]))
|
#define S_slice(s) ((s).len * S_((s).ptr[0]))
|
||||||
|
|
||||||
#define slice_ut(ptr,len) slice_ut_(u4_(ptr), u4_(len))
|
#define slice_ut(ptr,len) slice_ut_(u4_(ptr), u4_(len))
|
||||||
@@ -131,3 +131,14 @@ FI_ U4 farena_unused_start(FArena arena) { return arena.start + arena.used; }
|
|||||||
#define farena_push_array(arena, type, amount, ...) (tmpl(Slice,type)){ C_(type*, farena_push((arena), (amount), opt_(farena, .type_width=S_(type), __VA_ARGS__)).ptr), (amount) }
|
#define farena_push_array(arena, type, amount, ...) (tmpl(Slice,type)){ C_(type*, farena_push((arena), (amount), opt_(farena, .type_width=S_(type), __VA_ARGS__)).ptr), (amount) }
|
||||||
|
|
||||||
#pragma endregion FArena
|
#pragma endregion FArena
|
||||||
|
|
||||||
|
#pragma region BIOS Scratchpad
|
||||||
|
/* BIOS scratchpad location. 1 KB at 0x1F800000.
|
||||||
|
* TapeHostFrame occupies the final 44 bytes while tape code executes. */
|
||||||
|
enum {
|
||||||
|
Scratchpad_Loc = 0x1F800000,
|
||||||
|
Scratchpad_Len = 0x400, /* 1 KB */
|
||||||
|
Scratchpad_End = Scratchpad_Loc + Scratchpad_Len, /* 0x1F800400 */
|
||||||
|
};
|
||||||
|
#define C_scratch(type) C_(type, Scratchpad_Loc)
|
||||||
|
#pragma endregion BIOS Scratchpad
|
||||||
|
|||||||
+40
-5
@@ -16,6 +16,34 @@ atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|||||||
or_i_self( dst, u4_lo(imm)),
|
or_i_self( dst, u4_lo(imm)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_shift_aright_v3_self(AtomBuilder_R ab, Reg dt_x, Reg dt_y, Reg dt_z, U2 shift_amount)
|
||||||
|
MipsAtomComp_Proc_( ab, {
|
||||||
|
shift_aright(dt_x, dt_x, shift_amount),
|
||||||
|
shift_aright(dt_y, dt_y, shift_amount),
|
||||||
|
shift_aright(dt_z, dt_z, shift_amount),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_shift_aright_v3s4_self(AtomBuilder_R ab, Reg_(V3_S4) dt, U2 shift) MipsAtomComp_ProcMap_(ab, mac_shift_aright_v3_self(dt.x, dt.y, dt.z, shift))
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_shift_aright_var_v3(AtomBuilder_R ab
|
||||||
|
, Reg rd_v0, Reg rd_v1, Reg rd_v2
|
||||||
|
, Reg rs_v0, Reg rs_v1, Reg rs_v2
|
||||||
|
, Reg r_shift)
|
||||||
|
MipsAtomComp_Proc_(ab, {
|
||||||
|
shift_aright_var(rd_v0, rs_v0, r_shift),
|
||||||
|
shift_aright_var(rd_v1, rs_v1, r_shift),
|
||||||
|
shift_aright_var(rd_v2, rs_v2, r_shift),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_shift_aright_var_v3_self(AtomBuilder_R ab, Reg rds_v0, Reg rds_v1, Reg rds_v2, Reg r_shift)
|
||||||
|
atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
|
shift_aright_var(rds_v0, rds_v0, r_shift),
|
||||||
|
shift_aright_var(rds_v1, rds_v1, r_shift),
|
||||||
|
shift_aright_var(rds_v2, rds_v2, r_shift),
|
||||||
|
})
|
||||||
|
|
||||||
|
FI_ Slice_MipsCode ac_shift_aright_var_v3s4_self(AtomBuilder_R ab, Reg_(V3_S4) ds, Reg shift) MipsAtomComp_ProcMap_(ab, mac_shift_aright_var_v3_self(ds.x, ds.y, ds.z, shift))
|
||||||
|
|
||||||
#pragma endregion MACs (Mips Atom Components)
|
#pragma endregion MACs (Mips Atom Components)
|
||||||
|
|
||||||
#pragma region Baked Atoms
|
#pragma region Baked Atoms
|
||||||
@@ -27,9 +55,15 @@ atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
|||||||
* 3. $t0 = bios_table_addr ; t0 = &BIOS A-function table
|
* 3. $t0 = bios_table_addr ; t0 = &BIOS A-function table
|
||||||
* 4. jalr $t0, $ra ; call BIOS(flushcache)
|
* 4. jalr $t0, $ra ; call BIOS(flushcache)
|
||||||
* nop ; branch delay slot
|
* nop ; branch delay slot
|
||||||
* 5. lw $ra, 4($sp); jr $ra ; restore & return
|
* 5. lw $ra, 4($sp)
|
||||||
* 6. sp += 8
|
* 6. sp += 8 ; load-delay
|
||||||
|
* 7. jr $ra
|
||||||
|
* nop ; BD
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
#if 0
|
||||||
|
// Note: Can't do this without having a way to do C-Runtime frame call from Tape ABI.
|
||||||
|
// Don't support this without adjusting scratchpad to save tape frame in some way.
|
||||||
internal MipsAtom_(mips_flush_icache) {
|
internal MipsAtom_(mips_flush_icache) {
|
||||||
add_ui(R_SP, R_SP, -MipsStackAlignment), // sp -= 8
|
add_ui(R_SP, R_SP, -MipsStackAlignment), // sp -= 8
|
||||||
store_word(R_RA, R_SP, S_(U4)), // sw $ra, 4($sp)
|
store_word(R_RA, R_SP, S_(U4)), // sw $ra, 4($sp)
|
||||||
@@ -37,9 +71,10 @@ internal MipsAtom_(mips_flush_icache) {
|
|||||||
add_ui(R_T0, R_0, bios_table_addr), // addiu $t0, $0, 0xA0
|
add_ui(R_T0, R_0, bios_table_addr), // addiu $t0, $0, 0xA0
|
||||||
jump_link(R_T0, R_RA), nop, // jalr $t0, $ra, BD slot
|
jump_link(R_T0, R_RA), nop, // jalr $t0, $ra, BD slot
|
||||||
load_word(R_RA, R_SP, S_(U4)), // lw $ra, 4($sp)
|
load_word(R_RA, R_SP, S_(U4)), // lw $ra, 4($sp)
|
||||||
jump_reg(R_RA), // jr $ra
|
add_ui(R_SP, R_SP, MipsStackAlignment), // sp += 8 (load-delay)
|
||||||
add_ui(R_SP, R_SP, MipsStackAlignment), // sp += 8 (BD)
|
jump_reg(R_RA), nop, // jr $ra, BD slot
|
||||||
mac_yield(),
|
// mac_yield(),
|
||||||
};
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
#pragma endregion Baked Atoms
|
#pragma endregion Baked Atoms
|
||||||
|
|||||||
+15
-19
@@ -81,13 +81,8 @@ enum {
|
|||||||
* (e.g. for asm clobber lists and register-variable declarations via `rgcc(R_X)`).
|
* (e.g. for asm clobber lists and register-variable declarations via `rgcc(R_X)`).
|
||||||
* The enum value is bound to the `#define` so the two forms cannot drift apart.
|
* The enum value is bound to the `#define` so the two forms cannot drift apart.
|
||||||
*
|
*
|
||||||
* Only registers that get stringified need a `_Code` form; the rest are plain enum values.
|
|
||||||
* If you need to add a new one, follow the pattern:
|
|
||||||
* #define R_T7_Code 15
|
|
||||||
* R_T7 = R_T7_Code, // in the enum
|
|
||||||
*
|
|
||||||
* User code should always reference the enum form (`R_T4`) at arithmetic sites and let
|
* User code should always reference the enum form (`R_T4`) at arithmetic sites and let
|
||||||
* `rlit(R_T4_Code)` / `rgcc(R_T4)` handle the stringify cases — never write the bare number `12`.
|
* `rlit(R_T4_Code)` / `rgcc(R_T4)` handle the stringify cases
|
||||||
* ============================================================================ */
|
* ============================================================================ */
|
||||||
#define R_0_Code 0
|
#define R_0_Code 0
|
||||||
#define R_AT_Code 1
|
#define R_AT_Code 1
|
||||||
@@ -252,12 +247,12 @@ enum {
|
|||||||
enum { _BitOffsets = 0
|
enum { _BitOffsets = 0
|
||||||
/* Bit Offsets for MIPS Instruction Fields */
|
/* Bit Offsets for MIPS Instruction Fields */
|
||||||
|
|
||||||
, OPCODE_SHIFT = 26
|
, OPCODE_POS = 26
|
||||||
, RS_SHIFT = 21
|
, RS_POS = 21
|
||||||
, RT_SHIFT = 16
|
, RT_POS = 16
|
||||||
, RD_SHIFT = 11
|
, RD_POS = 11
|
||||||
, SHAMT_SHIFT = 6 /* Shift Amount */
|
, SHAMT_POS = 6 /* Shift Amount: Offset Position */
|
||||||
, FC_SHIFT = 0
|
, FC_POS = 0
|
||||||
|
|
||||||
/* IMM_MASK is the 16-bit two's-complement truncation for the immediate field.
|
/* IMM_MASK is the 16-bit two's-complement truncation for the immediate field.
|
||||||
* It is NOT a range guard — it is load-bearing for negative branch offsets
|
* It is NOT a range guard — it is load-bearing for negative branch offsets
|
||||||
@@ -268,12 +263,12 @@ enum { _BitOffsets = 0
|
|||||||
, IMM_MASK = 0xFFFF
|
, IMM_MASK = 0xFFFF
|
||||||
};
|
};
|
||||||
|
|
||||||
#define enc_op(op) ((op) << OPCODE_SHIFT)
|
#define enc_op(op) ((op) << OPCODE_POS)
|
||||||
#define enc_rs(rs) ((rs) << RS_SHIFT)
|
#define enc_rs(rs) ((rs) << RS_POS)
|
||||||
#define enc_rt(rt) ((rt) << RT_SHIFT)
|
#define enc_rt(rt) ((rt) << RT_POS)
|
||||||
#define enc_rd(rd) ((rd) << RD_SHIFT)
|
#define enc_rd(rd) ((rd) << RD_POS)
|
||||||
#define enc_shamt(shamt) ((shamt) << SHAMT_SHIFT)
|
#define enc_shamt(shamt) ((shamt) << SHAMT_POS)
|
||||||
#define enc_fc(fc) ((fc) << FC_SHIFT)
|
#define enc_fc(fc) ((fc) << FC_POS)
|
||||||
#define enc_imm(imm) ((imm) & IMM_MASK)
|
#define enc_imm(imm) ((imm) & IMM_MASK)
|
||||||
|
|
||||||
/* MIPS R-Type Instruction Format (Register-to-Register) */
|
/* MIPS R-Type Instruction Format (Register-to-Register) */
|
||||||
@@ -586,6 +581,7 @@ enum { _BitOffsets = 0
|
|||||||
, jump_link(rtmp_0, rret_addr) \
|
, jump_link(rtmp_0, rret_addr) \
|
||||||
, nop \
|
, nop \
|
||||||
, load_word(rret_addr, rstack_ptr, 4) \
|
, load_word(rret_addr, rstack_ptr, 4) \
|
||||||
, jump_reg(rret_addr) \
|
|
||||||
, add_ui(rstack_ptr, rstack_ptr, MipsStackAlignment) \
|
, add_ui(rstack_ptr, rstack_ptr, MipsStackAlignment) \
|
||||||
|
, jump_reg(rret_addr) \
|
||||||
|
, nop \
|
||||||
) asm_clobber: clbr_volatile_gprs )
|
) asm_clobber: clbr_volatile_gprs )
|
||||||
|
|||||||
@@ -13,8 +13,7 @@ ATOM_FILE_DEBUGGER_LINE_MARKER(pad_atom_c);
|
|||||||
|
|
||||||
FI_ Slice_MipsCode ac_pad_set_centered_axes(AtomBuilder_R ab, Reg state, Reg scratch) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
FI_ Slice_MipsCode ac_pad_set_centered_axes(AtomBuilder_R ab, Reg state, Reg scratch) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
load_upper_i(scratch, (PadAxis_Centered >> 16) & 0xFFFF),
|
load_upper_i(scratch, (PadAxis_Centered >> 16) & 0xFFFF),
|
||||||
or_i_self( scratch, PadAxis_Centered & 0xFFFF),
|
or_i_self( scratch, PadAxis_Centered & 0xFFFF), // mac_load_word_imm(scratch, PadAxis_Centered),
|
||||||
// mac_load_word_imm(scratch, PadAxis_Centered),
|
|
||||||
store_word( scratch, state, O_(PadState,axes)),
|
store_word( scratch, state, O_(PadState,axes)),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -33,7 +32,7 @@ FI_ Slice_MipsCode ac_pad_set_status(AtomBuilder_R ab, U4 r_tmp, U1 r_state, U4
|
|||||||
* the preceding load_half_u with an instruction that doesn't read r_buttons). */
|
* the preceding load_half_u with an instruction that doesn't read r_buttons). */
|
||||||
FI_ Slice_MipsCode ac_pad_store_inverted_buttons(AtomBuilder_R ab, U1 r_buttons, U1 r_pad_state) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
FI_ Slice_MipsCode ac_pad_store_inverted_buttons(AtomBuilder_R ab, U1 r_buttons, U1 r_pad_state) atom_dbg_skip MipsAtomComp_Proc_(ab, {
|
||||||
nor_u( r_buttons, r_buttons, R_0),
|
nor_u( r_buttons, r_buttons, R_0),
|
||||||
store_half( r_buttons, r_pad_state, O_(PadState,buttons)),
|
store_half(r_buttons, r_pad_state, O_(PadState,buttons)),
|
||||||
})
|
})
|
||||||
|
|
||||||
#pragma endregion MACs (Mips Atom Components)
|
#pragma endregion MACs (Mips Atom Components)
|
||||||
@@ -125,7 +124,7 @@ atom_label(id_dispatch) /* === Case 3-6: ID dispatch */
|
|||||||
* R_T5 is then "dead" — only consumed at the analog_pad range check downstream. */
|
* R_T5 is then "dead" — only consumed at the analog_pad range check downstream. */
|
||||||
mac_pad_set_status(R_T4, R_PadState, PadStatus_Digital),
|
mac_pad_set_status(R_T4, R_PadState, PadStatus_Digital),
|
||||||
load_half_u( R_T4, R_PadRaw, O_(PadBiosRaw, buttons)), /* R_T4 = raw_buttons; */
|
load_half_u( R_T4, R_PadRaw, O_(PadBiosRaw, buttons)), /* R_T4 = raw_buttons; */
|
||||||
mac_load_word_imm(R_T5, PadAxis_Centered), /* fills the buttons-load's delay slot (doesn't read R_T4) */
|
mac_load_word_imm( R_T5, PadAxis_Centered), /* fills the buttons-load's delay slot (doesn't read R_T4) */
|
||||||
// load_upper_i(R_T5, PadAxis_Centered_Hi), or_i_self(R_T5, PadAxis_Centered_Lo),
|
// load_upper_i(R_T5, PadAxis_Centered_Hi), or_i_self(R_T5, PadAxis_Centered_Lo),
|
||||||
mac_pad_store_inverted_buttons(R_T4, R_PadState), /* R_T4 settled: nor + sh writes ~raw_buttons to state.buttons */
|
mac_pad_store_inverted_buttons(R_T4, R_PadState), /* R_T4 settled: nor + sh writes ~raw_buttons to state.buttons */
|
||||||
store_word(R_T5, R_PadState, O_(PadState, axes)), /* single sw writes the 4-byte axes block at offset 8 (left_x, left_y, right_x, right_y) */
|
store_word(R_T5, R_PadState, O_(PadState, axes)), /* single sw writes the 4-byte axes block at offset 8 (left_x, left_y, right_x, right_y) */
|
||||||
|
|||||||
+2
-11
@@ -6,16 +6,10 @@
|
|||||||
# include "pad.h"
|
# include "pad.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/* Uses ONE 8-byte frame allocated via the compiler's standard prologue.
|
/* Uses an 8-byte frame allocated via the compiler's standard prologue.
|
||||||
* 4 wasted-arg words for B(12h) InitPAD2 are at [SP+0..15] but are not explicitly allocated.
|
* 4 wasted-arg words for B(12h) InitPAD2 are at [SP+0..15] but are not explicitly allocated.
|
||||||
* Compiler handles the MIPS O32 "wasted stack" convention for us by treating the B-call as a 4-arg call.
|
* Compiler handles the MIPS O32 "wasted stack" convention for us by treating the B-call as a 4-arg call.
|
||||||
*
|
*/
|
||||||
* The buffer pointers are passed as arguments so the compiler keeps them in callee-saved registers;
|
|
||||||
* The B(12h) asm volatile block does NOT clobber those registers (it clobbers only the volatile GPRs + B-table arg registers explicitly).
|
|
||||||
* The C-level writes after the call re-load the pointers from their callee-saved homes.
|
|
||||||
*
|
|
||||||
* The clobber list for both B-calls names the full BIOS destroy set documented in kernelbios.md:167-174 (R1..R15, R24..R25, R31, HI/LO).
|
|
||||||
* The kernel-ABI "volatile GPRs" subset is clb_mem_drain; the rest of the destroy set is enumerated explicitly here. */
|
|
||||||
NI_ void pad_bios_init_start(PadBiosRaw* raw0, PadBiosRaw* raw1)
|
NI_ void pad_bios_init_start(PadBiosRaw* raw0, PadBiosRaw* raw1)
|
||||||
{
|
{
|
||||||
/* Pin raw0 + raw1 to $a0 + $a1 via rgcc; the B(12h) call uses these directly.
|
/* Pin raw0 + raw1 to $a0 + $a1 via rgcc; the B(12h) call uses these directly.
|
||||||
@@ -24,9 +18,6 @@ NI_ void pad_bios_init_start(PadBiosRaw* raw0, PadBiosRaw* raw1)
|
|||||||
register PadBiosRaw* p1 rgcc(R_A1) = raw1;
|
register PadBiosRaw* p1 rgcc(R_A1) = raw1;
|
||||||
(void)p0; (void)p1;
|
(void)p0; (void)p1;
|
||||||
|
|
||||||
// TODO(Ed): Properly annotate the raw values in the inline asm instructions.
|
|
||||||
// Use enums.
|
|
||||||
|
|
||||||
/* B(12h) InitPAD2(raw0, 0x22, raw1, 0x22)
|
/* B(12h) InitPAD2(raw0, 0x22, raw1, 0x22)
|
||||||
* $a0 = raw0 (rgcc-bound; survives the sequence below)
|
* $a0 = raw0 (rgcc-bound; survives the sequence below)
|
||||||
* $a1 = raw1 (preserved into $a2 before $a1 is overwritten)
|
* $a1 = raw1 (preserved into $a2 before $a1 is overwritten)
|
||||||
|
|||||||
+2
-9
@@ -4,10 +4,7 @@
|
|||||||
# include "math.h"
|
# include "math.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/* PSX button bit positions — 1:1 with PSX-SPX docs at docs/psx-spx/docs/controllersandmemorycards.md:405-421.
|
// PSX button bit positions: PSX-SPX docs/psx-spx/docs/controllersandmemorycards.md:405-421.
|
||||||
* Wire is active-low (0 = pressed).
|
|
||||||
* The decoder atom computes buttons = (~raw_buttons) & 0xFFFF;
|
|
||||||
* active-low-to-active-high inversion is applied bit-by-bit. */
|
|
||||||
typedef Enum_(U2, PadBtns) {
|
typedef Enum_(U2, PadBtns) {
|
||||||
Bit_(Pad_Select, 0),
|
Bit_(Pad_Select, 0),
|
||||||
Bit_(Pad_L3, 1),
|
Bit_(Pad_L3, 1),
|
||||||
@@ -62,11 +59,7 @@ typedef Enum_(U4, PadStatus) {
|
|||||||
PadStatus_Invalid,
|
PadStatus_Invalid,
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Distinct from the game-facing PadStatus enum: PadRawStatus_Ok and PadRawStatus_Timeout are raw BIOS values;
|
// Distinct from the game-facing PadStatus enum: PadRawStatus_Ok and PadRawStatus_Timeout are raw BIOS values
|
||||||
* PadStatus_* are game-facing post-decode states. PadUnknownId_Sentinel is written by the decoder
|
|
||||||
* when the controller id does not match any known controller type.
|
|
||||||
* PadAxisCentered_Word: Four-byte 0x80 pattern used to clear / center
|
|
||||||
* four byte axes at PadState.left_x through PadState.right_y. */
|
|
||||||
typedef Enum_(U1, PadRawStatus) {
|
typedef Enum_(U1, PadRawStatus) {
|
||||||
PadRawStatus_Ok = 0x00,
|
PadRawStatus_Ok = 0x00,
|
||||||
PadRawStatus_Timeout = 0xFF,
|
PadRawStatus_Timeout = 0xFF,
|
||||||
|
|||||||
+1
-1
@@ -104,7 +104,7 @@ void gte_matrix_set_translation(MT3_S2S4* mat) asm("SetTransMatrix");
|
|||||||
|
|
||||||
// Einheit, Metrication to unit vector. "Normalization", not Orthogonal "Normal, Normalis". Directionalization.
|
// Einheit, Metrication to unit vector. "Normalization", not Orthogonal "Normal, Normalis". Directionalization.
|
||||||
// RGA(Lengyel): Normalize the bulk of a zero-weight direction. This is not finite-point unitization (which forces w=1).
|
// RGA(Lengyel): Normalize the bulk of a zero-weight direction. This is not finite-point unitization (which forces w=1).
|
||||||
S4 normalize_v3s4(V3_S4* v0, V3_S4* v1) asm("VectorNormal");
|
S4 psy_normalize_v3s4(V3_S4* v0, V3_S4* v1) asm("VectorNormal");
|
||||||
|
|
||||||
// RGA(Lengyel): Apply the matrix expansion of a rigid transformation.
|
// RGA(Lengyel): Apply the matrix expansion of a rigid transformation.
|
||||||
// Motor antiproduct is equivalent for unitized points; LA form is what GTE consumes.
|
// Motor antiproduct is equivalent for unitized points; LA form is what GTE consumes.
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ WORD_COUNT(gte_mv_to_ctrl_r, 1)
|
|||||||
WORD_COUNT(gte_sw, 1)
|
WORD_COUNT(gte_sw, 1)
|
||||||
WORD_COUNT(gte_cmdw_rtpt, 1)
|
WORD_COUNT(gte_cmdw_rtpt, 1)
|
||||||
WORD_COUNT(gte_cmdw_nclip, 1)
|
WORD_COUNT(gte_cmdw_nclip, 1)
|
||||||
|
WORD_COUNT(gte_cmdw_op, 1)
|
||||||
WORD_COUNT(gte_avg_sort_z3, 1)
|
WORD_COUNT(gte_avg_sort_z3, 1)
|
||||||
WORD_COUNT(gte_cmdw_sqr, 1)
|
WORD_COUNT(gte_cmdw_sqr, 1)
|
||||||
WORD_COUNT(gte_cmdw_gpf, 1)
|
WORD_COUNT(gte_cmdw_gpf, 1)
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ enum {
|
|||||||
atom_offset_end_low_exit_stick = _atom_offset_end_low_exit_stick,
|
atom_offset_end_low_exit_stick = _atom_offset_end_low_exit_stick,
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- atom: pad_input_cam (40 words) ---
|
// --- atom: pad_input_cam (39 words) ---
|
||||||
|
|
||||||
#define _atom_offset_left_x_exit_left_x 3
|
#define _atom_offset_left_x_exit_left_x 3
|
||||||
#define _atom_offset_right_x_exit_right_x 3
|
#define _atom_offset_right_x_exit_right_x 3
|
||||||
@@ -44,7 +44,7 @@ enum {
|
|||||||
atom_offset_circle_z_exit_circle_z = _atom_offset_circle_z_exit_circle_z,
|
atom_offset_circle_z_exit_circle_z = _atom_offset_circle_z_exit_circle_z,
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- atom: cube_g4_face (76 words) ---
|
// --- atom: cube_g4_face (73 words) ---
|
||||||
|
|
||||||
#define _atom_offset_cull_cube_g4_face_exit 41
|
#define _atom_offset_cull_cube_g4_face_exit 41
|
||||||
#define _atom_offset_bounds_chk_cube_g4_face_exit 24
|
#define _atom_offset_bounds_chk_cube_g4_face_exit 24
|
||||||
@@ -54,7 +54,7 @@ enum {
|
|||||||
atom_offset_bounds_chk_cube_g4_face_exit = _atom_offset_bounds_chk_cube_g4_face_exit,
|
atom_offset_bounds_chk_cube_g4_face_exit = _atom_offset_bounds_chk_cube_g4_face_exit,
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- atom: floor_f3_face (58 words) ---
|
// --- atom: floor_f3_face (56 words) ---
|
||||||
|
|
||||||
#define _atom_offset_culling_floor_f3_face_exit 25
|
#define _atom_offset_culling_floor_f3_face_exit 25
|
||||||
#define _atom_offset_bounds_chk_floor_f3_face_exit 16
|
#define _atom_offset_bounds_chk_floor_f3_face_exit 16
|
||||||
|
|||||||
@@ -10,9 +10,9 @@
|
|||||||
# include "duffle/pad.h"
|
# include "duffle/pad.h"
|
||||||
# include "duffle/word_count.metadata.h"
|
# include "duffle/word_count.metadata.h"
|
||||||
# include "duffle/psyq.h"
|
# include "duffle/psyq.h"
|
||||||
# include "duffle/math.atom.c"
|
# include "duffle/math.atom.h"
|
||||||
|
# include "duffle/gte.atom.h"
|
||||||
# include "duffle/mips.atom.c"
|
# include "duffle/mips.atom.c"
|
||||||
# include "duffle/gte.atom.c"
|
|
||||||
# include "duffle/gp.atom.c"
|
# include "duffle/gp.atom.c"
|
||||||
# include "duffle/psyq.atom.c"
|
# include "duffle/psyq.atom.c"
|
||||||
# include "gen/offsets.h"
|
# include "gen/offsets.h"
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
# include "hello_camera.h"
|
# include "hello_camera.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
ATOM_FILE_DEBUGGER_LINE_MARKER(hello_joypad_atom_c);
|
ATOM_FILE_DEBUGGER_LINE_MARKER(hello_camera_atom_c);
|
||||||
|
|
||||||
#pragma region MACs (Mips Atom components)
|
#pragma region MACs (Mips Atom components)
|
||||||
|
|
||||||
@@ -92,441 +92,138 @@ MipsAtomComp_Proc_(ab, {
|
|||||||
#pragma endregion MACs
|
#pragma endregion MACs
|
||||||
|
|
||||||
#pragma region Atom Procs
|
#pragma region Atom Procs
|
||||||
// Modular Atoms
|
|
||||||
|
|
||||||
enum {
|
|
||||||
// TODO(Ed): We can resolve scratch at anytime its fixed to a specific address.
|
|
||||||
R_ResolveScratch = R_T4 atom_reg atom_type(U4*),
|
|
||||||
#define R_ResolveScratch_Code R_T4_Code
|
|
||||||
};
|
|
||||||
typedef Struct_(Binds_ResolveLookAt) {
|
|
||||||
MT3_S2S4* look_at;
|
|
||||||
P3_S4* eye;
|
|
||||||
P3_S4* target;
|
|
||||||
V3_S4* up_in;
|
|
||||||
};
|
|
||||||
|
|
||||||
/* ─── ResolveLookAtScratch — offset schema for the resolve_look_at bundle's */
|
|
||||||
typedef Struct_(ResolveLookAtScratch) {
|
|
||||||
V3_S4 fwd; /* offset +0 (16 bytes — 4 S4 fields incl. internal pad) */
|
|
||||||
V3_S4 uz; /* offset +16 (16 bytes) */
|
|
||||||
V3_S4 right; /* offset +32 (16 bytes) */
|
|
||||||
V3_S4 ux; /* offset +48 (16 bytes) */
|
|
||||||
V3_S4 up; /* offset +64 (16 bytes) */
|
|
||||||
V3_S4 uy; /* offset +80 (16 bytes) */
|
|
||||||
P3_S4 eye; /* offset +96 (16 bytes; storage alias of V3_S4) */
|
|
||||||
P3_S4 target; /* offset +112 (16 bytes; storage alias of V3_S4) */
|
|
||||||
V3_S4 up_in; /* offset +128 (16 bytes) */
|
|
||||||
};
|
|
||||||
|
|
||||||
|
#pragma region resolve_look_at
|
||||||
/* ─── resolve_look_at bundle chain atoms ──────────────────────────── */
|
/* ─── resolve_look_at bundle chain atoms ──────────────────────────── */
|
||||||
|
|
||||||
typedef Struct_(Binds_ResolveLookAtSub) {
|
typedef AtomBundle_(resolve_look_at) { MipsAtom
|
||||||
P3_S4* target; /* U4 (C-side P3_S4* — read by atom 0 directly; NOT a scratchpad address) */
|
*input_and_sub,
|
||||||
P3_S4* eye; /* U4 (C-side P3_S4* — read by atom 0 directly; staged into scratchpad by atom 0) */
|
*normalize_fwd_uz,
|
||||||
V3_S4* up_in; /* U4 (C-side V3_S4* — read by atom 0 directly; staged into scratchpad by atom 0) */
|
*cross_to_right,
|
||||||
ResolveLookAtScratch* scratchpad;
|
*normalize_right_ux,
|
||||||
|
*cross_to_up,
|
||||||
|
*normalize_up_uy,
|
||||||
|
*populate_mt3s4s2;
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Atom 0 in the bundle: input_and_sub. Stages C-side inputs into the scratchpad and computes fwd = target - eye.
|
typedef Struct_(ResolveLookAtScratch) {
|
||||||
* Staging work:
|
V3_S4 fwd;
|
||||||
* * Stage eye.x/y/z → scratch (for atom 6's translation column)
|
V3_S4 uz;
|
||||||
* * Stage up_in.x/y/z → scratch (for atom 2's outer-product operand)
|
V3_S4 right;
|
||||||
* * Compute fwd = target - eye, store fwd.x/y/z → scratch+0/+4/+8 (for atom 1)
|
V3_S4 ux;
|
||||||
* GPR codes (assigned by resolve_look_at_init):
|
V3_S4 up;
|
||||||
* r_target_ptr : R_T0
|
V3_S4 uy;
|
||||||
* r_eye_ptr : R_T1
|
P3_S4 eye;
|
||||||
* r_up_in_ptr : R_T2
|
P3_S4 target;
|
||||||
* r_scratch : R_T4 (R_ResolveScratch; wave-context carrier)
|
V3_S4 up_in;
|
||||||
* r_tmp0 : R_T3 (stage eye/up_in + load eye.y)
|
};
|
||||||
* r_tmp1 : R_T5 (stage eye/up_in + load eye.z)
|
|
||||||
* r_tmp2 : R_T6 (stage eye/up_in + load target.x)
|
typedef Struct_(Binds_ResolveLookAtSub) {
|
||||||
* r_tmp3 : R_T7 (stage eye/up_in + load target.y)
|
P3_S4* target;
|
||||||
* R_AT : hardcoded (load eye.y / eye.z / target.z)
|
P3_S4* eye;
|
||||||
* R_V0 : hardcoded (load eye.z / target.z)
|
V3_S4* up_in;
|
||||||
* Pool cost: 8 GPRs + R_T4 (carrier) + R_AT + R_V0 (hardcoded) = 11 GPRs.
|
};
|
||||||
*/
|
typedef Struct_(RegUse_resolve_look_at_input_and_sub) {
|
||||||
internal MipsAtom* resolve_look_at__input_and_sub_proc(AtomArena_R aa,
|
Reg target_ptr;
|
||||||
// TODO(Ed): We can resolve scratch at anytime its fixed to a specific address.
|
Reg eye_ptr;
|
||||||
U4 r_scratch
|
Reg up_in_ptr;
|
||||||
, U4 r_target_ptr,U4 r_eye_ptr, U4 r_up_in_ptr
|
union { Reg_(V3_S4) r012, up_in, eye; };
|
||||||
, U4 r_tmp0, U4 r_tmp1, U4 r_tmp2, U4 r_tmp3
|
union { Reg_(V3_S4) r345, target, fwd; };
|
||||||
) MipsAtom_Proc_(aa, {
|
};
|
||||||
load_word(r_target_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,target)),
|
/* Atom 0 in the bundle: input_and_sub. Stages C-side inputs into the scratchpad and computes fwd = target - eye. */
|
||||||
load_word(r_eye_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,eye)),
|
internal MipsAtom* AtomBundleEntry_(resolve_look_at,input_and_sub)(AtomArena_R aa, RegUse_resolve_look_at_input_and_sub r)
|
||||||
load_word(r_up_in_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,up_in)),
|
atom_info(atom_bind(Binds_ResolveLookAtSub)) MipsAtom_Proc_(aa, {
|
||||||
load_word(r_scratch, R_TapePtr, O_(Binds_ResolveLookAtSub,scratchpad)),
|
load_word(r.target_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,target)),
|
||||||
add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtSub)),
|
load_word(r.eye_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,eye)),
|
||||||
|
load_word(r.up_in_ptr, R_TapePtr, O_(Binds_ResolveLookAtSub,up_in)),
|
||||||
|
LdSlot_ add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtSub)),
|
||||||
|
|
||||||
|
/* Stage up_in.x/y/z into the scratchpad. R_ScratchBase = R_SP = 0x1F800000. */
|
||||||
|
mac_load_v3s4( r.up_in, r.up_in_ptr, 0), LdSlot_
|
||||||
|
mac_store_v3s4(r.up_in, R_ScratchBase, O_(ResolveLookAtScratch,up_in)),
|
||||||
|
|
||||||
// Stage eye.x/y/z into the scratchpad (atom 6 reads these for the translation column).
|
// Stage eye.x/y/z into the scratchpad (atom 6 reads these for the translation column).
|
||||||
mac_load_p3s4( r_tmp0, r_tmp1, r_tmp2, r_eye_ptr, 0),
|
mac_load_v3s4( r.eye, r.eye_ptr, 0), LdSlot_
|
||||||
mac_store_p3s4(r_tmp0, r_tmp1, r_tmp2, r_scratch, O_(ResolveLookAtScratch,eye)),
|
mac_store_v3s4(r.eye, R_ScratchBase, O_(ResolveLookAtScratch,eye)),
|
||||||
|
|
||||||
/* Stage up_in.x/y/z into the scratchpad. */
|
|
||||||
mac_load_p3s4( r_tmp0, r_tmp1, r_tmp2, r_up_in_ptr, 0),
|
|
||||||
mac_store_p3s4(r_tmp0, r_tmp1, r_tmp2, r_scratch, O_(ResolveLookAtScratch,up_in)),
|
|
||||||
|
|
||||||
/* Compute fwd = target - eye. */
|
/* Compute fwd = target - eye. */
|
||||||
mac_load_p3s4(r_tmp0, r_tmp1, r_tmp2, r_target_ptr, 0),
|
mac_load_v3s4( r.target, r.target_ptr, 0), LdSlot_
|
||||||
mac_load_p3s4(r_tmp3, R_AT, R_V0, r_eye_ptr, 0),
|
mac_sub_v3s4_self(r.fwd, r.eye),
|
||||||
mac_sub_v3s4(
|
mac_store_v3s4( r.fwd, R_ScratchBase, O_(ResolveLookAtScratch,fwd)),
|
||||||
r_tmp0, r_tmp1, r_tmp2,
|
|
||||||
r_tmp3, R_AT, R_V0),
|
|
||||||
mac_store_v3s4(r_tmp0, r_tmp1, r_tmp2, r_scratch, O_(ResolveLookAtScratch,fwd)),
|
|
||||||
|
|
||||||
mac_yield()
|
mac_yield()
|
||||||
})
|
})
|
||||||
|
|
||||||
/* Atom 2: cross uz × up_in → right. */
|
typedef Struct_(Binds_ResolveLookAt_PopulateMT3S4S2) {
|
||||||
internal MipsAtom* resolve_look_at__cross_uz_up_in_to_right_proc(AtomArena_R aa, U4 r_scratch
|
MT3_S2S4* look_at; /* MT3_S2S4* — destination matrix address */
|
||||||
, U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */
|
|
||||||
, U4 r_d /* load b.x */
|
|
||||||
, U4 r_f, U4 r_g, U4 r_h /* r_f = &right (out ptr), r_g = &uz, r_h = &up_in */
|
|
||||||
) MipsAtom_Proc_(aa, {
|
|
||||||
/* FIX: build packed RT22+RT33 with proper sign extension. */
|
|
||||||
add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_g = &uz */
|
|
||||||
add_si(r_h, r_scratch, O_(ResolveLookAtScratch,up_in)), /* r_h = &up_in */
|
|
||||||
add_si(r_f, r_scratch, O_(ResolveLookAtScratch,right)), /* r_f = &right (out) */
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* Load a (uz).x/y/z into r_a/r_b/r_c. */
|
|
||||||
load_word(r_a, r_g, O_(V3_S4,x)),
|
|
||||||
load_word(r_b, r_g, O_(V3_S4,y)),
|
|
||||||
load_word(r_c, r_g, O_(V3_S4,z)),
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* Load b (up_in).x/y/z into r_d + R_AT/R_V0 (R_AT/R_V0 are hardcoded scratch). */
|
|
||||||
load_word(r_d, r_h, O_(V3_S4,x)),
|
|
||||||
load_word(R_AT, r_h, O_(V3_S4,y)),
|
|
||||||
load_word(R_V0, r_h, O_(V3_S4,z)),
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* Save the two RT control-register slots OP will clobber. We reuse
|
|
||||||
* r_g/r_h (scratch pointers, no longer needed) as the save targets. */
|
|
||||||
gte_mv_from_ctrl_r(r_g, gte_cr_RT11), /* r_g = C2 r0 (RT11|RT12) */
|
|
||||||
gte_mv_from_ctrl_r(r_h, gte_cr_RT22), /* r_h = C2 r4 (RT22|RT33) */
|
|
||||||
|
|
||||||
/* Load uz.x/uz.y/uz.z into COP2 control registers.
|
|
||||||
* OP reads D1 = RT11 from $0.low, D2 = RT22 from $2.high, D3 = RT33 from $4.high.
|
|
||||||
* RT22 is in BOTH $2.high AND $4.low (shared bit position). OP reads from $2.high.
|
|
||||||
* So set RT22 via ctc2 r_b, $2 (sets $2.high = a.y.high = RT22, $2.low = a.y.low = RT13).
|
|
||||||
* Then set RT33 via ctc2 r_c, $4 (sets $4.high = a.z.high = RT33, $4.low = a.z.low).
|
|
||||||
* The $2 and $4 writes don't clobber each other (separate registers).
|
|
||||||
* The 2nd ctc2 DOES clobber $4.low (becomes a.z.low, NOT a.y.high), but since OP
|
|
||||||
* reads RT22 from $2.high (which the 2nd ctc2 doesn't touch), D2 is still a.y.high.
|
|
||||||
* This is libpsyx's OuterProduct12 convention EXACTLY. */
|
|
||||||
gte_mv_to_ctrl_r(r_b, gte_cr_RT13), /* $2 = r_b = a.y. RT13=a.y.low, RT22=a.y.high. */
|
|
||||||
gte_mv_to_ctrl_r(r_c, gte_cr_RT22), /* $4 = r_c = a.z. RT22=a.z.low, RT33=a.z.high. */
|
|
||||||
|
|
||||||
/* Load uz into the RT diagonal. */
|
|
||||||
gte_mv_to_ctrl_r(r_a, gte_cr_RT11), /* D1 = RT11 = uz.x (low 16 of $0, sign-extended by OP). */
|
|
||||||
nop2, /* CTC2 retirement (CPU→COP2 2-slot delay) */
|
|
||||||
|
|
||||||
/* Load up_in into IR (the second operand for OP). */
|
|
||||||
gte_mv_to_data_r(r_d, C2_IR1), /* IR1 = up_in.x */
|
|
||||||
gte_mv_to_data_r(R_AT, C2_IR2), /* IR2 = up_in.y */
|
|
||||||
gte_mv_to_data_r(R_V0, C2_IR3), /* IR3 = up_in.z */
|
|
||||||
nop2, /* MTC2 retirement (CPU→COP2 2-slot delay) */
|
|
||||||
|
|
||||||
gte_cmdw_outer_product, /* OP: MAC1/2/3 = uz × up_in
|
|
||||||
* MAC1 = IR3*D2 - IR2*D3 = up_in.z*uz.y.high - up_in.y*uz.z.high
|
|
||||||
* MAC2 = IR1*D3 - IR3*D1 = up_in.x*uz.z.high - up_in.z*uz.x
|
|
||||||
* MAC3 = IR2*D1 - IR1*D2 = up_in.y*uz.x - up_in.x*uz.y.high
|
|
||||||
* For up_in = (0, -fp_one, 0):
|
|
||||||
* MAC1 = 0 - (-fp_one)*uz.z.high = fp_one*uz.z.high
|
|
||||||
* MAC2 = 0 - 0 = 0
|
|
||||||
* MAC3 = (-fp_one)*uz.x - 0 = -fp_one*uz.x */
|
|
||||||
|
|
||||||
/* Restore the RT slots we clobbered. */
|
|
||||||
gte_mv_to_ctrl_r(r_g, gte_cr_RT11), /* restore C2 r0 (RT11|RT12) */
|
|
||||||
gte_mv_to_ctrl_r(r_h, gte_cr_RT22), /* restore C2 r4 (RT22|RT33) */
|
|
||||||
|
|
||||||
/* mfc2 MAC1/2/3 → r_a/r_b/r_c (out.x/y/z). */
|
|
||||||
gte_mv_from_data_r(r_a, C2_MAC1),
|
|
||||||
gte_mv_from_data_r(r_b, C2_MAC2),
|
|
||||||
gte_mv_from_data_r(r_c, C2_MAC3),
|
|
||||||
nop, /* MFC2 retirement */
|
|
||||||
|
|
||||||
/* Right-shift MAC by 12 to convert from GTE's S12.20 fixed-point scale back to libpsyx OuterProduct12 convention (S12.0, fp_one=4096=1<<12).
|
|
||||||
* Without this, MAC values (~16M for unit-vector cross products) overflow the GTE's 16-bit IR registers when atom 3 normalizes via mtc2. */
|
|
||||||
shift_aright(r_a, r_a, 12),
|
|
||||||
shift_aright(r_b, r_b, 12),
|
|
||||||
shift_aright(r_c, r_c, 12),
|
|
||||||
|
|
||||||
/* Store out.x/y/z to r_f (out ptr = scratch+32). */
|
|
||||||
store_word(r_a, r_f, O_(V3_S4,x)),
|
|
||||||
store_word(r_b, r_f, O_(V3_S4,y)),
|
|
||||||
store_word(r_c, r_f, O_(V3_S4,z)),
|
|
||||||
|
|
||||||
mac_yield()
|
|
||||||
})
|
|
||||||
|
|
||||||
/* Atom 4: cross uz × ux → up. */
|
|
||||||
internal MipsAtom* resolve_look_at__cross_uz_ux_to_up_proc(AtomArena_R aa, U4 r_scratch
|
|
||||||
, U4 r_a, U4 r_b, U4 r_c /* load a.x/y/z; result out.x/y/z */
|
|
||||||
, U4 r_d /* load b.x */
|
|
||||||
, U4 r_f, U4 r_g, U4 r_h /* r_f = &up (out ptr), r_g = &uz, r_h = &ux */
|
|
||||||
) MipsAtom_Proc_(aa, {
|
|
||||||
/* Compute the three scratch pointers from r_scratch. */
|
|
||||||
add_si(r_g, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_g = &uz */
|
|
||||||
add_si(r_h, r_scratch, O_(ResolveLookAtScratch,ux)), /* r_h = &ux */
|
|
||||||
add_si(r_f, r_scratch, O_(ResolveLookAtScratch,up)), /* r_f = &up (out) */
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* Load a (uz).x/y/z into r_a/r_b/r_c. */
|
|
||||||
load_word(r_a, r_g, O_(V3_S4,x)),
|
|
||||||
load_word(r_b, r_g, O_(V3_S4,y)),
|
|
||||||
load_word(r_c, r_g, O_(V3_S4,z)),
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* Load b (ux).x/y/z into r_d + R_AT/R_V0. */
|
|
||||||
load_word(r_d, r_h, O_(V3_S4,x)),
|
|
||||||
load_word(R_AT, r_h, O_(V3_S4,y)),
|
|
||||||
load_word(R_V0, r_h, O_(V3_S4,z)),
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* OP reads D1/D2/D3 from RT11/RT22/RT33 ($0/$2/$4), not V0/V1/V2.
|
|
||||||
* Mirror atom 1: cfc2 RT save, ctc2 RT diagonal from uz, mtc2 IR from ux,
|
|
||||||
* ctc2 RT restore. */
|
|
||||||
|
|
||||||
/* Save the two RT control-register slots OP will clobber (reusing
|
|
||||||
* r_g/r_h — they're no longer needed as scratch pointers). */
|
|
||||||
gte_mv_from_ctrl_r(r_g, gte_cr_RT11), /* r_g = C2 $0 (RT11|RT12) */
|
|
||||||
gte_mv_from_ctrl_r(r_h, gte_cr_RT22), /* r_h = C2 $4 (RT22|RT33) */
|
|
||||||
|
|
||||||
/* Load uz into the RT diagonal — same packing as atom 1.
|
|
||||||
* OP reads D1 = RT11 from $0.low, D2 = RT22 from $2.high, D3 = RT33 from $4.high.
|
|
||||||
* RT22 is shared between $2.high and $4.low — the ctc2 sequence to $2 then $4
|
|
||||||
* sets RT22 to uz.y.high (via $2), then to uz.z.low (via $4). OP reads
|
|
||||||
* RT22 from $2.high which the second ctc2 doesn't touch, so D2 stays uz.y.high.
|
|
||||||
* (This is libpsyx OuterProduct12 convention EXACTLY.) */
|
|
||||||
gte_mv_to_ctrl_r(r_b, gte_cr_RT13), /* $2 = uz.y. RT13=uz.y.low, RT22=uz.y.high. */
|
|
||||||
gte_mv_to_ctrl_r(r_c, gte_cr_RT22), /* $4 = uz.z. RT22=uz.z.low, RT33=uz.z.high. */
|
|
||||||
gte_mv_to_ctrl_r(r_a, gte_cr_RT11), /* $0 = uz.x. RT11=uz.x. */
|
|
||||||
nop2, /* CTC2 retirement (CPU→COP2 2-slot delay) */
|
|
||||||
|
|
||||||
/* Load ux into the IR registers (the second operand for OP). */
|
|
||||||
gte_mv_to_data_r(r_d, C2_IR1), /* IR1 = ux.x */
|
|
||||||
gte_mv_to_data_r(R_AT, C2_IR2), /* IR2 = ux.y */
|
|
||||||
gte_mv_to_data_r(R_V0, C2_IR3), /* IR3 = ux.z */
|
|
||||||
nop2, /* MTC2 retirement (CPU→COP2 2-slot delay) */
|
|
||||||
|
|
||||||
gte_cmdw_outer_product,
|
|
||||||
|
|
||||||
/* Restore the RT slots we clobbered. */
|
|
||||||
gte_mv_to_ctrl_r(r_g, gte_cr_RT11), /* restore C2 $0 (RT11|RT12) */
|
|
||||||
gte_mv_to_ctrl_r(r_h, gte_cr_RT22), /* restore C2 $4 (RT22|RT33) */
|
|
||||||
|
|
||||||
gte_mv_from_data_r(r_a, C2_MAC1),
|
|
||||||
gte_mv_from_data_r(r_b, C2_MAC2),
|
|
||||||
gte_mv_from_data_r(r_c, C2_MAC3),
|
|
||||||
nop,
|
|
||||||
/* Right-shift MAC by 12 to convert from GTE's S12.20 scale back to libpsyx
|
|
||||||
* OuterProduct12 convention (S12.0, fp_one=4096). See atom 1 for rationale. */
|
|
||||||
shift_aright(r_a, r_a, 12),
|
|
||||||
shift_aright(r_b, r_b, 12),
|
|
||||||
shift_aright(r_c, r_c, 12),
|
|
||||||
store_word(r_a, r_f, O_(V3_S4,x)),
|
|
||||||
store_word(r_b, r_f, O_(V3_S4,y)),
|
|
||||||
store_word(r_c, r_f, O_(V3_S4,z)),
|
|
||||||
|
|
||||||
mac_yield()
|
|
||||||
})
|
|
||||||
|
|
||||||
typedef Struct_(Binds_ResolveLookAtPopAndTrans) {
|
|
||||||
U4 look_at; /* U4 (MT3_S2S4* — destination matrix address) */
|
|
||||||
};
|
};
|
||||||
/* Atom 6 in the bundle: write look_at->m[][] from ux/uy/uz, then compute the translation column t[] = R * (-eye).
|
typedef Struct_(RegUse_resolve_look_at_populate_mt3s4s2) {
|
||||||
|
Reg look_at;
|
||||||
|
Reg eye; /* matrix_vector phase: load -eye */
|
||||||
|
Reg_(V3_S4) row; /* populate phase: load ux/uy/uz */
|
||||||
|
union { Reg r0, ux, vx; }; /* populate addr → matrix_vector v_x */
|
||||||
|
union { Reg r1, uy, vy; }; /* populate uy → matrix_vector v_y */
|
||||||
|
union { Reg r2, uz, vz; }; /* populate uz → matrix_vector v_z */
|
||||||
|
};
|
||||||
|
/* write look_at->m[][] from ux/uy/uz as packed S2 (populate),
|
||||||
|
* ctc2 RT chain into C2[0..4] (matrix_vector), MVMVA RT*(-eye)>>12, store off
|
||||||
|
* directly to look_at->t[] (trans_matrix).
|
||||||
*
|
*
|
||||||
* GPR codes (assigned by resolve_look_at_init):
|
* C11 ApplyMatrixLV semantics (gte.atom.c ac_apply_matrix_lv; libgte reference):
|
||||||
* r_look_at : MT3_S2S4* (popped from tape; output matrix destination)
|
|
||||||
* r_pux : pointer to ux (offset O_(ResolveLookAtScratch,ux))
|
|
||||||
* r_puy : pointer to uy (offset O_(ResolveLookAtScratch,uy))
|
|
||||||
* r_puz : pointer to uz (offset O_(ResolveLookAtScratch,uz))
|
|
||||||
* r_peye : pointer to eye (offset O_(ResolveLookAtScratch,eye))
|
|
||||||
* r_tmp0/1/2 : atom-local scratch (load + MVMVA + store temps)
|
|
||||||
*
|
|
||||||
* 4 pointer regs (r_pux/r_puy/r_puz/r_peye) are DEDICATED — they hold the scratch addresses for the entire body.
|
|
||||||
* They are computed in-body via `add_si(r_px, r_scratch, O_(ResolveLookAtScratch, field))` so no tape-data pointer is needed.
|
|
||||||
*
|
|
||||||
* Struct layout (per duffle/math.h):
|
|
||||||
* MT3_S2S4 { A3x3_S2 m; A3_S4 t; } → m[][] is S2 packed (9 × 2 = 18 bytes at offset 0)
|
|
||||||
* t[0/1/2] is S4 (3 × 4 = 12 bytes at offset 18)
|
|
||||||
*
|
|
||||||
* Translation column: GTE MVMVA with the world rotation matrix pre-set
|
|
||||||
* (helper emits set_gte_world before the bundle, per the bundle design).
|
|
||||||
* MVMVA computes R * pos (with cv=0/mx=0/sf=0/v=0); MAC1/2/3 = R * (-eye).
|
|
||||||
* Pool cost: r_look_at (1) + r_scratch (R_T4 carrier) + 4 ptr regs + 3 tmp regs = 9 GPRs.
|
|
||||||
*/
|
|
||||||
internal MipsAtom* resolve_look_at__populate_proc(AtomArena_R aa
|
|
||||||
, U4 r_look_at
|
|
||||||
, U4 r_scratch
|
|
||||||
, U4 r_pux, U4 r_puy, U4 r_puz
|
|
||||||
, U4 r_tmp0, U4 r_tmp1, U4 r_tmp2
|
|
||||||
) MipsAtom_Proc_(aa, {
|
|
||||||
/* Pop look_at* (the matrix output) — advance R_TapePtr by 4 bytes. */
|
|
||||||
load_word(r_look_at, R_TapePtr, O_(Binds_ResolveLookAtPopAndTrans,look_at)),
|
|
||||||
add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtPopAndTrans)),
|
|
||||||
|
|
||||||
/* Compute the 3 scratch pointers in their dedicated GPRs (eye isn't needed by 6a — 6b reads it). */
|
|
||||||
add_si(r_pux, r_scratch, O_(ResolveLookAtScratch,ux)), /* r_pux = &ux */
|
|
||||||
add_si(r_puy, r_scratch, O_(ResolveLookAtScratch,uy)), /* r_puy = &uy */
|
|
||||||
add_si(r_puz, r_scratch, O_(ResolveLookAtScratch,uz)), /* r_puz = &uz */
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* ── m[0] = (S2)ux ── */
|
|
||||||
load_word(r_tmp0, r_pux, O_(V3_S4,x)),
|
|
||||||
load_word(r_tmp1, r_pux, O_(V3_S4,y)),
|
|
||||||
load_word(r_tmp2, r_pux, O_(V3_S4,z)),
|
|
||||||
nop,
|
|
||||||
store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[0][0])),
|
|
||||||
store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[0][1])),
|
|
||||||
store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[0][2])),
|
|
||||||
|
|
||||||
/* ── m[1] = (S2)uy ── */
|
|
||||||
load_word(r_tmp0, r_puy, O_(V3_S4,x)),
|
|
||||||
load_word(r_tmp1, r_puy, O_(V3_S4,y)),
|
|
||||||
load_word(r_tmp2, r_puy, O_(V3_S4,z)),
|
|
||||||
nop,
|
|
||||||
store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[1][0])),
|
|
||||||
store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[1][1])),
|
|
||||||
store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[1][2])),
|
|
||||||
|
|
||||||
/* ── m[2] = (S2)uz ── */
|
|
||||||
load_word(r_tmp0, r_puz, O_(V3_S4,x)),
|
|
||||||
load_word(r_tmp1, r_puz, O_(V3_S4,y)),
|
|
||||||
load_word(r_tmp2, r_puz, O_(V3_S4,z)),
|
|
||||||
nop,
|
|
||||||
store_half(r_tmp0, r_look_at, O_(MT3_S2S4,m[2][0])),
|
|
||||||
store_half(r_tmp1, r_look_at, O_(MT3_S2S4,m[2][1])),
|
|
||||||
store_half(r_tmp2, r_look_at, O_(MT3_S2S4,m[2][2])),
|
|
||||||
|
|
||||||
/* Zero t[0..2] — atom 6c writes the final values here. */
|
|
||||||
store_word(R_0, r_look_at, O_(MT3_S2S4,t[0])),
|
|
||||||
store_word(R_0, r_look_at, O_(MT3_S2S4,t[1])),
|
|
||||||
store_word(R_0, r_look_at, O_(MT3_S2S4,t[2])),
|
|
||||||
|
|
||||||
mac_yield()
|
|
||||||
})
|
|
||||||
|
|
||||||
/* Atom 6b in the bundle: matrix-vector product off = R * (-eye) >> 12.
|
|
||||||
* Uses RTPS with V0 loaded from scratch via lwc2. The RT matrix is
|
|
||||||
* pre-loaded by atom 6a.5 (resolve_look_at__load_rt).
|
|
||||||
* Stores off to scratch+96 (overwriting the packed pos).
|
|
||||||
*
|
|
||||||
* GPR codes (assigned by resolve_look_at_init):
|
|
||||||
* r_scratch : R_ResolveScratch (R_T4) — scratch base
|
|
||||||
* r_peye : pointer to eye (slot +96, reused as off destination)
|
|
||||||
* r_tmp0/1/2: -eye + GTE transfer scratch
|
|
||||||
*
|
|
||||||
* Pool cost: r_scratch (carrier) + 1 ptr reg + 3 tmp regs = 5 GPRs.
|
|
||||||
*/
|
|
||||||
internal MipsAtom* resolve_look_at__matrix_vector_proc(AtomArena_R aa
|
|
||||||
, U4 r_scratch
|
|
||||||
, U4 r_peye
|
|
||||||
, U4 r_look_at
|
|
||||||
, U4 r_tmp0, U4 r_tmp1, U4 r_tmp2
|
|
||||||
) MipsAtom_Proc_(aa, {
|
|
||||||
/* === EXACT C11 ApplyMatrixLV replication ===
|
|
||||||
* The C11 does:
|
|
||||||
* 1. ctc2 RT matrix (5 ctc2s to C2[0..4])
|
* 1. ctc2 RT matrix (5 ctc2s to C2[0..4])
|
||||||
* 2. lw v.x/y/z from memory
|
* 2. lw -eye from memory
|
||||||
* 3. S15 decomposition (negu + sra 15 + negu + andi 0x7FFF + negu)
|
* 3. S15 decomposition (eliminated here — the fused body takes the >>12 path
|
||||||
* 4. mtc2 HIGH bits to IR1/2/3, nop, MVMVA pass1 (sf=0, mx=0, v=3, cv=3)
|
* directly via mtc2 IR + MVMVA pass2, matching the libgte canonical output)
|
||||||
* 5. mfc2 MACs
|
* 4. mtc2 to IR1/2/3, nop2, MVMVA pass2 (sf=1, mx=0, v=3, cv=3)
|
||||||
* 6. mtc2 LOW bits to IR1/2/3, nop, MVMVA pass2 (sf=1, mx=0, v=3, cv=3)
|
* 5. mfc2 MACs → off
|
||||||
* 7. mfc2 MACs
|
* 6. store off to look_at->t[] (skip scratch.eye intermediate)
|
||||||
* 8. Combine: (pass1 << 3) + pass2
|
|
||||||
*
|
|
||||||
* For S16-fitting pos (|pos| < 32768), pos >> 15 = 0, so pass1 = 0.
|
|
||||||
* The combine simplifies: result = 0 + pass2 = pass2.
|
|
||||||
* So we skip the S15 decomposition and just do pass 2 directly.
|
|
||||||
* We still use v=3 (IR input) and mx=0 (RT matrix) like the C11. */
|
|
||||||
|
|
||||||
/* Pop look_at* from tape. */
|
|
||||||
load_word(r_look_at, R_TapePtr, O_(Binds_ResolveLookAtPopAndTrans,look_at)),
|
|
||||||
add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtPopAndTrans)),
|
|
||||||
|
|
||||||
/* r_peye = &eye (slot +96, reused as off destination). */
|
|
||||||
add_si(r_peye, r_scratch, O_(ResolveLookAtScratch,eye)),
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* === Load RT matrix from look_at into C2[0..4] via ctc2 ===
|
|
||||||
* Exact s ame sequence as set_gte_mt3s2s4 / C11's ApplyMatrixLV. */
|
|
||||||
load_word( r_tmp0, r_look_at, 0), nop, gte_mv_to_ctrl_r(r_tmp0, gte_cr_RT11),
|
|
||||||
load_word( r_tmp0, r_look_at, 4), nop, gte_mv_to_ctrl_r(r_tmp0, gte_cr_RT12),
|
|
||||||
load_word( r_tmp0, r_look_at, 8), nop, gte_mv_to_ctrl_r(r_tmp0, gte_cr_RT13),
|
|
||||||
load_word( r_tmp0, r_look_at, 12), nop, gte_mv_to_ctrl_r(r_tmp0, gte_cr_RT21),
|
|
||||||
load_half_u(r_tmp0, r_look_at, 16), nop, gte_mv_to_ctrl_r(r_tmp0, gte_cr_RT22),
|
|
||||||
nop2, /* CTC2 retirement (2 slots × 5 ctc2s) */
|
|
||||||
|
|
||||||
/* Load pos = -eye after the matrix load releases r_tmp0. */
|
|
||||||
load_word(r_tmp0, r_peye, O_(P3_S4,x)),
|
|
||||||
load_word(r_tmp1, r_peye, O_(P3_S4,y)),
|
|
||||||
load_word(r_tmp2, r_peye, O_(P3_S4,z)),
|
|
||||||
nop,
|
|
||||||
sub_u(r_tmp0, R_0, r_tmp0), /* pos.x = -eye.x */
|
|
||||||
sub_u(r_tmp1, R_0, r_tmp1),
|
|
||||||
sub_u(r_tmp2, R_0, r_tmp2),
|
|
||||||
|
|
||||||
/* === mtc2 pos (as S16) to IR1/2/3 ===
|
|
||||||
* The GTE takes low 16 bits. pos fits in S16. For negative pos, the
|
|
||||||
* 32-bit sign-extended value's low 16 bits = correct S16. */
|
|
||||||
/* Mask pos to 16 bits to be safe. For S16-fitting pos, pos & 0xFFFF
|
|
||||||
* gives the correct S16 value (sign bit preserved). */
|
|
||||||
/* r_tmp0/1/2 already have pos values. */
|
|
||||||
gte_mv_to_data_r(r_tmp0, C2_IR1),
|
|
||||||
gte_mv_to_data_r(r_tmp1, C2_IR2),
|
|
||||||
gte_mv_to_data_r(r_tmp2, C2_IR3),
|
|
||||||
nop2, /* MTC2 retirement (2 slots) */
|
|
||||||
|
|
||||||
/* === MVMVA pass 2 — C11 ApplyMatrixLV command ===
|
|
||||||
* sf=1, mx=0 (RT), v=3 (IR), cv=3. Reads RT × IR >> 12. */
|
|
||||||
gte_cmdw_mvmva_c11_pass2,
|
|
||||||
nop, /* GTE interlock */
|
|
||||||
|
|
||||||
/* === mfc2 MAC1/2/3 → r_tmp0/1/2 === */
|
|
||||||
gte_mv_from_data_r(r_tmp0, C2_MAC1),
|
|
||||||
gte_mv_from_data_r(r_tmp1, C2_MAC2),
|
|
||||||
gte_mv_from_data_r(r_tmp2, C2_MAC3),
|
|
||||||
nop,
|
|
||||||
|
|
||||||
/* === Store off → scratch+96 (overwriting pos) === */
|
|
||||||
store_word(r_tmp0, r_peye, O_(V3_S4,x)),
|
|
||||||
store_word(r_tmp1, r_peye, O_(V3_S4,y)),
|
|
||||||
store_word(r_tmp2, r_peye, O_(V3_S4,z)),
|
|
||||||
|
|
||||||
mac_yield()
|
|
||||||
})
|
|
||||||
|
|
||||||
/* Atom 6c in the bundle: copy scratch+96 (off, written by atom 6b) → look_at->t[].
|
|
||||||
* Uses mac_trans_matrix component (m->t = v, libgte TransMatrix semantics = struct copy).
|
|
||||||
*
|
|
||||||
* GPR codes (assigned by resolve_look_at_init):
|
|
||||||
* r_look_at : MT3_S2S4* (popped from tape; output matrix destination)
|
|
||||||
* r_scratch : R_ResolveScratch (R_T4) — scratch base
|
|
||||||
* r_off_ptr : pointer to off (= &scratch.eye, reused slot)
|
|
||||||
* r_tmp0 : transfer reg for mac_trans_matrix
|
|
||||||
*
|
|
||||||
* Pool cost: r_look_at (1) + r_scratch (carrier) + r_off_ptr + 1 clobber = 4 GPRs.
|
|
||||||
*/
|
*/
|
||||||
I_ MipsAtom* resolve_look_at__trans_matrix_proc(AtomArena_R aa
|
internal MipsAtom* AtomBundleEntry_(resolve_look_at,populate_mt3s4s2)(AtomArena_R aa, RegUse_resolve_look_at_populate_mt3s4s2 r)
|
||||||
, U4 r_look_at, U4 r_scratch, U4 r_off_ptr
|
atom_info(atom_bind(Binds_ResolveLookAt_PopulateMT3S4S2)) MipsAtom_Proc_(aa, {
|
||||||
, U4 r_tmp0, U4 r_tmp1, U4 r_tmp2
|
/* --- Tape pop: look_at pointer --- */
|
||||||
) MipsAtom_Proc_(aa, {
|
load_word(r.look_at, R_TapePtr, O_(Binds_ResolveLookAt_PopulateMT3S4S2,look_at)),
|
||||||
/* Pop look_at* from tape. */
|
LdSlot_ add_ui_self( R_TapePtr, S_(Binds_ResolveLookAt_PopulateMT3S4S2)),
|
||||||
// load_word(r_Vlook_at, R_TapePtr, O_(Binds_ResolveLookAtPopAndTrans,look_at)),
|
|
||||||
// add_ui_self( R_TapePtr, S_(Binds_ResolveLookAtPopAndTrans)),
|
|
||||||
|
|
||||||
/* r_off_ptr = &off (= &scratch.eye since atom 6b overwrote eye with off). */
|
add_si(r.ux, R_ScratchBase, O_(ResolveLookAtScratch, ux)), LdSlot_
|
||||||
add_si(r_off_ptr, r_scratch, O_(ResolveLookAtScratch,eye)),
|
add_si(r.uy, R_ScratchBase, O_(ResolveLookAtScratch, uy)),
|
||||||
nop,
|
add_si(r.uz, R_ScratchBase, O_(ResolveLookAtScratch, uz)),
|
||||||
|
add_si(r.eye, R_ScratchBase, O_(ResolveLookAtScratch, eye)),
|
||||||
|
|
||||||
/* Copy off → look_at.t[] (mac_trans_matrix: m->t = v). */
|
/* write look_at->m[][] from ux/uy/uz as packed S2 */
|
||||||
mac_trans_mt3s3s4(r_look_at, r_off_ptr, r_tmp0, r_tmp1, r_tmp2),
|
mac_load_v3s4(r.row, r.ux, 0), LdSlot_ mac_store_v3s2(r.row, r.look_at, O_(MT3_S2S4, m[0])),
|
||||||
|
mac_load_v3s4(r.row, r.uy, 0), LdSlot_ mac_store_v3s2(r.row, r.look_at, O_(MT3_S2S4, m[1])),
|
||||||
|
mac_load_v3s4(r.row, r.uz, 0), LdSlot_ mac_store_v3s2(r.row, r.look_at, O_(MT3_S2S4, m[2])),
|
||||||
|
|
||||||
mac_yield()
|
/* ctc2 RT chain + MVMVA RT * (-eye) >> 12 */
|
||||||
|
/* C2[0] = (RT12<<16)|RT11 ← ctc2 RT11 from m[0][0..1]
|
||||||
|
* C2[1] = (RT21<<16)|RT13 ← ctc2 RT12 from m[0][2..3]
|
||||||
|
* C2[2] = (RT23<<16)|RT22 ← ctc2 RT13 from m[1][1..2]
|
||||||
|
* C2[3] = (RT32<<16)|RT31 ← ctc2 RT21 from m[2][0..1]
|
||||||
|
* C2[4] = (RT33<<16)|junk ← ctc2 RT22 from m[2][2] (half) */
|
||||||
|
load_word( r.vx, r.look_at, O_(MT3_S2S4, m[0][0])), /* RT11|RT12 */ LdSlot_
|
||||||
|
load_word( r.vy, r.look_at, O_(MT3_S2S4, m[0][2])), /* RT13|RT21 */ LdSlot_ gte_mv_to_ctrl_r(r.vx, gte_cr_RT11),
|
||||||
|
load_word( r.vz, r.look_at, O_(MT3_S2S4, m[1][1])), /* RT22|RT23 */ LdSlot_ gte_mv_to_ctrl_r(r.vy, gte_cr_RT12),
|
||||||
|
load_word( r.vx, r.look_at, O_(MT3_S2S4, m[2][0])), /* RT31|RT32 */ LdSlot_ gte_mv_to_ctrl_r(r.vz, gte_cr_RT13),
|
||||||
|
load_half_u(r.vy, r.look_at, O_(MT3_S2S4, m[2][2])), /* RT33 */ LdSlot_ gte_mv_to_ctrl_r(r.vx, gte_cr_RT21),
|
||||||
|
|
||||||
|
GteDelay_ mac_load_word_v3(r.vx, r.vy, r.vz, r.eye, 0), LdSlot_
|
||||||
|
mac_sub_s_v3(r.vx, r.vy, r.vz, R_0, R_0, R_0, r.vx, r.vy, r.vz),
|
||||||
|
|
||||||
|
gte_mv_to_data_r(r.vx, C2_IR1),
|
||||||
|
gte_mv_to_data_r(r.vy, C2_IR2),
|
||||||
|
gte_mv_to_data_r(r.vz, C2_IR3),
|
||||||
|
GteDelay_ nop2,
|
||||||
|
|
||||||
|
/* MVMVA pass 2 — C11 ApplyMatrixLV command. sf=1, mx=0 (RT), v=3 (IR), cv=3. Reads RT × IR >> 12. */
|
||||||
|
gte_cmdw_mvmva_c11_pass2, GteDelay_ load_word(R_AtomJmp, R_TapePtr, 0), // ac_yield: word 1
|
||||||
|
mac_gte_mv_from_data_r_mac123(r.vx, r.vy, r.vz), GteDelay_ add_ui_self( R_TapePtr, S_(MipsCode)), // ac_yield: word 2
|
||||||
|
|
||||||
|
/* store off directly to look_at->t[] (skip scratch.eye intermediate) */
|
||||||
|
mac_store_word_v3(r.vx, r.vy, r.vz, r.look_at, O_(MT3_S2S4, t)),
|
||||||
|
|
||||||
|
jump_reg(R_AtomJmp), BdSlot_ nop, // ac_yield: word 3-4
|
||||||
})
|
})
|
||||||
|
#pragma endregion resolve_look_at
|
||||||
|
|
||||||
#pragma endregion Atom Procs
|
#pragma endregion Atom Procs
|
||||||
|
|
||||||
@@ -591,23 +288,6 @@ internal MipsAtom_(screen_env_init) atom_info(atom_phase(screen_init)
|
|||||||
mac_yield(),
|
mac_yield(),
|
||||||
};
|
};
|
||||||
|
|
||||||
/* gp_screen_init's GPR setup. Tests the mixed user-pinning + auto-reg pattern:
|
|
||||||
* - R_IO_BaseAddr = R_T4 (user-pinned via atom_reg; pre-existing)
|
|
||||||
* - R_GP1_Offset = R_T2 (user-pinned via atom_reg; NEW -- for GPIO_PORT1_OFFSET)
|
|
||||||
* - R_ScreenX = R_T5 (user-pinned via atom_reg; used as a transfer and GTE setup reg)
|
|
||||||
* - R_GpTmp = auto-allocated by the lua pass and used for several GPU transfers;
|
|
||||||
* the C preprocessor resolves it to the chosen free pool GPR.
|
|
||||||
*
|
|
||||||
* For gp_screen_init, the auto-reg pool exclusions are:
|
|
||||||
* user_pinned (from the corpus register_alias_registry) : R_T0..R_T7 (all 8 user-pinned across hello_camera.atom.c)
|
|
||||||
* body-parsed physical registers : aliases resolve through the registry;
|
|
||||||
* the body uses R_ScreenX, not raw R_T5
|
|
||||||
* source_pool after both subtractions : {R_V0, R_V1} only
|
|
||||||
* R_GpTmp gets R_V0 (the first-fit choice). Its repeated GPU-transfer use proves that the
|
|
||||||
* auto-reg allocation is active while the R_ScreenX references prove the pinned alias is used.
|
|
||||||
* R_TapePtr (R_T9), R_AtomJmp (R_T8), R_AT are excluded from the POOL by construction in
|
|
||||||
* passes/auto_reg.lua -- see the "obvious exclusions" comment block at the top of that file.
|
|
||||||
*/
|
|
||||||
enum {
|
enum {
|
||||||
R_IO_BaseAddr = R_T4 atom_reg, /* Caller-pinned: IO_BASE_ADDR = 0x1F800000 */
|
R_IO_BaseAddr = R_T4 atom_reg, /* Caller-pinned: IO_BASE_ADDR = 0x1F800000 */
|
||||||
R_GP1_Offset = R_T2 atom_reg, /* Caller-pinned: GPIO_PORT1_OFFSET = 0x10 */
|
R_GP1_Offset = R_T2 atom_reg, /* Caller-pinned: GPIO_PORT1_OFFSET = 0x10 */
|
||||||
@@ -658,15 +338,15 @@ internal MipsAtom_(pad_input_cube_rotation) atom_info(atom_bind(Binds_PadApplyIn
|
|||||||
load_word(R_PadStateT5, R_TapePtr, O_(Binds_PadApplyInput,state)),
|
load_word(R_PadStateT5, R_TapePtr, O_(Binds_PadApplyInput,state)),
|
||||||
load_word(R_CubeRot, R_TapePtr, O_(Binds_PadApplyInput,cube_rot)),
|
load_word(R_CubeRot, R_TapePtr, O_(Binds_PadApplyInput,cube_rot)),
|
||||||
load_word(R_FloorRot, R_TapePtr, O_(Binds_PadApplyInput,floor_rot)),
|
load_word(R_FloorRot, R_TapePtr, O_(Binds_PadApplyInput,floor_rot)),
|
||||||
add_ui_self( R_TapePtr, S_(Binds_PadApplyInput)),
|
LdSlot_ add_ui_self( R_TapePtr, S_(Binds_PadApplyInput)),
|
||||||
|
|
||||||
/* Load pad[0].buttons into R_T0. */
|
/* Load pad[0].buttons into R_T0. */
|
||||||
load_word(R_T0, R_PadStateT5, O_(PadState,buttons)), nop,
|
load_word(R_T0, R_PadStateT5, O_(PadState,buttons)), LdSlot_ nop,
|
||||||
// Note(Ed): Potential op with delay slot?
|
// Note(Ed): Potential op with delay slot?
|
||||||
|
|
||||||
/* D-pad Left: cube_rot.y += 30, floor_rot.y += 5. */
|
/* D-pad Left: cube_rot.y += 30, floor_rot.y += 5. */
|
||||||
and_i(R_T3, R_T0, Pad_Left), branch_le_zero(R_T3, atom_offset(dpad_left, exit_dpad_left)),
|
and_i(R_T3, R_T0, Pad_Left), branch_le_zero(R_T3, atom_offset(dpad_left, exit_dpad_left)), BdSlot_
|
||||||
load_half( R_T4, R_CubeRot, O_(V3_S2,y)), /* BD-slot */
|
load_half( R_T4, R_CubeRot, O_(V3_S2,y)), LdSlot_
|
||||||
load_half( R_T3, R_FloorRot, O_(V3_S2,y)),
|
load_half( R_T3, R_FloorRot, O_(V3_S2,y)),
|
||||||
add_si( R_T4, R_T4, 30),
|
add_si( R_T4, R_T4, 30),
|
||||||
add_si( R_T3, R_T3, 5),
|
add_si( R_T3, R_T3, 5),
|
||||||
@@ -675,8 +355,8 @@ internal MipsAtom_(pad_input_cube_rotation) atom_info(atom_bind(Binds_PadApplyIn
|
|||||||
atom_label(exit_dpad_left)
|
atom_label(exit_dpad_left)
|
||||||
|
|
||||||
/* D-pad Right: cube_rot.y -= 30, floor_rot.y -= 5. */
|
/* D-pad Right: cube_rot.y -= 30, floor_rot.y -= 5. */
|
||||||
and_i(R_T3, R_T0, Pad_Right), branch_le_zero(R_T3, atom_offset(dpad_right, exit_dpad_right)),
|
and_i(R_T3, R_T0, Pad_Right), branch_le_zero(R_T3, atom_offset(dpad_right, exit_dpad_right)), BdSlot_
|
||||||
load_half( R_T4, R_CubeRot, O_(V3_S2,y)), /* BD-slot */
|
load_half( R_T4, R_CubeRot, O_(V3_S2,y)), LdSlot_
|
||||||
load_half( R_T3, R_FloorRot, O_(V3_S2,y)),
|
load_half( R_T3, R_FloorRot, O_(V3_S2,y)),
|
||||||
add_si( R_T4, R_T4, -30),
|
add_si( R_T4, R_T4, -30),
|
||||||
add_si( R_T3, R_T3, -5),
|
add_si( R_T3, R_T3, -5),
|
||||||
@@ -686,7 +366,7 @@ internal MipsAtom_(pad_input_cube_rotation) atom_info(atom_bind(Binds_PadApplyIn
|
|||||||
|
|
||||||
/* Analog left-stick X: dead zone 0x70..0x90.
|
/* Analog left-stick X: dead zone 0x70..0x90.
|
||||||
* Cube delta = (0x80 - left_x) >> 2; floor delta = (0x80 - left_x) >> 5. */
|
* Cube delta = (0x80 - left_x) >> 2; floor delta = (0x80 - left_x) >> 5. */
|
||||||
load_byte_u(R_T3, R_PadStateT5, O_(PadState,left.x)),
|
load_byte_u(R_T3, R_PadStateT5, O_(PadState,left.x)), LdSlot_ //?
|
||||||
|
|
||||||
/* Dead-zone check: skip analog if left_x in [0x70, 0x90] inclusive. Outside dead zone on LOW side: left_x < 0x70 (strictly).
|
/* Dead-zone check: skip analog if left_x in [0x70, 0x90] inclusive. Outside dead zone on LOW side: left_x < 0x70 (strictly).
|
||||||
* set_lt_u(R_T4, R_T3, R_T4=0x70) → R_T4 = (left_x < 0x70) ? 1 : 0. */
|
* set_lt_u(R_T4, R_T3, R_T4=0x70) → R_T4 = (left_x < 0x70) ? 1 : 0. */
|
||||||
@@ -695,14 +375,14 @@ internal MipsAtom_(pad_input_cube_rotation) atom_info(atom_bind(Binds_PadApplyIn
|
|||||||
|
|
||||||
atom_label(dead_check_upper)
|
atom_label(dead_check_upper)
|
||||||
/* left_x >= 0x70 → check upper bound. */
|
/* left_x >= 0x70 → check upper bound. */
|
||||||
load_byte_u(R_T3, R_PadStateT5, O_(PadState,left.x)), /* reload */
|
load_byte_u(R_T3, R_PadStateT5, O_(PadState,left.x)), /* reload */ LdSlot_ //?
|
||||||
add_ui( R_T4, R_0, PadDeadZone_HighBound),
|
add_ui( R_T4, R_0, PadDeadZone_HighBound),
|
||||||
|
|
||||||
/* R_T4 = (0x90 < left_x) ? 1 : 0 → (left_x > 0x90) ? 1 : 0 */
|
/* R_T4 = (0x90 < left_x) ? 1 : 0 → (left_x > 0x90) ? 1 : 0 */
|
||||||
set_lt_u(R_T4, R_T4, R_T3), branch_ne(R_T4, R_0, atom_offset(dead_zone_high_check, dead_high_active)),
|
set_lt_u(R_T4, R_T4, R_T3), branch_ne(R_T4, R_0, atom_offset(dead_zone_high_check, dead_high_active)), BdSlot_
|
||||||
add_ui( R_T4, R_0, PadDeadZone_Center), /* BD-slot: pre-load 0x80 for dead_high_active */
|
add_ui( R_T4, R_0, PadDeadZone_Center), /* BD-slot: pre-load 0x80 for dead_high_active */
|
||||||
jump_rel(atom_offset(dead_zone_skip, exit_stick)),
|
jump_rel(atom_offset(dead_zone_skip, exit_stick)),
|
||||||
mac_yield_load(),
|
BdSlot_ mac_yield_load(), LdSlot_
|
||||||
|
|
||||||
atom_label(dead_low_active)
|
atom_label(dead_low_active)
|
||||||
/* R_T3 = left_x (from line 632 lbu; not clobbered between dead_zone_low_check branch + its BD-slot `add_ui R_T4, 0x80`).
|
/* R_T3 = left_x (from line 632 lbu; not clobbered between dead_zone_low_check branch + its BD-slot `add_ui R_T4, 0x80`).
|
||||||
@@ -713,18 +393,18 @@ atom_label(dead_low_active)
|
|||||||
|
|
||||||
/* R_T4 = cube_delta */
|
/* R_T4 = cube_delta */
|
||||||
shift_aright(R_T4, R_T3, 2),
|
shift_aright(R_T4, R_T3, 2),
|
||||||
load_half( R_T0, R_CubeRot, O_(V3_S2,y)), nop,
|
load_half( R_T0, R_CubeRot, O_(V3_S2,y)), LdSlot_ nop,
|
||||||
add_u( R_T0, R_T0, R_T4),
|
add_u( R_T0, R_T0, R_T4),
|
||||||
store_half( R_T0, R_CubeRot, O_(V3_S2,y)),
|
store_half( R_T0, R_CubeRot, O_(V3_S2,y)),
|
||||||
/* R_T4 = floor_delta — moved into the load-delay slot of the floor load below (fills the 1-instruction gap;
|
/* R_T4 = floor_delta — moved into the load-delay slot of the floor load below (fills the 1-instruction gap;
|
||||||
* doesn't read R_T0; R_T4 settles by the subsequent add_u). */
|
* doesn't read R_T0; R_T4 settles by the subsequent add_u). */
|
||||||
load_half( R_T0, R_FloorRot, O_(V3_S2,y)),
|
load_half( R_T0, R_FloorRot, O_(V3_S2,y)), LdSlot_
|
||||||
shift_aright(R_T4, R_T3, 5),
|
shift_aright(R_T4, R_T3, 5),
|
||||||
add_u( R_T0, R_T0, R_T4),
|
add_u( R_T0, R_T0, R_T4),
|
||||||
store_half( R_T0, R_FloorRot, O_(V3_S2,y)),
|
store_half( R_T0, R_FloorRot, O_(V3_S2,y)),
|
||||||
|
|
||||||
jump_rel(atom_offset(end_low, exit_stick)),
|
jump_rel(atom_offset(end_low, exit_stick)),
|
||||||
mac_yield_load(),
|
BdSlot_ mac_yield_load(), LdSlot_
|
||||||
|
|
||||||
atom_label(dead_high_active)
|
atom_label(dead_high_active)
|
||||||
/* R_T3 = left_x (from line 641 lbu in dead_check_upper; not clobbered between dead_zone_high_check branch + its BD-slot `add_ui R_T4, 0x80`).
|
/* R_T3 = left_x (from line 641 lbu in dead_check_upper; not clobbered between dead_zone_high_check branch + its BD-slot `add_ui R_T4, 0x80`).
|
||||||
@@ -734,18 +414,18 @@ atom_label(dead_high_active)
|
|||||||
/* delta = 0x80 - left_x (signed negative). */
|
/* delta = 0x80 - left_x (signed negative). */
|
||||||
|
|
||||||
shift_aright(R_T4, R_T3, 2), /* R_T4 = cube_delta (signed) */
|
shift_aright(R_T4, R_T3, 2), /* R_T4 = cube_delta (signed) */
|
||||||
load_half( R_T0, R_CubeRot, O_(V3_S2,y)), nop,
|
load_half( R_T0, R_CubeRot, O_(V3_S2,y)), LdSlot_ nop,
|
||||||
add_u( R_T0, R_T0, R_T4),
|
add_u( R_T0, R_T0, R_T4),
|
||||||
store_half( R_T0, R_CubeRot, O_(V3_S2,y)),
|
store_half( R_T0, R_CubeRot, O_(V3_S2,y)),
|
||||||
|
|
||||||
/* R_T4 = floor_delta (signed) — moved into the load-delay slot of the floor load below. */
|
/* R_T4 = floor_delta (signed) — moved into the load-delay slot of the floor load below. */
|
||||||
load_half( R_T0, R_FloorRot, O_(V3_S2,y)),
|
load_half( R_T0, R_FloorRot, O_(V3_S2,y)), LdSlot_
|
||||||
shift_aright(R_T4, R_T3, 5),
|
shift_aright(R_T4, R_T3, 5),
|
||||||
add_u( R_T0, R_T0, R_T4),
|
add_u( R_T0, R_T0, R_T4),
|
||||||
store_half( R_T0, R_FloorRot, O_(V3_S2,y)),
|
store_half( R_T0, R_FloorRot, O_(V3_S2,y)),
|
||||||
|
|
||||||
atom_label(no_jump_fallthrough)
|
atom_label(no_jump_fallthrough)
|
||||||
mac_yield_load(),
|
mac_yield_load(), LdSlot_
|
||||||
|
|
||||||
atom_label(exit_stick)
|
atom_label(exit_stick)
|
||||||
/* NOT mac_yield() — R_AtomJmp was already loaded in the BD-slot of the dead-zone/exit branch. */
|
/* NOT mac_yield() — R_AtomJmp was already loaded in the BD-slot of the dead-zone/exit branch. */
|
||||||
@@ -767,45 +447,45 @@ internal MipsAtom_(pad_input_cam) atom_info(atom_bind(Binds_PadInputCam)
|
|||||||
/* Bind pop: state → R_CamPadState (R_T5), cam → R_Cam (R_T4), advance R_TapePtr by 8. */
|
/* Bind pop: state → R_CamPadState (R_T5), cam → R_Cam (R_T4), advance R_TapePtr by 8. */
|
||||||
load_word(R_CamPadState, R_TapePtr, O_(Binds_PadInputCam,state)),
|
load_word(R_CamPadState, R_TapePtr, O_(Binds_PadInputCam,state)),
|
||||||
load_word(R_Cam, R_TapePtr, O_(Binds_PadInputCam,cam)),
|
load_word(R_Cam, R_TapePtr, O_(Binds_PadInputCam,cam)),
|
||||||
add_ui_self( R_TapePtr, S_(Binds_PadInputCam)),
|
LdSlot_ add_ui_self( R_TapePtr, S_(Binds_PadInputCam)),
|
||||||
|
|
||||||
/* Load pad[0].buttons into R_T0; nop fills the load-delay slot. */
|
/* Load pad[0].buttons into R_T0; nop fills the load-delay slot. */
|
||||||
load_word(R_T0, R_CamPadState, O_(PadState,buttons)),
|
load_word(R_T0, R_CamPadState, O_(PadState,buttons)), LdSlot_
|
||||||
load_word(R_T1, R_Cam, O_(Camera,pos.x)), // BD-Slot.
|
load_word(R_T1, R_Cam, O_(Camera,pos.x)),
|
||||||
|
|
||||||
// D-pad Left → cam.pos.x -= 50. and_i fulfills BD-slot for load on R_Cam.
|
// D-pad Left → cam.pos.x -= 50. and_i fulfills BD-slot for load on R_Cam.
|
||||||
and_i(R_T3, R_T0, Pad_Left), branch_le_zero(R_T3, atom_offset(left_x, exit_left_x)), mac_yield_load(),
|
LdSlot_ and_i(R_T3, R_T0, Pad_Left), branch_le_zero(R_T3, atom_offset(left_x, exit_left_x)), BdSlot_ nop,
|
||||||
add_si(R_T1, R_T1, -50), store_word(R_T1, R_Cam, O_(Camera,pos.x)),
|
add_si(R_T1, R_T1, -50), store_word(R_T1, R_Cam, O_(Camera,pos.x)),
|
||||||
atom_label(exit_left_x)
|
atom_label(exit_left_x)
|
||||||
|
|
||||||
/* D-pad Right → cam.pos.x += 50. Reuses R_T1 from Left. */
|
/* D-pad Right → cam.pos.x += 50. Reuses R_T1 from Left. */
|
||||||
and_i(R_T3, R_T0, Pad_Right), branch_le_zero(R_T3, atom_offset(right_x, exit_right_x)), nop,
|
and_i(R_T3, R_T0, Pad_Right), branch_le_zero(R_T3, atom_offset(right_x, exit_right_x)), BdSlot_ nop,
|
||||||
add_si(R_T1, R_T1, 50), store_word(R_T1, R_Cam, O_(Camera,pos.x)),
|
add_si(R_T1, R_T1, 50), store_word(R_T1, R_Cam, O_(Camera,pos.x)),
|
||||||
atom_label(exit_right_x)
|
atom_label(exit_right_x)
|
||||||
|
|
||||||
/* D-pad Up → cam.pos.y -= 50. Load pos.y BEFORE the andi. */
|
/* D-pad Up → cam.pos.y -= 50. Load pos.y BEFORE the andi. */
|
||||||
load_word(R_T1, R_Cam, O_(Camera,pos.y)),
|
load_word(R_T1, R_Cam, O_(Camera,pos.y)), LdSlot_
|
||||||
and_i(R_T3, R_T0, Pad_Up), branch_le_zero(R_T3, atom_offset(up_y, exit_up_y)), nop,
|
and_i(R_T3, R_T0, Pad_Up), branch_le_zero(R_T3, atom_offset(up_y, exit_up_y)), BdSlot_ nop,
|
||||||
add_si(R_T1, R_T1, -50), store_word(R_T1, R_Cam, O_(Camera,pos.y)),
|
add_si(R_T1, R_T1, -50), store_word(R_T1, R_Cam, O_(Camera,pos.y)),
|
||||||
atom_label(exit_up_y)
|
atom_label(exit_up_y)
|
||||||
|
|
||||||
/* D-pad Down → cam.pos.y += 50. Reuses R_T1 from Up. */
|
/* D-pad Down → cam.pos.y += 50. Reuses R_T1 from Up. */
|
||||||
and_i(R_T3, R_T0, Pad_Down), branch_le_zero(R_T3, atom_offset(down_y, exit_down_y)), nop,
|
and_i(R_T3, R_T0, Pad_Down), branch_le_zero(R_T3, atom_offset(down_y, exit_down_y)), BdSlot_ nop,
|
||||||
add_si(R_T1, R_T1, 50), store_word(R_T1, R_Cam, O_(Camera,pos.y)),
|
add_si(R_T1, R_T1, 50), store_word(R_T1, R_Cam, O_(Camera,pos.y)),
|
||||||
atom_label(exit_down_y)
|
atom_label(exit_down_y)
|
||||||
|
|
||||||
/* D-pad Cross → cam.pos.z -= 50. Load pos.z BEFORE the andi. */
|
/* D-pad Cross → cam.pos.z -= 50. Load pos.z BEFORE the andi. */
|
||||||
load_word(R_T1, R_Cam, O_(Camera,pos.z)),
|
load_word(R_T1, R_Cam, O_(Camera,pos.z)), LdSlot_
|
||||||
and_i(R_T3, R_T0, Pad_Cross), branch_le_zero(R_T3, atom_offset(cross_z, exit_cross_z)), nop,
|
and_i(R_T3, R_T0, Pad_Cross), branch_le_zero(R_T3, atom_offset(cross_z, exit_cross_z)), BdSlot_ load_word(R_AtomJmp, R_TapePtr, 0), LdSlot_ // ac_yield: word 1
|
||||||
add_si(R_T1, R_T1, -50), store_word(R_T1, R_Cam, O_(Camera,pos.z)),
|
add_si(R_T1, R_T1, -50), store_word(R_T1, R_Cam, O_(Camera,pos.z)),
|
||||||
atom_label(exit_cross_z)
|
atom_label(exit_cross_z)
|
||||||
|
|
||||||
/* D-pad Circle → cam.pos.z += 50. Reuses R_T1 from Cross. */
|
/* D-pad Circle → cam.pos.z += 50. Reuses R_T1 from Cross. */
|
||||||
and_i(R_T3, R_T0, Pad_Circle), branch_le_zero(R_T3, atom_offset(circle_z, exit_circle_z)), nop,
|
and_i(R_T3, R_T0, Pad_Circle), branch_le_zero(R_T3, atom_offset(circle_z, exit_circle_z)), BdSlot_ add_ui_self(R_TapePtr, S_(MipsCode)), // ac_yield: word 2
|
||||||
add_si(R_T1, R_T1, 50), store_word(R_T1, R_Cam, O_(Camera,pos.z)),
|
add_si(R_T1, R_T1, 50), store_word(R_T1, R_Cam, O_(Camera,pos.z)),
|
||||||
atom_label(exit_circle_z)
|
atom_label(exit_circle_z)
|
||||||
|
|
||||||
mac_yield_tail(),
|
jump_reg(R_AtomJmp), BdSlot_ nop // ac_yield: word 3-4
|
||||||
};
|
};
|
||||||
|
|
||||||
enum {
|
enum {
|
||||||
@@ -833,7 +513,7 @@ internal MipsAtom_(rbind_cube_g4_face) atom_info(atom_bind(Binds_CubeTri), atom_
|
|||||||
load_word(R_FaceCursor, R_TapePtr, O_(Binds_CubeTri,FaceCursor)),
|
load_word(R_FaceCursor, R_TapePtr, O_(Binds_CubeTri,FaceCursor)),
|
||||||
load_word(R_VertBase, R_TapePtr, O_(Binds_CubeTri,VertBase)),
|
load_word(R_VertBase, R_TapePtr, O_(Binds_CubeTri,VertBase)),
|
||||||
load_word(R_OtBase, R_TapePtr, O_(Binds_CubeTri,OtBase)),
|
load_word(R_OtBase, R_TapePtr, O_(Binds_CubeTri,OtBase)),
|
||||||
add_ui_self( R_TapePtr, S_(Binds_CubeTri)),
|
LdSlot_ add_ui_self( R_TapePtr, S_(Binds_CubeTri)),
|
||||||
mac_yield()
|
mac_yield()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -846,20 +526,22 @@ MipsAtom_(cube_g4_face) atom_info(atom_phase(cube_g4),
|
|||||||
load_half_u(R_T0, R_FaceCursor, 0 * S_(S2)),
|
load_half_u(R_T0, R_FaceCursor, 0 * S_(S2)),
|
||||||
load_half_u(R_T1, R_FaceCursor, 1 * S_(S2)),
|
load_half_u(R_T1, R_FaceCursor, 1 * S_(S2)),
|
||||||
load_half_u(R_T2, R_FaceCursor, 2 * S_(S2)),
|
load_half_u(R_T2, R_FaceCursor, 2 * S_(S2)),
|
||||||
load_half_u(R_T3, R_FaceCursor, 3 * S_(S2)),
|
// load_half_u(R_T3, R_FaceCursor, 3 * S_(S2)),
|
||||||
|
|
||||||
mac_gte_load_tri_verts(R_VertBase, R_T0, R_T1, R_T2),
|
LdSlot_ mac_gte_load_tri_verts(R_VertBase, R_T0, R_T1, R_T2),
|
||||||
nop2, gte_cmdw_rotate_translate_perspective_triple, // required cpu -> gte delay slot
|
GteDelay_ load_half_u(R_T3, R_FaceCursor, 3 * S_(S2)), LdSlot_
|
||||||
|
GteDelay_ load_word(R_AtomJmp, R_TapePtr, 0), LdSlot_ //ac_yield: word 2,
|
||||||
|
gte_cmdw_rotate_translate_perspective_triple,
|
||||||
gte_cmdw_nclip,
|
gte_cmdw_nclip,
|
||||||
|
|
||||||
gte_mv_from_data_r(R_T0, C2_MAC0), nop,
|
gte_mv_from_data_r(R_T0, C2_MAC0), GteDelay_ add_ui_self(R_TapePtr, S_(MipsCode)), // ac_yield: word 1
|
||||||
branch_le_zero(R_T0, atom_offset(cull, cube_g4_face_exit)),
|
branch_le_zero(R_T0, atom_offset(cull, cube_g4_face_exit)),
|
||||||
/* BD-slot: Write the prim tag (R_0=0; overwrites the legacy tag word in the prim_buffer).
|
/* BD-slot: Write the prim tag (R_0=0; overwrites the legacy tag word in the prim_buffer).
|
||||||
* If branch IS taken (face culled), the body is skipped and this 0-tag is stranded —
|
* If branch IS taken (face culled), the body is skipped and this 0-tag is stranded —
|
||||||
* harmless because the OT entry that points to this prim is created later. */
|
* harmless because the OT entry that points to this prim is created later. */
|
||||||
store_word(R_0, R_PrimCursor, O_(Poly_G4, tag)),
|
BdSlot_ store_word(R_0, R_PrimCursor, O_(Poly_G4, tag)),
|
||||||
shift_lleft(R_AT, R_T3, v3s2_byteoff), add_u(R_AT, R_AT, R_VertBase),
|
shift_lleft(R_AT, R_T3, v3s2_byteoff), add_u(R_AT, R_AT, R_VertBase),
|
||||||
load_word(R_V0, R_AT, O_(V3_S2, x)), load_word(R_V1, R_AT, O_(V3_S2, z)),
|
load_word(R_V0, R_AT, O_(V3_S2, x)), load_word(R_V1, R_AT, O_(V3_S2, z)), LdSlot_
|
||||||
gte_mv_to_data_r(R_V0, C2_VXY0), gte_mv_to_data_r(R_V1, C2_VZ0),
|
gte_mv_to_data_r(R_V0, C2_VXY0), gte_mv_to_data_r(R_V1, C2_VZ0),
|
||||||
|
|
||||||
mac_gte_store_g4_p012(R_PrimCursor),
|
mac_gte_store_g4_p012(R_PrimCursor),
|
||||||
@@ -871,7 +553,7 @@ MipsAtom_(cube_g4_face) atom_info(atom_phase(cube_g4),
|
|||||||
add_ui( R_AT, R_0, OrderingTbl_Len),
|
add_ui( R_AT, R_0, OrderingTbl_Len),
|
||||||
set_lt_u( R_AT, R_T1, R_AT),
|
set_lt_u( R_AT, R_T1, R_AT),
|
||||||
|
|
||||||
branch_equal(R_AT, R_0, atom_offset(bounds_chk, cube_g4_face_exit)), nop,
|
branch_equal(R_AT, R_0, atom_offset(bounds_chk, cube_g4_face_exit)), BdSlot_ nop,
|
||||||
mac_insert_ot_tag(R_OtBase, R_PrimCursor, S_(Poly_G4)),
|
mac_insert_ot_tag(R_OtBase, R_PrimCursor, S_(Poly_G4)),
|
||||||
mac_format_g4_color(R_PrimCursor,
|
mac_format_g4_color(R_PrimCursor,
|
||||||
/* c0 magenta */ 0xFF, 0x00, 0xFF,
|
/* c0 magenta */ 0xFF, 0x00, 0xFF,
|
||||||
@@ -884,7 +566,7 @@ MipsAtom_(cube_g4_face) atom_info(atom_phase(cube_g4),
|
|||||||
atom_label(cube_g4_face_exit)
|
atom_label(cube_g4_face_exit)
|
||||||
add_ui_self(R_PrimCursor, S_(Poly_G4)), /* 9 words = Poly_G4 */
|
add_ui_self(R_PrimCursor, S_(Poly_G4)), /* 9 words = Poly_G4 */
|
||||||
add_ui_self(R_FaceCursor, S_(S2) * 4), /* 4 × S2 = 8 bytes */
|
add_ui_self(R_FaceCursor, S_(S2) * 4), /* 4 × S2 = 8 bytes */
|
||||||
mac_yield()
|
jump_reg(R_AtomJmp), BdSlot_ nop // ac_yield: word 3-4
|
||||||
};
|
};
|
||||||
|
|
||||||
typedef Struct_(Binds_FloorTri) {
|
typedef Struct_(Binds_FloorTri) {
|
||||||
@@ -903,7 +585,7 @@ MipsAtom_(rbind_floor_f3_face) atom_info(atom_bind(Binds_FloorTri), atom_phase(f
|
|||||||
load_word(R_FaceCursor, R_TapePtr, O_(Binds_FloorTri,FaceCursor)),
|
load_word(R_FaceCursor, R_TapePtr, O_(Binds_FloorTri,FaceCursor)),
|
||||||
load_word(R_VertBase, R_TapePtr, O_(Binds_FloorTri,VertBase)),
|
load_word(R_VertBase, R_TapePtr, O_(Binds_FloorTri,VertBase)),
|
||||||
load_word(R_OtBase, R_TapePtr, O_(Binds_FloorTri,OtBase)),
|
load_word(R_OtBase, R_TapePtr, O_(Binds_FloorTri,OtBase)),
|
||||||
add_ui_self( R_TapePtr, S_(Binds_FloorTri)),
|
LdSlot_ add_ui_self( R_TapePtr, S_(Binds_FloorTri)),
|
||||||
mac_yield()
|
mac_yield()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -914,13 +596,13 @@ MipsAtom_(floor_f3_face) atom_info(atom_phase(floor_f3)
|
|||||||
, atom_writes(R_PrimCursor, R_FaceCursor)
|
, atom_writes(R_PrimCursor, R_FaceCursor)
|
||||||
) {
|
) {
|
||||||
mac_load_tri_indices(R_FaceCursor, R_T0, R_T1, R_T2),
|
mac_load_tri_indices(R_FaceCursor, R_T0, R_T1, R_T2),
|
||||||
mac_gte_load_tri_verts(R_VertBase, R_T0, R_T1, R_T2),
|
mac_gte_load_tri_verts(R_VertBase, R_T0, R_T1, R_T2), GteDelay_ nop2,
|
||||||
nop2, gte_cmdw_rotate_translate_perspective_triple, // 2 nops retire the final cpu -> gte writes before RTPT
|
gte_cmdw_rotate_translate_perspective_triple, // 2 nops retire the final cpu -> gte writes before RTPT
|
||||||
gte_cmdw_nclip,
|
gte_cmdw_nclip,
|
||||||
|
|
||||||
/* Culling (Branch forward if Backface) */
|
/* Culling (Branch forward if Backface) */
|
||||||
gte_mv_from_data_r(R_T0, C2_MAC0),
|
gte_mv_from_data_r(R_T0, C2_MAC0), GteDelay_ load_word(R_AtomJmp, R_TapePtr, 0), // ac_yield: word 1
|
||||||
nop, branch_le_zero(R_T0, atom_offset(culling, floor_f3_face_exit)), nop, // required gte -> cpu load-delay slot.
|
branch_le_zero(R_T0, atom_offset(culling, floor_f3_face_exit)), BdSlot_ add_ui_self(R_TapePtr, S_(MipsCode)), // ac_yield: word 2
|
||||||
/* Format Primitive */
|
/* Format Primitive */
|
||||||
mac_gte_store_f3(R_PrimCursor),
|
mac_gte_store_f3(R_PrimCursor),
|
||||||
|
|
||||||
@@ -930,7 +612,7 @@ MipsAtom_(floor_f3_face) atom_info(atom_phase(floor_f3)
|
|||||||
/* Bounds Check OTZ < 2048 (Branch forward to skip insertion) */
|
/* Bounds Check OTZ < 2048 (Branch forward to skip insertion) */
|
||||||
add_ui( R_AT, R_0, OrderingTbl_Len),
|
add_ui( R_AT, R_0, OrderingTbl_Len),
|
||||||
set_lt_u( R_AT, R_T1, R_AT),
|
set_lt_u( R_AT, R_T1, R_AT),
|
||||||
branch_equal(R_AT, R_0, atom_offset(bounds_chk, floor_f3_face_exit)), nop,
|
branch_equal(R_AT, R_0, atom_offset(bounds_chk, floor_f3_face_exit)), BdSlot_ nop,
|
||||||
mac_format_f3_color(R_PrimCursor, 0xFF, 0xFF, 0xFF), // RGB-form (R=FF, G=FF, B=FF = white)
|
mac_format_f3_color(R_PrimCursor, 0xFF, 0xFF, 0xFF), // RGB-form (R=FF, G=FF, B=FF = white)
|
||||||
mac_insert_ot_tag(R_OtBase, R_PrimCursor, S_(Poly_F3)), /* Insert into Ordering Table Linked List */
|
mac_insert_ot_tag(R_OtBase, R_PrimCursor, S_(Poly_F3)), /* Insert into Ordering Table Linked List */
|
||||||
add_ui_self(R_PrimCursor, S_(Poly_F3)), /* Advance Prim Cursor (5 words) */
|
add_ui_self(R_PrimCursor, S_(Poly_F3)), /* Advance Prim Cursor (5 words) */
|
||||||
@@ -941,7 +623,7 @@ MipsAtom_(floor_f3_face) atom_info(atom_phase(floor_f3)
|
|||||||
/* Advance Input Cursor & Yield (Both branch targets land here) */
|
/* Advance Input Cursor & Yield (Both branch targets land here) */
|
||||||
atom_label(floor_f3_face_exit)
|
atom_label(floor_f3_face_exit)
|
||||||
add_ui_self(R_FaceCursor, S_(S2) * 4), /* Advance Face Cursor (4 * S2 = 8 bytes) */
|
add_ui_self(R_FaceCursor, S_(S2) * 4), /* Advance Face Cursor (4 * S2 = 8 bytes) */
|
||||||
mac_yield()
|
jump_reg(R_AtomJmp), BdSlot_ nop // ac_yield: word 3-4
|
||||||
};
|
};
|
||||||
|
|
||||||
typedef Struct_(Binds_SyncPrimitiveArena) { U4 used; U4 cursor; };
|
typedef Struct_(Binds_SyncPrimitiveArena) { U4 used; U4 cursor; };
|
||||||
@@ -950,7 +632,7 @@ internal MipsAtom_(sync_primitive_arena) atom_info(atom_bind(Binds_SyncPrimitive
|
|||||||
, atom_writes(R_TapePtr)
|
, atom_writes(R_TapePtr)
|
||||||
){
|
){
|
||||||
load_word(R_AT, R_TapePtr, O_(Binds_SyncPrimitiveArena,used)),
|
load_word(R_AT, R_TapePtr, O_(Binds_SyncPrimitiveArena,used)),
|
||||||
load_word(R_T0, R_TapePtr, O_(Binds_SyncPrimitiveArena,cursor)),
|
load_word(R_T0, R_TapePtr, O_(Binds_SyncPrimitiveArena,cursor)), LdSlot_
|
||||||
add_ui_self( R_TapePtr, S_(Binds_SyncPrimitiveArena)),
|
add_ui_self( R_TapePtr, S_(Binds_SyncPrimitiveArena)),
|
||||||
/* Calculate byte offset and store directly back to RAM */
|
/* Calculate byte offset and store directly back to RAM */
|
||||||
sub_u( R_T0, R_PrimCursor, R_T0), // R_T0 = R_PrimCursor - binds.cursor
|
sub_u( R_T0, R_PrimCursor, R_T0), // R_T0 = R_PrimCursor - binds.cursor
|
||||||
|
|||||||
+121
-229
@@ -32,9 +32,9 @@
|
|||||||
|
|
||||||
#pragma region Duffle TUs
|
#pragma region Duffle TUs
|
||||||
#include "duffle/pad.c"
|
#include "duffle/pad.c"
|
||||||
#include "duffle/math.atom.c"
|
#include "duffle/math.atom.h"
|
||||||
#include "duffle/mips.atom.c"
|
#include "duffle/mips.atom.c"
|
||||||
#include "duffle/gte.atom.c"
|
#include "duffle/gte.atom.h"
|
||||||
#include "duffle/gp.atom.c"
|
#include "duffle/gp.atom.c"
|
||||||
#include "duffle/pad.atom.c"
|
#include "duffle/pad.atom.c"
|
||||||
#include "duffle/psyq.atom.c"
|
#include "duffle/psyq.atom.c"
|
||||||
@@ -53,15 +53,13 @@
|
|||||||
#pragma endregion Hello Joypad TUs
|
#pragma endregion Hello Joypad TUs
|
||||||
|
|
||||||
enum {
|
enum {
|
||||||
Scratchpad_Loc = 0x1F800000,
|
|
||||||
};
|
|
||||||
#define C_scratch(type) C_(type, Scratchpad_Loc)
|
|
||||||
|
|
||||||
enum {
|
|
||||||
Scratchpad_Len = 1024,
|
|
||||||
MemTape_Len = 512,
|
MemTape_Len = 512,
|
||||||
|
|
||||||
ResolveLookAtArena_Words = 1024,
|
ResolveLookAtArena_Words = 1024,
|
||||||
ResolveLookAtArena_Size = ResolveLookAtArena_Words * S_(MipsCode),
|
ResolveLookAtArena_Size = ResolveLookAtArena_Words * S_(MipsCode),
|
||||||
|
|
||||||
|
CT_InitAtomMem_Words = Kilo_(4),
|
||||||
|
CT_InitAtomMem_Size = CT_InitAtomMem_Words * S_(MipsCode),
|
||||||
};
|
};
|
||||||
typedef Struct_(SMemory) {
|
typedef Struct_(SMemory) {
|
||||||
PrimitiveArena primitives;
|
PrimitiveArena primitives;
|
||||||
@@ -82,11 +80,12 @@ typedef Struct_(SMemory) {
|
|||||||
PadBiosRaw pad_raw[2];
|
PadBiosRaw pad_raw[2];
|
||||||
PadState pad[2];
|
PadState pad[2];
|
||||||
|
|
||||||
// TODO(Ed): We don't need this we can just cast at any point an address to a desired view of scratchpad, we have the address.
|
U1 ct_init_atom_mem[CT_InitAtomMem_Size];
|
||||||
U4_V scratchpad; // d-cache
|
MipsAtom* normalize_v3s4;
|
||||||
|
MipsAtom* gte_cross_v3s4;
|
||||||
|
|
||||||
U1 resolve_look_at_mem[ResolveLookAtArena_Size];
|
U1 resolve_look_at_mem[ResolveLookAtArena_Size];
|
||||||
MipsAtom* resolve_look_at_atom_addrs[10];
|
MipsAtom* resolve_look_at_bundle[AtomBundle_Len(resolve_look_at)];
|
||||||
};
|
};
|
||||||
global SMemory smem;
|
global SMemory smem;
|
||||||
extern SMemory smem;
|
extern SMemory smem;
|
||||||
@@ -112,10 +111,10 @@ I_ void resolve_look_at_c11(MT3_S2S4* look_at, P3_S4* eye, P3_S4* target, V3_S4*
|
|||||||
V3_S4 pos, off;
|
V3_S4 pos, off;
|
||||||
|
|
||||||
forward = target[0]; sub_v3s4(& forward, eye[0]); // RGA(Lengyel): Affine point - point = zero-weight direction.
|
forward = target[0]; sub_v3s4(& forward, eye[0]); // RGA(Lengyel): Affine point - point = zero-weight direction.
|
||||||
normalize_v3s4(& forward, & uz); // RGA(Lengyel): Normalize the direction bulk. Not finite-point unitization.
|
psy_normalize_v3s4(& forward, & uz); // RGA(Lengyel): Normalize the direction bulk. Not finite-point unitization.
|
||||||
|
|
||||||
cross_v3s4(& uz, up_in, & right); normalize_v3s4(& right, & ux); // RGA(Lengyel): Complement(Wedge(forward, up_in)) -> right axis.
|
cross_v3s4(& uz, up_in, & right); psy_normalize_v3s4(& right, & ux); // RGA(Lengyel): Complement(Wedge(forward, up_in)) -> right axis.
|
||||||
cross_v3s4(& uz, & ux, & up); normalize_v3s4(& up, & uy); // RGA(Lengyel): Complement(Wedge(forward, right)) -> up axis.
|
cross_v3s4(& uz, & ux, & up); psy_normalize_v3s4(& up, & uy); // RGA(Lengyel): Complement(Wedge(forward, right)) -> up axis.
|
||||||
|
|
||||||
// RGA(Lengyel): matrix expansion of the world-to-camera rotation (basis rows).
|
// RGA(Lengyel): matrix expansion of the world-to-camera rotation (basis rows).
|
||||||
look_at->m[0][0] = ux.x; look_at->m[0][1] = ux.y; look_at->m[0][2] = ux.z;
|
look_at->m[0][0] = ux.x; look_at->m[0][1] = ux.y; look_at->m[0][2] = ux.z;
|
||||||
@@ -131,206 +130,114 @@ I_ void resolve_look_at_c11(MT3_S2S4* look_at, P3_S4* eye, P3_S4* target, V3_S4*
|
|||||||
}
|
}
|
||||||
FI_ void camera_look_at_c11(Camera* c, P3_S4* target, V3_S4* up_in) { resolve_look_at_c11(& c->look_at, & c->pos, target, up_in); }
|
FI_ void camera_look_at_c11(Camera* c, P3_S4* target, V3_S4* up_in) { resolve_look_at_c11(& c->look_at, & c->pos, target, up_in); }
|
||||||
|
|
||||||
/* Pre-build all 7 chain atoms of the resolve_look_at bundle into the static arena.
|
internal void compile_init_atoms(void) {
|
||||||
* 4 unique procs in hello_camera.atom.c (chain atoms 0, 2, 4, 6); atoms 1, 3, 5
|
AtomArena ab = atomarena_make(slice_ut_arr(smem.ct_init_atom_mem));
|
||||||
* share the GENERIC normalize_v3s4_proc from gte.atom.c
|
RegFile rf = regfile(regfile_abi_mask);
|
||||||
* 0: resolve_look_at__input_and_sub_proc
|
#define ralloc() regfile_alloc(& rf)
|
||||||
* 1: normalize_v3s4_proc (fwd → uz; offsets 0, 16)
|
#define ralloc_v3() { ralloc(), ralloc(), ralloc() }
|
||||||
* 2: resolve_look_at__cross_uz_up_in_to_right_proc
|
|
||||||
* 3: normalize_v3s4_proc (right → ux; offsets 32, 48)
|
smem.gte_cross_v3s4 = gte_cross_v3s4(& ab,
|
||||||
* 4: resolve_look_at__cross_uz_ux_to_up_proc
|
RegUse_(gte_cross_v3s4) {
|
||||||
* 5: normalize_v3s4_proc (up → uy; offsets 64, 80)
|
.a = ralloc_v3(),
|
||||||
* 6: resolve_look_at__populate_and_translate_proc
|
.b = ralloc_v3(),
|
||||||
*/
|
.out = ralloc(),
|
||||||
internal void resolve_look_at_init(void) {
|
.src_a = ralloc(),
|
||||||
/* Wrap the static arena in a MipsAtomBuilder. */
|
.src_b = ralloc(),
|
||||||
|
});
|
||||||
|
regfile_reset(& rf);
|
||||||
|
|
||||||
|
smem.normalize_v3s4 = normalize_v3s4(& ab,
|
||||||
|
RegUse_(normalize_v3s4) {
|
||||||
|
.res = ralloc_v3(),
|
||||||
|
.r0 = ralloc(),
|
||||||
|
.r1 = ralloc(),
|
||||||
|
.r2 = ralloc(),
|
||||||
|
.r3 = ralloc(),
|
||||||
|
.r4 = ralloc(),
|
||||||
|
.r5 = ralloc(),
|
||||||
|
});
|
||||||
|
regfile_reset(& rf);
|
||||||
|
|
||||||
|
assert(ab.used <= CT_InitAtomMem_Size);
|
||||||
|
#undef ralloc
|
||||||
|
#undef ralloc_v3
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void compile_resolve_look_at(void) {
|
||||||
|
AtomBundle_resolve_look_at_R bundle = C_(void*, smem.resolve_look_at_bundle);
|
||||||
AtomArena ab = atomarena_make(slice_ut_arr(smem.resolve_look_at_mem));
|
AtomArena ab = atomarena_make(slice_ut_arr(smem.resolve_look_at_mem));
|
||||||
TapeBuilder tb = tb_make(slice_ut_arr(smem.resolve_look_at_atom_addrs));
|
RegFile rf = regfile(regfile_abi_mask);
|
||||||
|
#define ralloc() regfile_alloc(& rf)
|
||||||
|
#define ralloc_v3() { ralloc(), ralloc(), ralloc() }
|
||||||
|
bundle->input_and_sub = AtomBundleEntry_(resolve_look_at, input_and_sub)(& ab,
|
||||||
|
RegUse_(resolve_look_at_input_and_sub) {
|
||||||
|
.target_ptr = ralloc(),
|
||||||
|
.eye_ptr = ralloc(),
|
||||||
|
.up_in_ptr = ralloc(),
|
||||||
|
.up_in = ralloc_v3(),
|
||||||
|
.r012 = ralloc_v3(),
|
||||||
|
.r345 = {ralloc(), R_AT, ralloc() },
|
||||||
|
});
|
||||||
|
regfile_reset(& rf);
|
||||||
|
|
||||||
U4 pin_mask = regfile_abi_mask | (1 << R_ResolveScratch);
|
bundle->normalize_fwd_uz = smem.normalize_v3s4;
|
||||||
RegFile rf = regfile(pin_mask);
|
bundle->cross_to_right = smem.gte_cross_v3s4;
|
||||||
|
bundle->normalize_right_ux = smem.normalize_v3s4;
|
||||||
|
bundle->cross_to_up = smem.gte_cross_v3s4;
|
||||||
|
bundle->normalize_up_uy = smem.normalize_v3s4;
|
||||||
|
|
||||||
U4 r_target_ptr = regfile_alloc(& rf);
|
bundle->populate_mt3s4s2 = AtomBundleEntry_(resolve_look_at,populate_mt3s4s2)(& ab,
|
||||||
U4 r_eye_ptr = regfile_alloc(& rf);
|
RegUse_(resolve_look_at_populate_mt3s4s2){
|
||||||
U4 r_up_in_ptr = regfile_alloc(& rf);
|
.look_at = ralloc(),
|
||||||
U4 r_tmp0 = regfile_alloc(& rf);
|
.eye = ralloc(),
|
||||||
U4 r_tmp1 = regfile_alloc(& rf);
|
.row = ralloc_v3(),
|
||||||
U4 r_tmp2 = regfile_alloc(& rf);
|
.r0 = ralloc(),
|
||||||
U4 r_tmp3 = regfile_alloc(& rf);
|
.r1 = ralloc(),
|
||||||
smem.resolve_look_at_atom_addrs[0] = resolve_look_at__input_and_sub_proc(& ab,
|
.r2 = ralloc(),
|
||||||
R_ResolveScratch,
|
|
||||||
r_target_ptr, r_eye_ptr, r_up_in_ptr,
|
|
||||||
r_tmp0, r_tmp1, r_tmp2, r_tmp3);
|
|
||||||
|
|
||||||
/* === ATOM 1: normalize fwd→uz === */
|
|
||||||
U2 src_offset = O_(ResolveLookAtScratch, fwd);
|
|
||||||
U2 dst_offset = O_(ResolveLookAtScratch, uz);
|
|
||||||
smem.resolve_look_at_atom_addrs[1] = normalize_v3s4_proc(& ab,
|
|
||||||
src_offset, dst_offset, RegUse_(normalize_v3s4_proc){
|
|
||||||
.scratch = R_ResolveScratch,
|
|
||||||
.src_ptr = R_T0,
|
|
||||||
.dst_ptr = R_T1,
|
|
||||||
.recip_est = R_T6,
|
|
||||||
.norm = R_T7,
|
|
||||||
.shift = R_V0,
|
|
||||||
.src_x = R_T2,
|
|
||||||
.t3 = R_T3,
|
|
||||||
.t4 = R_T5,
|
|
||||||
.t5 = R_V1,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/* === ATOM 2: cross uz×up_in→right === */
|
assert(ab.used <= ResolveLookAtArena_Size); // Sanity check: arena didn't overflow.
|
||||||
U4 r_a_2 = R_T0;
|
#undef ralloc
|
||||||
U4 r_b_2 = R_T1;
|
|
||||||
U4 r_c_2 = R_T2;
|
|
||||||
U4 r_d_2 = R_T3;
|
|
||||||
U4 r_f_2 = R_T5; /* out ptr (HARDCODED in body: scratch+32) */
|
|
||||||
U4 r_g_2 = R_T6; /* a ptr = scratch+16 */
|
|
||||||
U4 r_h_2 = R_T7; /* b ptr = scratch+128 */
|
|
||||||
smem.resolve_look_at_atom_addrs[2] = resolve_look_at__cross_uz_up_in_to_right_proc(& ab,
|
|
||||||
R_ResolveScratch,
|
|
||||||
r_a_2, r_b_2, r_c_2, r_d_2, r_f_2, r_g_2, r_h_2);
|
|
||||||
|
|
||||||
/* === ATOM 3: normalize right→ux === */
|
|
||||||
src_offset = O_(ResolveLookAtScratch, right);
|
|
||||||
dst_offset = O_(ResolveLookAtScratch, ux);
|
|
||||||
smem.resolve_look_at_atom_addrs[3] = normalize_v3s4_proc(& ab,
|
|
||||||
src_offset, dst_offset, RegUse_(normalize_v3s4_proc){
|
|
||||||
.scratch = R_ResolveScratch,
|
|
||||||
.src_ptr = R_T0,
|
|
||||||
.dst_ptr = R_T1,
|
|
||||||
.recip_est = R_T6,
|
|
||||||
.norm = R_T7,
|
|
||||||
.shift = R_V0,
|
|
||||||
.src_x = R_T2,
|
|
||||||
.t3 = R_T3,
|
|
||||||
.t4 = R_T5,
|
|
||||||
.t5 = R_V1,
|
|
||||||
});
|
|
||||||
|
|
||||||
/* === ATOM 4: cross uz×ux→up === */
|
|
||||||
U4 r_a_4 = R_T0;
|
|
||||||
U4 r_b_4 = R_T1;
|
|
||||||
U4 r_c_4 = R_T2;
|
|
||||||
U4 r_d_4 = R_T3;
|
|
||||||
U4 r_f_4 = R_T5; /* out ptr (HARDCODED: scratch+64) */
|
|
||||||
U4 r_g_4 = R_T6; /* a ptr = scratch+16 */
|
|
||||||
U4 r_h_4 = R_T7; /* b ptr = scratch+48 */
|
|
||||||
smem.resolve_look_at_atom_addrs[4] = resolve_look_at__cross_uz_ux_to_up_proc(& ab,
|
|
||||||
R_ResolveScratch,
|
|
||||||
r_a_4, r_b_4, r_c_4, r_d_4, r_f_4, r_g_4, r_h_4);
|
|
||||||
|
|
||||||
/* === ATOM 5: normalize up→uy === */
|
|
||||||
src_offset = O_(ResolveLookAtScratch, up);
|
|
||||||
dst_offset = O_(ResolveLookAtScratch, uy);
|
|
||||||
smem.resolve_look_at_atom_addrs[5] = normalize_v3s4_proc(& ab,
|
|
||||||
src_offset, dst_offset,
|
|
||||||
RegUse_(normalize_v3s4_proc){
|
|
||||||
.scratch = R_ResolveScratch,
|
|
||||||
.src_ptr = R_T0,
|
|
||||||
.dst_ptr = R_T1,
|
|
||||||
.recip_est = R_T6,
|
|
||||||
.norm = R_T7,
|
|
||||||
.shift = R_V0,
|
|
||||||
.src_x = R_T2,
|
|
||||||
.t3 = R_T3,
|
|
||||||
.t4 = R_T5,
|
|
||||||
.t5 = R_V1,
|
|
||||||
});
|
|
||||||
|
|
||||||
/* === ATOM 6a: populate (m[][] from ux/uy/uz, t[]=0) === */
|
|
||||||
U4 r_look_at_6a = R_T0; /* tape pop → look_at* */
|
|
||||||
U4 r_scratch_6a = R_ResolveScratch;
|
|
||||||
U4 r_pux_6a = R_T1;
|
|
||||||
U4 r_puy_6a = R_T3;
|
|
||||||
U4 r_puz_6a = R_T5;
|
|
||||||
U4 r_tmp0_6a = R_T2;
|
|
||||||
U4 r_tmp1_6a = R_T6;
|
|
||||||
U4 r_tmp2_6a = R_V0;
|
|
||||||
smem.resolve_look_at_atom_addrs[6] = resolve_look_at__populate_proc(& ab,
|
|
||||||
r_look_at_6a, r_scratch_6a,
|
|
||||||
r_pux_6a, r_puy_6a, r_puz_6a,
|
|
||||||
r_tmp0_6a, r_tmp1_6a, r_tmp2_6a);
|
|
||||||
|
|
||||||
/* === ATOM 6a.5: set_gte_mt3s2s4 (BAKED — ctc2 RT matrix) ===
|
|
||||||
* This is a BAKED atom from gte.atom.c. Its body hardcodes R_T3 as
|
|
||||||
* the matrix pointer (popped from tape). It does NOT need GPR
|
|
||||||
* assignment from us — it has its own internal GPR usage.
|
|
||||||
* We just take its address. */
|
|
||||||
smem.resolve_look_at_atom_addrs[7] = (MipsAtom*) & set_gte_mt3s2s4;
|
|
||||||
|
|
||||||
/* === ATOM 6b: matrix_vector (RT * (-eye) >> 12) ===
|
|
||||||
* Uses mac_apply_matrix_lv component macro which internally uses
|
|
||||||
* r_t0 for the RT matrix load + V0 load, then r_t0/r_t1/r_t2
|
|
||||||
* for the mfc2/store. We pass our GPRs. */
|
|
||||||
U4 r_scratch_6b = R_ResolveScratch;
|
|
||||||
U4 r_peye_6b = R_T1; /* scratch+96 (packed V0 dst, then off dst) */
|
|
||||||
U4 r_look_at_6b = R_T0; /* tape pop → look_at* */
|
|
||||||
U4 r_tmp0_6b = R_T2;
|
|
||||||
U4 r_tmp1_6b = R_T3;
|
|
||||||
U4 r_tmp2_6b = R_T5;
|
|
||||||
smem.resolve_look_at_atom_addrs[8] = resolve_look_at__matrix_vector_proc(& ab,
|
|
||||||
r_scratch_6b, r_peye_6b, r_look_at_6b,
|
|
||||||
r_tmp0_6b, r_tmp1_6b, r_tmp2_6b);
|
|
||||||
|
|
||||||
/* === ATOM 6c: trans_matrix (off → look_at->t[]) === */
|
|
||||||
U4 r_look_at_6c = R_T0; /* tape pop → look_at* */
|
|
||||||
U4 r_scratch_6c = R_ResolveScratch;
|
|
||||||
U4 r_off_ptr_6c = R_T1; /* &scratch.eye (= off dst) */
|
|
||||||
U4 r_tmp0_6c = R_T2;
|
|
||||||
smem.resolve_look_at_atom_addrs[9] = resolve_look_at__trans_matrix_proc(& ab,
|
|
||||||
r_look_at_6c, r_scratch_6c, r_off_ptr_6c, r_tmp0_6c, R_T3, R_T4);
|
|
||||||
|
|
||||||
/* Sanity check: arena didn't overflow. */
|
|
||||||
assert(ab.used <= ResolveLookAtArena_Size);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Emit the resolve_look_at bundle into the tape. Called once per frame from update().
|
// Emit the resolve_look_at bundle into the tape. Called once per frame from update().
|
||||||
* The 7 chain atoms are pre-built at init time (resolve_look_at_init) and referenced by address via smem.resolve_look_at_atom_addrs[].
|
I_ void resolve_look_at(TapeBuilder_R tb, MT3_S2S4* look_at, P3_S4* eye, P3_S4* target, V3_S4* up_in) {
|
||||||
* Per-frame work: 7 tb_emit (atom pointer emissions) + 5 tb_data (C-side pointers for atom 0 + look_at for atom 6).
|
/* Typed view of the scratchpad for field-address arithmetic. */
|
||||||
*
|
ResolveLookAtScratch* sp = C_scratch(ResolveLookAtScratch*);
|
||||||
* Binds_ contract (the field-name labels are for human readability):
|
AtomBundle_resolve_look_at_R bundle = C_(void*, smem.resolve_look_at_bundle);
|
||||||
* Atom 0 input_and_sub target(4) eye(4) up_in(4) scratch_base(4) = 4 words
|
tb_emit(tb, bundle->input_and_sub); tb_bind_(tb, Binds_ResolveLookAtSub,
|
||||||
* Atoms 1-5 (no tape data — atom uses r_scratch + offset internally)
|
.target = target,
|
||||||
* Atom 6 populate_and_translate look_at(4) = 1 word
|
.eye = eye,
|
||||||
* ----
|
.up_in = up_in,
|
||||||
* 5 tb_data words total per frame.
|
);
|
||||||
*/
|
tb_emit(tb, bundle->normalize_fwd_uz); tb_bind_(tb, Binds_normalize_v3s4,
|
||||||
I_ void resolve_look_at(
|
.src_offset = O_(ResolveLookAtScratch,fwd),
|
||||||
TapeBuilder_R tb
|
.dst_offset = O_(ResolveLookAtScratch,uz),
|
||||||
, MT3_S2S4* look_at
|
);
|
||||||
, P3_S4* eye
|
tb_emit(tb, bundle->cross_to_right); tb_bind_(tb, Binds_gte_cross_v3s4,
|
||||||
, P3_S4* target
|
.src_a = & sp->uz,
|
||||||
, V3_S4* up_in
|
.src_b = & sp->up_in,
|
||||||
){
|
.out = & sp->right,
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[0]); {
|
);
|
||||||
tb_data(tb, u4_(target));
|
tb_emit(tb, bundle->normalize_right_ux); tb_bind_(tb, Binds_normalize_v3s4,
|
||||||
tb_data(tb, u4_(eye));
|
.src_offset = O_(ResolveLookAtScratch,right),
|
||||||
tb_data(tb, u4_(up_in));
|
.dst_offset = O_(ResolveLookAtScratch,ux),
|
||||||
tb_data(tb, u4_(smem.scratchpad));
|
);
|
||||||
}
|
tb_emit(tb, bundle->cross_to_up); tb_bind_(tb, Binds_gte_cross_v3s4,
|
||||||
|
.src_a = & sp->uz,
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[1]); { }
|
.src_b = & sp->ux,
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[2]); { }
|
.out = & sp->up,
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[3]); { }
|
);
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[4]); { }
|
tb_emit(tb, bundle->normalize_up_uy); tb_bind_(tb, Binds_normalize_v3s4,
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[5]); { }
|
.src_offset = O_(ResolveLookAtScratch,up),
|
||||||
|
.dst_offset = O_(ResolveLookAtScratch,uy),
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[6]); {
|
);
|
||||||
tb_data(tb, u4_(look_at));
|
tb_emit(tb, bundle->populate_mt3s4s2); tb_bind_(tb, Binds_ResolveLookAt_PopulateMT3S4S2,
|
||||||
}
|
.look_at = look_at,
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[7]); {
|
);
|
||||||
tb_data(tb, u4_(look_at));
|
|
||||||
}
|
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[8]); {
|
|
||||||
tb_data(tb, u4_(look_at));
|
|
||||||
}
|
|
||||||
tb_emit(tb, smem.resolve_look_at_atom_addrs[9]); {
|
|
||||||
// tb_data(tb, u4_(look_at));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
FI_ void camera_look_at(TapeBuilder_R tb, Camera* c, P3_S4* target, V3_S4* up_in) { resolve_look_at(tb, & c->look_at, & c->pos, target, up_in); }
|
||||||
|
|
||||||
GCC_OPTIMIZATION_DISABLE
|
|
||||||
void update(PrimitiveArena* pa, U4* ordering_buf)
|
void update(PrimitiveArena* pa, U4* ordering_buf)
|
||||||
{
|
{
|
||||||
TapeBuilder tb = tb_make(slice_ut_arr(smem.MemTape));
|
TapeBuilder tb = tb_make(slice_ut_arr(smem.MemTape));
|
||||||
@@ -340,15 +247,15 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
|
|||||||
tb.used = 0; tb_scope_run(& tb) {
|
tb.used = 0; tb_scope_run(& tb) {
|
||||||
// Grab latest state from bios.
|
// Grab latest state from bios.
|
||||||
tb_emit_(pad_bios_snapshot);
|
tb_emit_(pad_bios_snapshot);
|
||||||
tb_data_(raw, & smem.pad_raw[0]);
|
tb_data(& tb, u4_(& smem.pad_raw[0]));
|
||||||
tb_data_(state, & smem.pad[0]);
|
tb_data(& tb, u4_(& smem.pad[0]));
|
||||||
// tb_emit_(pad_bios_snapshot);
|
// tb_emit_(pad_bios_snapshot);
|
||||||
// tb_data_(raw, & smem.pad_raw[1]);
|
// tb_data_(raw, & smem.pad_raw[1]);
|
||||||
// tb_data_(state, & smem.pad[1]);
|
// tb_data_(state, & smem.pad[1]);
|
||||||
|
|
||||||
tb_emit_(pad_input_cam);
|
tb_emit_(pad_input_cam);
|
||||||
tb_data_(state, & smem.pad[0]);
|
tb_data(& tb, u4_(& smem.pad[0]));
|
||||||
tb_data_(cam, & smem.cam);
|
tb_data(& tb, u4_(& smem.cam));
|
||||||
|
|
||||||
// tb_emit_(pad_input_cube_rotation);
|
// tb_emit_(pad_input_cube_rotation);
|
||||||
// tb_data_(state, & smem.pad[0]);
|
// tb_data_(state, & smem.pad[0]);
|
||||||
@@ -365,12 +272,6 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
|
|||||||
gknown V3_S4_R acc = & smem.cube.accel;
|
gknown V3_S4_R acc = & smem.cube.accel;
|
||||||
add_v3s4(vel, acc[0]);
|
add_v3s4(vel, acc[0]);
|
||||||
add_v3s4_fp(pos, vel[0]);
|
add_v3s4_fp(pos, vel[0]);
|
||||||
// vel->x += acc->x;
|
|
||||||
// vel->y += acc->y;
|
|
||||||
// vel->z += acc->z;
|
|
||||||
// pos->x += vel->x;
|
|
||||||
// pos->y += vel->y;
|
|
||||||
// pos->z += vel->z;
|
|
||||||
|
|
||||||
if (pos->y + 150 > smem.floor.pos.y) vel->y *= -1;
|
if (pos->y + 150 > smem.floor.pos.y) vel->y *= -1;
|
||||||
|
|
||||||
@@ -387,7 +288,7 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
|
|||||||
if (use_c11_path == false)
|
if (use_c11_path == false)
|
||||||
{
|
{
|
||||||
tb.used = 0; tb_scope_run(& tb) {
|
tb.used = 0; tb_scope_run(& tb) {
|
||||||
resolve_look_at(& tb, & smem.cam.look_at, & smem.cam.pos, & smem.cube.pos, & v3s4(0, -fp_one, 0));
|
camera_look_at(& tb, & smem.cam, & smem.cube.pos, & v3s4(0, -fp_one, 0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -403,9 +304,6 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
|
|||||||
gte_matrix_set_rotation (& smem.tform_view);
|
gte_matrix_set_rotation (& smem.tform_view);
|
||||||
gte_matrix_set_translation(& smem.tform_view);
|
gte_matrix_set_translation(& smem.tform_view);
|
||||||
|
|
||||||
// gte_matrix_set_rotation (& smem.tform_world);
|
|
||||||
// gte_matrix_set_translation(& smem.tform_world);
|
|
||||||
|
|
||||||
U4 prim_base = u4_(pa->buf[smem.active_buf_id]);
|
U4 prim_base = u4_(pa->buf[smem.active_buf_id]);
|
||||||
U4 prim_cursor = prim_base + pa->used;
|
U4 prim_cursor = prim_base + pa->used;
|
||||||
|
|
||||||
@@ -425,7 +323,7 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
|
|||||||
tb_data(& tb, u4_(& pa->used));
|
tb_data(& tb, u4_(& pa->used));
|
||||||
tb_data(& tb, prim_base);
|
tb_data(& tb, prim_base);
|
||||||
}
|
}
|
||||||
tape_run_a02_s07(tb_slice(tb));// Fire off the tape (bigger-clobber variant).
|
tape_run(tb_slice(tb));// Fire off the tape (bigger-clobber variant).
|
||||||
|
|
||||||
// smem.cube.rot.y += 30;
|
// smem.cube.rot.y += 30;
|
||||||
}
|
}
|
||||||
@@ -467,13 +365,12 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
|
|||||||
tb_data(& tb, u4_(& pa->used));
|
tb_data(& tb, u4_(& pa->used));
|
||||||
tb_data(& tb, prim_base);
|
tb_data(& tb, prim_base);
|
||||||
}
|
}
|
||||||
tape_run_a02_s07(tb_slice(tb));// Fire off the tape (bigger-clobber variant).
|
tape_run(tb_slice(tb));// Fire off the tape (bigger-clobber variant).
|
||||||
|
|
||||||
// C-side state (pa->used) has already been updated by the tape!
|
// C-side state (pa->used) has already been updated by the tape!
|
||||||
// smem.floor.rot.y += 5;
|
// smem.floor.rot.y += 5;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GCC_OPTIMIZATION_ENABLE
|
|
||||||
|
|
||||||
void render(void) {
|
void render(void) {
|
||||||
}
|
}
|
||||||
@@ -490,12 +387,9 @@ void gp_display_frame(DoubleBuffer* screen_buf, S4* active_buf_id, U4* ordering_
|
|||||||
active_buf_id[0] = ! active_buf_id[0]; // Swap current buffer
|
active_buf_id[0] = ! active_buf_id[0]; // Swap current buffer
|
||||||
}
|
}
|
||||||
|
|
||||||
GCC_OPTIMIZATION_DISABLE
|
|
||||||
int main(void)
|
int main(void)
|
||||||
{
|
{
|
||||||
smem = (SMemory){0};
|
smem = (SMemory){0};
|
||||||
// TODO(Ed): remove this field we don't need it in smem.
|
|
||||||
smem.scratchpad = C_(U4_V, Scratchpad_Loc);
|
|
||||||
// smem.primitives.used = 0;
|
// smem.primitives.used = 0;
|
||||||
// smem.active_buf_id = 0;
|
// smem.active_buf_id = 0;
|
||||||
smem.cam.pos = v3s4(500, -1000, -1500);
|
smem.cam.pos = v3s4(500, -1000, -1500);
|
||||||
@@ -519,8 +413,8 @@ int main(void)
|
|||||||
/* Direct BIOS: poll both ports during VBlank. */
|
/* Direct BIOS: poll both ports during VBlank. */
|
||||||
pad_bios_init_start(& smem.pad_raw[0], & smem.pad_raw[1]);
|
pad_bios_init_start(& smem.pad_raw[0], & smem.pad_raw[1]);
|
||||||
|
|
||||||
/* Pre-build the resolve_look_at bundle atoms into the static arena. */
|
compile_init_atoms();
|
||||||
resolve_look_at_init();
|
compile_resolve_look_at();
|
||||||
|
|
||||||
/* Pinned registers for the GPU init atom. */
|
/* Pinned registers for the GPU init atom. */
|
||||||
register U4* io_base_addr rgcc(R_IO_BaseAddr) = u4_r(IO_BASE_ADDR);
|
register U4* io_base_addr rgcc(R_IO_BaseAddr) = u4_r(IO_BASE_ADDR);
|
||||||
@@ -540,5 +434,3 @@ int main(void)
|
|||||||
};
|
};
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
GCC_OPTIMIZATION_ENABLE
|
|
||||||
|
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ I_ void ent_cube128_init(A8_V3_S2* verts, A6_V4_S2* faces) {
|
|||||||
typedef Struct_(Ent_Cube) {
|
typedef Struct_(Ent_Cube) {
|
||||||
V3_S4 accel;
|
V3_S4 accel;
|
||||||
V3_S4 vel;
|
V3_S4 vel;
|
||||||
V3_S4 pos; // RGA(Lengyel): affine point with implicit weight one. Storage alias of V3_S4.
|
V3_S4 pos;
|
||||||
V3_S4 scale;
|
V3_S4 scale;
|
||||||
V3_S2 rot;
|
V3_S2 rot;
|
||||||
A8_V3_S2 verts;
|
A8_V3_S2 verts;
|
||||||
@@ -88,7 +88,7 @@ I_ void ent_floor_init(A4_V3_S2* verts, A2_V3_S2* faces) {
|
|||||||
};
|
};
|
||||||
typedef Struct_(Ent_Floor) {
|
typedef Struct_(Ent_Floor) {
|
||||||
V3_S4 accel;
|
V3_S4 accel;
|
||||||
V3_S4 pos; // RGA(Lengyel): affine point with implicit weight one. Storage alias of V3_S4.
|
V3_S4 pos;
|
||||||
V3_S4 scale;
|
V3_S4 scale;
|
||||||
V3_S2 rot;
|
V3_S2 rot;
|
||||||
A4_V3_S2 verts;
|
A4_V3_S2 verts;
|
||||||
@@ -96,7 +96,7 @@ typedef Struct_(Ent_Floor) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
typedef Struct_(Camera) {
|
typedef Struct_(Camera) {
|
||||||
P3_S4 pos; // RGA(Lengyel): affine point with implicit weight one. Storage alias of V3_S4.
|
P3_S4 pos;
|
||||||
V3_S2 rot;
|
V3_S2 rot;
|
||||||
MT3_S2S4 look_at;
|
MT3_S2S4 look_at;
|
||||||
};
|
};
|
||||||
|
|||||||
+74
-2862
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,866 @@
|
|||||||
|
--- duffle_isa.lua — encoder / GTE / hardware tables.
|
||||||
|
|
||||||
|
--- @class InstructionImm
|
||||||
|
--- @field arg integer
|
||||||
|
--- @field signed boolean|nil
|
||||||
|
--- @field width integer
|
||||||
|
|
||||||
|
--- @class InstructionValue
|
||||||
|
--- @field dest integer
|
||||||
|
--- @field op string
|
||||||
|
--- @field sources integer[]|nil
|
||||||
|
--- @field immediate integer|nil
|
||||||
|
--- @field source integer|nil
|
||||||
|
|
||||||
|
--- @class InstructionRow
|
||||||
|
--- @field cycles integer
|
||||||
|
--- @field kind string
|
||||||
|
--- @field reads integer[]|nil
|
||||||
|
--- @field writes integer[]|nil
|
||||||
|
--- @field imm InstructionImm[]|nil
|
||||||
|
--- @field value InstructionValue|nil
|
||||||
|
--- @field delay_slot boolean|nil
|
||||||
|
--- @field suppress_arg1 table<string, string>|nil -- bag: GPR ident -> reason
|
||||||
|
|
||||||
|
--- @class TapeAtomMacroRow
|
||||||
|
--- @field kind string
|
||||||
|
--- @field binds boolean
|
||||||
|
|
||||||
|
--- @class GteCommandPort
|
||||||
|
--- @field register string
|
||||||
|
--- @field role string
|
||||||
|
|
||||||
|
--- @class GteCommandLatch
|
||||||
|
--- @field register string
|
||||||
|
--- @field required integer
|
||||||
|
|
||||||
|
--- @class GteCommandRow
|
||||||
|
--- @field aliases string[]
|
||||||
|
--- @field cycles integer
|
||||||
|
--- @field inputs string[]
|
||||||
|
--- @field outputs GteCommandPort[]
|
||||||
|
--- @field latch GteCommandLatch[]
|
||||||
|
|
||||||
|
--- @class GteCrAliasGroup
|
||||||
|
--- @field [1] integer -- C2 control-register slot
|
||||||
|
--- @field [2] string[] -- aliases that share that slot
|
||||||
|
|
||||||
|
--- @class GtePackedSlotRelation
|
||||||
|
--- @field slot integer
|
||||||
|
--- @field first string
|
||||||
|
--- @field second string
|
||||||
|
|
||||||
|
--- @class HardwareRelationPort
|
||||||
|
--- @field domain string
|
||||||
|
--- @field arg integer
|
||||||
|
|
||||||
|
--- @class HardwareRelationVisibility
|
||||||
|
--- @field kind string
|
||||||
|
--- @field required integer
|
||||||
|
|
||||||
|
--- @class HardwareRelationEvidence
|
||||||
|
--- @field confidence string
|
||||||
|
--- @field source string
|
||||||
|
|
||||||
|
--- @class HardwareRelationRow
|
||||||
|
--- @field id string
|
||||||
|
--- @field semantic string
|
||||||
|
--- @field consumer string
|
||||||
|
--- @field token string
|
||||||
|
--- @field direction string
|
||||||
|
--- @field reads HardwareRelationPort
|
||||||
|
--- @field writes HardwareRelationPort
|
||||||
|
--- @field visibility HardwareRelationVisibility|nil
|
||||||
|
--- @field evidence HardwareRelationEvidence
|
||||||
|
--- @field violation_kind string
|
||||||
|
--- @field destination_match string|nil
|
||||||
|
--- @field fanout_to string[]|nil
|
||||||
|
--- @field required integer|nil
|
||||||
|
--- @field clear_on_consumer boolean|nil
|
||||||
|
--- @field stage boolean|nil
|
||||||
|
--- @field cu2_transition boolean|nil
|
||||||
|
--- @field status_register integer|nil
|
||||||
|
|
||||||
|
--- @class Cu2TransitionPolicy
|
||||||
|
--- @field status_register integer
|
||||||
|
--- @field enable_bit integer
|
||||||
|
--- @field required integer
|
||||||
|
--- @field visibility_kind string
|
||||||
|
--- @field evidence HardwareRelationEvidence
|
||||||
|
|
||||||
|
--- @class GprRole
|
||||||
|
--- @field name string
|
||||||
|
--- @field pool boolean
|
||||||
|
--- @field optional boolean
|
||||||
|
--- @field carrier boolean
|
||||||
|
|
||||||
|
--- @class DuffleIsa
|
||||||
|
--- @field GPR_ROLE table<string, GprRole>
|
||||||
|
--- @field TAPE_ATOM_MACROS table<string, TapeAtomMacroRow>
|
||||||
|
--- @field DELAY_MARKERS table<string, boolean>
|
||||||
|
--- @field INSTRUCTION table<string, InstructionRow>
|
||||||
|
--- @field GTE_COMMAND table<string, GteCommandRow>
|
||||||
|
--- @field ALIAS_TO_CANONICAL table<string, string>
|
||||||
|
--- @field instr fun(ident: string): InstructionRow|nil
|
||||||
|
--- @field gte_canon fun(ident: string): string
|
||||||
|
--- @field gte fun(ident: string): GteCommandRow|nil
|
||||||
|
--- @field GTE_CR_ALIAS_GROUPS GteCrAliasGroup[]
|
||||||
|
--- @field GTE_PACKED_SLOT_RELATIONS GtePackedSlotRelation[]
|
||||||
|
--- @field OPERAND_READ_POSITIONS table<string, integer[]>
|
||||||
|
--- @field GP0_CMD_SIZE table<integer, integer>
|
||||||
|
--- @field GP0_CMD_BY_SHAPE table<string, integer>
|
||||||
|
--- @field UNKNOWN_INSTRUCTION_CYCLES integer
|
||||||
|
--- @field HARDWARE_RELATIONS HardwareRelationRow[]
|
||||||
|
--- @field CU2_TRANSITION_POLICY Cu2TransitionPolicy
|
||||||
|
|
||||||
|
local M = {} ---@type DuffleIsa
|
||||||
|
|
||||||
|
-- Section 7: domain tables
|
||||||
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
-- One GprRole row per name. Construction order is the auto_reg pool order,
|
||||||
|
-- then R_AT, then the three carriers. Index by name into M.GPR_ROLE.
|
||||||
|
--- @type table<string, GprRole>
|
||||||
|
M.GPR_ROLE = {
|
||||||
|
{ name = "R_V0", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_V1", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T0", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T1", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T2", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T3", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T4", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T5", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T6", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T7", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_A0", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_A1", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_A2", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_A3", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S0", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S1", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S2", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S3", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S4", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S5", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S6", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_S7", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T8", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_T9", pool = true, optional = true, carrier = false },
|
||||||
|
{ name = "R_AT", pool = false, optional = true, carrier = false },
|
||||||
|
{ name = "R_TapePtr", pool = false, optional = true, carrier = true },
|
||||||
|
{ name = "R_AtomJmp", pool = false, optional = true, carrier = true },
|
||||||
|
{ name = "R_ScratchBase", pool = false, optional = true, carrier = true },
|
||||||
|
}
|
||||||
|
for _, row in ipairs(M.GPR_ROLE) do ---@type integer, GprRole
|
||||||
|
M.GPR_ROLE[row.name] = row
|
||||||
|
end
|
||||||
|
|
||||||
|
-- atom_info sub-calls: atom_bind, atom_reads, atom_writes, atom_view, atom_reg_types, atom_ctx, atom_phase.
|
||||||
|
--- @type table<string, TapeAtomMacroRow>
|
||||||
|
M.TAPE_ATOM_MACROS = {
|
||||||
|
["atom_info"] = { kind = "info", binds = false },
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Empty C macros that prefix the next encoder. Zero words.
|
||||||
|
-- BdSlot_ nop is one nop word. The marker is not the BD instruction.
|
||||||
|
--- @type table<string, boolean> -- bag: marker prefix -> true
|
||||||
|
M.DELAY_MARKERS = {
|
||||||
|
["GteDelay_"] = true,
|
||||||
|
["LdSlot_"] = true,
|
||||||
|
["BdSlot_"] = true,
|
||||||
|
["DmaSlot_"] = true,
|
||||||
|
}
|
||||||
|
|
||||||
|
-- One row per encoder. Read through duffle.instr.
|
||||||
|
--- @type table<string, InstructionRow>
|
||||||
|
M.INSTRUCTION = {
|
||||||
|
["BdSlot_"] = { cycles = 0, kind = "marker", },
|
||||||
|
["LdSlot_"] = { cycles = 0, kind = "marker", },
|
||||||
|
["add_s"] = { cycles = 1, kind = "alu", },
|
||||||
|
["add_si"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, },}, },
|
||||||
|
["add_u"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["add_u_self"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, value = { dest = 1, op = "add_u", sources = { 1, 2 }, }, },
|
||||||
|
["add_ui"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, }, }, value = { dest = 1, immediate = 3, op = "add_ui", source = 2, }, },
|
||||||
|
["add_ui_self"] = { cycles = 1, kind = "alu", reads = { 1 }, writes = { 1 }, imm = { { arg = 2, signed = true, width = 16, }, }, value = { dest = 1, immediate = 2, op = "add_ui", source = 1, }, },
|
||||||
|
["and"] = { cycles = 1, kind = "alu", },
|
||||||
|
["and_i"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, imm = { { arg = 3, width = 16, }, }, value = { dest = 1, immediate = 3, op = "and_i", source = 2, }, },
|
||||||
|
["and_u"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["atom_bind"] = { cycles = 0, kind = "marker", reads = {}, writes = {}, },
|
||||||
|
["atom_info"] = { cycles = 0, kind = "marker", reads = {}, writes = {}, },
|
||||||
|
["atom_label"] = { cycles = 0, kind = "marker", reads = {}, writes = {}, },
|
||||||
|
["atom_offset"] = { cycles = 0, kind = "marker", reads = {}, writes = {}, },
|
||||||
|
["atom_reads"] = { cycles = 0, kind = "marker", reads = {}, writes = {}, },
|
||||||
|
["atom_writes"] = { cycles = 0, kind = "marker", reads = {}, writes = {}, },
|
||||||
|
["branch_equal"] = { cycles = 2, kind = "branch", reads = { 1, 2 }, writes = {}, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["branch_ge_zero"] = { cycles = 2, kind = "branch", reads = { 1 }, writes = {}, imm = { { arg = 2, signed = true, width = 16, }, }, },
|
||||||
|
["branch_gt_zero"] = { cycles = 2, kind = "branch", reads = { 1 }, writes = {}, imm = { { arg = 2, signed = true, width = 16, }, }, },
|
||||||
|
["branch_le_zero"] = { cycles = 2, kind = "branch", reads = { 1 }, writes = {}, imm = { { arg = 2, signed = true, width = 16, }, }, },
|
||||||
|
["branch_lt_zero"] = { cycles = 2, kind = "branch", reads = { 1 }, writes = {}, imm = { { arg = 2, signed = true, width = 16, }, }, },
|
||||||
|
["branch_ne"] = { cycles = 2, kind = "branch", reads = { 1, 2 }, writes = {}, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["call_addr"] = { cycles = 2, kind = "call", reads = {}, writes = { 1 }, },
|
||||||
|
["call_reg"] = { cycles = 2, kind = "call", reads = { 1 }, writes = { 2 }, },
|
||||||
|
["div_s"] = { cycles = 35, kind = "alu", reads = { 1, 2 }, writes = {}, },
|
||||||
|
["div_u"] = { cycles = 35, kind = "alu", reads = { 1, 2 }, writes = {}, },
|
||||||
|
["gte_load_v0"] = { cycles = 2, kind = "cop2_xfer", reads = { 2 }, writes = {}, },
|
||||||
|
["gte_load_v0v1v2"] = { cycles = 6, kind = "cop2_xfer", reads = { 2 }, writes = {}, },
|
||||||
|
["gte_load_v1"] = { cycles = 2, kind = "cop2_xfer", reads = { 2 }, writes = {}, },
|
||||||
|
["gte_load_v2"] = { cycles = 2, kind = "cop2_xfer", reads = { 2 }, writes = {}, },
|
||||||
|
["gte_lw"] = { cycles = 1, kind = "load", reads = { 2 }, writes = {}, },
|
||||||
|
["gte_lwc2"] = { cycles = 1, kind = "load", },
|
||||||
|
["gte_mv_from_ctrl_r"] = { cycles = 1, kind = "cop2_xfer", reads = {}, writes = { 1 }, },
|
||||||
|
["gte_mv_from_data_r"] = { cycles = 1, kind = "cop2_xfer", reads = {}, writes = { 1 }, },
|
||||||
|
["gte_mv_to_ctrl_r"] = { cycles = 1, kind = "cop2_xfer", reads = { 1 }, writes = {}, },
|
||||||
|
["gte_mv_to_data_r"] = { cycles = 1, kind = "cop2_xfer", reads = { 1 }, writes = {}, },
|
||||||
|
["gte_stotz"] = { cycles = 1, kind = "cop2_xfer", reads = {}, writes = {}, },
|
||||||
|
["gte_stsxy3"] = { cycles = 1, kind = "cop2_xfer", reads = {}, writes = {}, },
|
||||||
|
["gte_sw"] = { cycles = 1, kind = "store", reads = { 2 }, writes = {}, },
|
||||||
|
["gte_swc2"] = { cycles = 1, kind = "store", },
|
||||||
|
["jump"] = { cycles = 2, kind = "jump", reads = {}, writes = {}, },
|
||||||
|
["jump_link"] = { cycles = 2, kind = "call", reads = { 1 }, writes = { 2 }, },
|
||||||
|
["jump_reg"] = { cycles = 2, kind = "jump", reads = { 1 }, writes = {}, suppress_arg1 = { R_AtomJmp = "fixed mac_yield handshake", }, },
|
||||||
|
["jump_rel"] = { cycles = 2, kind = "branch", delay_slot = true, },
|
||||||
|
["li_s"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, value = { dest = 1, immediate = 3, op = "add_ui", source = 2, }, },
|
||||||
|
["load_byte"] = { cycles = 1, kind = "load", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["load_byte_u"] = { cycles = 1, kind = "load", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["load_half"] = { cycles = 1, kind = "load", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["load_half_u"] = { cycles = 1, kind = "load", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["load_imm"] = { cycles = 2, kind = "alu", reads = {}, writes = { 1 }, },
|
||||||
|
["load_ui"] = { cycles = 1, kind = "alu", reads = {}, writes = { 1 }, },
|
||||||
|
["load_upper_i"] = { cycles = 1, kind = "alu", reads = {}, writes = { 1 }, imm = { { arg = 2, width = 16, }, }, value = { dest = 1, immediate = 2, op = "load_upper_i", }, },
|
||||||
|
["load_word"] = { cycles = 1, kind = "load", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["mac_yield"] = { cycles = 0, kind = "marker", reads = {}, writes = {}, },
|
||||||
|
["mask_upper"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, },
|
||||||
|
["mov_from_high"] = { cycles = 2, kind = "alu", reads = {}, writes = { 1 }, },
|
||||||
|
["mov_from_low"] = { cycles = 2, kind = "alu", reads = {}, writes = { 1 }, },
|
||||||
|
["mov_to_high"] = { cycles = 1, kind = "alu", reads = { 1 }, writes = {}, },
|
||||||
|
["mov_to_low"] = { cycles = 1, kind = "alu", reads = { 1 }, writes = {}, },
|
||||||
|
["mult_s"] = { cycles = 12, kind = "alu", reads = { 1, 2 }, writes = {}, },
|
||||||
|
["mult_u"] = { cycles = 12, kind = "alu", reads = { 1, 2 }, writes = {}, },
|
||||||
|
["nop"] = { cycles = 1, kind = "nop", reads = {}, writes = {}, },
|
||||||
|
["nop2"] = { cycles = 2, kind = "nop", reads = {}, writes = {}, },
|
||||||
|
["nor_u"] = { cycles = 1, kind = "alu", },
|
||||||
|
["or_i"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, imm = { { arg = 3, width = 16, }, }, value = { dest = 1, immediate = 3, op = "or_i", source = 2, }, },
|
||||||
|
["or_i_self"] = { cycles = 1, kind = "alu", reads = { 1 }, writes = { 1 }, imm = { { arg = 2, width = 16, }, }, value = { dest = 1, immediate = 2, op = "or_i", source = 1, }, },
|
||||||
|
["or_u"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["or_u_self"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, value = { dest = 1, op = "or", sources = { 1, 2 }, }, },
|
||||||
|
["set_lt_s"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["set_lt_si"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, },
|
||||||
|
["set_lt_u"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["set_lt_ui"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, },
|
||||||
|
["shift_aright"] = { cycles = 1, kind = "alu", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, width = 5, }, }, },
|
||||||
|
["shift_aright_var"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, imm = { { arg = 3, width = 5, }, }, },
|
||||||
|
["shift_lleft"] = { cycles = 1, kind = "alu", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, width = 5, }, }, },
|
||||||
|
["shift_lleft_self"] = { cycles = 1, kind = "alu", reads = { 1 }, writes = { 1 }, imm = { { arg = 2, width = 5, }, }, value = { dest = 1, immediate = 2, op = "shift_lleft", source = 1, }, },
|
||||||
|
["shift_lleft_var"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["shift_lright"] = { cycles = 1, kind = "alu", reads = { 2 }, writes = { 1 }, imm = { { arg = 3, width = 5, }, }, },
|
||||||
|
["slt_s"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["slt_si"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["slt_u"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["slt_ui"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, imm = { { arg = 3, signed = true, width = 16,}, }, },
|
||||||
|
["store_byte"] = { cycles = 1, kind = "store", reads = { 1, 2 }, writes = {}, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["store_half"] = { cycles = 1, kind = "store", reads = { 1, 2 }, writes = {}, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["store_word"] = { cycles = 1, kind = "store", reads = { 1, 2 }, writes = {}, imm = { { arg = 3, signed = true, width = 16, }, }, },
|
||||||
|
["sub_s"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["sub_u"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
["sys_mov_from_cop0"] = { cycles = 1, kind = "cop0_xfer", reads = {}, writes = { 1 }, },
|
||||||
|
["sys_mov_to_cop0"] = { cycles = 1, kind = "cop0_xfer", reads = { 1 }, writes = {}, },
|
||||||
|
["xor_i"] = { cycles = 1, kind = "alu", reads = { 1, 2 }, writes = { 1 }, imm = { { arg = 3, width = 16, }, }, value = { dest = 1, immediate = 3, op = "xor_i", source = 2, }, },
|
||||||
|
["xor_u"] = { cycles = 1, kind = "alu", reads = { 2, 3 }, writes = { 1 }, },
|
||||||
|
}
|
||||||
|
|
||||||
|
-- One row per GTE command. Alias cycle numbers live here, not on INSTRUCTION.
|
||||||
|
--- @type table<string, GteCommandRow>
|
||||||
|
M.GTE_COMMAND = {
|
||||||
|
["gte_cmdw_avsz3"] = {
|
||||||
|
aliases = { "gte_avg_sort_z3", "gte_avsz3", "gte_cmdw_avg_sort_z3" },
|
||||||
|
cycles = 5,
|
||||||
|
inputs = { "C2_SZ0", "C2_SZ1", "C2_SZ2", "C2_SZ3", "gte_cr_ZSF3" },
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_OTZ", role = "otz", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_OTZ", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_avsz4"] = {
|
||||||
|
aliases = { "gte_avg_sort_z4", "gte_avsz4", "gte_cmdw_avg_sort_z4" },
|
||||||
|
cycles = 6,
|
||||||
|
inputs = { "C2_SZ0", "C2_SZ1", "C2_SZ2", "C2_SZ3", "gte_cr_ZSF4" },
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_OTZ", role = "otz", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_OTZ", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_gpf"] = {
|
||||||
|
aliases = {},
|
||||||
|
cycles = 5,
|
||||||
|
inputs = { "C2_IR0", "C2_IR1", "C2_IR2", "C2_IR3" },
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_MAC1", role = "mac_result", },
|
||||||
|
{ register = "C2_MAC2", role = "mac_result", },
|
||||||
|
{ register = "C2_MAC3", role = "mac_result", },
|
||||||
|
{ register = "C2_IR1", role = "latest_color", },
|
||||||
|
{ register = "C2_IR2", role = "latest_color", },
|
||||||
|
{ register = "C2_IR3", role = "latest_color", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_MAC1", required = 4, },
|
||||||
|
{ register = "C2_MAC2", required = 4, },
|
||||||
|
{ register = "C2_MAC3", required = 4, },
|
||||||
|
{ register = "C2_IR1", required = 4, },
|
||||||
|
{ register = "C2_IR2", required = 4, },
|
||||||
|
{ register = "C2_IR3", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_mvmva"] = {
|
||||||
|
aliases = {},
|
||||||
|
cycles = 8,
|
||||||
|
inputs = {
|
||||||
|
"C2_VXY0", "C2_VZ0",
|
||||||
|
"C2_VXY1", "C2_VZ1",
|
||||||
|
"C2_VXY2", "C2_VZ2",
|
||||||
|
"C2_IR1", "C2_IR2", "C2_IR3",
|
||||||
|
"gte_cr_RT11", "gte_cr_RT12", "gte_cr_RT13",
|
||||||
|
"gte_cr_RT21", "gte_cr_RT22", "gte_cr_RT23",
|
||||||
|
"gte_cr_RT31", "gte_cr_RT32", "gte_cr_RT33",
|
||||||
|
"gte_cr_TRX", "gte_cr_TRY", "gte_cr_TRZ"
|
||||||
|
},
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_IR1", role = "latest_color", },
|
||||||
|
{ register = "C2_IR2", role = "latest_color", },
|
||||||
|
{ register = "C2_IR3", role = "latest_color", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_IR1", required = 4, },
|
||||||
|
{ register = "C2_IR2", required = 4, },
|
||||||
|
{ register = "C2_IR3", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_nclip"] = {
|
||||||
|
aliases = { "gte_nclip" },
|
||||||
|
cycles = 8,
|
||||||
|
inputs = { "C2_SXY0", "C2_SXY1", "C2_SXY2" },
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_SZ3", role = "mac_result", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_SZ3", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_op"] = {
|
||||||
|
aliases = { "gte_cmdw_outer_product", "gte_cmdw_wedge" },
|
||||||
|
cycles = 6,
|
||||||
|
inputs = {},
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_IR1", role = "latest_color", },
|
||||||
|
{ register = "C2_IR2", role = "latest_color", },
|
||||||
|
{ register = "C2_IR3", role = "latest_color", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_IR1", required = 4, },
|
||||||
|
{ register = "C2_IR2", required = 4, },
|
||||||
|
{ register = "C2_IR3", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_rtps"] = {
|
||||||
|
aliases = { "gte_cmdw_rotate_translate_perspective_single", "gte_rtps" },
|
||||||
|
cycles = 15,
|
||||||
|
inputs = {
|
||||||
|
"C2_VXY0", "C2_VZ0",
|
||||||
|
"C2_VXY1", "C2_VZ1",
|
||||||
|
"C2_VXY2", "C2_VZ2",
|
||||||
|
"C2_RGB", "C2_OTZ",
|
||||||
|
"C2_IR0", "C2_IR1", "C2_IR2", "C2_IR3",
|
||||||
|
"C2_SZ0", "C2_SZ1", "C2_SZ2", "C2_SZ3",
|
||||||
|
"gte_cr_RT11", "gte_cr_RT12", "gte_cr_RT13",
|
||||||
|
"gte_cr_RT21", "gte_cr_RT22", "gte_cr_RT23",
|
||||||
|
"gte_cr_RT31", "gte_cr_RT32", "gte_cr_RT33",
|
||||||
|
"gte_cr_TRX", "gte_cr_TRY", "gte_cr_TRZ",
|
||||||
|
"gte_cr_OFX", "gte_cr_OFY",
|
||||||
|
"gte_cr_H",
|
||||||
|
"gte_cr_DQA", "gte_cr_DQB"
|
||||||
|
},
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_SXY2", role = "latest_screen_xy", },
|
||||||
|
{ register = "C2_SZ2", role = "latest_screen_z", },
|
||||||
|
{ register = "C2_OTZ", role = "otz", },
|
||||||
|
{ register = "C2_IR0", role = "latest_color", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_SXY2", required = 4, },
|
||||||
|
{ register = "C2_SZ2", required = 4, },
|
||||||
|
{ register = "C2_OTZ", required = 4, },
|
||||||
|
{ register = "C2_IR0", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_rtpt"] = {
|
||||||
|
aliases = { "gte_cmdw_rotate_translate_perspective_triple", "gte_rtpt" },
|
||||||
|
cycles = 23,
|
||||||
|
inputs = {
|
||||||
|
"C2_VXY0", "C2_VZ0",
|
||||||
|
"C2_VXY1", "C2_VZ1",
|
||||||
|
"C2_VXY2", "C2_VZ2",
|
||||||
|
"C2_RGB", "C2_OTZ",
|
||||||
|
"C2_IR0", "C2_IR1", "C2_IR2", "C2_IR3",
|
||||||
|
"C2_SZ0", "C2_SZ1", "C2_SZ2", "C2_SZ3",
|
||||||
|
"gte_cr_RT11", "gte_cr_RT12", "gte_cr_RT13",
|
||||||
|
"gte_cr_RT21", "gte_cr_RT22", "gte_cr_RT23",
|
||||||
|
"gte_cr_RT31", "gte_cr_RT32", "gte_cr_RT33",
|
||||||
|
"gte_cr_TRX", "gte_cr_TRY", "gte_cr_TRZ",
|
||||||
|
"gte_cr_OFX", "gte_cr_OFY",
|
||||||
|
"gte_cr_H",
|
||||||
|
"gte_cr_DQA", "gte_cr_DQB"
|
||||||
|
},
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_SXY0", role = "screen_xy[0]", },
|
||||||
|
{ register = "C2_SXY1", role = "screen_xy[1]", },
|
||||||
|
{ register = "C2_SXY2", role = "latest_screen_xy", },
|
||||||
|
{ register = "C2_SZ3", role = "latest_screen_z", },
|
||||||
|
{ register = "C2_OTZ", role = "otz", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_SXY0", required = 4, },
|
||||||
|
{ register = "C2_SXY1", required = 4, },
|
||||||
|
{ register = "C2_SXY2", required = 4, },
|
||||||
|
{ register = "C2_SZ3", required = 4, },
|
||||||
|
{ register = "C2_OTZ", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
["gte_cmdw_sqr"] = {
|
||||||
|
aliases = {},
|
||||||
|
cycles = 5,
|
||||||
|
inputs = { "C2_IR1", "C2_IR2", "C2_IR3" },
|
||||||
|
outputs = {
|
||||||
|
{ register = "C2_MAC1", role = "mac_result", },
|
||||||
|
{ register = "C2_MAC2", role = "mac_result", },
|
||||||
|
{ register = "C2_MAC3", role = "mac_result", },
|
||||||
|
{ register = "C2_IR1", role = "latest_color", },
|
||||||
|
{ register = "C2_IR2", role = "latest_color", },
|
||||||
|
{ register = "C2_IR3", role = "latest_color", },
|
||||||
|
},
|
||||||
|
latch = {
|
||||||
|
{ register = "C2_MAC1", required = 4, },
|
||||||
|
{ register = "C2_MAC2", required = 4, },
|
||||||
|
{ register = "C2_MAC3", required = 4, },
|
||||||
|
{ register = "C2_IR1", required = 4, },
|
||||||
|
{ register = "C2_IR2", required = 4, },
|
||||||
|
{ register = "C2_IR3", required = 4, },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
--- @param ident string
|
||||||
|
--- @return InstructionRow|nil
|
||||||
|
function M.instr (ident) return M.INSTRUCTION [ident] end
|
||||||
|
--- @param ident string
|
||||||
|
--- @return string
|
||||||
|
function M.gte_canon(ident) return M.ALIAS_TO_CANONICAL [ident] or ident end
|
||||||
|
--- @param ident string
|
||||||
|
--- @return GteCommandRow|nil
|
||||||
|
function M.gte (ident) return M.GTE_COMMAND[M.gte_canon(ident)] end
|
||||||
|
|
||||||
|
--- @return nil
|
||||||
|
local function build_alias_map()
|
||||||
|
--- @type table<string, string> -- bag: alias or canon -> canon
|
||||||
|
M.ALIAS_TO_CANONICAL = {}
|
||||||
|
for canon, row in pairs(M.GTE_COMMAND) do ---@type string, GteCommandRow
|
||||||
|
M.ALIAS_TO_CANONICAL[canon] = canon
|
||||||
|
for _, alias in ipairs(row.aliases or {}) do ---@type integer, string
|
||||||
|
M.ALIAS_TO_CANONICAL[alias] = canon
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
build_alias_map()
|
||||||
|
|
||||||
|
|
||||||
|
--- GTE control-register alias groups.
|
||||||
|
--- Aliases within a group write to the same C2 control-register slot (the HW double-maps some C2 slots across multiple PSX SDK / libgte conventions).
|
||||||
|
--- Aliases across groups write to distinct C2 slots.
|
||||||
|
---
|
||||||
|
--- Cross-alias writes inside one atom body, or across the wave-context boundary, silently clobber each other.
|
||||||
|
--- The `check_gte_cr_alias_writes` check warns about each pair per source. See `docs/gte_reference.md` §"Control-register alias table"
|
||||||
|
--- for the HW rationale and the libgte outer-product convention.
|
||||||
|
--- @type GteCrAliasGroup[]
|
||||||
|
M.GTE_CR_ALIAS_GROUPS = {
|
||||||
|
{ 24, { "gte_cr_RBK", "gte_cr_OFX" } }, -- background R vs screen offset X
|
||||||
|
{ 25, { "gte_cr_GBK", "gte_cr_OFY" } }, -- background G vs screen offset Y
|
||||||
|
{ 26, { "gte_cr_BBK", "gte_cr_H" } }, -- background B vs projection plane distance H
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Packed RT slots named by the gte.h packed-slot comment. First must be written before second.
|
||||||
|
--- @type GtePackedSlotRelation[]
|
||||||
|
M.GTE_PACKED_SLOT_RELATIONS = {
|
||||||
|
{ slot = 2, first = "gte_cr_RT13", second = "gte_cr_RT22" },
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Operand-class table for the COP2->GPR load-delay check.
|
||||||
|
-- Maps each emitting-token ident to the set of GPR operand positions it reads.
|
||||||
|
-- Covers the current encoder vocabulary (`code/duffle/mips.h` + `code/duffle/gte.h`); add rows here as new encoders land.
|
||||||
|
--
|
||||||
|
-- Semantics:
|
||||||
|
-- * A "GPR operand position" is the textual slot in the macro's argument list, 1-based; e.g. `load_word(rt, base, off)` has positional operands 1 (rt), 2 (base), 3 (off).
|
||||||
|
-- The table reads operands 1 + 2 + 3 to find what GPRs the macro touches.
|
||||||
|
-- * The check tracks one entry per destination GPR per MFC2 / CFC2 event.
|
||||||
|
-- A subsequent event counts as a "use" iff any of its read operand positions reference that destination GPR's ident (e.g. `R_T0`).
|
||||||
|
-- * Branch delay slots are out of scope (MIPS control-flow; tracked separately).
|
||||||
|
--- @type table<string, integer[]> -- bag: encoder ident -> GPR operand positions
|
||||||
|
M.OPERAND_READ_POSITIONS = {
|
||||||
|
-- CPU ALU with one or two GPR operands. Reads every GPR operand.
|
||||||
|
["add_ui"] = {1, 2},
|
||||||
|
["li_s"] = {1, 2}, -- rt (write), imm16 (immediate)
|
||||||
|
["add_ui_self"] = {1},
|
||||||
|
["add_si"] = {1, 2},
|
||||||
|
["add_u"] = {1, 2, 3},
|
||||||
|
["add_u_self"] = {1, 2},
|
||||||
|
["sub_s"] = {1, 2, 3},
|
||||||
|
["sub_u"] = {1, 2, 3},
|
||||||
|
["and_i"] = {1, 2},
|
||||||
|
["and"] = {1, 2, 3},
|
||||||
|
["or_i"] = {1, 2},
|
||||||
|
["or_i_self"] = {1},
|
||||||
|
["or"] = {1, 2, 3},
|
||||||
|
["or_self"] = {1, 2},
|
||||||
|
["xor_i"] = {1, 2},
|
||||||
|
["xor"] = {1, 2, 3},
|
||||||
|
["slt_s"] = {1, 2, 3},
|
||||||
|
["slt_u"] = {1, 2, 3},
|
||||||
|
["slt_si"] = {1, 2},
|
||||||
|
["slt_ui"] = {1, 2},
|
||||||
|
["mult_s"] = {1, 2},
|
||||||
|
["mult_u"] = {1, 2},
|
||||||
|
["div_s"] = {1, 2},
|
||||||
|
["div_u"] = {1, 2},
|
||||||
|
-- Shifts: shift_lleft(rd, rt, shamt); the rt operand is the value, rd is dest.
|
||||||
|
["shift_lleft"] = {1, 2},
|
||||||
|
["shift_lright"] = {1, 2},
|
||||||
|
["shift_aright"] = {1, 2},
|
||||||
|
["shift_lleft_self"] = {1},
|
||||||
|
-- Loads: load_word(rt, base, off); the rt operand is the destination (it's written, not read) and base + off are non-GPR operands.
|
||||||
|
-- The check treats the rt operand as a write, so the read-positions table for `load_*` is empty.
|
||||||
|
["load_word"] = {},
|
||||||
|
["load_half_u"] = {},
|
||||||
|
["load_byte_u"] = {},
|
||||||
|
["load_half"] = {},
|
||||||
|
["load_byte"] = {},
|
||||||
|
["load_upper_i"] = {},
|
||||||
|
["load_ui"] = {},
|
||||||
|
-- Stores write to memory; base + rt operands are non-read for load-delay purposes.
|
||||||
|
["store_word"] = {},
|
||||||
|
["store_half"] = {},
|
||||||
|
["store_byte"] = {},
|
||||||
|
-- Branches read rs (+ rt for beq/bne). The branch delay slot is out of scope.
|
||||||
|
["branch_equal"] = {1, 2},
|
||||||
|
["branch_ne"] = {1, 2},
|
||||||
|
["branch_le_zero"] = {1},
|
||||||
|
["branch_lt_zero"] = {1},
|
||||||
|
["branch_ge_zero"] = {1},
|
||||||
|
["branch_gt_zero"] = {1},
|
||||||
|
-- Jumps / link: jr / jalr read rs only (the target). RD is the destination link.
|
||||||
|
["jump_reg"] = {1},
|
||||||
|
["jump_link"] = {1},
|
||||||
|
["call_reg"] = {1},
|
||||||
|
["call_addr"] = {},
|
||||||
|
["jump"] = {},
|
||||||
|
-- mask_upper is a 2-word macro: shift_lleft then shift_lright. The first reads rt.
|
||||||
|
["mask_upper"] = {1, 2},
|
||||||
|
-- move from/to HI/LO.
|
||||||
|
["mov_from_high"] = {},
|
||||||
|
["mov_from_low"] = {},
|
||||||
|
["mov_to_high"] = {1},
|
||||||
|
["mov_to_low"] = {1},
|
||||||
|
-- GTE transfers / loads / stores / commands: the relevant table values live in the check itself.
|
||||||
|
-- `gte_mv_to_*` writes its rt operand; `gte_mv_from_*` writes its rt operand; `gte_*` commands are atomic-from-the-CPU-POV
|
||||||
|
-- once they issue (the CPU holds until the command completes, so load-delay violations don't surface here).
|
||||||
|
["gte_mv_from_data_r"] = {},
|
||||||
|
["gte_mv_from_ctrl_r"] = {},
|
||||||
|
["gte_mv_to_data_r"] = {},
|
||||||
|
["gte_mv_to_ctrl_r"] = {},
|
||||||
|
["gte_lw"] = {},
|
||||||
|
["gte_sw"] = {},
|
||||||
|
["shift_lleft_var"] = {1, 2, 3}, -- rd, rt, rs (variable shift amount)
|
||||||
|
["shift_aright_var"] = {1, 2, 3},
|
||||||
|
}
|
||||||
|
|
||||||
|
-- GP0 packet sizes (total words including the 1-word tag) per GP0 cmd byte.
|
||||||
|
-- Per PSX-SPX `docs/psx-spx/docs/graphicsprocessingunitgpu.md` §"GPU Render Polygon Commands":
|
||||||
|
-- Each polygon command's word count = 1 (tag/cmd) + per-vertex (vertex + optional color + optional UV).
|
||||||
|
-- F3: cmd + 3 vertices = 4 words; +1 tag = 5
|
||||||
|
-- F4: cmd + 4 vertices = 5 words; +1 tag = 6
|
||||||
|
-- G3: cmd + 3×(color + vertex) = 6 words; +1 tag = 7
|
||||||
|
-- G4: cmd + 4×(color + vertex) = 8 words; +1 tag = 9
|
||||||
|
-- FT3: cmd + tpage + clut + 3×(vertex + UV) = 7 words; +1 tag = 8
|
||||||
|
-- FT4: cmd + tpage + clut + 4×(vertex + UV) = 9 words; +1 tag = 10
|
||||||
|
-- GT3: cmd + tpage + clut + 3×(color + vertex + UV) = 9 words; +1 tag = 10
|
||||||
|
-- GT4: cmd + tpage + clut + 4×(color + vertex + UV) = 12 words; +1 tag = 13
|
||||||
|
--
|
||||||
|
-- Cross-checked against code/duffle/gp.h struct sizes + the set_poly_* macros
|
||||||
|
-- (which encode "len" = "words after tag"):
|
||||||
|
-- set_poly_f3(p) -> set_len(p, 4) -> 5 total GP0 0x20
|
||||||
|
-- set_poly_ft3(p) -> set_len(p, 7) -> 8 total GP0 0x24
|
||||||
|
-- set_poly_f4(p) -> set_len(p, 5) -> 6 total GP0 0x28
|
||||||
|
-- set_poly_ft4(p) -> set_len(p, 9) -> 10 total GP0 0x2C
|
||||||
|
-- set_poly_g3(p) -> set_len(p, 6) -> 7 total GP0 0x30
|
||||||
|
-- set_poly_gt3(p) -> set_len(p, 9) -> 10 total GP0 0x34
|
||||||
|
-- set_poly_g4(p) -> set_len(p, 8) -> 9 total GP0 0x38
|
||||||
|
-- set_poly_gt4(p) -> set_len(p, 12) -> 13 total GP0 0x3C
|
||||||
|
--- @type table<integer, integer> -- bag: GP0 cmd byte -> word count
|
||||||
|
M.GP0_CMD_SIZE = {
|
||||||
|
[0x20] = 5, -- Poly_F3
|
||||||
|
[0x24] = 8, -- Poly_FT3
|
||||||
|
[0x28] = 6, -- Poly_F4
|
||||||
|
[0x2C] = 10, -- Poly_FT4
|
||||||
|
[0x30] = 7, -- Poly_G3
|
||||||
|
[0x34] = 10, -- Poly_GT3
|
||||||
|
[0x38] = 9, -- Poly_G4
|
||||||
|
[0x3C] = 13, -- Poly_GT4
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Shape suffix (after `ac_format_` / `mac_format_` prefix) -> GP0 cmd byte.
|
||||||
|
-- Lets the static-analysis check derive the cmd byte from a macro name like `mac_format_g4_color` -> `g4` -> 0x38 -> 9 expected words.
|
||||||
|
--- @type table<string, integer> -- bag: shape suffix -> GP0 cmd byte
|
||||||
|
M.GP0_CMD_BY_SHAPE = {
|
||||||
|
["f3"] = 0x20, ["ft3"] = 0x24,
|
||||||
|
["f4"] = 0x28, ["ft4"] = 0x2C,
|
||||||
|
["g3"] = 0x30, ["gt3"] = 0x34,
|
||||||
|
["g4"] = 0x38, ["gt4"] = 0x3C,
|
||||||
|
}
|
||||||
|
|
||||||
|
--- @type integer
|
||||||
|
M.UNKNOWN_INSTRUCTION_CYCLES = 1
|
||||||
|
|
||||||
|
-- Hardware-relation policy table.
|
||||||
|
--
|
||||||
|
-- The forward walker in `passes/static_analysis.lua::analyze_hardware_relations` reads every emitted word_event, matches its `encoder` against `row.token`, and:
|
||||||
|
-- * stages the event as a producer in `atom.paths.forward_state`; or
|
||||||
|
-- * matches it as a consumer against pending producers and records a hazard on `atom.paths.hazards` when the gap is below `visibility.required`.
|
||||||
|
--
|
||||||
|
-- Each row is the contract for one CPU-to-coprocessor transfer semantic (the coprocessor-to-CPU path mirrors the same shape).
|
||||||
|
-- The `reads` / `writes` sub-tables carry the argument positions the analyzer inspects:
|
||||||
|
-- * `writes.arg` is the destination operand (the producer's effect); the analyzer stages this register as a pending producer.
|
||||||
|
-- * `reads` (when present) lists the operand positions the same token reads back from hardware; for MTC2 / CTC2 the producer reads the GPR source it is loading from.
|
||||||
|
-- The `fanout_to` field (MTC2-IRGB row only) tells the consumer-match logic which downstream COP2 registers are transitively updated by the write.
|
||||||
|
--
|
||||||
|
-- Visibility semantics:
|
||||||
|
-- * `kind = "post_producer_words"` means the consumer observes the producer's effect after `required` independent emitted words that are
|
||||||
|
-- strictly between the producer and the consumer. The producer's own emitted slot is implicit (it counts as the slot of issue, not toward `required`)
|
||||||
|
-- per the PSX-SPX rule: "Store delays are counted in numbers of clock cycles (not in numbers of opcodes).
|
||||||
|
-- For 3 cycle delay, one must usually insert 3 cached opcodes (or one uncached opcode)."
|
||||||
|
-- * `required` is the minimum count of intervening emitted words between producer and consumer.
|
||||||
|
-- `required = 0` permits the consumer on the very next slot; `required < 0` would place the consumer on the same slot as the producer
|
||||||
|
-- and is reserved for future "self-retires" relations.
|
||||||
|
--
|
||||||
|
-- Evidence:
|
||||||
|
-- * `evidence.confidence` is one of `"exact"`, `"conservative"`, `"unknown"`. The severity comes from `violation_kind`;
|
||||||
|
-- A hardware measurement that the vendor caveats may still classify as `"conservative"` even when the underlying timing is numerically known.
|
||||||
|
-- * `evidence.source` is the upstream reference (file + line range) the row is sourced from. New rows must carry this citation.
|
||||||
|
--
|
||||||
|
-- Consumers:
|
||||||
|
-- * passes/static_analysis.lua::analyze_hardware_relations (forward walker).
|
||||||
|
-- * passes/static_analysis.lua::transfer_hazards CHECK_RULES reader (renders hazards onto `findings`).
|
||||||
|
-- This table is consumed by the hardware-relation analyzer and hazard renderer.
|
||||||
|
--- @type HardwareRelationRow[]
|
||||||
|
M.HARDWARE_RELATIONS = {
|
||||||
|
-- CPU → COP2 data register (MTC2). The ordinary default is 2 cached words between producer and consumer (cpuspecifications.md:407-419).
|
||||||
|
{
|
||||||
|
id = "mtc2_gpr_visibility",
|
||||||
|
semantic = "MTC2",
|
||||||
|
consumer = "cop2_input",
|
||||||
|
token = "gte_mv_to_data_r",
|
||||||
|
direction = "gpr_to_cop2_data",
|
||||||
|
reads = { domain = "gpr", arg = 1 },
|
||||||
|
writes = { domain = "cop2.data", arg = 2 },
|
||||||
|
visibility = { kind = "post_producer_words", required = 2 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "exact",
|
||||||
|
source = "cpuspecifications.md:407-419",
|
||||||
|
},
|
||||||
|
violation_kind = "error",
|
||||||
|
},
|
||||||
|
-- CPU → COP2 data register when the destination is C2_IRGB (data 28).
|
||||||
|
-- C2_IRGB drives the IR1/IR2/IR3 color-conversion fan-out, which extends the propagation delay to 3 cached words.
|
||||||
|
-- `destination_match = "C2_IRGB"` is the row's filter; the analyzer consults this when the producer's destination operand equals "C2_IRGB".
|
||||||
|
-- C2_ORGB (data 29) is read-only and is never classified as a writable fan-out destination.
|
||||||
|
{
|
||||||
|
id = "mtc2_irgb_visibility",
|
||||||
|
semantic = "MTC2",
|
||||||
|
consumer = "cop2_input",
|
||||||
|
token = "gte_mv_to_data_r",
|
||||||
|
direction = "gpr_to_cop2_data",
|
||||||
|
reads = { domain = "gpr", arg = 1 },
|
||||||
|
writes = { domain = "cop2.data", arg = 2 },
|
||||||
|
destination_match = "C2_IRGB",
|
||||||
|
fanout_to = { "C2_IR1", "C2_IR2", "C2_IR3" },
|
||||||
|
visibility = { kind = "post_producer_words", required = 3 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "exact",
|
||||||
|
source = "cpuspecifications.md:407-419",
|
||||||
|
},
|
||||||
|
violation_kind = "error",
|
||||||
|
},
|
||||||
|
-- CPU → COP2 control register (CTC2). Ordinary minimum 2;
|
||||||
|
-- no IRGB-style fan-out exists for control registers (per spec §3.6: only C2_IRGB has the 3-cycle fan-out on the data side).
|
||||||
|
{
|
||||||
|
id = "ctc2_gpr_visibility",
|
||||||
|
semantic = "CTC2",
|
||||||
|
consumer = "cop2_input",
|
||||||
|
token = "gte_mv_to_ctrl_r",
|
||||||
|
direction = "gpr_to_cop2_control",
|
||||||
|
reads = { domain = "gpr", arg = 1 },
|
||||||
|
writes = { domain = "cop2.ctrl", arg = 2 },
|
||||||
|
visibility = { kind = "post_producer_words", required = 2 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "exact",
|
||||||
|
source = "cpuspecifications.md:407-419",
|
||||||
|
},
|
||||||
|
violation_kind = "error",
|
||||||
|
},
|
||||||
|
-- COP2 data → GPR (MFC2). One cached slot between the transfer and the first GPR consumer;
|
||||||
|
-- the GPR is not updated until the instruction AFTER the MFC2 completes (geometrytransformationenginegte.md:29-32).
|
||||||
|
{
|
||||||
|
id = "mfc2_gpr_visibility",
|
||||||
|
semantic = "MFC2",
|
||||||
|
consumer = "gpr_read",
|
||||||
|
token = "gte_mv_from_data_r",
|
||||||
|
direction = "cop2_data_to_gpr",
|
||||||
|
reads = { domain = "cop2.data", arg = 2 },
|
||||||
|
writes = { domain = "gpr", arg = 1 },
|
||||||
|
visibility = { kind = "post_producer_words", required = 1 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "exact",
|
||||||
|
source = "geometrytransformationenginegte.md:29-32",
|
||||||
|
},
|
||||||
|
violation_kind = "error",
|
||||||
|
},
|
||||||
|
-- COP2 control → GPR (CFC2). Same delay as MFC2 (cpuspecifications.md treats the two load-from-COP2 paths symmetrically).
|
||||||
|
{
|
||||||
|
id = "cfc2_gpr_visibility",
|
||||||
|
semantic = "CFC2",
|
||||||
|
consumer = "gpr_read",
|
||||||
|
token = "gte_mv_from_ctrl_r",
|
||||||
|
direction = "cop2_control_to_gpr",
|
||||||
|
reads = { domain = "cop2.ctrl", arg = 2 },
|
||||||
|
writes = { domain = "gpr", arg = 1 },
|
||||||
|
visibility = { kind = "post_producer_words", required = 1 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "exact",
|
||||||
|
source = "cpuspecifications.md:382-419",
|
||||||
|
},
|
||||||
|
violation_kind = "error",
|
||||||
|
},
|
||||||
|
-- COP0 control → GPR (MFC0).
|
||||||
|
-- One cached slot; the analyzer treats `sys_mov_from_cop0(rt, 12)` (the SR/CU2 transfer) as the same shape as the COP2 load-delay path.
|
||||||
|
-- The semantic-level SR/CU2 transition models the load delay;
|
||||||
|
-- SR.CU2 bounded-value propagation is modeled separately).
|
||||||
|
{
|
||||||
|
id = "mfc0_gpr_visibility",
|
||||||
|
semantic = "MFC0",
|
||||||
|
consumer = "gpr_read",
|
||||||
|
token = "sys_mov_from_cop0",
|
||||||
|
direction = "cop0_control_to_gpr",
|
||||||
|
reads = { domain = "cop0.ctrl", arg = 2 },
|
||||||
|
writes = { domain = "gpr", arg = 1 },
|
||||||
|
visibility = { kind = "post_producer_words", required = 1 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "exact",
|
||||||
|
source = "cpuspecifications.md:171-178",
|
||||||
|
},
|
||||||
|
violation_kind = "error",
|
||||||
|
},
|
||||||
|
-- Memory -> COP2 data register (LWC2).
|
||||||
|
-- The memory-side timing is not measured by the vendored GTE latch experiment, so this relation has no numeric retirement threshold.
|
||||||
|
-- The LWC2 destination has TWO retirement regimes (per PSX-SPX):
|
||||||
|
-- * GTE-command consumer (`gte_cmdw_*`): the GTE pipeline LATCHES the LWC2 result, so a `gte_cmdw_*`
|
||||||
|
-- in the very next slot uses the latched value. Gap = 0 is allowed. (Per `docs/psx-spx/docs/gtepipelinetimings.md:271-274`.)
|
||||||
|
-- * Any other consumer: standard MIPS load delay applies. Gap = 1 required. (Per `docs/psx-spx/docs/cpuspecifications.md:407-419`.)
|
||||||
|
-- Two separate relations so the walker can dispatch by consumer type and emit different severities
|
||||||
|
-- (the GTE-command path is `info` because the latch is intentional; the non-GTE-consumer path is `error` because the missing nop is a real bug).
|
||||||
|
{
|
||||||
|
id = "lwc2_to_gte_command",
|
||||||
|
semantic = "LWC2_to_GTE",
|
||||||
|
consumer = "cop2_input",
|
||||||
|
token = "gte_lw",
|
||||||
|
direction = "memory_to_cop2_data",
|
||||||
|
reads = { domain = "memory", arg = 2 },
|
||||||
|
writes = { domain = "cop2.data", arg = 1 },
|
||||||
|
required = 0, -- GTE-command consumer: gap = 0 OK (latched).
|
||||||
|
evidence = {
|
||||||
|
confidence = "measured",
|
||||||
|
source = "gtepipelinetimings.md:271-274",
|
||||||
|
},
|
||||||
|
violation_kind = "info",
|
||||||
|
clear_on_consumer = true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id = "lwc2_to_other_consumer",
|
||||||
|
semantic = "LWC2_to_other",
|
||||||
|
consumer = "cop2_input",
|
||||||
|
token = "gte_lw",
|
||||||
|
direction = "memory_to_cop2_data",
|
||||||
|
reads = { domain = "memory", arg = 2 },
|
||||||
|
writes = { domain = "cop2.data", arg = 1 },
|
||||||
|
required = 1, -- Non-GTE-consumer: standard MIPS load delay.
|
||||||
|
evidence = {
|
||||||
|
confidence = "inferred",
|
||||||
|
source = "cpuspecifications.md:407-419",
|
||||||
|
},
|
||||||
|
violation_kind = "error",
|
||||||
|
clear_on_consumer = true,
|
||||||
|
},
|
||||||
|
-- COP2 data register -> memory (SWC2). A read of C2 state, not a CPU-to-COP2 write.
|
||||||
|
-- The policy row stays in for direction/provenance; staging it as a later command-input producer is suppressed.
|
||||||
|
{
|
||||||
|
id = "swc2_memory_write",
|
||||||
|
semantic = "SWC2",
|
||||||
|
consumer = "gpr_read",
|
||||||
|
token = "gte_sw",
|
||||||
|
direction = "cop2_data_to_memory",
|
||||||
|
reads = { domain = "cop2.data", arg = 1 },
|
||||||
|
writes = { domain = "memory", arg = 2 },
|
||||||
|
visibility = { kind = "none", required = 0 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "exact",
|
||||||
|
source = "cpuspecifications.md:79",
|
||||||
|
},
|
||||||
|
violation_kind = "info",
|
||||||
|
stage = false,
|
||||||
|
},
|
||||||
|
-- MTC0 Status/SR.CU2. The ordinary COP0 store has no general store-delay relation;
|
||||||
|
-- this row feeds the dedicated CU2 transition logic in the same forward walk and is therefore not staged in `pending`.
|
||||||
|
{
|
||||||
|
id = "mtc0_cu2_visibility",
|
||||||
|
semantic = "MTC0",
|
||||||
|
consumer = "gpr_read",
|
||||||
|
token = "sys_mov_to_cop0",
|
||||||
|
direction = "gpr_to_cop0_status",
|
||||||
|
reads = { domain = "gpr", arg = 1 },
|
||||||
|
writes = { domain = "cop0.status", arg = 2 },
|
||||||
|
status_register = 12,
|
||||||
|
visibility = { kind = "post_producer_words", required = 2 },
|
||||||
|
evidence = {
|
||||||
|
confidence = "conservative",
|
||||||
|
source = "cpuspecifications.md:543,625-628",
|
||||||
|
},
|
||||||
|
violation_kind = "warning",
|
||||||
|
stage = false,
|
||||||
|
cu2_transition = true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Bounded Status/SR.CU2 transition policy.
|
||||||
|
-- The value lattice and the transition consumer both read this immutable row; no second value pass is permitted.
|
||||||
|
-- The source says the enable/disable transition takes "2 clock cycles or so", so the boundary is conservative rather than exact.
|
||||||
|
--- @type Cu2TransitionPolicy
|
||||||
|
M.CU2_TRANSITION_POLICY = {
|
||||||
|
status_register = 12,
|
||||||
|
enable_bit = 0x40000000,
|
||||||
|
required = 2,
|
||||||
|
visibility_kind = "post_producer_words",
|
||||||
|
evidence = {
|
||||||
|
confidence = "conservative",
|
||||||
|
source = "cpuspecifications.md:543,625-628",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return M
|
||||||
+23
-25
@@ -16,30 +16,31 @@
|
|||||||
--- Net effect: the caller gets the duffle module in one statement; no separate `dofile(...)` + `require("duffle")` dance.
|
--- Net effect: the caller gets the duffle module in one statement; no separate `dofile(...)` + `require("duffle")` dance.
|
||||||
---
|
---
|
||||||
|
|
||||||
local M = {}
|
--- @class DufflePaths
|
||||||
|
--- @field setup fun(): nil
|
||||||
|
|
||||||
|
local M = {} ---@type DufflePaths
|
||||||
|
|
||||||
-- Cache key for the repo root. Stored in `package.loaded` (process-global) so all 8 entry scripts + passes scripts share one resolution.
|
-- Cache key for the repo root. Stored in `package.loaded` (process-global) so all 8 entry scripts + passes scripts share one resolution.
|
||||||
local CACHE_KEY = "__duffle_repo_root__"
|
local CACHE_KEY = "__duffle_repo_root__" ---@type string
|
||||||
|
|
||||||
--- Resolve the repo root from this script's own path. Zero shell spawn.
|
--- Resolve the repo root from this script's own path. Zero shell spawn.
|
||||||
--- `duffle_paths.lua` always lives at `<repo>/scripts/duffle_paths.lua`, so the repo root is the
|
--- `duffle_paths.lua` always lives at `<repo>/scripts/duffle_paths.lua`, so the repo root is the parent of the directory containing this script.
|
||||||
--- parent of the directory containing this script. We derive it directly from `debug.getinfo(1, "S").source`
|
--- We derive it directly from `debug.getinfo(1, "S").source` (returns `@<path>` for the currently-running chunk).
|
||||||
--- (returns `@<path>` for the currently-running chunk).
|
|
||||||
---
|
---
|
||||||
--- If `debug.getinfo` can't parse this script's path (shouldn't happen — dofile always populates source),
|
--- If `debug.getinfo` can't parse this script's path (shouldn't happen — dofile always populates source), return nil and let `M.setup()` fail loud.
|
||||||
--- return nil and let `M.setup()` fail loud.
|
|
||||||
--- @return string|nil
|
--- @return string|nil
|
||||||
local function find_repo_root()
|
local function find_repo_root()
|
||||||
if package.loaded[CACHE_KEY] then return package.loaded[CACHE_KEY] end
|
if package.loaded[CACHE_KEY] then return package.loaded[CACHE_KEY] end
|
||||||
|
|
||||||
local source = debug.getinfo(1, "S").source
|
local source = debug.getinfo(1, "S").source ---@type string
|
||||||
-- Strip the leading `@` (Lua's dofile marker) and the trailing `/duffle_paths.lua` filename.
|
-- Strip the leading `@` (Lua's dofile marker) and the trailing `/duffle_paths.lua` filename.
|
||||||
-- What remains is the directory containing this script, i.e. `<repo>/scripts/`.
|
-- What remains is the directory containing this script, i.e. `<repo>/scripts/`.
|
||||||
local scripts_dir = source and source:match("^@?(.*)[/\\]duffle_paths%.lua$")
|
local scripts_dir = source and source:match("^@?(.*)[/\\]duffle_paths%.lua$") ---@type string|nil
|
||||||
if not scripts_dir then return nil end
|
if not scripts_dir then return nil end
|
||||||
|
|
||||||
-- The repo root is the parent of `scripts/`. Strip the trailing `scripts/` (with or without trailing slash).
|
-- The repo root is the parent of `scripts/`. Strip the trailing `scripts/` (with or without trailing slash).
|
||||||
local root = scripts_dir:gsub("scripts[\\/]?$", "")
|
local root = scripts_dir:gsub("scripts[\\/]?$", "") ---@type string
|
||||||
root = root:gsub("\\", "/")
|
root = root:gsub("\\", "/")
|
||||||
if root == "" then root = "./" end
|
if root == "" then root = "./" end
|
||||||
if not root:match("/$") then root = root .. "/" end
|
if not root:match("/$") then root = root .. "/" end
|
||||||
@@ -51,22 +52,19 @@ end
|
|||||||
---
|
---
|
||||||
--- This script does NOT touch the OS environment: no `os.setenv`, no `os.putenv`, no `$PATH` mods.
|
--- This script does NOT touch the OS environment: no `os.setenv`, no `os.putenv`, no `$PATH` mods.
|
||||||
--- It just sets `package.path` and `package.cpath` (the standard Lua way to register module search dirs).
|
--- It just sets `package.path` and `package.cpath` (the standard Lua way to register module search dirs).
|
||||||
--- lpeg is built by `update_deps.ps1` to `toolchain/lpeg/`,
|
--- lpeg is built by `update_deps.ps1` to `toolchain/lpeg/`, which we wire into `package.cpath` here (so `require("lpeg")` from `duffle.lua` resolves without any global state).
|
||||||
--- which we wire into `package.cpath` here (so `require("lpeg")` from `duffle.lua` resolves without any global state).
|
--- @return nil
|
||||||
function M.setup()
|
function M.setup()
|
||||||
local repo_root = find_repo_root()
|
local repo_root = find_repo_root() ---@type string|nil
|
||||||
if not repo_root then
|
if not repo_root then
|
||||||
-- Unreachable in practice: find_repo_root() derives the repo root from this script's
|
-- Unreachable in practice: find_repo_root() derives the repo root from this script's own source path via debug.getinfo(1, "S").source (no subprocess, no git CLI, <1ms).
|
||||||
-- own source path via debug.getinfo(1, "S").source (no subprocess, no git CLI, <1ms).
|
-- A nil return means the source path did not match the expected <repo>/scripts/duffle_paths.lua layout — a packaging bug, not a "missing git repo" condition.
|
||||||
-- A nil return means the source path did not match the expected
|
-- os.exit(2) is retained so a real failure surfaces loud rather than silently producing an unconfigured module table.
|
||||||
-- <repo>/scripts/duffle_paths.lua layout — a packaging bug, not a "missing git repo"
|
|
||||||
-- condition. os.exit(2) is retained so a real failure surfaces loud rather than
|
|
||||||
-- silently producing an unconfigured module table.
|
|
||||||
os.exit(2)
|
os.exit(2)
|
||||||
end
|
end
|
||||||
|
|
||||||
local scripts_dir = repo_root .. "scripts/"
|
local scripts_dir = repo_root .. "scripts/" ---@type string
|
||||||
local passes_dir = repo_root .. "scripts/passes/"
|
local passes_dir = repo_root .. "scripts/passes/" ---@type string
|
||||||
package.path = scripts_dir .. "?.lua;"
|
package.path = scripts_dir .. "?.lua;"
|
||||||
.. scripts_dir .. "?/init.lua;"
|
.. scripts_dir .. "?/init.lua;"
|
||||||
.. passes_dir .. "?.lua;"
|
.. passes_dir .. "?.lua;"
|
||||||
@@ -76,8 +74,8 @@ function M.setup()
|
|||||||
-- lpeg: built by `update_deps.ps1` to `toolchain/lpeg/lpeg.dll`.
|
-- lpeg: built by `update_deps.ps1` to `toolchain/lpeg/lpeg.dll`.
|
||||||
-- lfs: compiled from pcsx-redux's vendored luafilesystem source to `toolchain/lfs/lfs.dll`.
|
-- lfs: compiled from pcsx-redux's vendored luafilesystem source to `toolchain/lfs/lfs.dll`.
|
||||||
-- Wire both directories into cpath so `require("lpeg")` and `require("lfs")` resolve.
|
-- Wire both directories into cpath so `require("lpeg")` and `require("lfs")` resolve.
|
||||||
local lpeg_dir = repo_root .. "toolchain/lpeg/"
|
local lpeg_dir = repo_root .. "toolchain/lpeg/" ---@type string
|
||||||
local lfs_dir = repo_root .. "toolchain/lfs/"
|
local lfs_dir = repo_root .. "toolchain/lfs/" ---@type string
|
||||||
package.cpath = lpeg_dir .. "?.dll;"
|
package.cpath = lpeg_dir .. "?.dll;"
|
||||||
.. lfs_dir .. "?.dll;"
|
.. lfs_dir .. "?.dll;"
|
||||||
.. package.cpath
|
.. package.cpath
|
||||||
@@ -86,6 +84,6 @@ end
|
|||||||
-- Run the setup as a side effect.
|
-- Run the setup as a side effect.
|
||||||
M.setup()
|
M.setup()
|
||||||
|
|
||||||
-- Now that package.path includes scripts/, `require("duffle")` resolves. Return the duffle module
|
-- Now that package.path includes scripts/, `require("duffle")` resolves.
|
||||||
-- so callers can do `local duffle = dofile(...duffle_paths.lua)` in one line.
|
-- Return the duffle module so callers can do `local duffle = dofile(...duffle_paths.lua)` in one line.
|
||||||
return require("duffle")
|
return require("duffle")
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+159
-66
@@ -22,7 +22,94 @@
|
|||||||
-- spec: System V ABI gABI v1.2 §"ELF Header" (Table 1) + §"Section Header Table"
|
-- spec: System V ABI gABI v1.2 §"ELF Header" (Table 1) + §"Section Header Table"
|
||||||
-- spec: System V ABI gABI v1.2 §"Symbol Table" (Elf32_Sym layout)
|
-- spec: System V ABI gABI v1.2 §"Symbol Table" (Elf32_Sym layout)
|
||||||
|
|
||||||
local M = {}
|
--- @class Elf32Adapter
|
||||||
|
--- @field read_u8_at fun(off: integer): integer|nil
|
||||||
|
--- @field read_u16_at fun(off: integer): integer|nil
|
||||||
|
--- @field read_u32_at fun(off: integer): integer|nil
|
||||||
|
--- @field read_size fun(): integer
|
||||||
|
|
||||||
|
--- @class Elf32Header
|
||||||
|
--- @field e_entry integer
|
||||||
|
--- @field e_shoff integer
|
||||||
|
--- @field e_shentsize integer
|
||||||
|
--- @field e_shnum integer
|
||||||
|
--- @field e_shstrndx integer
|
||||||
|
--- @field error string|nil
|
||||||
|
|
||||||
|
--- @class Elf32Section
|
||||||
|
--- @field sh_name integer
|
||||||
|
--- @field sh_type integer
|
||||||
|
--- @field sh_flags integer
|
||||||
|
--- @field sh_addr integer
|
||||||
|
--- @field sh_offset integer
|
||||||
|
--- @field sh_size integer
|
||||||
|
--- @field sh_link integer
|
||||||
|
--- @field name string
|
||||||
|
|
||||||
|
--- @class Elf32Sym
|
||||||
|
--- @field value integer
|
||||||
|
--- @field size integer
|
||||||
|
--- @field info integer
|
||||||
|
--- @field shndx integer
|
||||||
|
|
||||||
|
--- @class Elf32HeaderLayout
|
||||||
|
--- @field magic_offset integer
|
||||||
|
--- @field magic string
|
||||||
|
--- @field class_offset integer
|
||||||
|
--- @field endian_offset integer
|
||||||
|
--- @field header_bytes integer
|
||||||
|
--- @field e_entry_offset integer
|
||||||
|
--- @field e_shoff_offset integer
|
||||||
|
--- @field e_shentsize_offset integer
|
||||||
|
--- @field e_shnum_offset integer
|
||||||
|
--- @field e_shstrndx_offset integer
|
||||||
|
|
||||||
|
--- @class Elf32SectionLayout
|
||||||
|
--- @field sh_name_offset integer
|
||||||
|
--- @field sh_type_offset integer
|
||||||
|
--- @field sh_flags_offset integer
|
||||||
|
--- @field sh_addr_offset integer
|
||||||
|
--- @field sh_offset_offset integer
|
||||||
|
--- @field sh_size_offset integer
|
||||||
|
--- @field sh_link_offset integer
|
||||||
|
--- @field sh_entsize_bytes integer
|
||||||
|
|
||||||
|
--- @class Elf32SymLayout
|
||||||
|
--- @field st_name integer
|
||||||
|
--- @field st_value integer
|
||||||
|
--- @field st_size integer
|
||||||
|
--- @field st_info integer
|
||||||
|
--- @field sym_entry_bytes integer
|
||||||
|
|
||||||
|
--- @class Elf32Mod
|
||||||
|
--- @field ELFCLASS32 integer
|
||||||
|
--- @field ELFDATA2LSB integer
|
||||||
|
--- @field EM_MIPS integer
|
||||||
|
--- @field SHT_SYMTAB integer
|
||||||
|
--- @field SHT_STRTAB integer
|
||||||
|
--- @field SHT_NOBITS integer
|
||||||
|
--- @field SHF_WRITE integer
|
||||||
|
--- @field SHF_ALLOC integer
|
||||||
|
--- @field SHF_EXECINSTR integer
|
||||||
|
--- @field ELF32_HEADER Elf32HeaderLayout
|
||||||
|
--- @field ELF32_SECTION Elf32SectionLayout
|
||||||
|
--- @field ELF32_SYM Elf32SymLayout
|
||||||
|
--- @field dw_dwarf32_terminator integer
|
||||||
|
--- @field read_u32 fun(adapter: Elf32Adapter, off: integer): integer|nil
|
||||||
|
--- @field read_u16 fun(adapter: Elf32Adapter, off: integer): integer|nil
|
||||||
|
--- @field read_u8 fun(adapter: Elf32Adapter, off: integer): integer|nil
|
||||||
|
--- @field size fun(adapter: Elf32Adapter): integer
|
||||||
|
--- @field read_u32_le fun(buf: string, off: integer): integer
|
||||||
|
--- @field read_u16_le fun(buf: string, off: integer): integer
|
||||||
|
--- @field validate_adapter fun(adapter: any): boolean, string|nil
|
||||||
|
--- @field get_str fun(strtab: string, off: integer): string|nil
|
||||||
|
--- @field parse_elf32_headers fun(adapter: Elf32Adapter): Elf32Header|nil, string|nil
|
||||||
|
--- @field walk_sections fun(adapter: Elf32Adapter, hdr: Elf32Header): Elf32Section[]|nil, string|nil
|
||||||
|
--- @field read_section_bytes fun(adapter: Elf32Adapter, section: Elf32Section): string|nil
|
||||||
|
--- @field read_named_section fun(adapter: Elf32Adapter, sections: Elf32Section[], name: string): string|nil, string|nil
|
||||||
|
--- @field collect_symbols fun(adapter: Elf32Adapter, sections: Elf32Section[]): table<string, Elf32Sym>|nil, string|nil
|
||||||
|
|
||||||
|
local M = {} ---@type Elf32Mod
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Little-endian readers (bit-weighted accumulator, math.floor only)
|
-- Little-endian readers (bit-weighted accumulator, math.floor only)
|
||||||
@@ -39,7 +126,7 @@ local M = {}
|
|||||||
--- **Call form:** explicit-pass. The reader receives `adapter` as the first positional argument and the offset as the second; no `self` is passed.
|
--- **Call form:** explicit-pass. The reader receives `adapter` as the first positional argument and the offset as the second; no `self` is passed.
|
||||||
--- Test fixtures declare `function(offset) ... end` and the parsers call them via dot syntax `adapter.read_u8_at(off)`.
|
--- Test fixtures declare `function(offset) ... end` and the parsers call them via dot syntax `adapter.read_u8_at(off)`.
|
||||||
--- The colon form `adapter:read_u8_at(off)` would prepend the adapter table as `offset` and break the contract.
|
--- The colon form `adapter:read_u8_at(off)` would prepend the adapter table as `offset` and break the contract.
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param off integer -- zero-based wire offset
|
--- @param off integer -- zero-based wire offset
|
||||||
--- @return integer|nil
|
--- @return integer|nil
|
||||||
function M.read_u32(adapter, off)
|
function M.read_u32(adapter, off)
|
||||||
@@ -50,7 +137,7 @@ function M.read_u32(adapter, off)
|
|||||||
end
|
end
|
||||||
|
|
||||||
--- Read a 2-byte little-endian unsigned integer from `adapter` at zero-based wire offset `off`.
|
--- Read a 2-byte little-endian unsigned integer from `adapter` at zero-based wire offset `off`.
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param off integer -- zero-based wire offset
|
--- @param off integer -- zero-based wire offset
|
||||||
--- @return integer|nil
|
--- @return integer|nil
|
||||||
function M.read_u16(adapter, off)
|
function M.read_u16(adapter, off)
|
||||||
@@ -59,7 +146,7 @@ function M.read_u16(adapter, off)
|
|||||||
end
|
end
|
||||||
|
|
||||||
--- Read a 1-byte unsigned integer from `adapter` at zero-based wire offset `off`.
|
--- Read a 1-byte unsigned integer from `adapter` at zero-based wire offset `off`.
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param off integer -- zero-based wire offset
|
--- @param off integer -- zero-based wire offset
|
||||||
--- @return integer|nil
|
--- @return integer|nil
|
||||||
function M.read_u8(adapter, off)
|
function M.read_u8(adapter, off)
|
||||||
@@ -67,7 +154,7 @@ function M.read_u8(adapter, off)
|
|||||||
end
|
end
|
||||||
|
|
||||||
--- Total adapter byte length.
|
--- Total adapter byte length.
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @return integer
|
--- @return integer
|
||||||
function M.size(adapter)
|
function M.size(adapter)
|
||||||
return adapter.read_size()
|
return adapter.read_size()
|
||||||
@@ -76,8 +163,11 @@ end
|
|||||||
--- Forwarders kept for backward compat with scripts/elf_dwarf.lua.
|
--- Forwarders kept for backward compat with scripts/elf_dwarf.lua.
|
||||||
--- The metaprogram side keeps `read_u32_le` / `read_u16_le`;
|
--- The metaprogram side keeps `read_u32_le` / `read_u16_le`;
|
||||||
--- both layers now use the same byte-level helpers under the hood.
|
--- both layers now use the same byte-level helpers under the hood.
|
||||||
|
--- @param buf string
|
||||||
|
--- @param off integer
|
||||||
|
--- @return integer
|
||||||
function M.read_u32_le(buf, off)
|
function M.read_u32_le(buf, off)
|
||||||
local byte_off = off + 1
|
local byte_off = off + 1 ---@type integer
|
||||||
return buf:byte(byte_off)
|
return buf:byte(byte_off)
|
||||||
+ buf:byte(byte_off + 0x01) * 0x00000100
|
+ buf:byte(byte_off + 0x01) * 0x00000100
|
||||||
+ buf:byte(byte_off + 0x02) * 0x00010000
|
+ buf:byte(byte_off + 0x02) * 0x00010000
|
||||||
@@ -89,7 +179,7 @@ end
|
|||||||
--- @param off integer -- zero-based wire offset
|
--- @param off integer -- zero-based wire offset
|
||||||
--- @return integer
|
--- @return integer
|
||||||
function M.read_u16_le(buf, off)
|
function M.read_u16_le(buf, off)
|
||||||
local byte_off = off + 1
|
local byte_off = off + 1 ---@type integer
|
||||||
return buf:byte(byte_off) + buf:byte(byte_off + 0x01) * 0x00000100
|
return buf:byte(byte_off) + buf:byte(byte_off + 0x01) * 0x00000100
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -116,6 +206,7 @@ M.SHF_EXECINSTR = 0x4 -- spec: gABI v1.2 §"Section Attributes" — executable
|
|||||||
-- ELF32 header layout (System V ABI gABI v1.2 §"ELF Header" Table 1)
|
-- ELF32 header layout (System V ABI gABI v1.2 §"ELF Header" Table 1)
|
||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
-- All offsets are zero-based wire offsets. The header is 52 bytes total (header_bytes = 0x34 = 52).
|
-- All offsets are zero-based wire offsets. The header is 52 bytes total (header_bytes = 0x34 = 52).
|
||||||
|
--- @type Elf32HeaderLayout
|
||||||
M.ELF32_HEADER = {
|
M.ELF32_HEADER = {
|
||||||
magic_offset = 0x00, -- 4 bytes; expected "\127ELF"
|
magic_offset = 0x00, -- 4 bytes; expected "\127ELF"
|
||||||
magic = "\127ELF",
|
magic = "\127ELF",
|
||||||
@@ -134,6 +225,7 @@ M.ELF32_HEADER = {
|
|||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
-- Each entry is 40 bytes (sh_entsize_bytes = 0x28 = 40);
|
-- Each entry is 40 bytes (sh_entsize_bytes = 0x28 = 40);
|
||||||
-- zero-based, field offsets relative to the start of the entry.
|
-- zero-based, field offsets relative to the start of the entry.
|
||||||
|
--- @type Elf32SectionLayout
|
||||||
M.ELF32_SECTION = {
|
M.ELF32_SECTION = {
|
||||||
sh_name_offset = 0x00, -- 4-byte LE; offset into .shstrtab
|
sh_name_offset = 0x00, -- 4-byte LE; offset into .shstrtab
|
||||||
sh_type_offset = 0x04, -- 4-byte LE; section type (SHT_*)
|
sh_type_offset = 0x04, -- 4-byte LE; section type (SHT_*)
|
||||||
@@ -150,6 +242,7 @@ M.ELF32_SECTION = {
|
|||||||
-- ---------------------------------------------------------------------------
|
-- ---------------------------------------------------------------------------
|
||||||
-- Each entry is 16 bytes (sym_entry_bytes = 0x10 = 16);
|
-- Each entry is 16 bytes (sym_entry_bytes = 0x10 = 16);
|
||||||
-- zero-based, field offsets relative to the start of the entry.
|
-- zero-based, field offsets relative to the start of the entry.
|
||||||
|
--- @type Elf32SymLayout
|
||||||
M.ELF32_SYM = {
|
M.ELF32_SYM = {
|
||||||
st_name = 0x00, -- 4-byte LE; offset into the linked string table
|
st_name = 0x00, -- 4-byte LE; offset into the linked string table
|
||||||
st_value = 0x04, -- 4-byte LE; symbol value (address / absolute)
|
st_value = 0x04, -- 4-byte LE; symbol value (address / absolute)
|
||||||
@@ -190,7 +283,7 @@ end
|
|||||||
--- @return string|nil
|
--- @return string|nil
|
||||||
function M.get_str(strtab, off)
|
function M.get_str(strtab, off)
|
||||||
if off < 0 or off >= #strtab then return nil end
|
if off < 0 or off >= #strtab then return nil end
|
||||||
local end_pos = strtab:find("\0", off + 1, true)
|
local end_pos = strtab:find("\0", off + 1, true) ---@type integer|nil
|
||||||
if not end_pos then return nil end
|
if not end_pos then return nil end
|
||||||
return strtab:sub(off + 1, end_pos - 1)
|
return strtab:sub(off + 1, end_pos - 1)
|
||||||
end
|
end
|
||||||
@@ -205,39 +298,39 @@ end
|
|||||||
--- On failure returns nil + a stable error code:
|
--- On failure returns nil + a stable error code:
|
||||||
--- bad_magic, unsupported_elf_class, unsupported_elf_data, truncated_header
|
--- bad_magic, unsupported_elf_class, unsupported_elf_data, truncated_header
|
||||||
--- The header's machine field is NOT validated here — callers (e.g. the helper's prime path) decide whether to require EM_MIPS before symbol reads.
|
--- The header's machine field is NOT validated here — callers (e.g. the helper's prime path) decide whether to require EM_MIPS before symbol reads.
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @return table|nil, string|nil
|
--- @return Elf32Header|nil, string|nil
|
||||||
function M.parse_elf32_headers(adapter)
|
function M.parse_elf32_headers(adapter)
|
||||||
local ok, err = M.validate_adapter(adapter)
|
local ok, err = M.validate_adapter(adapter) ---@type boolean, string|nil
|
||||||
if not ok then return nil, err end
|
if not ok then return nil, err end
|
||||||
|
|
||||||
-- 4-byte magic: 0x7F 'E' 'L' 'F'.
|
-- 4-byte magic: 0x7F 'E' 'L' 'F'.
|
||||||
-- The byte readers take the adapter explicitly.
|
-- The byte readers take the adapter explicitly.
|
||||||
-- The production `Support.File` adapter is wrapped by the caller to drop its implicit `self` so the parser shape is flat pass-style.
|
-- The production `Support.File` adapter is wrapped by the caller to drop its implicit `self` so the parser shape is flat pass-style.
|
||||||
local b1 = M.read_u8(adapter, 0)
|
local b1 = M.read_u8(adapter, 0) ---@type integer|nil
|
||||||
local b2 = M.read_u8(adapter, 1)
|
local b2 = M.read_u8(adapter, 1) ---@type integer|nil
|
||||||
local b3 = M.read_u8(adapter, 2)
|
local b3 = M.read_u8(adapter, 2) ---@type integer|nil
|
||||||
local b4 = M.read_u8(adapter, 3)
|
local b4 = M.read_u8(adapter, 3) ---@type integer|nil
|
||||||
if not (b1 and b2 and b3 and b4)
|
if not (b1 and b2 and b3 and b4)
|
||||||
or not (b1 == 0x7f and b2 == 0x45 and b3 == 0x4c and b4 == 0x46) then
|
or not (b1 == 0x7f and b2 == 0x45 and b3 == 0x4c and b4 == 0x46) then
|
||||||
return nil, "bad_magic"
|
return nil, "bad_magic"
|
||||||
end
|
end
|
||||||
|
|
||||||
local class = M.read_u8(adapter, M.ELF32_HEADER.class_offset)
|
local class = M.read_u8(adapter, M.ELF32_HEADER.class_offset) ---@type integer|nil
|
||||||
if class ~= M.ELFCLASS32 then
|
if class ~= M.ELFCLASS32 then
|
||||||
return nil, "unsupported_elf_class"
|
return nil, "unsupported_elf_class"
|
||||||
end
|
end
|
||||||
|
|
||||||
local data = M.read_u8(adapter, M.ELF32_HEADER.endian_offset)
|
local data = M.read_u8(adapter, M.ELF32_HEADER.endian_offset) ---@type integer|nil
|
||||||
if data ~= M.ELFDATA2LSB then
|
if data ~= M.ELFDATA2LSB then
|
||||||
return nil, "unsupported_elf_data"
|
return nil, "unsupported_elf_data"
|
||||||
end
|
end
|
||||||
|
|
||||||
local e_entry = M.read_u32(adapter, M.ELF32_HEADER.e_entry_offset)
|
local e_entry = M.read_u32(adapter, M.ELF32_HEADER.e_entry_offset) ---@type integer|nil
|
||||||
local e_shoff = M.read_u32(adapter, M.ELF32_HEADER.e_shoff_offset)
|
local e_shoff = M.read_u32(adapter, M.ELF32_HEADER.e_shoff_offset) ---@type integer|nil
|
||||||
local e_shentsize = M.read_u16(adapter, M.ELF32_HEADER.e_shentsize_offset)
|
local e_shentsize = M.read_u16(adapter, M.ELF32_HEADER.e_shentsize_offset) ---@type integer|nil
|
||||||
local e_shnum = M.read_u16(adapter, M.ELF32_HEADER.e_shnum_offset)
|
local e_shnum = M.read_u16(adapter, M.ELF32_HEADER.e_shnum_offset) ---@type integer|nil
|
||||||
local e_shstrndx = M.read_u16(adapter, M.ELF32_HEADER.e_shstrndx_offset)
|
local e_shstrndx = M.read_u16(adapter, M.ELF32_HEADER.e_shstrndx_offset) ---@type integer|nil
|
||||||
if not (e_entry and e_shoff and e_shentsize and e_shnum and e_shstrndx) then
|
if not (e_entry and e_shoff and e_shentsize and e_shnum and e_shstrndx) then
|
||||||
return nil, "truncated_header"
|
return nil, "truncated_header"
|
||||||
end
|
end
|
||||||
@@ -254,11 +347,11 @@ end
|
|||||||
|
|
||||||
--- Read one section-header entry from `adapter` at `sh_off`.
|
--- Read one section-header entry from `adapter` at `sh_off`.
|
||||||
--- Returns a table with the wire fields plus a (yet-unresolved) `name` field.
|
--- Returns a table with the wire fields plus a (yet-unresolved) `name` field.
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param sh_off integer
|
--- @param sh_off integer
|
||||||
--- @return table|nil, string|nil -- entry, error
|
--- @return Elf32Section|nil, string|nil
|
||||||
local function read_section_entry(adapter, sh_off)
|
local function read_section_entry(adapter, sh_off)
|
||||||
local entry = {
|
local entry = { ---@type Elf32Section
|
||||||
sh_name = M.read_u32(adapter, sh_off + M.ELF32_SECTION.sh_name_offset),
|
sh_name = M.read_u32(adapter, sh_off + M.ELF32_SECTION.sh_name_offset),
|
||||||
sh_type = M.read_u32(adapter, sh_off + M.ELF32_SECTION.sh_type_offset),
|
sh_type = M.read_u32(adapter, sh_off + M.ELF32_SECTION.sh_type_offset),
|
||||||
sh_flags = M.read_u32(adapter, sh_off + M.ELF32_SECTION.sh_flags_offset),
|
sh_flags = M.read_u32(adapter, sh_off + M.ELF32_SECTION.sh_flags_offset),
|
||||||
@@ -279,22 +372,22 @@ end
|
|||||||
--- (the section at logical index 0 is at array position 1, etc.).
|
--- (the section at logical index 0 is at array position 1, etc.).
|
||||||
--- Each entry has the wire fields plus a resolved `name` derived from `.shstrtab`.
|
--- Each entry has the wire fields plus a resolved `name` derived from `.shstrtab`.
|
||||||
--- Returns nil + a stable error code on failure: truncated_section_headers, missing_shstrtab, truncated_strtab
|
--- Returns nil + a stable error code on failure: truncated_section_headers, missing_shstrtab, truncated_strtab
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param hdr table -- the table returned by parse_elf32_headers
|
--- @param hdr Elf32Header
|
||||||
--- @return table|nil, string|nil
|
--- @return Elf32Section[]|nil, string|nil
|
||||||
function M.walk_sections(adapter, hdr)
|
function M.walk_sections(adapter, hdr)
|
||||||
if not hdr or hdr.error then return nil, hdr and hdr.error or "truncated_section_headers" end
|
if not hdr or hdr.error then return nil, hdr and hdr.error or "truncated_section_headers" end
|
||||||
|
|
||||||
local file_size = M.size(adapter)
|
local file_size = M.size(adapter) ---@type integer
|
||||||
if hdr.e_shoff + hdr.e_shnum * hdr.e_shentsize > file_size then
|
if hdr.e_shoff + hdr.e_shnum * hdr.e_shentsize > file_size then
|
||||||
return nil, "truncated_section_headers"
|
return nil, "truncated_section_headers"
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Read every section header first; we need .shstrtab to resolve names.
|
-- Read every section header first; we need .shstrtab to resolve names.
|
||||||
local sections = {}
|
local sections = {} ---@type Elf32Section[]
|
||||||
for i = 0, hdr.e_shnum - 1 do
|
for i = 0, hdr.e_shnum - 1 do ---@type integer
|
||||||
local sh_off = hdr.e_shoff + i * hdr.e_shentsize
|
local sh_off = hdr.e_shoff + i * hdr.e_shentsize ---@type integer
|
||||||
local entry, err = read_section_entry(adapter, sh_off)
|
local entry, err = read_section_entry(adapter, sh_off) ---@type Elf32Section|nil, string|nil
|
||||||
if not entry then return nil, err end
|
if not entry then return nil, err end
|
||||||
sections[i + 1] = entry
|
sections[i + 1] = entry
|
||||||
end
|
end
|
||||||
@@ -303,17 +396,17 @@ function M.walk_sections(adapter, hdr)
|
|||||||
return nil, "missing_shstrtab"
|
return nil, "missing_shstrtab"
|
||||||
end
|
end
|
||||||
|
|
||||||
local shstrtab = sections[hdr.e_shstrndx + 1]
|
local shstrtab = sections[hdr.e_shstrndx + 1] ---@type Elf32Section|nil
|
||||||
if not shstrtab or shstrtab.sh_type ~= M.SHT_STRTAB then
|
if not shstrtab or shstrtab.sh_type ~= M.SHT_STRTAB then
|
||||||
return nil, "missing_shstrtab"
|
return nil, "missing_shstrtab"
|
||||||
end
|
end
|
||||||
if shstrtab.sh_offset + shstrtab.sh_size > file_size then
|
if shstrtab.sh_offset + shstrtab.sh_size > file_size then
|
||||||
return nil, "truncated_section_headers"
|
return nil, "truncated_section_headers"
|
||||||
end
|
end
|
||||||
local shstrtab_bytes = M.read_section_bytes(adapter, shstrtab)
|
local shstrtab_bytes = M.read_section_bytes(adapter, shstrtab) ---@type string|nil
|
||||||
if not shstrtab_bytes then return nil, "truncated_section_headers" end
|
if not shstrtab_bytes then return nil, "truncated_section_headers" end
|
||||||
|
|
||||||
for _, s in ipairs(sections) do
|
for _, s in ipairs(sections) do ---@type integer, Elf32Section
|
||||||
s.name = M.get_str(shstrtab_bytes, s.sh_name) or ""
|
s.name = M.get_str(shstrtab_bytes, s.sh_name) or ""
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -322,15 +415,15 @@ end
|
|||||||
|
|
||||||
--- Read the bytes of one section. Returns a string, or nil if the adapter returns nil for any byte (out-of-bounds).
|
--- Read the bytes of one section. Returns a string, or nil if the adapter returns nil for any byte (out-of-bounds).
|
||||||
--- The caller is responsible fors sizing the buffer (the section's sh_offset + sh_size must fit in adapter.size).
|
--- The caller is responsible fors sizing the buffer (the section's sh_offset + sh_size must fit in adapter.size).
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param section table -- one entry from walk_sections
|
--- @param section Elf32Section
|
||||||
--- @return string|nil
|
--- @return string|nil
|
||||||
function M.read_section_bytes(adapter, section)
|
function M.read_section_bytes(adapter, section)
|
||||||
local size = section.sh_size
|
local size = section.sh_size ---@type integer
|
||||||
if size == 0 then return "" end
|
if size == 0 then return "" end
|
||||||
local out = {}
|
local out = {} ---@type string[]
|
||||||
for i = 0, size - 1 do
|
for i = 0, size - 1 do ---@type integer
|
||||||
local b = M.read_u8(adapter, section.sh_offset + i)
|
local b = M.read_u8(adapter, section.sh_offset + i) ---@type integer|nil
|
||||||
if b == nil then return nil end
|
if b == nil then return nil end
|
||||||
out[#out + 1] = string.char(b)
|
out[#out + 1] = string.char(b)
|
||||||
end
|
end
|
||||||
@@ -339,15 +432,15 @@ end
|
|||||||
|
|
||||||
--- Convenience: walk sections, then look up the named section, then read its bytes.
|
--- Convenience: walk sections, then look up the named section, then read its bytes.
|
||||||
--- Returns nil + a stable error code if the section is absent or out-of-bounds.
|
--- Returns nil + a stable error code if the section is absent or out-of-bounds.
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param sections table -- 1-based array from walk_sections
|
--- @param sections Elf32Section[]
|
||||||
--- @param name string
|
--- @param name string
|
||||||
--- @return string|nil, string|nil
|
--- @return string|nil, string|nil
|
||||||
function M.read_named_section(adapter, sections, name)
|
function M.read_named_section(adapter, sections, name)
|
||||||
if not sections then return nil, "missing_section" end
|
if not sections then return nil, "missing_section" end
|
||||||
for _, s in ipairs(sections) do
|
for _, s in ipairs(sections) do ---@type integer, Elf32Section
|
||||||
if s.name == name then
|
if s.name == name then
|
||||||
local bytes = M.read_section_bytes(adapter, s)
|
local bytes = M.read_section_bytes(adapter, s) ---@type string|nil
|
||||||
if not bytes then return nil, "truncated_section_data" end
|
if not bytes then return nil, "truncated_section_data" end
|
||||||
return bytes, nil
|
return bytes, nil
|
||||||
end
|
end
|
||||||
@@ -359,47 +452,47 @@ end
|
|||||||
--- Each stored entry is `{ value = st_value, size = st_size, info = st_info, shndx = st_shndx }`.
|
--- Each stored entry is `{ value = st_value, size = st_size, info = st_info, shndx = st_shndx }`.
|
||||||
--- Both STB_LOCAL and STB_GLOBAL symbols are included; the live ELF stores `smem` as a local symbol.
|
--- Both STB_LOCAL and STB_GLOBAL symbols are included; the live ELF stores `smem` as a local symbol.
|
||||||
--- Returns nil + a stable error code on failure: missing_symtab_strtab, truncated_section_headers
|
--- Returns nil + a stable error code on failure: missing_symtab_strtab, truncated_section_headers
|
||||||
--- @param adapter table
|
--- @param adapter Elf32Adapter
|
||||||
--- @param sections table
|
--- @param sections Elf32Section[]
|
||||||
--- @return table|nil, string|nil
|
--- @return table<string, Elf32Sym>|nil, string|nil
|
||||||
function M.collect_symbols(adapter, sections)
|
function M.collect_symbols(adapter, sections)
|
||||||
if not sections then return nil, "missing_sections" end
|
if not sections then return nil, "missing_sections" end
|
||||||
local symbols = {}
|
local symbols = {} ---@type table<string, Elf32Sym> -- bag: symbol name -> Elf32Sym
|
||||||
local file_size = M.size(adapter)
|
local file_size = M.size(adapter) ---@type integer
|
||||||
for _, s in ipairs(sections) do
|
for _, s in ipairs(sections) do ---@type integer, Elf32Section
|
||||||
if s.sh_type == M.SHT_SYMTAB then
|
if s.sh_type == M.SHT_SYMTAB then
|
||||||
local strtab = sections[s.sh_link + 1]
|
local strtab = sections[s.sh_link + 1] ---@type Elf32Section|nil
|
||||||
if not strtab or strtab.sh_type ~= M.SHT_STRTAB then
|
if not strtab or strtab.sh_type ~= M.SHT_STRTAB then
|
||||||
return nil, "missing_symtab_strtab"
|
return nil, "missing_symtab_strtab"
|
||||||
end
|
end
|
||||||
if strtab.sh_offset + strtab.sh_size > file_size then
|
if strtab.sh_offset + strtab.sh_size > file_size then
|
||||||
return nil, "truncated_section_headers"
|
return nil, "truncated_section_headers"
|
||||||
end
|
end
|
||||||
local strtab_bytes = M.read_section_bytes(adapter, strtab)
|
local strtab_bytes = M.read_section_bytes(adapter, strtab) ---@type string|nil
|
||||||
if not strtab_bytes then return nil, "truncated_section_headers" end
|
if not strtab_bytes then return nil, "truncated_section_headers" end
|
||||||
if s.sh_offset + s.sh_size > file_size then
|
if s.sh_offset + s.sh_size > file_size then
|
||||||
return nil, "truncated_section_headers"
|
return nil, "truncated_section_headers"
|
||||||
end
|
end
|
||||||
local symtab_bytes = M.read_section_bytes(adapter, s)
|
local symtab_bytes = M.read_section_bytes(adapter, s) ---@type string|nil
|
||||||
if not symtab_bytes then return nil, "truncated_section_headers" end
|
if not symtab_bytes then return nil, "truncated_section_headers" end
|
||||||
local n = #symtab_bytes / M.ELF32_SYM.sym_entry_bytes
|
local n = #symtab_bytes / M.ELF32_SYM.sym_entry_bytes ---@type number
|
||||||
for j = 0, n - 1 do
|
for j = 0, n - 1 do ---@type integer
|
||||||
local e = s.sh_offset + j * M.ELF32_SYM.sym_entry_bytes
|
local e = s.sh_offset + j * M.ELF32_SYM.sym_entry_bytes ---@type integer
|
||||||
local st_name = M.read_u32(adapter, e + M.ELF32_SYM.st_name)
|
local st_name = M.read_u32(adapter, e + M.ELF32_SYM.st_name) ---@type integer|nil
|
||||||
if st_name then
|
if st_name then
|
||||||
local st_value = M.read_u32(adapter, e + M.ELF32_SYM.st_value)
|
local st_value = M.read_u32(adapter, e + M.ELF32_SYM.st_value) ---@type integer|nil
|
||||||
local st_size = M.read_u32(adapter, e + M.ELF32_SYM.st_size)
|
local st_size = M.read_u32(adapter, e + M.ELF32_SYM.st_size) ---@type integer|nil
|
||||||
local st_info = M.read_u8(adapter, e + M.ELF32_SYM.st_info)
|
local st_info = M.read_u8(adapter, e + M.ELF32_SYM.st_info) ---@type integer|nil
|
||||||
-- st_shndx is at offset 14 (2 bytes) — derived from the layout
|
-- st_shndx is at offset 14 (2 bytes) — derived from the layout
|
||||||
-- the metaprogram reads too. Inline the read to keep the
|
-- the metaprogram reads too. Inline the read to keep the
|
||||||
-- adapter as the only I/O surface.
|
-- adapter as the only I/O surface.
|
||||||
local b1 = M.read_u8(adapter, e + 14)
|
local b1 = M.read_u8(adapter, e + 14) ---@type integer|nil
|
||||||
local b2 = M.read_u8(adapter, e + 15)
|
local b2 = M.read_u8(adapter, e + 15) ---@type integer|nil
|
||||||
if not (b1 and b2) then
|
if not (b1 and b2) then
|
||||||
return nil, "truncated_section_headers"
|
return nil, "truncated_section_headers"
|
||||||
end
|
end
|
||||||
local st_shndx = b1 + b2 * 0x100
|
local st_shndx = b1 + b2 * 0x100 ---@type integer
|
||||||
local name = M.get_str(strtab_bytes, st_name) or ""
|
local name = M.get_str(strtab_bytes, st_name) or "" ---@type string
|
||||||
if name ~= "" then
|
if name ~= "" then
|
||||||
symbols[name] = {
|
symbols[name] = {
|
||||||
value = st_value,
|
value = st_value,
|
||||||
|
|||||||
+431
-187
File diff suppressed because it is too large
Load Diff
@@ -16,7 +16,7 @@ define tape_atoms
|
|||||||
echo "[gdb_tape_atoms] STUB: run .\\build_psyq.ps1 to regenerate, then re-source this file."
|
echo "[gdb_tape_atoms] STUB: run .\\build_psyq.ps1 to regenerate, then re-source this file."
|
||||||
end
|
end
|
||||||
document tape_atoms
|
document tape_atoms
|
||||||
List every tape atom symbol in the loaded ELF (code_<name>) with its .rodata address and word count.
|
List every tape atom symbol in the loaded ELF with its .rodata address and word count.
|
||||||
STUB state: runtime file not sourced. Run build_psyq.ps1 to regenerate.
|
STUB state: runtime file not sourced. Run build_psyq.ps1 to regenerate.
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
# scripts/launch_pcsx_debug.ps1
|
# scripts/launch_pcsx_debug.ps1
|
||||||
#
|
#
|
||||||
# One-shot launcher for debug sessions: starts pcsx-redux with the .ps-exe
|
# One-shot launcher for debug sessions:
|
||||||
# loaded, the gdb stub enabled, AND the pcsx_debug_helper Lua plugin loaded
|
# Starts pcsx-redux with the .ps-exe loaded, the gdb stub enabled,
|
||||||
# so external CLI tools (gdb's `shell` command, etc.)
|
# AND the pcsx_debug_helper Lua plugin loaded so external CLI tools (gdb's `shell` command, etc.)
|
||||||
# can read GTE state via http://localhost:8080/api/v1/lua/gte
|
# can read GTE state via http://localhost:8080/api/v1/lua/gte (the gdb stub doesn't expose COP2 at all).
|
||||||
# (the gdb stub doesn't expose COP2 at all).
|
|
||||||
#
|
#
|
||||||
# usage:
|
# usage:
|
||||||
# .\scripts\launch_pcsx_debug.ps1
|
# .\scripts\launch_pcsx_debug.ps1
|
||||||
@@ -84,7 +83,8 @@ try {
|
|||||||
$r = Invoke-WebRequest -Uri "http://localhost:$WebPort/api/v1/lua/gte" -UseBasicParsing -TimeoutSec 5
|
$r = Invoke-WebRequest -Uri "http://localhost:$WebPort/api/v1/lua/gte" -UseBasicParsing -TimeoutSec 5
|
||||||
$firstLine = ([System.Text.Encoding]::UTF8.GetString($r.Content) -split "`n")[0]
|
$firstLine = ([System.Text.Encoding]::UTF8.GetString($r.Content) -split "`n")[0]
|
||||||
Write-Host "GTE handler OK: $firstLine" -ForegroundColor Green
|
Write-Host "GTE handler OK: $firstLine" -ForegroundColor Green
|
||||||
} catch {
|
}
|
||||||
|
catch {
|
||||||
Write-Warning "GTE handler NOT responding: $_"
|
Write-Warning "GTE handler NOT responding: $_"
|
||||||
Write-Host "Check the pcsx-redux Lua Console for debug cli messages." -ForegroundColor Yellow
|
Write-Host "Check the pcsx-redux Lua Console for debug cli messages." -ForegroundColor Yellow
|
||||||
}
|
}
|
||||||
|
|||||||
+135
-211
@@ -10,8 +10,8 @@
|
|||||||
|
|
||||||
-- Bootstrap follows the entry scripts; `scripts/duffle_paths.lua` sets package.path and package.cpath. See `ps1_meta.lua` for the rationale.
|
-- Bootstrap follows the entry scripts; `scripts/duffle_paths.lua` sets package.path and package.cpath. See `ps1_meta.lua` for the rationale.
|
||||||
-- `debug.getinfo(1, "S").source` locates this file for standalone and orchestrated runs, then `duffle_paths.lua` returns the loaded `duffle` module.
|
-- `debug.getinfo(1, "S").source` locates this file for standalone and orchestrated runs, then `duffle_paths.lua` returns the loaded `duffle` module.
|
||||||
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
|
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" ---@type string
|
||||||
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") ---@type DuffleExport
|
||||||
|
|
||||||
-- The annotation pass reads the source-derived registries from scan_source:
|
-- The annotation pass reads the source-derived registries from scan_source:
|
||||||
-- * pipe_ctx.register_alias_registry — for atom_dbg_reg_default(R_X, ...) and atom_reg_types(R_X, ...) member-identity checks
|
-- * pipe_ctx.register_alias_registry — for atom_dbg_reg_default(R_X, ...) and atom_reg_types(R_X, ...) member-identity checks
|
||||||
@@ -21,76 +21,40 @@ local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
|||||||
-- Type declarations
|
-- Type declarations
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- @class SourceFile
|
-- SourceFile, PassCtx, PassResult, PassShared, Corpus, Finding: see ps1_meta.lua
|
||||||
--- @field path string -- Absolute path to the source file
|
-- SourceScan, AtomEntry, AtomInfoEntry, BindsEntry, RegTypeDefault, AtomViewEntry: see scan_source.lua
|
||||||
--- @field text string -- Full source text
|
|
||||||
--- @field dir string -- Directory containing the source
|
|
||||||
--- @field basename string -- Filename without extension
|
|
||||||
--- @field scan table -- Pre-scanned SourceScan payload (from duffle.scan_source)
|
|
||||||
|
|
||||||
--- @class PassCtx
|
--- @class RegTypeOccurrence
|
||||||
--- @field sources SourceFile[]
|
--- @field reg string
|
||||||
--- @field metadata_path string
|
--- @field type_name string
|
||||||
--- @field shared table
|
--- @field source_line integer
|
||||||
--- @field shared.word_counts table<string, integer>
|
|
||||||
--- @field out_root string
|
|
||||||
--- @field project_root string
|
|
||||||
--- @field upstream table<string, table>
|
|
||||||
--- @field flags table
|
|
||||||
--- @field verbose boolean
|
|
||||||
|
|
||||||
--- @class PassResult
|
|
||||||
--- @field outputs table[]
|
|
||||||
--- @field errors table[]
|
|
||||||
--- @field warnings table[]
|
|
||||||
|
|
||||||
--- @class AtomAnnotation
|
|
||||||
--- @field line integer -- Source line of the atom_info call
|
|
||||||
--- @field macro string -- Macro name (always "atom_info" in the new shape)
|
|
||||||
--- @field name string -- Atom name
|
|
||||||
--- @field kind string -- Always "info"
|
|
||||||
--- @field binds string|nil -- Binds_X name if any
|
|
||||||
--- @field reads string[] -- R_* names (read targets)
|
|
||||||
--- @field writes string[] -- R_* names (write targets)
|
|
||||||
--- @field errors string[]|nil -- Parse-time errors from scan_source (atom_info body malformed)
|
|
||||||
|
|
||||||
--- @class DebugSkipMarker -- Sub-shape of scan_source.lua's @class DebugSkipMarker
|
|
||||||
--- @field marker_kind string -- Exact marker ident read from source. Only "atom_dbg_skip" (bare) is positive.
|
|
||||||
--- @field marker_line integer
|
|
||||||
--- @field args string|nil -- Trimmed text inside the parens (nil when has_parens is false)
|
|
||||||
--- @field has_parens boolean
|
|
||||||
--- @field is_bare boolean -- true iff marker_kind == "atom_dbg_skip" AND has_parens == false (the only positive form)
|
|
||||||
--- @field pending boolean -- true while awaiting the following declaration
|
|
||||||
--- @field superseded_by_marker_line integer|nil -- Set on a marker that was bumped out of the pending slot
|
|
||||||
--- @field target_kind string|nil -- "atom" | "comp_bare" | "comp_proc" | "unrelated" once observed
|
|
||||||
|
|
||||||
--- @class Finding
|
|
||||||
--- @field line integer -- Source line (or 0 for pass-level)
|
|
||||||
--- @field msg string -- Finding message
|
|
||||||
|
|
||||||
--- @class Findings
|
--- @class Findings
|
||||||
--- @field errors Finding[]
|
--- @field errors Finding[]
|
||||||
--- @field warnings Finding[]
|
--- @field warnings Finding[]
|
||||||
--- @field info Finding[]
|
--- @field info Finding[]
|
||||||
|
|
||||||
--- @class PipeCtx
|
-- PassScratch: see ps1_meta.lua
|
||||||
--- @field atom_index table<string, AtomAnnotation> -- Name -> AtomAnnotation (only kind=="atom")
|
|
||||||
--- @field binds_index table<string, BindsStruct> -- Name -> BindsStruct
|
|
||||||
--- @field annot_counts table<string, integer> -- Name -> annotation count (for unique_annotation check)
|
|
||||||
--- @field types table<string, RegTypeDefault> -- From scan_source
|
|
||||||
--- @field atom_views table<string, AtomViewEntry> -- From scan_source
|
|
||||||
--- @field seen_defaults table<string, integer> -- Duplicate atom_dbg_reg_default detection
|
|
||||||
--- @field seen_field table<string, integer> -- Binds_* -> count of fields (set/checked by check_binds_no_duplicate_fields)
|
|
||||||
--- @field _scan SourceScan -- Full scan payload (typed-view sub-calls live here)
|
|
||||||
|
|
||||||
--- @class AnnotatedResult
|
--- @class AnnotatedResult
|
||||||
--- @field atoms AtomEntry[]
|
--- @field atoms AtomEntry[]
|
||||||
--- @field annots AtomAnnotation[]
|
--- @field annots AtomInfoEntry[]
|
||||||
--- @field macros MacroEntry[]
|
--- @field macros MacroEntry[]
|
||||||
--- @field binds BindsEntry[]
|
--- @field binds BindsEntry[]
|
||||||
--- @field errors Finding[]
|
--- @field errors Finding[]
|
||||||
--- @field warnings Finding[]
|
--- @field warnings Finding[]
|
||||||
--- @field info Finding[]
|
--- @field info Finding[]
|
||||||
|
--- @field source string|nil
|
||||||
|
|
||||||
|
--- @class CheckRule
|
||||||
|
--- @field per_annot (fun(item: AtomInfoEntry, pipe_ctx: PassScratch, findings: Findings): nil)|nil
|
||||||
|
|
||||||
|
--- @class SourceScan
|
||||||
|
--- @field type_occurrences RegTypeOccurrence[]|nil
|
||||||
|
|
||||||
|
--- @class AnnotationPass
|
||||||
|
--- @field validate fun(ctx: PassCtx, src: SourceFile, corpus_pipe_ctx: PassScratch|nil): AnnotatedResult
|
||||||
|
--- @field run fun(ctx: PassCtx): PassResult
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Per-check functions (the CHECK_RULES table's payload)
|
-- Per-check functions (the CHECK_RULES table's payload)
|
||||||
@@ -99,24 +63,27 @@ local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
|||||||
--- `macro_word_drift` writes errors[] for missing or mismatched metadata and info[] for a match.
|
--- `macro_word_drift` writes errors[] for missing or mismatched metadata and info[] for a match.
|
||||||
|
|
||||||
--- Check: Every annotated atom must have a matching MipsAtom_(name) declaration.
|
--- Check: Every annotated atom must have a matching MipsAtom_(name) declaration.
|
||||||
--- @param a AtomAnnotation
|
--- @param info AtomInfoEntry
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
local function check_atom_decl_exists(a, pipe_ctx, findings)
|
--- @return nil
|
||||||
if not pipe_ctx.atom_index[a.name] then
|
local function check_atom_decl_exists(info, pipe_ctx, findings)
|
||||||
|
if not pipe_ctx.atom_index[info.atom_name] then
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = a.line,
|
line = info.info_line,
|
||||||
msg = string.format("annotation for '%s' has no matching MipsAtom_(%s) { ... }", a.name, a.name),
|
msg = string.format("annotation for '%s' has no matching MipsAtom_(%s) { ... }", info.atom_name, info.atom_name),
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Check: Every atom may have AT MOST ONE annotation.
|
--- Check: Every atom may have AT MOST ONE annotation.
|
||||||
--- Post-loop: Needs full-corpus `annot_counts` from pipe_ctx.
|
--- Post-loop: Needs full-corpus `annot_counts` from pipe_ctx.
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param _item AtomInfoEntry|nil
|
||||||
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
local function check_unique_annotation(pipe_ctx, findings)
|
--- @return nil
|
||||||
for name, n in pairs(pipe_ctx.annot_counts) do
|
local function check_unique_annotation(_item, pipe_ctx, findings)
|
||||||
|
for name, n in pairs(pipe_ctx.annot_counts) do ---@type string, integer
|
||||||
if n > 1 then
|
if n > 1 then
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = pipe_ctx.atom_index[name] and pipe_ctx.atom_index[name].line or 0,
|
line = pipe_ctx.atom_index[name] and pipe_ctx.atom_index[name].line or 0,
|
||||||
@@ -128,27 +95,30 @@ end
|
|||||||
|
|
||||||
--- Check: BIND atoms must reference a real Binds_* struct.
|
--- Check: BIND atoms must reference a real Binds_* struct.
|
||||||
--- I keep this as a warning so the annotation pass can report the common test-fixture case; `check_abi_handoff` in static analysis supplies the build-stopping error.
|
--- I keep this as a warning so the annotation pass can report the common test-fixture case; `check_abi_handoff` in static analysis supplies the build-stopping error.
|
||||||
--- @param a AtomAnnotation
|
--- @param info AtomInfoEntry
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
local function check_binds_struct_exists(a, pipe_ctx, findings)
|
--- @return nil
|
||||||
if not a.binds then return end
|
local function check_binds_struct_exists(info, pipe_ctx, findings)
|
||||||
if pipe_ctx.binds_index[a.binds] then return end
|
if not info.binds then return end
|
||||||
|
if pipe_ctx.binds_index[info.binds] then return end
|
||||||
findings.warnings[#findings.warnings + 1] = {
|
findings.warnings[#findings.warnings + 1] = {
|
||||||
line = a.line,
|
line = info.info_line,
|
||||||
msg = string.format("'%s' binds '%s' but no Struct_(%s) { ... } "
|
msg = string.format("'%s' binds '%s' but no Struct_(%s) { ... } "
|
||||||
.. "declaration found (also flagged as an error by check_abi_handoff in the static-analysis pass)"
|
.. "declaration found (also flagged as an error by check_abi_handoff in the static-analysis pass)"
|
||||||
, a.name, a.binds, a.binds),
|
, info.atom_name, info.binds, info.binds),
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Check: TAPE_WORDS(mac_X, N) ↔ WORD_COUNT(mac_X, N) drift.
|
--- Check: TAPE_WORDS(mac_X, N) ↔ WORD_COUNT(mac_X, N) drift.
|
||||||
--- Three outcomes: missing (error), mismatch (error), match (info).
|
--- Three outcomes: missing (error), mismatch (error), match (info).
|
||||||
--- @param m MacroEntry
|
--- @param m MacroEntry
|
||||||
--- @param wc table<string, integer> -- Shared word-count table (from ctx.shared.word_counts)
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
local function check_macro_word_drift(m, wc, findings)
|
--- @return nil
|
||||||
local declared = wc[m.name]
|
local function check_macro_word_drift(m, pipe_ctx, findings)
|
||||||
|
local wc = (pipe_ctx and pipe_ctx.word_counts) or {} ---@type WordCounts
|
||||||
|
local declared = wc[m.name] ---@type integer|nil
|
||||||
if not declared then
|
if not declared then
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = m.line,
|
line = m.line,
|
||||||
@@ -172,12 +142,13 @@ end
|
|||||||
--- Check: atom_dbg_reg_default(R_X, <type>) targets an alias in `pipe_ctx.register_alias_registry` and a type in `pipe_ctx.type_name_registry`.
|
--- Check: atom_dbg_reg_default(R_X, <type>) targets an alias in `pipe_ctx.register_alias_registry` and a type in `pipe_ctx.type_name_registry`.
|
||||||
--- Pointer depth remains bounded to 0 or 1, and duplicate defaults remain errors.
|
--- Pointer depth remains bounded to 0 or 1, and duplicate defaults remain errors.
|
||||||
--- @param _src SourceFile -- unused (kept for the per_source shape)
|
--- @param _src SourceFile -- unused (kept for the per_source shape)
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
|
--- @return nil
|
||||||
local function check_semantic_reg_defaults(_src, pipe_ctx, findings)
|
local function check_semantic_reg_defaults(_src, pipe_ctx, findings)
|
||||||
-- Detect duplicate defaults using the ordered occurrence list (the out.types hash only retains the last declaration).
|
-- Detect duplicate defaults using the ordered occurrence list (the out.types hash only retains the last declaration).
|
||||||
local seen_first_line = {}
|
local seen_first_line = {} ---@type table<string, integer> -- bag: register ident -> first source line
|
||||||
for _, occ in ipairs(pipe_ctx.type_occurrences or {}) do
|
for _, occ in ipairs(pipe_ctx.type_occurrences or {}) do ---@type integer, RegTypeOccurrence
|
||||||
if seen_first_line[occ.reg] == nil then
|
if seen_first_line[occ.reg] == nil then
|
||||||
seen_first_line[occ.reg] = occ.source_line
|
seen_first_line[occ.reg] = occ.source_line
|
||||||
else
|
else
|
||||||
@@ -189,9 +160,9 @@ local function check_semantic_reg_defaults(_src, pipe_ctx, findings)
|
|||||||
}
|
}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
local reg_registry = pipe_ctx.register_alias_registry or {}
|
local reg_registry = pipe_ctx.register_alias_registry or {} ---@type table<string, AliasEntry>
|
||||||
local type_registry = pipe_ctx.type_name_registry or {}
|
local type_registry = pipe_ctx.type_name_registry or {} ---@type table<string, TypeNameEntry>
|
||||||
for reg, def in pairs(pipe_ctx.types or {}) do
|
for reg, def in pairs(pipe_ctx.types or {}) do ---@type string, RegTypeDefault
|
||||||
if not reg_registry[reg] then
|
if not reg_registry[reg] then
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = def.source_line,
|
line = def.source_line,
|
||||||
@@ -222,14 +193,15 @@ end
|
|||||||
--- Check: atom_reg_types(R_X, <type>) entries target an alias in `pipe_ctx.register_alias_registry` and a type in `pipe_ctx.type_name_registry`.
|
--- Check: atom_reg_types(R_X, <type>) entries target an alias in `pipe_ctx.register_alias_registry` and a type in `pipe_ctx.type_name_registry`.
|
||||||
--- A bare `atom_reg` marker opts the `R_<n>` alias into GPR identity; references to R_T0..R_T3 require the same explicit marker.
|
--- A bare `atom_reg` marker opts the `R_<n>` alias into GPR identity; references to R_T0..R_T3 require the same explicit marker.
|
||||||
--- @param _src SourceFile
|
--- @param _src SourceFile
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
|
--- @return nil
|
||||||
local function check_atom_reg_types(_src, pipe_ctx, findings)
|
local function check_atom_reg_types(_src, pipe_ctx, findings)
|
||||||
local reg_registry = pipe_ctx.register_alias_registry or {}
|
local reg_registry = pipe_ctx.register_alias_registry or {} ---@type table<string, AliasEntry>
|
||||||
local type_registry = pipe_ctx.type_name_registry or {}
|
local type_registry = pipe_ctx.type_name_registry or {} ---@type table<string, TypeNameEntry>
|
||||||
for _, ai in ipairs(pipe_ctx.atom_infos_list or {}) do
|
for _, ai in ipairs(pipe_ctx.atom_infos_list or {}) do ---@type integer, AtomInfoEntry
|
||||||
if ai.reg_type_overrides then
|
if ai.reg_type_overrides then
|
||||||
for reg, ov in pairs(ai.reg_type_overrides) do
|
for reg, ov in pairs(ai.reg_type_overrides) do ---@type string, RegTypeOverride
|
||||||
if not reg_registry[reg] then
|
if not reg_registry[reg] then
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = ai.info_line,
|
line = ai.info_line,
|
||||||
@@ -253,14 +225,15 @@ end
|
|||||||
|
|
||||||
--- Check: atom_view(Binds_X) entries reference a Binds_* struct with at least one field.
|
--- Check: atom_view(Binds_X) entries reference a Binds_* struct with at least one field.
|
||||||
--- @param _src SourceFile
|
--- @param _src SourceFile
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
|
--- @return nil
|
||||||
local function check_atom_view_layout(_src, pipe_ctx, findings)
|
local function check_atom_view_layout(_src, pipe_ctx, findings)
|
||||||
for atom_name, view in pairs(pipe_ctx.atom_views or {}) do
|
for atom_name, view in pairs(pipe_ctx.atom_views or {}) do ---@type string, AtomViewEntry
|
||||||
if not view.binds_name then
|
if not view.binds_name then
|
||||||
-- The atom had atom_reg_types but no atom_view; no layout check needed.
|
-- The atom had atom_reg_types but no atom_view; no layout check needed.
|
||||||
else
|
else
|
||||||
local bs = pipe_ctx.binds_index[view.binds_name]
|
local bs = pipe_ctx.binds_index[view.binds_name] ---@type BindsEntry|nil
|
||||||
if not bs then
|
if not bs then
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = view.info_line,
|
line = view.info_line,
|
||||||
@@ -282,15 +255,16 @@ end
|
|||||||
|
|
||||||
--- Check: Binds_* structs require unique field names because atom_view uses those names for typed-field lookup in gdb.
|
--- Check: Binds_* structs require unique field names because atom_view uses those names for typed-field lookup in gdb.
|
||||||
--- @param _src SourceFile
|
--- @param _src SourceFile
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
|
--- @return nil
|
||||||
local function check_binds_no_duplicate_fields(_src, pipe_ctx, findings)
|
local function check_binds_no_duplicate_fields(_src, pipe_ctx, findings)
|
||||||
for _, bs in ipairs(pipe_ctx.binds_list or {}) do
|
for _, bs in ipairs(pipe_ctx.binds_list or {}) do ---@type integer, BindsEntry
|
||||||
local seen = {}
|
local seen = {} ---@type table<string, integer> -- bag: field name -> occurrence count
|
||||||
for _, f in ipairs(bs.fields or {}) do
|
for _, f in ipairs(bs.fields or {}) do ---@type integer, TypeField
|
||||||
seen[f.name] = (seen[f.name] or 0) + 1
|
seen[f.name] = (seen[f.name] or 0) + 1
|
||||||
end
|
end
|
||||||
for name, count in pairs(seen) do
|
for name, count in pairs(seen) do ---@type string, integer
|
||||||
if count > 1 then
|
if count > 1 then
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = bs.line,
|
line = bs.line,
|
||||||
@@ -314,11 +288,12 @@ end
|
|||||||
--- 6. unsupported target_kind -> marker precedes an unrelated declaration
|
--- 6. unsupported target_kind -> marker precedes an unrelated declaration
|
||||||
--- Valid markers stamp `debug_skip` on whole-atom, bare-component, and proc-component declaration records in scan_source.lua.
|
--- Valid markers stamp `debug_skip` on whole-atom, bare-component, and proc-component declaration records in scan_source.lua.
|
||||||
--- @param marker DebugSkipMarker
|
--- @param marker DebugSkipMarker
|
||||||
--- @param _pipe_ctx PipeCtx -- Unused; kept for consistency with per_annot // TODO(Ed): Remove?
|
--- @param _pipe_ctx PassScratch -- Unused; kept for consistency with per_annot
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
|
--- @return nil
|
||||||
local function check_skip_marker(marker, _pipe_ctx, findings)
|
local function check_skip_marker(marker, _pipe_ctx, findings)
|
||||||
local kind = marker.marker_kind
|
local kind = marker.marker_kind ---@type string
|
||||||
local line = marker.marker_line
|
local line = marker.marker_line ---@type integer
|
||||||
-- Left `scan.debug_skip_markers` with production records for `atom_dbg_skip` only; other identifiers take the walker's unrelated branch.
|
-- Left `scan.debug_skip_markers` with production records for `atom_dbg_skip` only; other identifiers take the walker's unrelated branch.
|
||||||
|
|
||||||
if marker.has_parens then
|
if marker.has_parens then
|
||||||
@@ -371,15 +346,16 @@ end
|
|||||||
--- Warn when a source references an unregistered alias.
|
--- Warn when a source references an unregistered alias.
|
||||||
--- When a source uses an unregistered R_X, this check emits one pass-level info entry for that source and directs C-ABI register names to explicit alias registration.
|
--- When a source uses an unregistered R_X, this check emits one pass-level info entry for that source and directs C-ABI register names to explicit alias registration.
|
||||||
--- @param _src SourceFile
|
--- @param _src SourceFile
|
||||||
--- @param pipe_ctx PipeCtx
|
--- @param pipe_ctx PassScratch
|
||||||
--- @param findings Findings
|
--- @param findings Findings
|
||||||
|
--- @return nil
|
||||||
local function check_wave_context_migration(_src, pipe_ctx, findings)
|
local function check_wave_context_migration(_src, pipe_ctx, findings)
|
||||||
if not (pipe_ctx.types and next(pipe_ctx.types)) then return end
|
if not (pipe_ctx.types and next(pipe_ctx.types)) then return end
|
||||||
if not (pipe_ctx.atom_infos_list) then return end
|
if not (pipe_ctx.atom_infos_list) then return end
|
||||||
local reg_registry = pipe_ctx.register_alias_registry or {}
|
local reg_registry = pipe_ctx.register_alias_registry or {} ---@type table<string, AliasEntry>
|
||||||
for _, ai in ipairs(pipe_ctx.atom_infos_list) do
|
for _, ai in ipairs(pipe_ctx.atom_infos_list) do ---@type integer, AtomInfoEntry
|
||||||
if ai.reg_type_overrides then
|
if ai.reg_type_overrides then
|
||||||
for reg, _ in pairs(ai.reg_type_overrides) do
|
for reg, _ in pairs(ai.reg_type_overrides) do ---@type string, RegTypeOverride
|
||||||
if not reg_registry[reg] then
|
if not reg_registry[reg] then
|
||||||
findings.warnings[#findings.warnings + 1] = {
|
findings.warnings[#findings.warnings + 1] = {
|
||||||
line = 0,
|
line = 0,
|
||||||
@@ -399,14 +375,14 @@ end
|
|||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
--
|
--
|
||||||
-- Each rule entry picks one of four "shapes" of dispatch:
|
-- Each rule entry picks one of four "shapes" of dispatch:
|
||||||
-- per_annot(annot, pipe_ctx, findings) -- runs once per AtomAnnotation
|
-- per_annot(info, pipe_ctx, findings) -- runs once per scan.atom_infos row
|
||||||
-- post(pipe_ctx, findings) -- runs once after all per_annot calls complete (full-corpus aggregation)
|
-- post(pipe_ctx, findings) -- runs once after all per_annot calls complete (full-corpus aggregation)
|
||||||
-- per_macro(macro, wc, findings) -- runs once per TAPE_WORDS / _Pragma macro declaration
|
-- per_macro(macro, wc, findings) -- runs once per TAPE_WORDS / _Pragma macro declaration
|
||||||
-- per_skip_marker(marker, pipe_ctx, findings) -- runs once per src.scan.debug_skip_markers entry
|
-- per_skip_marker(marker, pipe_ctx, findings) -- runs once per src.scan.debug_skip_markers entry
|
||||||
--
|
--
|
||||||
-- Adding a new check = 1 row here + 1 function above. The `validate()` dispatch loop never needs editing.
|
-- Adding a new check = 1 row here + 1 function above. The `validate()` dispatch loop never needs editing.
|
||||||
|
|
||||||
local CHECK_RULES = {
|
local CHECK_RULES = { ---@type CheckRule[]
|
||||||
{ name = "atom_decl_exists", per_annot = check_atom_decl_exists },
|
{ name = "atom_decl_exists", per_annot = check_atom_decl_exists },
|
||||||
{ name = "binds_struct_exists", per_annot = check_binds_struct_exists },
|
{ name = "binds_struct_exists", per_annot = check_binds_struct_exists },
|
||||||
{ name = "unique_annotation", post = check_unique_annotation },
|
{ name = "unique_annotation", post = check_unique_annotation },
|
||||||
@@ -427,81 +403,35 @@ local CHECK_RULES = {
|
|||||||
--- Builds one pass-wide pipe_ctx from the merged `corpus.*` registries and source-ordered `corpus.atom_infos`; per-source declarations and bodies remain in `src.scan`.
|
--- Builds one pass-wide pipe_ctx from the merged `corpus.*` registries and source-ordered `corpus.atom_infos`; per-source declarations and bodies remain in `src.scan`.
|
||||||
--- The module ownership contract above requires callers to construct `ctx.shared.corpus` through `build_ctx`; the error message below enforces that gate.
|
--- The module ownership contract above requires callers to construct `ctx.shared.corpus` through `build_ctx`; the error message below enforces that gate.
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @return PipeCtx
|
--- @return PassScratch
|
||||||
local function build_corpus_pipe_ctx(ctx)
|
local function build_corpus_pipe_ctx(ctx)
|
||||||
local corpus = ctx.shared and ctx.shared.corpus
|
local view = duffle.corpus_view(ctx) ---@type PassScratch
|
||||||
if not corpus then
|
local annot_counts = {} ---@type table<string, integer> -- bag: atom name -> annotation count
|
||||||
error("annotation requires ctx.shared.corpus "
|
for _, info in ipairs(view.atom_infos) do ---@type integer, AtomInfoEntry
|
||||||
.. "(the canonical corpus is the source of truth; "
|
|
||||||
.. "no per-source fallback is supported)", 0)
|
|
||||||
end
|
|
||||||
|
|
||||||
-- `corpus.atom_infos` preserves source order and duplicates; I precompute counts here for `check_unique_annotation` and the per-source checks.
|
|
||||||
local annot_counts = {}
|
|
||||||
for _, info in ipairs(corpus.atom_infos or {}) do
|
|
||||||
if info and info.atom_name then
|
if info and info.atom_name then
|
||||||
annot_counts[info.atom_name] = (annot_counts[info.atom_name] or 0) + 1
|
annot_counts[info.atom_name] = (annot_counts[info.atom_name] or 0) + 1
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
view.annot_counts = annot_counts
|
||||||
-- Every consumer of these fields observes mutations via the canonical corpus without independently mutable registry construction.
|
view.atom_infos_list = view.atom_infos
|
||||||
return {
|
view.word_counts = ctx.shared.corpus.word_counts or {}
|
||||||
-- Cross-source lookup tables from corpus.
|
return view
|
||||||
register_alias_registry = corpus.register_alias_registry or {},
|
|
||||||
type_name_registry = corpus.type_name_registry or {},
|
|
||||||
atom_views = corpus.atom_views or {},
|
|
||||||
atom_ctxs = corpus.atom_ctxs or {},
|
|
||||||
atom_phases = corpus.atom_phases or {},
|
|
||||||
binds_by_name = corpus.binds_by_name or {},
|
|
||||||
atoms_by_name = corpus.atoms_by_name or {},
|
|
||||||
-- Corpus-wide ordered list of atom_info records (source-order + duplicates).
|
|
||||||
atom_infos_list = corpus.atom_infos or {},
|
|
||||||
-- Corpus-wide annotation count aggregation (post-rule consumes this).
|
|
||||||
annot_counts = annot_counts,
|
|
||||||
-- Corpus-wide collisions (recorded by scan_source.merge_corpus_registries).
|
|
||||||
collisions = corpus.collisions or {},
|
|
||||||
-- `check_macro_word_drift` reads `corpus.word_counts`, populated by word_count_eval.run.
|
|
||||||
word_counts = corpus.word_counts or {},
|
|
||||||
}
|
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Validate one source against its pre-scanned SourceScan payload + the corpus-wide pipe_ctx.
|
--- Validate one source against its pre-scanned SourceScan payload + the corpus-wide pipe_ctx.
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @param src SourceFile
|
--- @param src SourceFile
|
||||||
--- @param corpus_pipe_ctx PipeCtx|nil -- Built once per pass from corpus registries; nil builds the same projection here.
|
--- @param corpus_pipe_ctx PassScratch|nil -- Built once per pass from corpus registries; nil builds the same projection here.
|
||||||
--- @return AnnotatedResult
|
--- @return AnnotatedResult
|
||||||
local function validate(ctx, src, corpus_pipe_ctx)
|
local function validate(ctx, src, corpus_pipe_ctx)
|
||||||
corpus_pipe_ctx = corpus_pipe_ctx or build_corpus_pipe_ctx(ctx)
|
corpus_pipe_ctx = corpus_pipe_ctx or build_corpus_pipe_ctx(ctx)
|
||||||
local scan = src.scan
|
local scan = src.scan ---@type SourceScan
|
||||||
|
|
||||||
-- Project the pre-scanned atoms to the AtomEntry shape this pass needs.
|
|
||||||
local atoms = {}
|
|
||||||
for _, a in ipairs(scan.atoms) do
|
|
||||||
if a.kind == "atom" then
|
|
||||||
atoms[#atoms + 1] = { line = a.line, name = a.raw_name }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
-- Project the pre-scanned atom_infos to AtomAnnotation shape.
|
|
||||||
local annots = {}
|
|
||||||
for _, info in ipairs(scan.atom_infos) do
|
|
||||||
annots[#annots + 1] = {
|
|
||||||
line = info.info_line,
|
|
||||||
macro = "atom_info",
|
|
||||||
name = info.atom_name,
|
|
||||||
kind = "info",
|
|
||||||
binds = info.binds,
|
|
||||||
reads = info.reads or {},
|
|
||||||
writes = info.writes or {},
|
|
||||||
errors = info.errors,
|
|
||||||
}
|
|
||||||
end
|
|
||||||
|
|
||||||
-- Build a per-source pipe_ctx: shared lookups come from `corpus_pipe_ctx`, while declarations, bodies, types, views, defaults, and occurrences come from `src.scan`.
|
-- Build a per-source pipe_ctx: shared lookups come from `corpus_pipe_ctx`, while declarations, bodies, types, views, defaults, and occurrences come from `src.scan`.
|
||||||
local seen_defaults = {}; for reg, _ in pairs (scan.types or {}) do seen_defaults[reg] = (seen_defaults[reg] or 0) + 1 end
|
local seen_defaults = {}; for reg, _ in pairs (scan.types or {}) do seen_defaults[reg] = (seen_defaults[reg] or 0) + 1 end ---@type table<string, integer> -- bag: register ident -> occurrence count
|
||||||
local atom_infos_list = {}; for _, ai in ipairs(scan.atom_infos or {}) do atom_infos_list[#atom_infos_list + 1] = ai end
|
local atom_infos_list = {}; for _, ai in ipairs(scan.atom_infos or {}) do atom_infos_list[#atom_infos_list + 1] = ai end ---@type AtomInfoEntry[]
|
||||||
|
|
||||||
local pipe_ctx = {
|
local pipe_ctx = { ---@type PassScratch
|
||||||
atom_index = {},
|
atom_index = {},
|
||||||
binds_index = {},
|
binds_index = {},
|
||||||
annot_counts = corpus_pipe_ctx.annot_counts,
|
annot_counts = corpus_pipe_ctx.annot_counts,
|
||||||
@@ -515,70 +445,66 @@ local function validate(ctx, src, corpus_pipe_ctx)
|
|||||||
register_alias_registry = corpus_pipe_ctx.register_alias_registry,
|
register_alias_registry = corpus_pipe_ctx.register_alias_registry,
|
||||||
type_name_registry = corpus_pipe_ctx.type_name_registry,
|
type_name_registry = corpus_pipe_ctx.type_name_registry,
|
||||||
}
|
}
|
||||||
for _, a in ipairs(atoms) do pipe_ctx.atom_index [a.name] = a end
|
local atoms = {} ---@type AtomEntry[]
|
||||||
for _, b in ipairs(scan.binds) do pipe_ctx.binds_index[b.name] = b end
|
for _, a in ipairs(scan.atoms) do ---@type integer, AtomEntry
|
||||||
|
if a.kind == "atom" or a.kind == "atom_proc" then
|
||||||
|
atoms[#atoms + 1] = a
|
||||||
|
pipe_ctx.atom_index[a.raw_name or a.name] = a
|
||||||
|
end
|
||||||
|
end
|
||||||
|
for _, b in ipairs(scan.binds) do pipe_ctx.binds_index[b.name] = b end ---@type integer, BindsEntry
|
||||||
|
|
||||||
-- Findings live in a single struct with three lists (errors / warnings / info).
|
-- Findings live in a single struct with three lists (errors / warnings / info).
|
||||||
-- Each check writes to the list appropriate for its severity.
|
-- Each check writes to the list appropriate for its severity.
|
||||||
local findings = { errors = {}, warnings = {}, info = {} }
|
local findings = { errors = {}, warnings = {}, info = {} } ---@type Findings
|
||||||
|
|
||||||
-- Lift parse-time errors already recorded in scan_source's atom_info payload into this pass's findings list.
|
-- Lift parse-time errors already recorded in scan_source's atom_info payload into this pass's findings list.
|
||||||
for _, a in ipairs(annots) do
|
for _, info in ipairs(scan.atom_infos) do ---@type integer, AtomInfoEntry
|
||||||
if a.errors then
|
if info.errors then
|
||||||
for _, msg in ipairs(a.errors) do
|
for _, msg in ipairs(info.errors) do ---@type integer, string
|
||||||
findings.errors[#findings.errors + 1] = {
|
findings.errors[#findings.errors + 1] = {
|
||||||
line = a.line,
|
line = info.info_line,
|
||||||
msg = string.format("'%s': %s", a.name, msg),
|
msg = string.format("'%s': %s", info.atom_name, msg),
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
-- THE per-annotation pipeline. ONE loop. CHECK_RULES dispatches per_annot rules.
|
-- THE per-annotation pipeline. ONE loop. CHECK_RULES dispatches per_annot rules.
|
||||||
for _, a in ipairs(annots) do
|
for _, info in ipairs(scan.atom_infos) do ---@type integer, AtomInfoEntry
|
||||||
for _, rule in ipairs(CHECK_RULES) do
|
duffle.run_check_rules(CHECK_RULES, "per_annot", info, pipe_ctx, findings)
|
||||||
if rule.per_annot then rule.per_annot(a, pipe_ctx, findings) end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Post-loop rules (one-shot checks that need full-corpus aggregation in pipe_ctx).
|
-- Post-loop rules (one-shot checks that need full-corpus aggregation in pipe_ctx).
|
||||||
for _, rule in ipairs(CHECK_RULES) do
|
duffle.run_check_rules(CHECK_RULES, "post", nil, pipe_ctx, findings)
|
||||||
if rule.post then rule.post(pipe_ctx, findings) end
|
|
||||||
end
|
|
||||||
|
|
||||||
-- scan_source records each marker in scan.debug_skip_markers; this loop validates each record independently and emits at most one error per marker.
|
-- scan_source records each marker in scan.debug_skip_markers; this loop validates each record independently and emits at most one error per marker.
|
||||||
-- Valid markers stamp `debug_skip = true` on the following atom or component declaration, which downstream consumers read directly.
|
-- Valid markers stamp `debug_skip = true` on the following atom or component declaration, which downstream consumers read directly.
|
||||||
local skip_markers = scan.debug_skip_markers or {}
|
local skip_markers = scan.debug_skip_markers or {} ---@type DebugSkipMarker[]
|
||||||
for _, marker in ipairs(skip_markers) do
|
for _, marker in ipairs(skip_markers) do ---@type integer, DebugSkipMarker
|
||||||
for _, rule in ipairs(CHECK_RULES) do
|
duffle.run_check_rules(CHECK_RULES, "per_skip_marker", marker, pipe_ctx, findings)
|
||||||
if rule.per_skip_marker then rule.per_skip_marker(marker, pipe_ctx, findings) end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Per-macro rules (TAPE_WORDS vs WORD_COUNT drift).
|
-- Per-macro rules (TAPE_WORDS vs WORD_COUNT drift).
|
||||||
local wc = corpus_pipe_ctx.word_counts
|
pipe_ctx.word_counts = corpus_pipe_ctx.word_counts
|
||||||
for _, m in ipairs(scan.macros) do
|
for _, m in ipairs(scan.macros) do ---@type integer, MacroEntry
|
||||||
for _, rule in ipairs(CHECK_RULES) do
|
duffle.run_check_rules(CHECK_RULES, "per_macro", m, pipe_ctx, findings)
|
||||||
if rule.per_macro then rule.per_macro(m, wc, findings) end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Per-source rules (reg defaults, atom_view layout, compute-register type overrides, Binds_* field uniqueness).
|
-- Per-source rules (reg defaults, atom_view layout, compute-register type overrides, Binds_* field uniqueness).
|
||||||
-- Each per_source rule sees the full scan payload via pipe_ctx.
|
-- Each per_source rule sees the full scan payload via pipe_ctx.
|
||||||
for _, rule in ipairs(CHECK_RULES) do
|
duffle.run_check_rules(CHECK_RULES, "per_source", src, pipe_ctx, findings)
|
||||||
if rule.per_source then rule.per_source(src, pipe_ctx, findings) end
|
|
||||||
end
|
|
||||||
|
|
||||||
-- Information summary (always emitted).
|
-- Information summary (always emitted).
|
||||||
findings.info[#findings.info + 1] = {
|
findings.info[#findings.info + 1] = {
|
||||||
line = 0,
|
line = 0,
|
||||||
msg = string.format("scanned: %d atom(s), %d annotation(s), %d macro-word-decl(s), %d binds struct(s)"
|
msg = string.format("scanned: %d atom(s), %d annotation(s), %d macro-word-decl(s), %d binds struct(s)"
|
||||||
, #atoms, #annots, #scan.macros, #scan.binds),
|
, #atoms, #scan.atom_infos, #scan.macros, #scan.binds),
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
atoms = atoms,
|
atoms = atoms,
|
||||||
annots = annots,
|
annots = scan.atom_infos,
|
||||||
macros = scan.macros,
|
macros = scan.macros,
|
||||||
binds = scan.binds,
|
binds = scan.binds,
|
||||||
errors = findings.errors,
|
errors = findings.errors,
|
||||||
@@ -591,9 +517,7 @@ end
|
|||||||
-- M.run — orchestrator entry
|
-- M.run — orchestrator entry
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- @class M
|
local M = {} ---@type AnnotationPass
|
||||||
|
|
||||||
local M = {}
|
|
||||||
|
|
||||||
-- Expose `validate` for downstream passes (e.g. report.lua) that need to re-render the per-source results into a per-MODULE report.
|
-- Expose `validate` for downstream passes (e.g. report.lua) that need to re-render the per-source results into a per-MODULE report.
|
||||||
M.validate = validate
|
M.validate = validate
|
||||||
@@ -601,32 +525,32 @@ M.validate = validate
|
|||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @return PassResult
|
--- @return PassResult
|
||||||
function M.run(ctx)
|
function M.run(ctx)
|
||||||
local outputs = {}
|
local outputs = {} ---@type PassOutputEntry[]
|
||||||
local errors = {}
|
local errors = {} ---@type Finding[]
|
||||||
local warnings = {}
|
local warnings = {} ---@type Finding[]
|
||||||
|
|
||||||
-- Build the shared pipe_ctx once for this run; every validate() call sees the same cross-source registries.
|
-- Build the shared pipe_ctx once for this run; every validate() call sees the same cross-source registries.
|
||||||
-- The corpus owns the canonical cross-source registries; per-source scans retain body / declaration ownership.
|
-- The corpus owns the canonical cross-source registries; per-source scans retain body / declaration ownership.
|
||||||
local corpus_pipe_ctx = build_corpus_pipe_ctx(ctx)
|
local corpus_pipe_ctx = build_corpus_pipe_ctx(ctx) ---@type PassScratch
|
||||||
local corpus = ctx.shared.corpus
|
local corpus = ctx.shared.corpus ---@type Corpus
|
||||||
|
|
||||||
-- Group `corpus.sources_by_dir` by module, validate every source in each bucket, and emit one errors.h per directory.
|
-- Group `corpus.sources_by_dir` by module, validate every source in each bucket, and emit one errors.h per directory.
|
||||||
local by_dir = (corpus and corpus.sources_by_dir) or {}
|
local by_dir = (corpus and corpus.sources_by_dir) or {} ---@type table<string, SourceFile[]>
|
||||||
|
|
||||||
for dir, dir_sources in pairs(by_dir) do
|
for dir, dir_sources in pairs(by_dir) do ---@type string, SourceFile[]
|
||||||
local dir_basename = dir:match("([^/\\]+)$") or dir
|
local dir_basename = dir:match("([^/\\]+)$") or dir ---@type string
|
||||||
local dir_atoms = 0
|
local dir_atoms = 0 ---@type integer
|
||||||
local dir_errors = {}
|
local dir_errors = {} ---@type Finding[]
|
||||||
local dir_warnings = {}
|
local dir_warnings = {} ---@type Finding[]
|
||||||
for _, src in ipairs(dir_sources) do
|
for _, src in ipairs(dir_sources) do ---@type integer, SourceFile
|
||||||
local result = validate(ctx, src, corpus_pipe_ctx)
|
local result = validate(ctx, src, corpus_pipe_ctx) ---@type AnnotatedResult
|
||||||
result.source = src.path -- tag for downstream rendering
|
result.source = src.path -- tag for downstream rendering
|
||||||
dir_atoms = dir_atoms + #result.atoms
|
dir_atoms = dir_atoms + #result.atoms
|
||||||
for _, e in ipairs(result.errors) do
|
for _, e in ipairs(result.errors) do ---@type integer, Finding
|
||||||
dir_errors[#dir_errors + 1] = { line = e.line, msg = e.msg, source = src.path }
|
dir_errors[#dir_errors + 1] = { line = e.line, msg = e.msg, source = src.path }
|
||||||
errors [#errors + 1] = { line = e.line, msg = e.msg }
|
errors [#errors + 1] = { line = e.line, msg = e.msg }
|
||||||
end
|
end
|
||||||
for _, w in ipairs(result.warnings) do
|
for _, w in ipairs(result.warnings) do ---@type integer, Finding
|
||||||
dir_warnings[#dir_warnings + 1] = { line = w.line, msg = w.msg }
|
dir_warnings[#dir_warnings + 1] = { line = w.line, msg = w.msg }
|
||||||
warnings [#warnings + 1] = { line = w.line, msg = w.msg }
|
warnings [#warnings + 1] = { line = w.line, msg = w.msg }
|
||||||
end
|
end
|
||||||
|
|||||||
+166
-108
@@ -37,9 +37,9 @@
|
|||||||
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source`
|
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source`
|
||||||
-- (works both standalone + when require'd). `duffle_paths.lua` sets package.path then returns `require("duffle")`
|
-- (works both standalone + when require'd). `duffle_paths.lua` sets package.path then returns `require("duffle")`
|
||||||
-- at the bottom, so the dofile value IS the duffle module.
|
-- at the bottom, so the dofile value IS the duffle module.
|
||||||
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
|
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" ---@type string
|
||||||
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") ---@type DuffleExport
|
||||||
local elf_dwarf = require("elf_dwarf")
|
local elf_dwarf = require("elf_dwarf") ---@type ElfDwarfMod
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Constants
|
-- Constants
|
||||||
@@ -47,42 +47,78 @@ local elf_dwarf = require("elf_dwarf")
|
|||||||
|
|
||||||
-- Format version emitted as the first line. Bump + add a migration test if the format changes;
|
-- Format version emitted as the first line. Bump + add a migration test if the format changes;
|
||||||
-- the gdb runtime loader rejects mismatches (E2).
|
-- the gdb runtime loader rejects mismatches (E2).
|
||||||
local FORMAT_VERSION = 1
|
local FORMAT_VERSION = 1 ---@type integer
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Type declarations
|
-- Type declarations
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- @class AtomSourceMapCtx
|
--- @class AtomSourceMapCtx
|
||||||
--- @field shared table -- `ctx.shared`
|
--- @field shared PassShared
|
||||||
--- @field shared.corpus table -- source-order registry; single writer is build_ctx
|
--- @field out_root string
|
||||||
--- @field shared.word_counts table
|
--- @field flags PassFlags
|
||||||
--- @field out_root string -- output root (e.g. "build/gen")
|
--- @field project_root string|nil
|
||||||
--- @field flags table -- `ctx.flags`; reads `flags.gdb_runtime` + `flags.elf_path`
|
|
||||||
|
--- @class WordMapEntry
|
||||||
|
--- @field pos integer
|
||||||
|
--- @field line integer
|
||||||
|
--- @field text string
|
||||||
|
--- @field body_line integer
|
||||||
|
--- @field gpr_keys string[]|nil
|
||||||
|
--- @field invocation InvocationRecord|nil
|
||||||
|
|
||||||
|
--- @class NmAddr
|
||||||
|
--- @field [1] integer -- st_value
|
||||||
|
--- @field [2] integer -- st_size
|
||||||
|
|
||||||
|
--- @class GdbAtomRecord
|
||||||
|
--- @field idx integer|nil
|
||||||
|
--- @field name string
|
||||||
|
--- @field src_path string
|
||||||
|
--- @field file_base string
|
||||||
|
--- @field addr integer
|
||||||
|
--- @field size_bytes integer
|
||||||
|
--- @field words integer
|
||||||
|
--- @field entries WordMapEntry[]
|
||||||
|
|
||||||
|
--- @class ElfDwarfMod
|
||||||
|
--- @field read_nm fun(elf_path: Path): table<string, NmAddr>
|
||||||
|
|
||||||
|
--- @class AtomSourceMapPass
|
||||||
|
--- @field render_source_map fun(src: SourceFile): string
|
||||||
|
--- @field render_provenance fun(src: SourceFile, wc: WordCounts): string
|
||||||
|
--- @field render_atom_source_map fun(atom: AtomEntry): string
|
||||||
|
--- @field render_atom_provenance fun(atom: AtomEntry, wc: WordCounts, rel_path: string): string
|
||||||
|
--- @field run fun(ctx: PassCtx): PassResult
|
||||||
|
|
||||||
|
--- @class AtomEntry
|
||||||
|
--- @field paths AtomPaths|nil
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Atom-path renderers
|
-- Atom-path renderers
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- Join word boundaries (from `items`) to per-word call text + source lines (from `word_events`).
|
--- Join word boundaries (from `items`) to per-word call text + source lines (from `word_events`).
|
||||||
--- @param atom table
|
--- @param atom AtomEntry
|
||||||
--- @return table[], integer
|
--- @return WordMapEntry[]
|
||||||
|
--- @return integer
|
||||||
local function canonical_word_entries(atom)
|
local function canonical_word_entries(atom)
|
||||||
local paths = atom.paths or {}
|
local paths = atom.paths or {} ---@type AtomPaths
|
||||||
local events = paths.word_events or {}
|
local events = paths.word_events or {} ---@type WordEvent[]
|
||||||
local word_items = {}
|
local word_items = {} ---@type EmissionItem[]
|
||||||
for _, item in ipairs(paths.items or {}) do
|
for _, item in ipairs(paths.items or {}) do ---@type integer, EmissionItem
|
||||||
if item.kind == "word" then word_items[#word_items + 1] = item end
|
if item.kind == "word" then word_items[#word_items + 1] = item end
|
||||||
end
|
end
|
||||||
|
|
||||||
local entries = {}
|
local entries = {} ---@type WordMapEntry[]
|
||||||
for index, event in ipairs(events) do
|
for index, event in ipairs(events) do ---@type integer, WordEvent
|
||||||
local item = word_items[index] or {}
|
local item = word_items[index] or {} ---@type EmissionItem
|
||||||
entries[#entries + 1] = {
|
entries[#entries + 1] = {
|
||||||
pos = event.i or (index - 1),
|
pos = event.i or (index - 1),
|
||||||
line = event.call_line or item.line or 0,
|
line = event.call_line or item.line or 0,
|
||||||
text = event.call_text or item.call_text or "",
|
text = event.call_text or item.call_text or "",
|
||||||
body_line = event.body_line or item.body_line or item.line or 0,
|
body_line = event.body_line or item.body_line or item.line or 0,
|
||||||
|
gpr_keys = event.gpr_keys,
|
||||||
invocation = (event.outermost_invocation_id
|
invocation = (event.outermost_invocation_id
|
||||||
and paths.invocations
|
and paths.invocations
|
||||||
and paths.invocations[event.outermost_invocation_id]) or nil,
|
and paths.invocations[event.outermost_invocation_id]) or nil,
|
||||||
@@ -96,19 +132,20 @@ end
|
|||||||
--- `WORD N CALL <src-path>:<src-line> RAW` (raw `.word` outside any mac_* component)
|
--- `WORD N CALL <src-path>:<src-line> RAW` (raw `.word` outside any mac_* component)
|
||||||
--- Component identity comes from the outermost invocation record; the count-table lookup confirms the component was declared in `corpus.word_counts`
|
--- Component identity comes from the outermost invocation record; the count-table lookup confirms the component was declared in `corpus.word_counts`
|
||||||
--- (populated by word_count_eval + components passes).
|
--- (populated by word_count_eval + components passes).
|
||||||
--- @param src table
|
--- @param src SourceFile
|
||||||
--- @param atom table
|
--- @param atom AtomEntry
|
||||||
--- @param wc table -- identity alias of corpus.word_counts
|
--- @param wc WordCounts
|
||||||
--- @return string[], integer
|
--- @return string[]
|
||||||
|
--- @return integer
|
||||||
local function emit_provenance_stanza(src, atom, wc)
|
local function emit_provenance_stanza(src, atom, wc)
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
local rel_path = src.path:gsub("\\\\", "/")
|
local rel_path = src.path:gsub("\\\\", "/") ---@type string
|
||||||
local entries, total = canonical_word_entries(atom)
|
local entries, total = canonical_word_entries(atom) ---@type WordMapEntry[], integer
|
||||||
lines[#lines + 1] = string.format('ATOM %s "%s" 0', atom.raw_name or atom.name, rel_path)
|
lines[#lines + 1] = string.format('ATOM %s "%s" 0', atom.raw_name or atom.name, rel_path)
|
||||||
|
|
||||||
for _, entry in ipairs(entries) do
|
for _, entry in ipairs(entries) do ---@type integer, WordMapEntry
|
||||||
local inv = entry.invocation
|
local inv = entry.invocation ---@type InvocationRecord|nil
|
||||||
local macro_count = inv and wc["mac_" .. inv.component_name]
|
local macro_count = inv and wc["mac_" .. inv.component_name] ---@type integer|nil
|
||||||
if inv and macro_count ~= nil then
|
if inv and macro_count ~= nil then
|
||||||
lines[#lines + 1] = string.format('WORD %d CALL %s:%d MACRO %s "%s:%d" BODY %d'
|
lines[#lines + 1] = string.format('WORD %d CALL %s:%d MACRO %s "%s:%d" BODY %d'
|
||||||
, entry.pos, rel_path, entry.line, inv.component_name
|
, entry.pos, rel_path, entry.line, inv.component_name
|
||||||
@@ -124,11 +161,11 @@ local function emit_provenance_stanza(src, atom, wc)
|
|||||||
end
|
end
|
||||||
|
|
||||||
--- Render the full provenance file content for one source.
|
--- Render the full provenance file content for one source.
|
||||||
--- @param src table
|
--- @param src SourceFile
|
||||||
--- @param wc table
|
--- @param wc WordCounts
|
||||||
--- @return string
|
--- @return string
|
||||||
local function render_provenance(src, wc)
|
local function render_provenance(src, wc)
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
lines[#lines + 1] = "# FORMAT_VERSION 1"
|
lines[#lines + 1] = "# FORMAT_VERSION 1"
|
||||||
lines[#lines + 1] = "# auto-generated by ps1_meta.lua (passes/atoms_source_map.lua) — DO NOT EDIT"
|
lines[#lines + 1] = "# auto-generated by ps1_meta.lua (passes/atoms_source_map.lua) — DO NOT EDIT"
|
||||||
lines[#lines + 1] = "# Per-.word provenance: maps each emitted .word to its call site (atom body"
|
lines[#lines + 1] = "# Per-.word provenance: maps each emitted .word to its call site (atom body"
|
||||||
@@ -137,14 +174,16 @@ local function render_provenance(src, wc)
|
|||||||
lines[#lines + 1] = "# dwarf_injection to synthesize DW_TAG_inlined_subroutine instances + per-word"
|
lines[#lines + 1] = "# dwarf_injection to synthesize DW_TAG_inlined_subroutine instances + per-word"
|
||||||
lines[#lines + 1] = "# line program rows for native source-level step into component bodies."
|
lines[#lines + 1] = "# line program rows for native source-level step into component bodies."
|
||||||
|
|
||||||
|
--- @param atom AtomEntry
|
||||||
|
--- @return nil
|
||||||
local function append(atom)
|
local function append(atom)
|
||||||
local stanza = emit_provenance_stanza(src, atom, wc)
|
local stanza = emit_provenance_stanza(src, atom, wc) ---@type string[]
|
||||||
for _, line in ipairs(stanza) do lines[#lines + 1] = line end
|
for _, line in ipairs(stanza) do lines[#lines + 1] = line end ---@type integer, string
|
||||||
end
|
end
|
||||||
for _, atom in ipairs(src.scan.atoms or {}) do
|
for _, atom in ipairs(src.scan.atoms or {}) do ---@type integer, AtomEntry
|
||||||
if atom.paths then append(atom) end
|
if atom.paths then append(atom) end
|
||||||
end
|
end
|
||||||
for _, atom in ipairs(src.scan.raw_atoms or {}) do
|
for _, atom in ipairs(src.scan.raw_atoms or {}) do ---@type integer, AtomEntry
|
||||||
if atom.paths then append(atom) end
|
if atom.paths then append(atom) end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -153,17 +192,17 @@ end
|
|||||||
|
|
||||||
--- Render one atom's stanza for the sourcemap.txt form (ATOM header line, N WORD lines, ENDATOM marker).
|
--- Render one atom's stanza for the sourcemap.txt form (ATOM header line, N WORD lines, ENDATOM marker).
|
||||||
--- Returns (lines, total_words).
|
--- Returns (lines, total_words).
|
||||||
--- @param src table
|
--- @param src SourceFile
|
||||||
--- @param atom table
|
--- @param atom AtomEntry
|
||||||
--- @param wc table
|
--- @return string[]
|
||||||
--- @return string[], integer
|
--- @return integer
|
||||||
local function emit_atom_stanza(src, atom)
|
local function emit_atom_stanza(src, atom)
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
local rel_path = src.path:gsub("\\\\", "/")
|
local rel_path = src.path:gsub("\\\\", "/") ---@type string
|
||||||
local entries, total = canonical_word_entries(atom)
|
local entries, total = canonical_word_entries(atom) ---@type WordMapEntry[], integer
|
||||||
|
|
||||||
lines[#lines + 1] = string.format('ATOM %s "%s" 0', atom.raw_name or atom.name, rel_path)
|
lines[#lines + 1] = string.format('ATOM %s "%s" 0', atom.raw_name or atom.name, rel_path)
|
||||||
for _, entry in ipairs(entries) do
|
for _, entry in ipairs(entries) do ---@type integer, WordMapEntry
|
||||||
lines[#lines + 1] = string.format("WORD %d LINE %d TEXT %s",
|
lines[#lines + 1] = string.format("WORD %d LINE %d TEXT %s",
|
||||||
entry.pos, entry.line, entry.text)
|
entry.pos, entry.line, entry.text)
|
||||||
end
|
end
|
||||||
@@ -174,22 +213,23 @@ end
|
|||||||
|
|
||||||
--- Render the full source map file content for one source (one .atoms.sourcemap.txt per source). Mirrors offsets.lua's
|
--- Render the full source map file content for one source (one .atoms.sourcemap.txt per source). Mirrors offsets.lua's
|
||||||
--- `project_atoms` shape: scan.atoms + scan.raw_atoms, no kind filter.
|
--- `project_atoms` shape: scan.atoms + scan.raw_atoms, no kind filter.
|
||||||
--- @param src table
|
--- @param src SourceFile
|
||||||
--- @param wc table
|
|
||||||
--- @return string
|
--- @return string
|
||||||
local function render_source_map(src)
|
local function render_source_map(src)
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
lines[#lines + 1] = "# FORMAT_VERSION " .. FORMAT_VERSION
|
lines[#lines + 1] = "# FORMAT_VERSION " .. FORMAT_VERSION
|
||||||
lines[#lines + 1] = "# auto-generated by ps1_meta.lua (passes/atoms_source_map.lua) — DO NOT EDIT"
|
lines[#lines + 1] = "# auto-generated by ps1_meta.lua (passes/atoms_source_map.lua) — DO NOT EDIT"
|
||||||
|
|
||||||
|
--- @param atom AtomEntry
|
||||||
|
--- @return nil
|
||||||
local function append(atom)
|
local function append(atom)
|
||||||
local stanza = emit_atom_stanza(src, atom)
|
local stanza = emit_atom_stanza(src, atom) ---@type string[]
|
||||||
for _, line in ipairs(stanza) do lines[#lines + 1] = line end
|
for _, line in ipairs(stanza) do lines[#lines + 1] = line end ---@type integer, string
|
||||||
end
|
end
|
||||||
for _, atom in ipairs(src.scan.atoms or {}) do
|
for _, atom in ipairs(src.scan.atoms or {}) do ---@type integer, AtomEntry
|
||||||
if atom.paths then append(atom) end
|
if atom.paths then append(atom) end
|
||||||
end
|
end
|
||||||
for _, atom in ipairs(src.scan.raw_atoms or {}) do
|
for _, atom in ipairs(src.scan.raw_atoms or {}) do ---@type integer, AtomEntry
|
||||||
if atom.paths then append(atom) end
|
if atom.paths then append(atom) end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -210,20 +250,22 @@ end
|
|||||||
|
|
||||||
--- Build the list of atoms with addresses + word entries. Shared helper for the gdb-runtime file emission.
|
--- Build the list of atoms with addresses + word entries. Shared helper for the gdb-runtime file emission.
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @return table[] -- list of {idx, name, src_path, file_base, addr, size_bytes, words, entries}
|
--- @return GdbAtomRecord[]
|
||||||
local function build_atom_table(ctx)
|
local function build_atom_table(ctx)
|
||||||
local addrs = elf_dwarf.read_nm(ctx.flags.elf_path)
|
local addrs = elf_dwarf.read_nm(ctx.flags.elf_path) ---@type table<string, NmAddr>
|
||||||
local corpus = ctx.shared and ctx.shared.corpus
|
local corpus = ctx.shared and ctx.shared.corpus ---@type Corpus|nil
|
||||||
local matched = {}
|
local matched = {} ---@type GdbAtomRecord[]
|
||||||
|
|
||||||
for _, src in ipairs(corpus.source_order or {}) do
|
for _, src in ipairs(corpus.source_order or {}) do ---@type integer, SourceFile
|
||||||
local file_base = src.path:match("([^/\\\\]+)$") or src.path
|
local file_base = src.path:match("([^/\\\\]+)$") or src.path ---@type string
|
||||||
|
--- @param atom AtomEntry
|
||||||
|
--- @return nil
|
||||||
local function append(atom)
|
local function append(atom)
|
||||||
if not atom.paths then return end
|
if not atom.paths then return end
|
||||||
local name = atom.raw_name or atom.name
|
local name = atom.raw_name or atom.name ---@type string
|
||||||
local info = addrs[name]
|
local info = addrs[name] ---@type NmAddr|nil
|
||||||
if not info then return end
|
if not info then return end
|
||||||
local entries, total = canonical_word_entries(atom)
|
local entries, total = canonical_word_entries(atom) ---@type WordMapEntry[], integer
|
||||||
matched[#matched + 1] = {
|
matched[#matched + 1] = {
|
||||||
name = name,
|
name = name,
|
||||||
src_path = src.path,
|
src_path = src.path,
|
||||||
@@ -234,13 +276,16 @@ local function build_atom_table(ctx)
|
|||||||
entries = entries,
|
entries = entries,
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
for _, atom in ipairs((src.scan or {}).atoms or {}) do append(atom) end
|
for _, atom in ipairs((src.scan or {}).atoms or {}) do append(atom) end ---@type integer, AtomEntry
|
||||||
for _, atom in ipairs((src.scan or {}).raw_atoms or {}) do append(atom) end
|
for _, atom in ipairs((src.scan or {}).raw_atoms or {}) do append(atom) end ---@type integer, AtomEntry
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Deterministic order: sort by address (matches `nm` output ordering).
|
-- Deterministic order: sort by address (matches `nm` output ordering).
|
||||||
|
--- @param a GdbAtomRecord
|
||||||
|
--- @param b GdbAtomRecord
|
||||||
|
--- @return boolean
|
||||||
table.sort(matched, function(a, b) return a.addr < b.addr end)
|
table.sort(matched, function(a, b) return a.addr < b.addr end)
|
||||||
for i, a in ipairs(matched) do a.idx = i - 1 end
|
for i, a in ipairs(matched) do a.idx = i - 1 end ---@type integer, GdbAtomRecord
|
||||||
return matched
|
return matched
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -251,28 +296,29 @@ end
|
|||||||
---
|
---
|
||||||
--- Why hardcoded per-atom: gdb's `$` substitution doesn't concat inside var names — `$__atom_name_$__i` in a `while`
|
--- Why hardcoded per-atom: gdb's `$` substitution doesn't concat inside var names — `$__atom_name_$__i` in a `while`
|
||||||
--- loop resolves to one literal identifier, not `name_i`. Compile-time emission is the only path.
|
--- loop resolves to one literal identifier, not `name_i`. Compile-time emission is the only path.
|
||||||
--- @param lines table -- output line buffer (mutated in place)
|
--- @param lines string[]
|
||||||
--- @param matched table -- list of atom records from `build_atom_table`
|
--- @param matched GdbAtomRecord[]
|
||||||
|
--- @return nil
|
||||||
local function append_gdb_commands(lines, matched)
|
local function append_gdb_commands(lines, matched)
|
||||||
-- ── tape_atoms ──
|
-- ── tape_atoms ──
|
||||||
-- Hardcoded one printf per atom. No loop.
|
-- Hardcoded one printf per atom. No loop.
|
||||||
lines[#lines + 1] = "define tape_atoms"
|
lines[#lines + 1] = "define tape_atoms"
|
||||||
for _, a in ipairs(matched) do
|
for _, a in ipairs(matched) do ---@type integer, GdbAtomRecord
|
||||||
-- gdb 12.1 quirk: literals in printf args require an attached target.
|
-- gdb 12.1 quirk: literals in printf args require an attached target.
|
||||||
-- Use the per-atom convenience vars set above as printf args.
|
-- Use the per-atom convenience vars set above as printf args.
|
||||||
lines[#lines + 1] = string.format(' printf " code_%%-32s @ 0x%%08x %%4d words\\n", $__atom_name_%d, $__atom_addr_%d, $__atom_words_%d',
|
lines[#lines + 1] = string.format(' printf " %%-32s @ 0x%%08x %%4d words\\n", $__atom_name_%d, $__atom_addr_%d, $__atom_words_%d',
|
||||||
a.idx, a.idx, a.idx)
|
a.idx, a.idx, a.idx)
|
||||||
end
|
end
|
||||||
lines[#lines + 1] = "end"
|
lines[#lines + 1] = "end"
|
||||||
lines[#lines + 1] = "document tape_atoms"
|
lines[#lines + 1] = "document tape_atoms"
|
||||||
lines[#lines + 1] = " List every tape atom symbol in the loaded ELF (code_<name>) with .rodata addr + word count."
|
lines[#lines + 1] = " List every tape atom symbol in the loaded ELF with .rodata addr + word count."
|
||||||
lines[#lines + 1] = "end"
|
lines[#lines + 1] = "end"
|
||||||
lines[#lines + 1] = ""
|
lines[#lines + 1] = ""
|
||||||
|
|
||||||
-- ── break_atom (generic) + per-atom break_atom_X ──
|
-- ── break_atom (generic) + per-atom break_atom_X ──
|
||||||
lines[#lines + 1] = "define break_atom"
|
lines[#lines + 1] = "define break_atom"
|
||||||
lines[#lines + 1] = ' echo "Usage: break_atom_<exact_name> (pick from the list below)"'
|
lines[#lines + 1] = ' echo "Usage: break_atom_<exact_name> (pick from the list below)"'
|
||||||
for _, a in ipairs(matched) do
|
for _, a in ipairs(matched) do ---@type integer, GdbAtomRecord
|
||||||
lines[#lines + 1] = string.format(' printf " break_atom_%%-32s\\n", $__atom_name_%d', a.idx)
|
lines[#lines + 1] = string.format(' printf " break_atom_%%-32s\\n", $__atom_name_%d', a.idx)
|
||||||
end
|
end
|
||||||
lines[#lines + 1] = "end"
|
lines[#lines + 1] = "end"
|
||||||
@@ -281,13 +327,13 @@ local function append_gdb_commands(lines, matched)
|
|||||||
lines[#lines + 1] = "end"
|
lines[#lines + 1] = "end"
|
||||||
lines[#lines + 1] = ""
|
lines[#lines + 1] = ""
|
||||||
|
|
||||||
for _, a in ipairs(matched) do
|
for _, a in ipairs(matched) do ---@type integer, GdbAtomRecord
|
||||||
lines[#lines + 1] = string.format("define break_atom_%s", a.name)
|
lines[#lines + 1] = string.format("define break_atom_%s", a.name)
|
||||||
lines[#lines + 1] = string.format(" break *$__atom_addr_%d", a.idx)
|
lines[#lines + 1] = string.format(" break *$__atom_addr_%d", a.idx)
|
||||||
lines[#lines + 1] = string.format(' printf " Breakpoint set at code_%s (0x%%08x)\\n", $__atom_addr_%d', a.name, a.idx)
|
lines[#lines + 1] = string.format(' printf " Breakpoint set at %s (0x%%08x)\\n", $__atom_addr_%d', a.name, a.idx)
|
||||||
lines[#lines + 1] = "end"
|
lines[#lines + 1] = "end"
|
||||||
lines[#lines + 1] = string.format("document break_atom_%s", a.name)
|
lines[#lines + 1] = string.format("document break_atom_%s", a.name)
|
||||||
lines[#lines + 1] = string.format(" Set a breakpoint at code_%s.", a.name)
|
lines[#lines + 1] = string.format(" Set a breakpoint at %s.", a.name)
|
||||||
lines[#lines + 1] = "end"
|
lines[#lines + 1] = "end"
|
||||||
lines[#lines + 1] = ""
|
lines[#lines + 1] = ""
|
||||||
end
|
end
|
||||||
@@ -295,7 +341,7 @@ local function append_gdb_commands(lines, matched)
|
|||||||
-- ── step_atom / next_atom ──
|
-- ── step_atom / next_atom ──
|
||||||
-- Hardcoded one tbreak per atom. No loop.
|
-- Hardcoded one tbreak per atom. No loop.
|
||||||
lines[#lines + 1] = "define step_atom"
|
lines[#lines + 1] = "define step_atom"
|
||||||
for _, a in ipairs(matched) do
|
for _, a in ipairs(matched) do ---@type integer, GdbAtomRecord
|
||||||
lines[#lines + 1] = string.format(" tbreak *$__atom_addr_%d", a.idx)
|
lines[#lines + 1] = string.format(" tbreak *$__atom_addr_%d", a.idx)
|
||||||
end
|
end
|
||||||
lines[#lines + 1] = " continue"
|
lines[#lines + 1] = " continue"
|
||||||
@@ -318,24 +364,24 @@ local function append_gdb_commands(lines, matched)
|
|||||||
lines[#lines + 1] = "define where_in_atom"
|
lines[#lines + 1] = "define where_in_atom"
|
||||||
lines[#lines + 1] = " set $__pc = (unsigned int)$pc"
|
lines[#lines + 1] = " set $__pc = (unsigned int)$pc"
|
||||||
lines[#lines + 1] = " set $__matched = 0"
|
lines[#lines + 1] = " set $__matched = 0"
|
||||||
for _, a in ipairs(matched) do
|
for _, a in ipairs(matched) do ---@type integer, GdbAtomRecord
|
||||||
-- Precompute end_addr (gdb 12.1's expression evaluator chokes on `addr + words*4`).
|
-- Precompute end_addr (gdb 12.1's expression evaluator chokes on `addr + words*4`).
|
||||||
lines[#lines + 1] = string.format(" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
|
lines[#lines + 1] = string.format(" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
|
||||||
lines[#lines + 1] = string.format(" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
|
lines[#lines + 1] = string.format(" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
|
||||||
lines[#lines + 1] = string.format(' printf "atom: code_%%s\\n", $__atom_name_%d', a.idx)
|
lines[#lines + 1] = string.format(' printf "atom: %%s\\n", $__atom_name_%d', a.idx)
|
||||||
lines[#lines + 1] = ' printf "addr: 0x%08x\\n", $__pc'
|
lines[#lines + 1] = ' printf "addr: 0x%08x\\n", $__pc'
|
||||||
lines[#lines + 1] = string.format(" set $__word = ($__pc - $__atom_addr_%d) / 4", a.idx)
|
lines[#lines + 1] = string.format(" set $__word = ($__pc - $__atom_addr_%d) / 4", a.idx)
|
||||||
lines[#lines + 1] = string.format(' printf "word: %%d/%%d\\n", $__word, $__atom_words_%d', a.idx)
|
lines[#lines + 1] = string.format(' printf "word: %%d/%%d\\n", $__word, $__atom_words_%d', a.idx)
|
||||||
-- One inner-if per WORD entry. Each word's line + text hardcoded.
|
-- One inner-if per WORD entry. Each word's line + text hardcoded.
|
||||||
for _, we in ipairs(a.entries) do
|
for _, we in ipairs(a.entries) do ---@type integer, WordMapEntry
|
||||||
lines[#lines + 1] = string.format(" if $__word == %d", we.pos)
|
lines[#lines + 1] = string.format(" if $__word == %d", we.pos)
|
||||||
-- Escape TEXT for printf format string.
|
-- Escape TEXT for printf format string.
|
||||||
local escaped_text = we.text:gsub("%%", "%%%%"):gsub('"', '\\"')
|
local escaped_text = we.text:gsub("%%", "%%%%"):gsub('"', '\\"') ---@type string
|
||||||
lines[#lines + 1] = string.format(' printf "source: %%s:%%d %%s\\n", $__atom_file_%d, %d, "%s"', a.idx, we.line, escaped_text)
|
lines[#lines + 1] = string.format(' printf "source: %%s:%%d %%s\\n", $__atom_file_%d, %d, "%s"', a.idx, we.line, escaped_text)
|
||||||
lines[#lines + 1] = " end"
|
lines[#lines + 1] = " end"
|
||||||
end
|
end
|
||||||
-- Fallback for words beyond the source map (shouldn't happen if nm matches).
|
-- Fallback for words beyond the source map (shouldn't happen if nm matches).
|
||||||
local max_word = 0
|
local max_word = 0 ---@type integer
|
||||||
if #a.entries > 0 then max_word = a.entries[#a.entries].pos end
|
if #a.entries > 0 then max_word = a.entries[#a.entries].pos end
|
||||||
lines[#lines + 1] = string.format(' if $__word > %d', max_word)
|
lines[#lines + 1] = string.format(' if $__word > %d', max_word)
|
||||||
lines[#lines + 1] = ' printf "source: (no source-map entry for word %%d; map may be stale)\\n", $__word'
|
lines[#lines + 1] = ' printf "source: (no source-map entry for word %%d; map may be stale)\\n", $__word'
|
||||||
@@ -360,7 +406,7 @@ local function append_gdb_commands(lines, matched)
|
|||||||
lines[#lines + 1] = " set $__in_atom = 0"
|
lines[#lines + 1] = " set $__in_atom = 0"
|
||||||
lines[#lines + 1] = " set $__did_step = 0"
|
lines[#lines + 1] = " set $__did_step = 0"
|
||||||
lines[#lines + 1] = " set $__pc = (unsigned int)$pc"
|
lines[#lines + 1] = " set $__pc = (unsigned int)$pc"
|
||||||
for _, a in ipairs(matched) do
|
for _, a in ipairs(matched) do ---@type integer, GdbAtomRecord
|
||||||
-- Precompute end_addr in the convenience var (single expression gdb handles).
|
-- Precompute end_addr in the convenience var (single expression gdb handles).
|
||||||
lines[#lines + 1] = string.format(" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
|
lines[#lines + 1] = string.format(" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
|
||||||
lines[#lines + 1] = string.format(" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
|
lines[#lines + 1] = string.format(" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
|
||||||
@@ -394,9 +440,10 @@ end
|
|||||||
--- Emit the gdb-runtime file (post-link). Pure gdb scripting — addresses come from `mipsel-none-elf-nm -S`, get embedded
|
--- Emit the gdb-runtime file (post-link). Pure gdb scripting — addresses come from `mipsel-none-elf-nm -S`, get embedded
|
||||||
--- in `<ctx.out_root>/gdb_tape_atoms_runtime.gdb`, and load via `set $var = ...` + `define ... end` blocks at gdb source-time.
|
--- in `<ctx.out_root>/gdb_tape_atoms_runtime.gdb`, and load via `set $var = ...` + `define ... end` blocks at gdb source-time.
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
|
--- @return nil
|
||||||
local function emit_gdb_runtime(ctx)
|
local function emit_gdb_runtime(ctx)
|
||||||
if not (ctx.flags and ctx.flags.gdb_runtime) then return end
|
if not (ctx.flags and ctx.flags.gdb_runtime) then return end
|
||||||
local elf_path = ctx.flags.elf_path
|
local elf_path = ctx.flags.elf_path ---@type string|nil
|
||||||
if not elf_path or elf_path == "" then
|
if not elf_path or elf_path == "" then
|
||||||
io.stderr:write("[atoms_source_map] --gdb-runtime requires --elf <elf>\n")
|
io.stderr:write("[atoms_source_map] --gdb-runtime requires --elf <elf>\n")
|
||||||
return
|
return
|
||||||
@@ -407,13 +454,13 @@ local function emit_gdb_runtime(ctx)
|
|||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
local matched = build_atom_table(ctx)
|
local matched = build_atom_table(ctx) ---@type GdbAtomRecord[]
|
||||||
if #matched == 0 then
|
if #matched == 0 then
|
||||||
io.stderr:write("[atoms_source_map] --gdb-runtime: no atoms matched against nm symbols (stale scan?).\n")
|
io.stderr:write("[atoms_source_map] --gdb-runtime: no atoms matched against nm symbols (stale scan?).\n")
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
|
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
lines[#lines + 1] = "# Auto-generated by ps1_meta.lua (passes/atoms_source_map.lua)"
|
lines[#lines + 1] = "# Auto-generated by ps1_meta.lua (passes/atoms_source_map.lua)"
|
||||||
lines[#lines + 1] = "# DO NOT EDIT — re-run ps1_meta.lua --atoms-source-map --gdb-runtime to regenerate"
|
lines[#lines + 1] = "# DO NOT EDIT — re-run ps1_meta.lua --atoms-source-map --gdb-runtime to regenerate"
|
||||||
lines[#lines + 1] = "# Sourced by scripts/gdb/gdb_tape_atoms.gdb (the wrapper)."
|
lines[#lines + 1] = "# Sourced by scripts/gdb/gdb_tape_atoms.gdb (the wrapper)."
|
||||||
@@ -434,7 +481,7 @@ local function emit_gdb_runtime(ctx)
|
|||||||
|
|
||||||
-- Per-atom convenience vars (used as printf args; literals aren't accepted
|
-- Per-atom convenience vars (used as printf args; literals aren't accepted
|
||||||
-- without an attached target on gdb 12.1).
|
-- without an attached target on gdb 12.1).
|
||||||
for _, a in ipairs(matched) do
|
for _, a in ipairs(matched) do ---@type integer, GdbAtomRecord
|
||||||
lines[#lines + 1] = string.format('set $__atom_name_%d = "%s"', a.idx, gdb_escape(a.name))
|
lines[#lines + 1] = string.format('set $__atom_name_%d = "%s"', a.idx, gdb_escape(a.name))
|
||||||
lines[#lines + 1] = string.format("set $__atom_addr_%d = 0x%x", a.idx, a.addr)
|
lines[#lines + 1] = string.format("set $__atom_addr_%d = 0x%x", a.idx, a.addr)
|
||||||
lines[#lines + 1] = string.format("set $__atom_words_%d = %d", a.idx, a.words)
|
lines[#lines + 1] = string.format("set $__atom_words_%d = %d", a.idx, a.words)
|
||||||
@@ -450,10 +497,12 @@ local function emit_gdb_runtime(ctx)
|
|||||||
-- Confirmation line for the source operator.
|
-- Confirmation line for the source operator.
|
||||||
lines[#lines + 1] = 'printf "[gdb_tape_atoms] runtime loaded %d atoms from %s\\n", $__atom_count, $__elf_path'
|
lines[#lines + 1] = 'printf "[gdb_tape_atoms] runtime loaded %d atoms from %s\\n", $__atom_count, $__elf_path'
|
||||||
|
|
||||||
local out_path
|
local out_path ---@type string
|
||||||
-- Move out of `<out_root>/gdb_tape_atoms_runtime.gdb` to `<out_root>/../gdb_tape_atoms_runtime.gdb` when the conventional `<out_root>` is `<build>/gen`
|
-- Move out of `<out_root>/gdb_tape_atoms_runtime.gdb` to `<out_root>/../gdb_tape_atoms_runtime.gdb` when the conventional `<out_root>` is `<build>/gen`
|
||||||
-- (any equivalent spelling — relative, absolute backslash, absolute forward-slash, trailing-separator variants).
|
-- (any equivalent spelling — relative, absolute backslash, absolute forward-slash, trailing-separator variants).
|
||||||
-- This puts the gdb runtime alongside the ELF at `build/` rather than under the report subdir.
|
-- This puts the gdb runtime alongside the ELF at `build/` rather than under the report subdir.
|
||||||
|
--- @param p string
|
||||||
|
--- @return boolean
|
||||||
local function ends_with_gen_dir(p)
|
local function ends_with_gen_dir(p)
|
||||||
if type(p) ~= "string" then return false end
|
if type(p) ~= "string" then return false end
|
||||||
return p:match("[/\\]gen[/\\]?$") ~= nil or p == "build/gen" or p == "build\\gen"
|
return p:match("[/\\]gen[/\\]?$") ~= nil or p == "build/gen" or p == "build\\gen"
|
||||||
@@ -461,7 +510,7 @@ local function emit_gdb_runtime(ctx)
|
|||||||
if ends_with_gen_dir(ctx.out_root) then
|
if ends_with_gen_dir(ctx.out_root) then
|
||||||
-- Strip the trailing `/gen` segment, then write the runtime script under `build/`.
|
-- Strip the trailing `/gen` segment, then write the runtime script under `build/`.
|
||||||
-- e.g. "C:/projects/Pikuma/ps1/build/gen" -> "C:/projects/Pikuma/ps1/build".
|
-- e.g. "C:/projects/Pikuma/ps1/build/gen" -> "C:/projects/Pikuma/ps1/build".
|
||||||
local parent = ctx.out_root:gsub("[/\\]gen[/\\]?$", "")
|
local parent = ctx.out_root:gsub("[/\\]gen[/\\]?$", "") ---@type string
|
||||||
out_path = parent .. "/gdb_tape_atoms_runtime.gdb"
|
out_path = parent .. "/gdb_tape_atoms_runtime.gdb"
|
||||||
else
|
else
|
||||||
out_path = ctx.out_root .. "/gdb_tape_atoms_runtime.gdb"
|
out_path = ctx.out_root .. "/gdb_tape_atoms_runtime.gdb"
|
||||||
@@ -475,24 +524,35 @@ end
|
|||||||
-- M — module exports
|
-- M — module exports
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
local M = {}
|
local M = {} ---@type AtomSourceMapPass
|
||||||
|
|
||||||
-- Expose the pure render functions so `report.lua` and the focused tests can call them directly without triggering the file-emit path.
|
-- Expose the pure render functions so `report.lua` and the focused tests can call them directly without triggering the file-emit path.
|
||||||
M.render_source_map = render_source_map
|
M.render_source_map = render_source_map
|
||||||
M.render_provenance = render_provenance
|
M.render_provenance = render_provenance
|
||||||
|
|
||||||
--- Render ONE atom's sourcemap stanza.
|
--- Render ONE atom's sourcemap stanza.
|
||||||
--- @param atom table -- atom record (must have `atom.paths` populated)
|
--- @param atom AtomEntry
|
||||||
--- @return string
|
--- @return string
|
||||||
function M.render_atom_source_map(atom)
|
function M.render_atom_source_map(atom)
|
||||||
assert(type(atom) == "table", "render_atom_source_map: atom must be a table")
|
assert(type(atom) == "table", "render_atom_source_map: atom must be a table")
|
||||||
assert(type(atom.paths) == "table", "render_atom_source_map: atom.paths must be a table")
|
assert(type(atom.paths) == "table", "render_atom_source_map: atom.paths must be a table")
|
||||||
local entries, total = canonical_word_entries(atom)
|
local entries, total = canonical_word_entries(atom) ---@type WordMapEntry[], integer
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
lines[#lines + 1] = string.format("ATOM %s %d", (atom.raw_name or atom.name), total)
|
lines[#lines + 1] = string.format("ATOM %s %d", (atom.raw_name or atom.name), total)
|
||||||
for _, entry in ipairs(entries) do
|
for _, entry in ipairs(entries) do ---@type integer, WordMapEntry
|
||||||
lines[#lines + 1] = string.format("WORD %d LINE %d TEXT %s",
|
local word_line = string.format("WORD %d LINE %d TEXT %s", ---@type string
|
||||||
entry.pos, entry.line, entry.text)
|
entry.pos, entry.line, entry.text)
|
||||||
|
local keys = {} ---@type string[]
|
||||||
|
for pos = 1, 16 do ---@type integer
|
||||||
|
local k = entry.gpr_keys and entry.gpr_keys[pos] ---@type string|nil
|
||||||
|
if type(k) == "string" and k:sub(1, 7) == "reguse:" then
|
||||||
|
keys[#keys + 1] = k
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if #keys > 0 then
|
||||||
|
word_line = word_line .. " KEYS " .. table.concat(keys, ",")
|
||||||
|
end
|
||||||
|
lines[#lines + 1] = word_line
|
||||||
end
|
end
|
||||||
lines[#lines + 1] = "ENDATOM"
|
lines[#lines + 1] = "ENDATOM"
|
||||||
return table.concat(lines, "\n") .. "\n"
|
return table.concat(lines, "\n") .. "\n"
|
||||||
@@ -502,25 +562,23 @@ end
|
|||||||
---
|
---
|
||||||
--- `rel_path` is the source path (forward-slashes) embedded in every `CALL` line.
|
--- `rel_path` is the source path (forward-slashes) embedded in every `CALL` line.
|
||||||
--- The .md caller (report.lua) is expected to derive this once per `## <source>` heading and pass it down for each atom in that source.
|
--- The .md caller (report.lua) is expected to derive this once per `## <source>` heading and pass it down for each atom in that source.
|
||||||
--- @param atom table -- atom record (must have `atom.paths` populated)
|
--- @param atom AtomEntry
|
||||||
--- @param wc table -- identity alias of `corpus.word_counts`
|
--- @param wc WordCounts
|
||||||
--- @param rel_path string -- source path (forward-slashes) for `CALL` fields
|
--- @param rel_path string
|
||||||
--- @return string
|
--- @return string
|
||||||
function M.render_atom_provenance(atom, wc, rel_path)
|
function M.render_atom_provenance(atom, wc, rel_path)
|
||||||
assert(type(atom) == "table", "render_atom_provenance: atom must be a table")
|
assert(type(atom) == "table", "render_atom_provenance: atom must be a table")
|
||||||
assert(type(atom.paths) == "table", "render_atom_provenance: atom.paths must be a table")
|
assert(type(atom.paths) == "table", "render_atom_provenance: atom.paths must be a table")
|
||||||
assert(type(rel_path) == "string", "render_atom_provenance: rel_path must be a string")
|
assert(type(rel_path) == "string", "render_atom_provenance: rel_path must be a string")
|
||||||
local entries, total = canonical_word_entries(atom)
|
local entries, total = canonical_word_entries(atom) ---@type WordMapEntry[], integer
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
lines[#lines + 1] = string.format("ATOM %s %d", (atom.raw_name or atom.name), total)
|
lines[#lines + 1] = string.format("ATOM %s %d", (atom.raw_name or atom.name), total)
|
||||||
for _, entry in ipairs(entries) do
|
for _, entry in ipairs(entries) do ---@type integer, WordMapEntry
|
||||||
local inv = entry.invocation
|
local inv = entry.invocation ---@type InvocationRecord|nil
|
||||||
local macro_count = inv and wc and wc["mac_" .. inv.component_name]
|
local macro_count = inv and wc and wc["mac_" .. inv.component_name] ---@type integer|nil
|
||||||
if inv and macro_count ~= nil then
|
if inv and macro_count ~= nil then
|
||||||
lines[#lines + 1] = string.format(
|
lines[#lines + 1] = string.format('WORD %d CALL %s:%d MACRO %s "%s:%d" BODY %d'
|
||||||
'WORD %d CALL %s:%d MACRO %s "%s:%d" BODY %d',
|
, entry.pos, rel_path, entry.line, inv.component_name, inv.def_path or "", inv.def_line or 0, entry.body_line)
|
||||||
entry.pos, rel_path, entry.line, inv.component_name,
|
|
||||||
inv.def_path or "", inv.def_line or 0, entry.body_line)
|
|
||||||
else
|
else
|
||||||
lines[#lines + 1] = string.format(
|
lines[#lines + 1] = string.format(
|
||||||
"WORD %d CALL %s:%d RAW", entry.pos, rel_path, entry.line)
|
"WORD %d CALL %s:%d RAW", entry.pos, rel_path, entry.line)
|
||||||
@@ -529,24 +587,24 @@ function M.render_atom_provenance(atom, wc, rel_path)
|
|||||||
return table.concat(lines, "\n") .. "\n"
|
return table.concat(lines, "\n") .. "\n"
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Pass entry. For each source that declares at least one `MipsAtom_(name)` / `MipsCode code_<name>`,
|
--- Pass entry. For each source that declares at least one tape atom,
|
||||||
--- emit two files in `<out_root>/`: `<basename>.atoms.sourcemap.txt` (per-word call-site map) and `<basename>.atoms.provenance.txt`
|
--- emit two files in `<out_root>/`: `<basename>.atoms.sourcemap.txt` (per-word call-site map) and `<basename>.atoms.provenance.txt`
|
||||||
--- (per-word definition + body line, resolved via the outermost `mac_X(...)` invocation).
|
--- (per-word definition + body line, resolved via the outermost `mac_X(...)` invocation).
|
||||||
--- When `ctx.flags.gdb_runtime` is true and `ctx.flags.elf_path` exists, also emit the post-link gdb script `<ctx.out_root>/gdb_tape_atoms_runtime.gdb`.
|
--- When `ctx.flags.gdb_runtime` is true and `ctx.flags.elf_path` exists, also emit the post-link gdb script `<ctx.out_root>/gdb_tape_atoms_runtime.gdb`.
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @return PassResult
|
--- @return PassResult
|
||||||
function M.run(ctx)
|
function M.run(ctx)
|
||||||
local outputs = {}
|
local outputs = {} ---@type PassOutputEntry[]
|
||||||
local errors = {}
|
local errors = {} ---@type Finding[]
|
||||||
local warnings = {}
|
local warnings = {} ---@type Finding[]
|
||||||
|
|
||||||
local corpus = ctx.shared and ctx.shared.corpus
|
local corpus = ctx.shared and ctx.shared.corpus ---@type Corpus|nil
|
||||||
if type(corpus) ~= "table" or type(corpus.source_order) ~= "table" then
|
if type(corpus) ~= "table" or type(corpus.source_order) ~= "table" then
|
||||||
error("atoms_source_map.run requires ctx.shared.corpus.source_order (canonical corpus).", 0)
|
error("atoms_source_map.run requires ctx.shared.corpus.source_order (canonical corpus).", 0)
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Word counts come from `corpus.word_counts` (populated by word_count_eval + components passes).
|
-- Word counts come from `corpus.word_counts` (populated by word_count_eval + components passes).
|
||||||
local wc = corpus.word_counts or {}
|
local wc = corpus.word_counts or {} ---@type WordCounts
|
||||||
if not next(wc) then
|
if not next(wc) then
|
||||||
warnings[#warnings + 1] = {
|
warnings[#warnings + 1] = {
|
||||||
line = 0,
|
line = 0,
|
||||||
|
|||||||
+136
-125
@@ -9,8 +9,7 @@
|
|||||||
--- These GPRs are unavailable to EVERY atom's source pool.
|
--- These GPRs are unavailable to EVERY atom's source pool.
|
||||||
--- Carriers are preserved across atoms by context discipline and must never be reallocated.
|
--- Carriers are preserved across atoms by context discipline and must never be reallocated.
|
||||||
--- Per-atom body parsing also catches alias references (R_<Alias>) and hardcoded R_Tn references,
|
--- Per-atom body parsing also catches alias references (R_<Alias>) and hardcoded R_Tn references,
|
||||||
--- so the user can write either `R_T4` or `R_ResolveScratch` in an atom body and the pass will
|
--- so the user can write either `R_T4` or `R_ResolveScratch` in an atom body and the pass will exclude R_T4 from that atom's pool.
|
||||||
--- exclude R_T4 from that atom's pool.
|
|
||||||
---
|
---
|
||||||
--- Conflict detection: If the user hardcodes `R_Tn` in an atom body that shares a phase with an auto-reg that picked `R_Tn`,
|
--- Conflict detection: If the user hardcodes `R_Tn` in an atom body that shares a phase with an auto-reg that picked `R_Tn`,
|
||||||
--- emit `phase_register_clash` as an info finding (no build stop).
|
--- emit `phase_register_clash` as an info finding (no build stop).
|
||||||
@@ -19,97 +18,97 @@
|
|||||||
--- Pool exhaustion: If a phase declares more `R_<Sym>` mappings than the 10-register pool can hold,
|
--- Pool exhaustion: If a phase declares more `R_<Sym>` mappings than the 10-register pool can hold,
|
||||||
--- emit `phase_register_pool_exhausted` as a build-stopping error.
|
--- emit `phase_register_pool_exhausted` as a build-stopping error.
|
||||||
|
|
||||||
--- @class AutoRegResult
|
--- @alias GprIdent string
|
||||||
--- @field outputs table[] -- {kind=, path=} entries
|
|
||||||
--- @field errors table[] -- {line=, msg=} entries (build-stops)
|
|
||||||
--- @field warnings table[] -- {line=, msg=} entries (build-continues)
|
|
||||||
|
|
||||||
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
|
--- @class GprAllocMap
|
||||||
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
--- @field [string] GprIdent -- bag: auto-reg symbol -> physical GPR
|
||||||
|
|
||||||
|
--- @class AutoRegOutput
|
||||||
|
--- @field auto_reg_h string
|
||||||
|
|
||||||
|
--- @class AutoRegResult
|
||||||
|
--- @field outputs AutoRegOutput[]
|
||||||
|
--- @field errors Finding[]
|
||||||
|
--- @field warnings Finding[]
|
||||||
|
|
||||||
|
--- @class AutoRegPass
|
||||||
|
--- @field run fun(ctx: PassCtx): AutoRegResult
|
||||||
|
--- @field POOL GprIdent[]
|
||||||
|
|
||||||
|
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" ---@type string
|
||||||
|
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") ---@type DuffleExport
|
||||||
|
local isa = require("duffle_isa") ---@type DuffleIsa
|
||||||
|
|
||||||
--- ════════════════════════════════════════════════════════════════════════════
|
--- ════════════════════════════════════════════════════════════════════════════
|
||||||
--- THE GPR ALLOCATION POOL — what is allocatable, and (more importantly) WHY
|
--- THE GPR ALLOCATION POOL — what's allocatable, and (more importantly) WHY
|
||||||
--- ════════════════════════════════════════════════════════════════════════════
|
--- ════════════════════════════════════════════════════════════════════════════
|
||||||
---
|
---
|
||||||
--- The auto-reg pass picks physical GPRs for `atom_auto_reg(...)` / `phase_auto_reg(...)` markers.
|
--- The auto-reg pass picks physical GPRs for `atom_auto_reg(...)` / `phase_auto_reg(...)` markers.
|
||||||
--- It allocates from a FIXED 10-register pool.
|
--- The 24-register pool covers R2-R25 (the user/atom allocatable surface):
|
||||||
--- This comment block makes the inclusion AND exclusion criteria obvious so a reader doesn't have
|
--- R_T0..R_T7, R_V0..R_V1, R_A0..A3, R_S0..S7, R_T8..T9.
|
||||||
--- to grep lottes_tape.h + mips.h to understand the design.
|
--- Excluded (and never added to the pool):
|
||||||
---
|
|
||||||
--- ── WHAT'S IN THE POOL (10 GPRs, all caller-trash per the O32 ABI) ────────
|
|
||||||
--- R_T0..R_T7 (GPR codes 8..15), R_V0..R_V1 (GPR codes 2..3)
|
|
||||||
--- The workhorse of every atom body. The uesr should be aware of atom allocation across atoms they chain.
|
|
||||||
--- If they have a collision it means either they didn't saturate the register file optimally for a phase,
|
|
||||||
--- or the may have made the workload to large for the run.
|
|
||||||
---
|
|
||||||
--- ── WHAT'S NOT IN THE POOL — and WHY (the "obvious exclusions") ────────────
|
|
||||||
--- R_T9 (GPR code 25) — R_TapePtr, the tape instruction stream pointer.
|
|
||||||
--- Owned by the tape runtime (in tape_run / tape_run_a02_s07).
|
|
||||||
--- `rgcc(R_TapePtr)` register-variable ties the C compiler's view to $t9 across the whole tape_run.
|
|
||||||
--- The auto-reg pass MUST NOT clobber this; doing so would desync the C-side tape pointer from the
|
|
||||||
--- hardware pointer and crash on the next tape_run.
|
|
||||||
---
|
|
||||||
--- R_T8 (GPR code 24) — R_AtomJmp, the atom-jump register used by the 4-word yield handshake.
|
|
||||||
--- Every `mac_yield()` / `mac_yield_tail` does `load_word R_AtomJmp, R_TapePtr, 0` then
|
|
||||||
--- `jump_reg R_AtomJmp`. The auto-reg pass MUST NOT clobber this either, or the atom dispatcher breaks.
|
|
||||||
--- Owned by the tape runtime, same family as R_TapePtr.
|
|
||||||
---
|
|
||||||
--- R_AT (GPR code 1) — Assembler temporary. Reserved by the MIPS O32 ABI for pseudoinstruction expansion
|
|
||||||
--- (lottes_tape.h:86, mips.h:93). The ISA's psuedo instructions use it as a scratch temporary.
|
|
||||||
---
|
|
||||||
--- R_A0..A3 (codes 4..7) — Function arguments. Used in tape_run_a02_s07, see below.
|
|
||||||
--- R_S0..S7 (codes 16..23) — Callee-saved. Preserved across C-ABI calls by convention.
|
|
||||||
--- The `tape_run_a02_s07` variant clobbers them deliberately, but the default `tape_run` does NOT.
|
|
||||||
--- Kept out of POOL to preserve the conservative default.
|
|
||||||
--- Add them in a separate "big clobber" pool if/when needed.
|
|
||||||
---
|
|
||||||
--- R_K0/K1 (codes 26..27) — Kernel / interrupt handler reserves. Never touched by user code; OS-internal.
|
|
||||||
--- R_GP/SP/FP/RA (codes 28..31) — Stack frame + return-address. Owned by the C compiler; never allocatable.
|
|
||||||
--- R_0 (code 0) — Hardwired zero. Cannot be written.
|
--- R_0 (code 0) — Hardwired zero. Cannot be written.
|
||||||
|
--- R_AT (code 1) — Assembler temporary. Reserved by the MIPS O32 ABI.
|
||||||
|
--- R_A0..A3 — Explicitly omitted above even though their integer codes map to POOL entries;
|
||||||
|
--- the pool-construction loop below only references the POOL string literals, never the integer codes, so they are NOT auto-allocated by default.
|
||||||
|
--- (A0-A3 become available when the user adds them to POOL or hardcodes an R_A0 reference in the atom body.)
|
||||||
|
--- R_K0/K1 (codes 26-27) — Kernel / interrupt handler reserves. Never touched by user code.
|
||||||
|
--- R_GP/SP/FP/RA (codes 28-31) — R_SP/R_FP/R_RA are tape-runtime carriers between tape_enter and tape_exit; R_GP stays the host global pointer.
|
||||||
---
|
---
|
||||||
local POOL = {
|
local POOL = {} ---@type GprIdent[]
|
||||||
"R_T0", "R_T1", "R_T2", "R_T3",
|
for _, row in ipairs(isa.GPR_ROLE) do ---@type integer, GprRole
|
||||||
"R_T4", "R_T5", "R_T6", "R_T7",
|
if row.pool then
|
||||||
"R_V0", "R_V1",
|
POOL[#POOL + 1] = row.name
|
||||||
}
|
end
|
||||||
|
end
|
||||||
|
|
||||||
-- Map from integer MIPS GPR code (the `code` field on AliasEntry) to the physical GPR ident in POOL.
|
-- Map from integer MIPS GPR code (the `code` field on AliasEntry) to the physical GPR ident in POOL.
|
||||||
-- The standard MIPS O32 ABI register numbering matches mips.h's R_*_Code #defines (mips.h).
|
-- The standard MIPS O32 ABI register numbering matches mips.h's R_*_Code #defines (mips.h).
|
||||||
-- Only the POOL entries matter for auto_reg — non-pool aliases
|
-- Only the POOL entries matter for auto_reg — non-pool aliases
|
||||||
-- (R_AT=1, R_A0..A3=4..7, R_T8=24, R_T9=25, R_K0/K1=26..27, R_GP/SP/FP/RA=28..31)
|
-- (R_AT=1, R_A0..A3=4..7, R_T8=24, R_T9=25, R_K0/K1=26..27, R_GP/SP/FP/RA=28..31)
|
||||||
-- are deliberately omitted — see the comment block above for the WHY of each exclusion.
|
-- are deliberately omitted — see the comment block above for the WHY of each exclusion.
|
||||||
local INT_CODE_TO_POOL_GPR = {
|
local INT_CODE_TO_POOL_GPR = { ---@type table<integer, GprIdent> -- bag: MIPS GPR code -> POOL ident
|
||||||
[2] = "R_V0", [3] = "R_V1",
|
[2] = "R_V0", [3] = "R_V1",
|
||||||
|
[4] = "R_A0", [5] = "R_A1", [6] = "R_A2", [7] = "R_A3",
|
||||||
[8] = "R_T0", [9] = "R_T1", [10] = "R_T2", [11] = "R_T3",
|
[8] = "R_T0", [9] = "R_T1", [10] = "R_T2", [11] = "R_T3",
|
||||||
[12] = "R_T4", [13] = "R_T5", [14] = "R_T6", [15] = "R_T7",
|
[12] = "R_T4", [13] = "R_T5", [14] = "R_T6", [15] = "R_T7",
|
||||||
|
[16] = "R_S0", [17] = "R_S1", [18] = "R_S2", [19] = "R_S3",
|
||||||
|
[20] = "R_S4", [21] = "R_S5", [22] = "R_S6", [23] = "R_S7",
|
||||||
|
[24] = "R_T8", [25] = "R_T9",
|
||||||
}
|
}
|
||||||
|
|
||||||
-- Stable sort for deterministic allocation order.
|
-- Stable sort for deterministic allocation order.
|
||||||
|
--- @param tbl table<string, string> -- bag: key set only; values unused
|
||||||
|
--- @return string[]
|
||||||
local function stable_sort_keys(tbl)
|
local function stable_sort_keys(tbl)
|
||||||
local keys = {}
|
local keys = {} ---@type string[]
|
||||||
for k in pairs(tbl) do keys[#keys + 1] = k end
|
for k in pairs(tbl) do keys[#keys + 1] = k end ---@type string
|
||||||
table.sort(keys)
|
table.sort(keys)
|
||||||
return keys
|
return keys
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Allocate one phase's auto-reg mappings.
|
-- Allocate one phase's auto-reg mappings.
|
||||||
-- Returns (allocated_map, errors). On pool exhaustion, errors is populated and the function halts.
|
-- Returns (allocated_map, errors). On pool exhaustion, errors is populated and the function halts.
|
||||||
|
--- @param phase_label string
|
||||||
|
--- @param decls table<string, string> -- bag: auto-reg symbol -> decl payload
|
||||||
|
--- @return GprAllocMap
|
||||||
|
--- @return Finding[]
|
||||||
local function allocate_phase(phase_label, decls)
|
local function allocate_phase(phase_label, decls)
|
||||||
-- Deep-copy POOL into a fresh sequence table. The original `table.unpack and table.unpack(POOL) or { unpack(POOL) }`
|
-- Deep-copy POOL into a fresh sequence table. The original `table.unpack and table.unpack(POOL) or { unpack(POOL) }`
|
||||||
-- idiom wraps the unpacked values in a single inner table under LuaJIT 5.1 (`table.unpack` is nil; the `or` returns one value),
|
-- idiom wraps the unpacked values in a single inner table under LuaJIT 5.1 (`table.unpack` is nil; the `or` returns one value),
|
||||||
-- which corrupts the pool into `{ {R_T0, R_T1, ...} }` — making `table.remove(pool, 1)` return the inner table on iteration.
|
-- which corrupts the pool into `{ {R_T0, R_T1, ...} }` — making `table.remove(pool, 1)` return the inner table on iteration.
|
||||||
local pool = {}
|
local pool = {} ---@type GprIdent[]
|
||||||
for i = 1, #POOL do pool[i] = POOL[i] end
|
for i = 1, #POOL do pool[i] = POOL[i] end ---@type integer
|
||||||
local result = {}
|
local result = {} ---@type GprAllocMap
|
||||||
local errors = {}
|
local errors = {} ---@type Finding[]
|
||||||
for _, sym in ipairs(stable_sort_keys(decls)) do
|
for _, sym in ipairs(stable_sort_keys(decls)) do ---@type integer, string
|
||||||
local next_gpr = table.remove(pool, 1)
|
local next_gpr = table.remove(pool, 1) ---@type GprIdent|nil
|
||||||
if not next_gpr then
|
if not next_gpr then
|
||||||
errors[#errors + 1] = {
|
errors[#errors + 1] = {
|
||||||
line = 0,
|
line = 0,
|
||||||
msg = string.format("phase_register_pool_exhausted: "
|
msg = string.format("phase_register_pool_exhausted: "
|
||||||
.. "phase '%s' requested symbol '%s' but the pool has no remaining registers "
|
.. "phase '%s' requested symbol '%s' but the pool has no remaining registers "
|
||||||
.. "(max 10 per phase: R_T0..R_T7 + R_V0..R_V1). Split the phase or use hardcoded GPRs."
|
.. "(max 24 per phase: R_T0..R_T7 + R_V0..R_V1 + R_A0..R_A3 + R_S0..R_S7 + R_T8..R_T9). Split the phase or use hardcoded GPRs."
|
||||||
, phase_label, sym),
|
, phase_label, sym),
|
||||||
}
|
}
|
||||||
return result, errors
|
return result, errors
|
||||||
@@ -127,13 +126,16 @@ end
|
|||||||
-- Each entry's `code` is the integer MIPS GPR number (0..31); INT_CODE_TO_POOL_GPR translates it back to the physical GPR ident.
|
-- Each entry's `code` is the integer MIPS GPR number (0..31); INT_CODE_TO_POOL_GPR translates it back to the physical GPR ident.
|
||||||
-- Aliases whose `code` points to a non-POOL GPR (e.g. R_S0, R_T8, R_K1) are ignored —
|
-- Aliases whose `code` points to a non-POOL GPR (e.g. R_S0, R_T8, R_K1) are ignored —
|
||||||
-- they don't affect the auto_reg pool, and they're already excluded from POOL above.
|
-- they don't affect the auto_reg pool, and they're already excluded from POOL above.
|
||||||
|
--- @param corpus Corpus
|
||||||
|
--- @return table<GprIdent, boolean>
|
||||||
|
--- @return table<string, GprIdent>
|
||||||
local function build_user_pins(corpus)
|
local function build_user_pins(corpus)
|
||||||
local user_pinned = {}
|
local user_pinned = {} ---@type table<GprIdent, boolean> -- bag: pinned physical GPR -> true
|
||||||
local alias_to_gpr = {}
|
local alias_to_gpr = {} ---@type table<string, GprIdent> -- bag: alias ident -> physical GPR
|
||||||
if not corpus.register_alias_registry then return user_pinned, alias_to_gpr end
|
if not corpus.register_alias_registry then return user_pinned, alias_to_gpr end
|
||||||
for alias_name, alias_entry in pairs(corpus.register_alias_registry) do
|
for alias_name, alias_entry in pairs(corpus.register_alias_registry) do ---@type string, AliasEntry
|
||||||
if alias_entry.has_atom_reg and alias_entry.code then
|
if alias_entry.has_atom_reg and alias_entry.code then
|
||||||
local gpr = INT_CODE_TO_POOL_GPR[alias_entry.code]
|
local gpr = INT_CODE_TO_POOL_GPR[alias_entry.code] ---@type GprIdent|nil
|
||||||
if gpr then
|
if gpr then
|
||||||
user_pinned[gpr] = true
|
user_pinned[gpr] = true
|
||||||
alias_to_gpr[alias_name] = gpr
|
alias_to_gpr[alias_name] = gpr
|
||||||
@@ -143,30 +145,33 @@ local function build_user_pins(corpus)
|
|||||||
return user_pinned, alias_to_gpr
|
return user_pinned, alias_to_gpr
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Find every physical GPR referenced in the atom body, via EITHER:
|
--- Find every physical GPR referenced in the atom body, via EITHER:
|
||||||
-- (a) A hardcoded physical GPR ident (R_T\d+|R_V\d+|R_A\d+|R_S\d+) — the existing regex;
|
--- (a) A hardcoded physical GPR ident (R_T\d+|R_V\d+|R_A\d+|R_S\d+) — the existing regex;
|
||||||
-- (b) An alias ident (R_<Alias>) resolved via alias_to_gpr back to its physical GPR ident.
|
--- (b) An alias ident (R_<Alias>) resolved via alias_to_gpr back to its physical GPR ident.
|
||||||
-- Returns { [physical_gpr_ident] = count }. Clash-detection and source-pool-exclusion logic
|
--- Returns { [physical_gpr_ident] = count }.
|
||||||
-- only needs the presence of each GPR (boolean test), but keeping count preserves the
|
--- Clash-detection and source-pool-exclusion logic only needs the presence of each GPR (boolean test),
|
||||||
-- original find_hardcoded_rn shape so callers can switch without churn.
|
--- but keeping count preserves the original find_hardcoded_rn shape so callers can switch without churn.
|
||||||
-- The alias pattern is sorted lexicographically to keep the regex deterministic.
|
--- The alias pattern is sorted lexicographically to keep the regex deterministic.
|
||||||
|
--- @param body_text string
|
||||||
|
--- @param alias_to_gpr table<string, GprIdent> -- bag: alias ident -> physical GPR
|
||||||
|
--- @return table<GprIdent, integer>
|
||||||
local function find_used_gprs(body_text, alias_to_gpr)
|
local function find_used_gprs(body_text, alias_to_gpr)
|
||||||
local found = {}
|
local found = {} ---@type table<GprIdent, integer> -- bag: physical GPR -> hit count
|
||||||
-- (a) Hardcoded physical GPRs (R_T0..R_T7, R_V0..R_V1, R_A0..R_A3, R_S0..R_S7).
|
-- (a) Hardcoded physical GPRs (R_T0..R_T7, R_V0..R_V1, R_A0..R_A3, R_S0..R_S7).
|
||||||
for gpr in body_text:gmatch("(R_T%d+|R_V%d+|R_A%d+|R_S%d+)") do
|
for gpr in body_text:gmatch("(R_T%d+|R_V%d+|R_A%d+|R_S%d+)") do ---@type GprIdent
|
||||||
found[gpr] = (found[gpr] or 0) + 1
|
found[gpr] = (found[gpr] or 0) + 1
|
||||||
end
|
end
|
||||||
-- (b) Alias references (R_<Alias>) resolved to physical GPRs via the registry.
|
-- (b) Alias references (R_<Alias>) resolved to physical GPRs via the registry.
|
||||||
-- Sorted by name so the regex is byte-stable across runs.
|
-- Sorted by name so the regex is byte-stable across runs.
|
||||||
if alias_to_gpr and next(alias_to_gpr) then
|
if alias_to_gpr and next(alias_to_gpr) then
|
||||||
local aliases = {}
|
local aliases = {} ---@type string[]
|
||||||
for alias_name in pairs(alias_to_gpr) do
|
for alias_name in pairs(alias_to_gpr) do ---@type string
|
||||||
aliases[#aliases + 1] = alias_name
|
aliases[#aliases + 1] = alias_name
|
||||||
end
|
end
|
||||||
table.sort(aliases)
|
table.sort(aliases)
|
||||||
local pattern = "(" .. table.concat(aliases, "|") .. ")"
|
local pattern = "(" .. table.concat(aliases, "|") .. ")" ---@type string
|
||||||
for alias_name in body_text:gmatch(pattern) do
|
for alias_name in body_text:gmatch(pattern) do ---@type string
|
||||||
local gpr = alias_to_gpr[alias_name]
|
local gpr = alias_to_gpr[alias_name] ---@type GprIdent|nil
|
||||||
if gpr and not found[gpr] then
|
if gpr and not found[gpr] then
|
||||||
found[gpr] = 1
|
found[gpr] = 1
|
||||||
end
|
end
|
||||||
@@ -176,26 +181,31 @@ local function find_used_gprs(body_text, alias_to_gpr)
|
|||||||
end
|
end
|
||||||
|
|
||||||
-- Emit one gen/auto_reg.h header per directory.
|
-- Emit one gen/auto_reg.h header per directory.
|
||||||
|
--- @param out_dir string
|
||||||
|
--- @param dir string
|
||||||
|
--- @param sources SourceFile[]
|
||||||
|
--- @param mappings GprAllocMap
|
||||||
|
--- @return string|nil
|
||||||
local function emit_auto_reg_h(out_dir, dir, sources, mappings)
|
local function emit_auto_reg_h(out_dir, dir, sources, mappings)
|
||||||
if not mappings or next(mappings) == nil then return end
|
if not mappings or next(mappings) == nil then return end
|
||||||
local out_path = out_dir .. "/" .. "auto_reg.h"
|
local out_path = out_dir .. "/" .. "auto_reg.h" ---@type string
|
||||||
duffle.ensure_dir(out_dir)
|
duffle.ensure_dir(out_dir)
|
||||||
local lines = {
|
local lines = { ---@type string[]
|
||||||
"#ifdef INTELLISENSE_DIRECTIVES",
|
"#ifdef INTELLISENSE_DIRECTIVES",
|
||||||
"#pragma once",
|
"#pragma once",
|
||||||
"#endif",
|
"#endif",
|
||||||
"// Auto-generated by ps1_meta.lua (passes/auto_reg.lua) — DO NOT EDIT",
|
"// Auto-generated by ps1_meta.lua (passes/auto_reg.lua) — DO NOT EDIT",
|
||||||
"// Directory: " .. dir:gsub("/", "\\"),
|
"// Directory: " .. dir:gsub("/", "\\"),
|
||||||
}
|
}
|
||||||
for _, src in ipairs(sources) do
|
for _, src in ipairs(sources) do ---@type integer, SourceFile
|
||||||
lines[#lines + 1] = "// source: " .. src.path
|
lines[#lines + 1] = "// source: " .. src.path
|
||||||
end
|
end
|
||||||
lines[#lines + 1] = "// Per-phase register allocations resolved by the lua pass."
|
lines[#lines + 1] = "// Per-phase register allocations resolved by the lua pass."
|
||||||
lines[#lines + 1] = "// R_<Sym>_Code = <chosen GPR's _Code constant> for every marker in this directory."
|
lines[#lines + 1] = "// R_<Sym>_Code = <chosen GPR's _Code constant> for every marker in this directory."
|
||||||
lines[#lines + 1] = ""
|
lines[#lines + 1] = ""
|
||||||
for _, sym in ipairs(stable_sort_keys(mappings)) do
|
for _, sym in ipairs(stable_sort_keys(mappings)) do ---@type integer, string
|
||||||
local gpr = mappings[sym]
|
local gpr = mappings[sym] ---@type GprIdent
|
||||||
local gpr_code = gpr .. "_Code"
|
local gpr_code = gpr .. "_Code" ---@type string
|
||||||
lines[#lines + 1] = "#define " .. sym .. "_Code " .. gpr_code
|
lines[#lines + 1] = "#define " .. sym .. "_Code " .. gpr_code
|
||||||
end
|
end
|
||||||
lines[#lines + 1] = ""
|
lines[#lines + 1] = ""
|
||||||
@@ -208,16 +218,16 @@ end
|
|||||||
-- Pass entry
|
-- Pass entry
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
local M = {}
|
local M = {} ---@type AutoRegPass
|
||||||
|
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @return AutoRegResult
|
--- @return AutoRegResult
|
||||||
function M.run(ctx)
|
function M.run(ctx)
|
||||||
local outputs = {}
|
local outputs = {} ---@type AutoRegOutput[]
|
||||||
local errors = {}
|
local errors = {} ---@type Finding[]
|
||||||
local warnings = {}
|
local warnings = {} ---@type Finding[]
|
||||||
|
|
||||||
local corpus = ctx.shared and ctx.shared.corpus
|
local corpus = ctx.shared and ctx.shared.corpus ---@type Corpus|nil
|
||||||
if type(corpus) ~= "table" then
|
if type(corpus) ~= "table" then
|
||||||
error("auto_reg.run requires ctx.shared.corpus", 0)
|
error("auto_reg.run requires ctx.shared.corpus", 0)
|
||||||
end
|
end
|
||||||
@@ -227,17 +237,17 @@ function M.run(ctx)
|
|||||||
-- MUST NOT be allocated to any auto-reg marker — they're preserved across atoms by the wave-context discipline.
|
-- MUST NOT be allocated to any auto-reg marker — they're preserved across atoms by the wave-context discipline.
|
||||||
-- The corpus's register_alias_registry is the source of truth for these opt-in pins.
|
-- The corpus's register_alias_registry is the source of truth for these opt-in pins.
|
||||||
-- Body references to those aliases (via alias_to_gpr) are also excluded on a per-atom basis in step 2 below.
|
-- Body references to those aliases (via alias_to_gpr) are also excluded on a per-atom basis in step 2 below.
|
||||||
local user_pinned, alias_to_gpr = build_user_pins(corpus)
|
local user_pinned, alias_to_gpr = build_user_pins(corpus) ---@type table<GprIdent, boolean>, table<string, GprIdent>
|
||||||
|
|
||||||
-- 1. Allocate phase pools first (phase declarations take precedence over per-atom declarations).
|
-- 1. Allocate phase pools first (phase declarations take precedence over per-atom declarations).
|
||||||
local phase_allocations = {}
|
local phase_allocations = {} ---@type table<string, GprAllocMap> -- bag: phase_label -> alloc map
|
||||||
for phase_label, decls in pairs(corpus.phase_auto_regs or {}) do
|
for phase_label, decls in pairs(corpus.phase_auto_regs or {}) do ---@type string, table<string, string>
|
||||||
local mapping, errs = allocate_phase(phase_label, decls)
|
local mapping, errs = allocate_phase(phase_label, decls) ---@type GprAllocMap, Finding[]
|
||||||
for sym, gpr in pairs(mapping) do
|
for sym, gpr in pairs(mapping) do ---@type string, GprIdent
|
||||||
phase_allocations[phase_label] = phase_allocations[phase_label] or {}
|
phase_allocations[phase_label] = phase_allocations[phase_label] or {}
|
||||||
phase_allocations[phase_label][sym] = gpr
|
phase_allocations[phase_label][sym] = gpr
|
||||||
end
|
end
|
||||||
for _, e in ipairs(errs) do
|
for _, e in ipairs(errs) do ---@type integer, Finding
|
||||||
errors[#errors + 1] = e
|
errors[#errors + 1] = e
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -246,16 +256,16 @@ function M.run(ctx)
|
|||||||
-- Otherwise, allocate a private pool for the atom.
|
-- Otherwise, allocate a private pool for the atom.
|
||||||
-- The phase membership is in `corpus.atom_phases[phase_label].atoms` (an array of atom names declared via `atom_phase(<phase>)`
|
-- The phase membership is in `corpus.atom_phases[phase_label].atoms` (an array of atom names declared via `atom_phase(<phase>)`
|
||||||
-- in the atom's `atom_info` line). Build a reverse map `atom_name -> phase_label` so the lookup is O(1) per atom scope.
|
-- in the atom's `atom_info` line). Build a reverse map `atom_name -> phase_label` so the lookup is O(1) per atom scope.
|
||||||
local atom_name_to_phase = {}
|
local atom_name_to_phase = {} ---@type table<AtomName, string> -- bag: atom name -> phase label
|
||||||
for phase_label, entry in pairs(corpus.atom_phases or {}) do
|
for phase_label, entry in pairs(corpus.atom_phases or {}) do ---@type string, AtomPhaseGroup
|
||||||
for _, atom_name in ipairs(entry.atoms or {}) do
|
for _, atom_name in ipairs(entry.atoms or {}) do ---@type integer, AtomName
|
||||||
atom_name_to_phase[atom_name] = phase_label
|
atom_name_to_phase[atom_name] = phase_label
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
local atom_allocations = {}
|
local atom_allocations = {} ---@type table<AtomName, GprAllocMap> -- bag: atom scope -> alloc map
|
||||||
for atom_scope, decls in pairs(corpus.atom_auto_regs or {}) do
|
for atom_scope, decls in pairs(corpus.atom_auto_regs or {}) do ---@type AtomName, table<string, string>
|
||||||
local phase_label = atom_name_to_phase[atom_scope]
|
local phase_label = atom_name_to_phase[atom_scope] ---@type string|nil
|
||||||
-- Build the atom's source pool: start with the full POOL, subtract:
|
-- Build the atom's source pool: start with the full POOL, subtract:
|
||||||
-- (a) every GPR already committed (phase allocations + prior atom allocations)
|
-- (a) every GPR already committed (phase allocations + prior atom allocations)
|
||||||
-- (b) every USER-PINNED GPR (wave-context carriers + file-scope pinned aliases)
|
-- (b) every USER-PINNED GPR (wave-context carriers + file-scope pinned aliases)
|
||||||
@@ -265,27 +275,26 @@ function M.run(ctx)
|
|||||||
-- the original `source_pool = phase_allocations[phase_label]` form used the phase
|
-- the original `source_pool = phase_allocations[phase_label]` form used the phase
|
||||||
-- allocation MAP as a pool, but that map has no array part, so `table.remove(source_pool, 1)`
|
-- allocation MAP as a pool, but that map has no array part, so `table.remove(source_pool, 1)`
|
||||||
-- returned nil and every atom-with-phase marker errored with `phase_register_pool_exhausted`.
|
-- returned nil and every atom-with-phase marker errored with `phase_register_pool_exhausted`.
|
||||||
local used = {}
|
local used = {} ---@type table<GprIdent, boolean> -- bag: committed or body-referenced GPR -> true
|
||||||
for _, m in pairs(phase_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end
|
for _, m in pairs(phase_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end ---@type integer, GprAllocMap
|
||||||
for _, m in pairs(atom_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end
|
for _, m in pairs(atom_allocations) do for _, gpr in pairs(m) do used[gpr] = true end end ---@type integer, GprAllocMap
|
||||||
-- (c) Body references — scan the atom body for hardcoded + alias-resolved GPRs.
|
-- (c) Body references — scan the atom body for hardcoded + alias-resolved GPRs.
|
||||||
-- Folded into `used` so the source_pool exclusion is a single check.
|
-- Folded into `used` so the source_pool exclusion is a single check.
|
||||||
local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope]
|
local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope] ---@type AtomEntry|nil
|
||||||
if atom and atom.body then
|
if atom and atom.body then
|
||||||
local body_used = find_used_gprs(atom.body, alias_to_gpr)
|
local body_used = find_used_gprs(atom.body, alias_to_gpr) ---@type table<GprIdent, integer>
|
||||||
for gpr in pairs(body_used) do used[gpr] = true end
|
for gpr in pairs(body_used) do used[gpr] = true end ---@type GprIdent
|
||||||
end
|
end
|
||||||
local source_pool = {}
|
local source_pool = {} ---@type GprIdent[]
|
||||||
for _, gpr in ipairs(POOL) do
|
for _, gpr in ipairs(POOL) do ---@type integer, GprIdent
|
||||||
-- Exclude (a) prior commitments, (b) USER-PINNED GPRs (wave-context carriers
|
-- Exclude (a) prior commitments, (b) USER-PINNED GPRs (wave-context carriers declared via atom_reg + _Code defs, preserved across atoms globally).
|
||||||
-- declared via atom_reg + _Code defs, preserved across atoms globally).
|
|
||||||
if not used[gpr] and not user_pinned[gpr] then
|
if not used[gpr] and not user_pinned[gpr] then
|
||||||
source_pool[#source_pool + 1] = gpr
|
source_pool[#source_pool + 1] = gpr
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
local result = {}
|
local result = {} ---@type GprAllocMap
|
||||||
for _, sym in ipairs(stable_sort_keys(decls)) do
|
for _, sym in ipairs(stable_sort_keys(decls)) do ---@type integer, string
|
||||||
local next_gpr = table.remove(source_pool, 1)
|
local next_gpr = table.remove(source_pool, 1) ---@type GprIdent|nil
|
||||||
if not next_gpr then
|
if not next_gpr then
|
||||||
errors[#errors + 1] = {
|
errors[#errors + 1] = {
|
||||||
line = 0,
|
line = 0,
|
||||||
@@ -307,11 +316,11 @@ function M.run(ctx)
|
|||||||
-- This warning is kept as a defensive safety net for cases the body scanner might miss
|
-- This warning is kept as a defensive safety net for cases the body scanner might miss
|
||||||
-- (e.g. macros that expand to register references the scanner cannot resolve).
|
-- (e.g. macros that expand to register references the scanner cannot resolve).
|
||||||
-- For each resolved (scope, sym) -> R_Tn mapping, scan the atom body source for used GPRs.
|
-- For each resolved (scope, sym) -> R_Tn mapping, scan the atom body source for used GPRs.
|
||||||
for atom_scope, decls in pairs(atom_allocations) do
|
for atom_scope, decls in pairs(atom_allocations) do ---@type AtomName, GprAllocMap
|
||||||
local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope]
|
local atom = corpus.atoms_by_name and corpus.atoms_by_name[atom_scope] ---@type AtomEntry|nil
|
||||||
if atom and atom.body then
|
if atom and atom.body then
|
||||||
local used_in_body = find_used_gprs(atom.body, alias_to_gpr)
|
local used_in_body = find_used_gprs(atom.body, alias_to_gpr) ---@type table<GprIdent, integer>
|
||||||
for sym, allocated_gpr in pairs(decls) do
|
for sym, allocated_gpr in pairs(decls) do ---@type string, GprIdent
|
||||||
if used_in_body[allocated_gpr] and used_in_body[allocated_gpr] > 0 then
|
if used_in_body[allocated_gpr] and used_in_body[allocated_gpr] > 0 then
|
||||||
warnings[#warnings + 1] = {
|
warnings[#warnings + 1] = {
|
||||||
line = atom.line or 0,
|
line = atom.line or 0,
|
||||||
@@ -326,30 +335,32 @@ function M.run(ctx)
|
|||||||
|
|
||||||
-- 4. Emit per-directory gen/auto_reg.h.
|
-- 4. Emit per-directory gen/auto_reg.h.
|
||||||
-- For each source directory that has atom_auto_regs or phase_auto_regs entries, emit one header.
|
-- For each source directory that has atom_auto_regs or phase_auto_regs entries, emit one header.
|
||||||
local sources_by_dir = corpus.sources_by_dir or {}
|
local sources_by_dir = corpus.sources_by_dir or {} ---@type table<string, SourceFile[]>
|
||||||
for dir, sources in pairs(sources_by_dir) do
|
for dir, sources in pairs(sources_by_dir) do ---@type string, SourceFile[]
|
||||||
local per_dir_mappings = {}
|
local per_dir_mappings = {} ---@type GprAllocMap
|
||||||
for _, src in ipairs(sources) do
|
for _, src in ipairs(sources) do ---@type integer, SourceFile
|
||||||
-- Collect every (sym -> gpr) entry that originated from a source in this directory.
|
-- Collect every (sym -> gpr) entry that originated from a source in this directory.
|
||||||
-- `src.scan.atom_auto_regs` is keyed by ATOM SCOPE NAME; `pairs(t)` iterates KEYS so `scope_name` here is the scope ident (e.g. "cube_g4_face").
|
-- `src.scan.atom_auto_regs` is keyed by ATOM SCOPE NAME; `pairs(t)` iterates KEYS so `scope_name` here is the scope ident (e.g. "cube_g4_face").
|
||||||
-- The previous `for _, scan_atom_auto` form silently assigned the VALUE (a `{sym = sym}` table) to the variable,
|
-- The previous `for _, scan_atom_auto` form silently assigned the VALUE (a `{sym = sym}` table) to the variable,
|
||||||
-- which made `atom_allocations[scan_atom_auto]` a table-indexed lookup that never resolved.
|
-- which made `atom_allocations[scan_atom_auto]` a table-indexed lookup that never resolved.
|
||||||
for scope_name in pairs(src.scan and src.scan.atom_auto_regs or {}) do
|
for scope_name in pairs(src.scan and src.scan.atom_auto_regs or {}) do ---@type string
|
||||||
for sym, gpr in pairs(atom_allocations[scope_name] or {}) do
|
for sym, gpr in pairs(atom_allocations[scope_name] or {}) do ---@type string, GprIdent
|
||||||
per_dir_mappings[sym] = gpr
|
per_dir_mappings[sym] = gpr
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
for scope_name in pairs(src.scan and src.scan.phase_auto_regs or {}) do
|
for scope_name in pairs(src.scan and src.scan.phase_auto_regs or {}) do ---@type string
|
||||||
for sym, gpr in pairs(phase_allocations[scope_name] or {}) do
|
for sym, gpr in pairs(phase_allocations[scope_name] or {}) do ---@type string, GprIdent
|
||||||
per_dir_mappings[sym] = gpr
|
per_dir_mappings[sym] = gpr
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
local out_dir = dir .. "/gen"
|
local out_dir = dir .. "/gen" ---@type string
|
||||||
local out_path = emit_auto_reg_h(out_dir, dir, sources, per_dir_mappings)
|
local out_path = emit_auto_reg_h(out_dir, dir, sources, per_dir_mappings) ---@type string|nil
|
||||||
if out_path then outputs[#outputs + 1] = { auto_reg_h = out_path } end
|
if out_path then outputs[#outputs + 1] = { auto_reg_h = out_path } end
|
||||||
end
|
end
|
||||||
return { outputs = outputs, errors = errors, warnings = warnings }
|
return { outputs = outputs, errors = errors, warnings = warnings }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
M.POOL = POOL
|
||||||
|
|
||||||
return M
|
return M
|
||||||
|
|||||||
+400
-265
@@ -1,13 +1,13 @@
|
|||||||
--- passes/components.lua — Component-macro header generator.
|
--- passes/components.lua — Component-macro header generator.
|
||||||
---
|
---
|
||||||
--- Ownership: `corpus.word_counts`, `corpus.components`, and `corpus.component_body_index`.
|
--- Ownership: `corpus.word_counts` and `corpus.components`.
|
||||||
--- Scanner owns `declaration_comment` and `debug_skip` on each declaration record; this pass projects both forward.
|
--- Scanner owns `declaration_comment` and `debug_skip` on each declaration record; this pass projects both forward.
|
||||||
---
|
---
|
||||||
--- Reads the pre-scanned SourceScan payload from `duffle.scan_source` for `MipsAtomComp_(ac_X)` and `MipsAtomComp_Proc_(ac_X, { body })` declarations (kind="comp_bare" / "comp_proc"),
|
--- Reads the pre-scanned SourceScan payload from `duffle.scan_source` for `MipsAtomComp_(ac_X)` and `MipsAtomComp_Proc_(ac_X, { body })` declarations (kind="comp_bare" / "comp_proc"),
|
||||||
--- then resolves the function-args string from the preceding `FI_ Slice_MipsCode ac_X(...)` declaration via a backward walk.
|
--- then resolves the function-args string from the preceding `FI_ Slice_MipsCode ac_X(...)` declaration via a backward walk.
|
||||||
---
|
---
|
||||||
--- `MipsAtom_Proc_(X, ab, { body })` declarations (kind="atom_proc") are ATOMS, not components, and are deliberately excluded —
|
--- `MipsAtom_Proc_(X, ab, { body })` declarations (kind="atom_proc") are ATOMS, not components, and are deliberately excluded —
|
||||||
--- atoms get emitted via `tb_emit(tb, code_<name>)` linker symbols, not inlined as `mac_*` macros.
|
--- the ELF symbol is the C ident. Raw `MipsCode code_*` is leftover, not the atom rule.
|
||||||
---
|
---
|
||||||
--- Emits one `gen/macs.h` per *immediate source directory* with `#define mac_X(sig) \` macros plus `WORD_COUNT(mac_X, N)` entries for downstream offset computation.
|
--- Emits one `gen/macs.h` per *immediate source directory* with `#define mac_X(sig) \` macros plus `WORD_COUNT(mac_X, N)` entries for downstream offset computation.
|
||||||
--- All sources inside the same directory contribute to the same file (per-directory aggregation).
|
--- All sources inside the same directory contribute to the same file (per-directory aggregation).
|
||||||
@@ -22,71 +22,77 @@
|
|||||||
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
|
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
|
||||||
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works both standalone + when require'd).
|
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works both standalone + when require'd).
|
||||||
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
|
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
|
||||||
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
|
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" ---@type string
|
||||||
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") ---@type DuffleExport
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Constants
|
-- Constants
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
-- Atom component declaration identifiers.
|
-- Atom component declaration identifiers.
|
||||||
local ATOM_COMP_PROC = "MipsAtomComp_Proc_"
|
local ATOM_COMP_PROC = "MipsAtomComp_Proc_" ---@type string
|
||||||
local MIPS_ATOM = "Slice_MipsCode" -- prefix on the function declaration that wraps an AtomComp_Proc_
|
local MIPS_ATOM = "Slice_MipsCode" ---@type string -- prefix on the function declaration that wraps an AtomComp_Proc_
|
||||||
|
|
||||||
-- Component-name prefixes.
|
-- Component-name prefixes.
|
||||||
local AC_PREFIX = "ac_" -- arg to MipsAtomComp_(ac_X); the X is the atom name
|
local AC_PREFIX = "ac_" ---@type string -- arg to MipsAtomComp_(ac_X); the X is the atom name
|
||||||
local AC_PREFIX_LEN = 3
|
local AC_PREFIX_LEN = 3 ---@type integer
|
||||||
local MAC_PREFIX = "mac_" -- prefix on generated macros; the rest is the atom name
|
local MAC_PREFIX = "mac_" ---@type string -- prefix on generated macros; the rest is the atom name
|
||||||
local MAC_PREFIX_LEN = 4
|
local MAC_PREFIX_LEN = 4 ---@type integer
|
||||||
|
|
||||||
-- ASCII byte values used in tokenization.
|
-- ASCII byte values used in tokenization.
|
||||||
local BYTE_NEWLINE = 10
|
local BYTE_NEWLINE = 10 ---@type integer
|
||||||
local BYTE_SLASH = 47
|
local BYTE_SLASH = 47 ---@type integer
|
||||||
|
|
||||||
-- Output gen subdirectory + filename (per-directory aggregation; the directory name is the namespace).
|
-- Output gen subdirectory + filename (per-directory aggregation; the directory name is the namespace).
|
||||||
local GEN_SUBDIR = "gen"
|
local GEN_SUBDIR = "gen" ---@type string
|
||||||
local MACS_FILENAME = "macs.h"
|
local MACS_FILENAME = "macs.h" ---@type string
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Type declarations
|
-- Type declarations
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- @class SourceFile
|
-- SourceFile, PassCtx, PassResult: see ps1_meta.lua
|
||||||
--- @field path string -- Absolute path to the source file
|
-- DuffleExport: see duffle.lua
|
||||||
--- @field text string -- Full source text
|
-- SourceScan, AtomEntry, CorpusCollision, CollisionSite: see scan_source.lua
|
||||||
--- @field dir string -- Directory containing the source
|
-- BodyToken: see emission_model.lua
|
||||||
--- @field basename string -- Filename without extension
|
-- WordCounts: see word_count_eval.lua
|
||||||
--- @field scan table -- Pre-scanned SourceScan payload (from duffle.scan_source)
|
-- InstructionRow, GteCommandRow: see duffle_isa.lua
|
||||||
|
|
||||||
--- @class PassCtx
|
|
||||||
--- @field sources SourceFile[] -- All source files in the build
|
|
||||||
--- @field metadata_path string -- Path to word_count.metadata.h
|
|
||||||
--- @field shared table -- Cross-pass shared state
|
|
||||||
--- @field out_root string -- Output root (e.g. "build/gen")
|
|
||||||
--- @field project_root string -- Project root (e.g. "code/")
|
|
||||||
--- @field upstream table<string, table> -- Per-pass upstream outputs
|
|
||||||
--- @field flags table -- CLI flags
|
|
||||||
--- @field verbose boolean -- Log diagnostic info
|
|
||||||
|
|
||||||
--- @class PassResult
|
|
||||||
--- @field outputs table[] -- {kind=, path=} entries describing emit files
|
|
||||||
--- @field errors table[] -- {line=, msg=} entries; build-stops
|
|
||||||
--- @field warnings table[] -- {line=, msg=} entries; build-succeeds
|
|
||||||
|
|
||||||
--- @class Component
|
--- @class Component
|
||||||
--- @field name string -- Atom name (without `ac_` prefix)
|
--- @field name string -- Atom name (without `ac_` prefix)
|
||||||
--- @field body string -- Brace-delimited body (without the braces)
|
--- @field body string -- Brace-delimited body (without the braces)
|
||||||
|
--- @field body_off integer|nil -- Byte offset of body[1] in source
|
||||||
|
--- @field body_tokens BodyToken[]|nil
|
||||||
--- @field args string|nil -- Function-args string (function form only)
|
--- @field args string|nil -- Function-args string (function form only)
|
||||||
|
--- @field arg_names string[]|nil -- Formal names with leading `ab` dropped
|
||||||
--- @field line integer -- Source line of the declaration
|
--- @field line integer -- Source line of the declaration
|
||||||
--- @field comment string|nil -- Scanner-owned `declaration_comment`; the components pass reads it from the scanner record
|
--- @field comment string|nil -- Scanner-owned `declaration_comment`; the components pass reads it from the scanner record
|
||||||
--- @field kind string -- "comp_bare" | "comp_proc" (atom_proc is NOT a component — see `project_components`)
|
--- @field kind string -- "comp_bare" | "comp_proc" (atom_proc is NOT a component — see `project_components`)
|
||||||
--- @field debug_skip boolean -- Mirror of `a.debug_skip` (scanner-owned); true iff a bare `atom_dbg_skip` marker immediately preceded the declaration
|
--- @field debug_skip boolean -- Mirror of `a.debug_skip` (scanner-owned); true iff a bare `atom_dbg_skip` marker immediately preceded the declaration
|
||||||
|
--- @field path string|nil -- Slash-normalized source path (collision sites)
|
||||||
|
--- @field source string|nil -- Absolute source path (emit)
|
||||||
|
--- @field line_of (fun(pos: integer): integer)|nil
|
||||||
|
--- @field cycle_cost integer|nil -- From metadata[c.name]; nil when the body was not costed
|
||||||
|
--- @field gp0_contrib integer|nil -- From metadata[c.name]; nil when the body was not costed
|
||||||
|
|
||||||
|
--- @class ComponentMeta
|
||||||
|
--- @field cycle_cost integer
|
||||||
|
--- @field gp0_contrib integer
|
||||||
|
|
||||||
|
--- @class ComponentMetaMap
|
||||||
|
--- @field [string] ComponentMeta -- bag: bare component name -> meta
|
||||||
|
|
||||||
|
--- @class MacsOutput
|
||||||
|
--- @field macs_h string
|
||||||
|
|
||||||
|
--- @class ComponentsPass
|
||||||
|
--- @field run fun(ctx: PassCtx): PassResult
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Local helpers (file I/O + path normalization)
|
-- Local helpers (file I/O + path normalization)
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
local M = {}
|
local M = {} ---@type ComponentsPass
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Back-walk helpers (composed into the entry point below: find_function_args_for)
|
-- Back-walk helpers (composed into the entry point below: find_function_args_for)
|
||||||
@@ -100,16 +106,15 @@ local M = {}
|
|||||||
--- Returns the args string (e.g., `"U4 off, U4 code, U1 r, U1 g, U1 b"`) or nil if no function declaration is found.
|
--- Returns the args string (e.g., `"U4 off, U4 code, U1 r, U1 g, U1 b"`) or nil if no function declaration is found.
|
||||||
---
|
---
|
||||||
--- After the `sym` arg was dropped from MipsAtomComp_Proc_, the component name
|
--- After the `sym` arg was dropped from MipsAtomComp_Proc_, the component name
|
||||||
--- and the args both come from the preceding `FI_ Slice_MipsCode ac_X(args)`
|
--- and the args both come from the preceding `FI_ Slice_MipsCode ac_X(args)` declaration.
|
||||||
--- declaration. The shared `duffle.find_function_decl_for` helper does the
|
--- The shared `duffle.find_function_decl_for` helper does the backward walk; this function returns just the args.
|
||||||
--- backward walk; this function returns just the args.
|
|
||||||
---
|
---
|
||||||
--- @param source string
|
--- @param source string
|
||||||
--- @param name string (retained for signature stability; unused — the walk derives the name)
|
--- @param name string (retained for signature stability; unused — the walk derives the name)
|
||||||
--- @param before_pos integer
|
--- @param before_pos integer
|
||||||
--- @return string|nil
|
--- @return string|nil
|
||||||
local function find_function_args_for(source, name, before_pos)
|
local function find_function_args_for(source, name, before_pos)
|
||||||
local _, args_inner = duffle.find_function_decl_for(source, before_pos, #MIPS_ATOM)
|
local _, args_inner = duffle.find_function_decl_for(source, before_pos, #MIPS_ATOM) ---@type string|nil, string|nil
|
||||||
return args_inner
|
return args_inner
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -125,25 +130,79 @@ end
|
|||||||
--- @return string[]|nil
|
--- @return string[]|nil
|
||||||
local function extract_arg_names(args_str)
|
local function extract_arg_names(args_str)
|
||||||
if not args_str or args_str == "" then return nil end
|
if not args_str or args_str == "" then return nil end
|
||||||
local names = {}
|
local names = {} ---@type string[]
|
||||||
local tokens = duffle.split_top_level_commas(args_str)
|
local tokens = duffle.split_top_level_commas(args_str) ---@type string[]
|
||||||
for _, tok in ipairs(tokens) do
|
for _, tok in ipairs(tokens) do ---@type integer, string
|
||||||
local trimmed = duffle.trim(tok)
|
local trimmed = duffle.trim(tok) ---@type string
|
||||||
if trimmed ~= "" then
|
if trimmed ~= "" then
|
||||||
|
-- Strip trailing block comment (/* ... */) from the token, if present.
|
||||||
|
-- split_top_level_commas only skips block comments at TOP LEVEL (between commas),
|
||||||
|
-- not block comments embedded WITHIN a token between a parameter and a trailing comma.
|
||||||
|
-- Without this strip, the identifier-walk below stops at the `/` of `*/` and returns
|
||||||
|
-- the wrong name (or nothing). See `test_extract_arg_names_handles_trailing_block_comments`.
|
||||||
|
local trimmed_end = #trimmed ---@type integer
|
||||||
|
if trimmed_end >= 2 and trimmed:sub(trimmed_end - 1, trimmed_end) == "*/" then
|
||||||
|
-- Find the matching `/*` that opens the trailing comment.
|
||||||
|
-- Walk back from the `*/` looking for `/*` (whitespace + `/*`).
|
||||||
|
local close_pos = trimmed_end - 1 ---@type integer -- position of the second-to-last char
|
||||||
|
-- Walk back: skip trailing whitespace, then look for the `/*` opener.
|
||||||
|
while close_pos > 1 do
|
||||||
|
local ch = trimmed:sub(close_pos, close_pos) ---@type string
|
||||||
|
if ch == " " or ch == "\t" or ch == "\n" or ch == "\r" then
|
||||||
|
close_pos = close_pos - 1
|
||||||
|
else
|
||||||
|
break
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- Now scan back from close_pos for the `/*` opener (slashes are at close_pos-1 and close_pos-2).
|
||||||
|
local opener_pos = nil ---@type integer|nil
|
||||||
|
local scan = close_pos - 3 ---@type integer
|
||||||
|
while scan >= 1 do
|
||||||
|
if trimmed:sub(scan, scan + 1) == "/*" then
|
||||||
|
opener_pos = scan
|
||||||
|
break
|
||||||
|
end
|
||||||
|
scan = scan - 1
|
||||||
|
end
|
||||||
|
if opener_pos then
|
||||||
|
-- Truncate everything from opener_pos onwards.
|
||||||
|
trimmed = duffle.trim(trimmed:sub(1, opener_pos - 1))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if trimmed == "" then goto continue end
|
||||||
|
-- Strip trailing array suffix `[N]` if present.
|
||||||
|
-- Example: `Reg r_data[4]` → identifier is `r_data`, not `4`.
|
||||||
|
trimmed_end = #trimmed
|
||||||
|
if trimmed_end >= 4 and trimmed:sub(trimmed_end, trimmed_end) == "]" then
|
||||||
|
-- Walk back: skip digits, expect `[`.
|
||||||
|
local bracket_pos = trimmed_end - 1 ---@type integer
|
||||||
|
while bracket_pos > 1 do
|
||||||
|
local ch = trimmed:sub(bracket_pos, bracket_pos) ---@type string
|
||||||
|
if ch >= "0" and ch <= "9" then
|
||||||
|
bracket_pos = bracket_pos - 1
|
||||||
|
else
|
||||||
|
break
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if bracket_pos >= 1 and trimmed:sub(bracket_pos, bracket_pos) == "[" then
|
||||||
|
trimmed = duffle.trim(trimmed:sub(1, bracket_pos - 1))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if trimmed == "" then goto continue end
|
||||||
-- Find the identifier at the end: walk back over trailers (whitespace + `*` + `[]`),
|
-- Find the identifier at the end: walk back over trailers (whitespace + `*` + `[]`),
|
||||||
-- then walk back over the identifier chars (alnum + `_`).
|
-- then walk back over the identifier chars (alnum + `_`).
|
||||||
local ident_end = #trimmed
|
local ident_end = #trimmed ---@type integer
|
||||||
while ident_end > 0 do
|
while ident_end > 0 do
|
||||||
local ch = trimmed:sub(ident_end, ident_end)
|
local ch = trimmed:sub(ident_end, ident_end) ---@type string
|
||||||
if ch == " " or ch == "\t" or ch == "*" or ch == "]" or ch == "[" then
|
if ch == " " or ch == "\t" or ch == "*" or ch == "]" or ch == "[" then
|
||||||
ident_end = ident_end - 1
|
ident_end = ident_end - 1
|
||||||
else
|
else
|
||||||
break
|
break
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
local ident_start = ident_end
|
local ident_start = ident_end ---@type integer
|
||||||
while ident_start > 0 do
|
while ident_start > 0 do
|
||||||
local ch = trimmed:sub(ident_start, ident_start)
|
local ch = trimmed:sub(ident_start, ident_start) ---@type string
|
||||||
if duffle.is_alnum_byte(string.byte(ch)) or ch == "_" then
|
if duffle.is_alnum_byte(string.byte(ch)) or ch == "_" then
|
||||||
ident_start = ident_start - 1
|
ident_start = ident_start - 1
|
||||||
else
|
else
|
||||||
@@ -151,14 +210,25 @@ local function extract_arg_names(args_str)
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
ident_start = ident_start + 1
|
ident_start = ident_start + 1
|
||||||
local name = trimmed:sub(ident_start, ident_end)
|
local name = trimmed:sub(ident_start, ident_end) ---@type string
|
||||||
if name ~= "" then names[#names + 1] = name end
|
if name ~= "" then names[#names + 1] = name end
|
||||||
|
::continue::
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
if #names == 0 then return nil end
|
if #names == 0 then return nil end
|
||||||
return names
|
return names
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--- @param args_str string|nil
|
||||||
|
--- @return string[]|nil
|
||||||
|
local function formal_arg_names(args_str)
|
||||||
|
local names = extract_arg_names(args_str) ---@type string[]|nil
|
||||||
|
if not names then return nil end
|
||||||
|
if names[1] == "ab" then table.remove(names, 1) end
|
||||||
|
if #names == 0 then return nil end
|
||||||
|
return names
|
||||||
|
end
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Component projection (read from pre-scanned SourceScan)
|
-- Component projection (read from pre-scanned SourceScan)
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -171,25 +241,25 @@ end
|
|||||||
--- Carries the scanner-owned `debug_skip` flag forward so the generated projection can emit `/* atom_dbg_skip */`
|
--- Carries the scanner-owned `debug_skip` flag forward so the generated projection can emit `/* atom_dbg_skip */`
|
||||||
--- before the authored comment and so `update_canonical_components` can mirror the same field onto `corpus.components[name]`.
|
--- before the authored comment and so `update_canonical_components` can mirror the same field onto `corpus.components[name]`.
|
||||||
--- @param source string -- the full source text (needed for backward lookups)
|
--- @param source string -- the full source text (needed for backward lookups)
|
||||||
--- @param scan table -- SourceScan from duffle.scan_source
|
--- @param scan SourceScan
|
||||||
--- @return Component[]
|
--- @return Component[]
|
||||||
local function project_components(source, scan)
|
local function project_components(source, scan)
|
||||||
local out = {}
|
local out = {} ---@type Component[]
|
||||||
for _, a in ipairs(scan.atoms) do
|
for _, a in ipairs(scan.atoms) do ---@type integer, AtomEntry
|
||||||
-- Only `MipsAtomComp_(ac_X)` (kind="comp_bare") and `MipsAtomComp_Proc_(ac_X, ...)` (kind="comp_proc")
|
-- Only `MipsAtomComp_(ac_X)` (kind="comp_bare") and `MipsAtomComp_Proc_(ac_X, ...)` (kind="comp_proc")
|
||||||
-- are COMPONENTS — they get inlined via `mac_<name>` aliases inside atom bodies.
|
-- are COMPONENTS — they get inlined via `mac_<name>` aliases inside atom bodies.
|
||||||
-- `MipsAtom_Proc_` (kind="atom_proc") is an ATOM (ends with `mac_yield()`); it gets emitted via
|
-- `MipsAtom_Proc_` (kind="atom_proc") is an ATOM (ends with `mac_yield()`); it gets emitted via
|
||||||
-- `tb_emit(tb, code_<name>)` (linker symbol), NOT inlined as a macro. Including `atom_proc` here
|
-- `tb_emit` of the C ident, NOT inlined as a macro. Including `atom_proc` here
|
||||||
-- would incorrectly emit `mac_<name>` aliases for atoms, polluting `gen/macs.h`.
|
-- would incorrectly emit `mac_<name>` aliases for atoms, polluting `gen/macs.h`.
|
||||||
-- See `docs/duffle_dsl_primer.md` §"mac_* aliases" for the contract.
|
-- See `docs/duffle_dsl_primer.md` §"mac_* aliases" for the contract.
|
||||||
if a.kind == "comp_bare" or a.kind == "comp_proc" then
|
if a.kind == "comp_bare" or a.kind == "comp_proc" then
|
||||||
-- Function-args lookup is meaningful for `MipsAtomComp_Proc_` components
|
-- Function-args lookup is meaningful for `MipsAtomComp_Proc_` components
|
||||||
-- (the macro sits inside `FI_ Slice_MipsCode ac_X(...)`); the alias expansion
|
-- (the macro sits inside `FI_ Slice_MipsCode ac_X(...)`); the alias expansion
|
||||||
-- discards the `ab` (atom-builder) arg the same way both forms do.
|
-- discards the `ab` (atom-builder) arg the same way both forms do.
|
||||||
local args = find_function_args_for(source, a.raw_name, a.ident_pos)
|
local args = find_function_args_for(source, a.raw_name, a.ident_pos) ---@type string|nil
|
||||||
-- Comment ownership: scan_source.lua stamps `declaration_comment` on the record by walking backward past any associated bare marker.
|
-- Comment ownership: scan_source.lua stamps `declaration_comment` on the record by walking backward past any associated bare marker.
|
||||||
-- The pass reads `declaration_comment` directly.
|
-- The pass reads `declaration_comment` directly.
|
||||||
local comment = a.declaration_comment or ""
|
local comment = a.declaration_comment or "" ---@type string
|
||||||
out[#out + 1] = {
|
out[#out + 1] = {
|
||||||
line = a.line,
|
line = a.line,
|
||||||
name = a.name,
|
name = a.name,
|
||||||
@@ -197,6 +267,7 @@ local function project_components(source, scan)
|
|||||||
body_off = a.body_off,
|
body_off = a.body_off,
|
||||||
body_tokens = a.body_tokens,
|
body_tokens = a.body_tokens,
|
||||||
args = args,
|
args = args,
|
||||||
|
arg_names = formal_arg_names(args),
|
||||||
comment = comment,
|
comment = comment,
|
||||||
kind = a.kind, -- "comp_bare" | "comp_proc"; provenance emitter reads this.
|
kind = a.kind, -- "comp_bare" | "comp_proc"; provenance emitter reads this.
|
||||||
debug_skip = a.debug_skip == true,
|
debug_skip = a.debug_skip == true,
|
||||||
@@ -219,23 +290,23 @@ end
|
|||||||
--- @param s string
|
--- @param s string
|
||||||
--- @return string
|
--- @return string
|
||||||
local function convert_line_comments_to_block(s)
|
local function convert_line_comments_to_block(s)
|
||||||
local result = s
|
local result = s ---@type string
|
||||||
local pos = 1
|
local pos = 1 ---@type integer
|
||||||
local len = #result
|
local len = #result ---@type integer
|
||||||
while pos <= len do
|
while pos <= len do
|
||||||
local is_double_slash = result:byte(pos) == BYTE_SLASH
|
local is_double_slash = result:byte(pos) == BYTE_SLASH ---@type boolean
|
||||||
and pos + 1 <= len and result:byte(pos + 1) == BYTE_SLASH
|
and pos + 1 <= len and result:byte(pos + 1) == BYTE_SLASH
|
||||||
if not is_double_slash then
|
if not is_double_slash then
|
||||||
pos = pos + 1
|
pos = pos + 1
|
||||||
else
|
else
|
||||||
-- Find end of line.
|
-- Find end of line.
|
||||||
local eol = pos
|
local eol = pos ---@type integer
|
||||||
while eol <= len and result:byte(eol) ~= BYTE_NEWLINE do
|
while eol <= len and result:byte(eol) ~= BYTE_NEWLINE do
|
||||||
eol = eol + 1
|
eol = eol + 1
|
||||||
end
|
end
|
||||||
local before = result:sub(1, pos - 1)
|
local before = result:sub(1, pos - 1) ---@type string
|
||||||
local comment = result:sub(pos + 2, eol - 1) -- skip the `//`
|
local comment = result:sub(pos + 2, eol - 1) ---@type string -- skip the `//`
|
||||||
local after
|
local after ---@type string
|
||||||
if eol <= len and result:byte(eol) == BYTE_NEWLINE then
|
if eol <= len and result:byte(eol) == BYTE_NEWLINE then
|
||||||
after = " */" .. result:sub(eol) -- keep the newline
|
after = " */" .. result:sub(eol) -- keep the newline
|
||||||
else
|
else
|
||||||
@@ -265,25 +336,54 @@ local function strip_mac_prefix(ident)
|
|||||||
return ident
|
return ident
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--- Strip a leading delay marker (`LdSlot_` / `BdSlot_` / `GteDelay_` / `DmaSlot_`)
|
||||||
|
--- plus following whitespace and block comments. Returns the remainder, or ""
|
||||||
|
--- when the token is only the marker.
|
||||||
|
--- `BdSlot_ nop` becomes `nop`. Bare `LdSlot_` becomes "".
|
||||||
|
--- @param tok string
|
||||||
|
--- @return string
|
||||||
|
local function strip_leading_delay_marker(tok)
|
||||||
|
local ident = duffle.read_ident(tok, 1) ---@type string|nil
|
||||||
|
if not ident or not duffle.DELAY_MARKERS[ident] then return tok end
|
||||||
|
local rest = tok:sub(#ident + 1):match("^%s*(.*)$") or "" ---@type string
|
||||||
|
while rest:sub(1, 2) == "/*" do
|
||||||
|
local close = rest:find("*/", 3, true) ---@type integer|nil
|
||||||
|
if not close then return "" end
|
||||||
|
rest = rest:sub(close + 2):match("^%s*(.*)$") or ""
|
||||||
|
end
|
||||||
|
return rest
|
||||||
|
end
|
||||||
|
|
||||||
--- (internal) Recursive word-count lookup. `cache` is the memoization table shared across all components
|
--- (internal) Recursive word-count lookup. `cache` is the memoization table shared across all components
|
||||||
--- in a single source's `count_all_components` pass; the in-progress -1 sentinel detects cycles (A -> B -> A).
|
--- in a single source's `count_all_components` pass; the in-progress -1 sentinel detects cycles (A -> B -> A).
|
||||||
--- @param name string -- the component name (without `mac_`)
|
--- @param name string -- the component name (without `mac_`)
|
||||||
--- @param comp_by_name table<string, Component>
|
--- @param comp_by_name table<string, Component>
|
||||||
--- @param wc table<string, integer>
|
--- @param wc WordCounts
|
||||||
--- @param cache table<string, integer>
|
--- @param cache table<string, integer> -- bag: name -> count; -1 in-progress sentinel
|
||||||
--- @return integer
|
--- @return integer
|
||||||
local function word_count_rec(name, comp_by_name, wc, cache)
|
local function word_count_rec(name, comp_by_name, wc, cache)
|
||||||
if cache[name] ~= nil then return cache[name] end
|
if cache[name] ~= nil then return cache[name] end
|
||||||
cache[name] = -1 -- mark in-progress (cycle detection)
|
cache[name] = -1 -- mark in-progress (cycle detection)
|
||||||
local cc = comp_by_name[name]
|
local cc = comp_by_name[name] ---@type Component|nil
|
||||||
local n
|
local n ---@type integer
|
||||||
if cc then
|
if cc then
|
||||||
n = 0
|
n = 0
|
||||||
local tokens = cc.body_tokens
|
local tokens = cc.body_tokens ---@type BodyToken[]
|
||||||
for _, t in ipairs(tokens) do
|
for _, t in ipairs(tokens) do ---@type integer, BodyToken
|
||||||
local trimmed = t.tok
|
local trimmed = t.tok ---@type string
|
||||||
if trimmed ~= "" then
|
if trimmed ~= "" then
|
||||||
local lookup = strip_mac_prefix(duffle.read_ident(trimmed, 1))
|
local work = trimmed ---@type string
|
||||||
|
while true do
|
||||||
|
local marker = duffle.read_ident(work, 1) ---@type string|nil
|
||||||
|
if marker and duffle.DELAY_MARKERS[marker] then
|
||||||
|
work = strip_leading_delay_marker(work)
|
||||||
|
if work == "" then break end
|
||||||
|
else
|
||||||
|
break
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if work ~= "" then
|
||||||
|
local lookup = strip_mac_prefix(duffle.read_ident(work, 1)) ---@type string|nil
|
||||||
if lookup == "atom_label" or lookup == "atom_offset" then
|
if lookup == "atom_label" or lookup == "atom_offset" then
|
||||||
-- Pure metaprogram anchors; emit zero words.
|
-- Pure metaprogram anchors; emit zero words.
|
||||||
elseif lookup and comp_by_name[lookup] then
|
elseif lookup and comp_by_name[lookup] then
|
||||||
@@ -298,6 +398,7 @@ local function word_count_rec(name, comp_by_name, wc, cache)
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
end
|
||||||
else
|
else
|
||||||
-- Not a known component: assume 1 word (regular instruction).
|
-- Not a known component: assume 1 word (regular instruction).
|
||||||
n = 1
|
n = 1
|
||||||
@@ -312,14 +413,14 @@ end
|
|||||||
--- references hit memoized values instead of re-walking the body.
|
--- references hit memoized values instead of re-walking the body.
|
||||||
--- Cycle detection (A -> B -> A) is preserved via the in-progress `-1` sentinel in `cache`.
|
--- Cycle detection (A -> B -> A) is preserved via the in-progress `-1` sentinel in `cache`.
|
||||||
--- @param components Component[]
|
--- @param components Component[]
|
||||||
--- @param wc table<string, integer>
|
--- @param wc WordCounts
|
||||||
--- @return table<string, integer> -- map of component name (without `mac_`) -> word count
|
--- @return table<string, integer> -- bag: bare component name -> word count
|
||||||
local function count_all_components(components, wc)
|
local function count_all_components(components, wc)
|
||||||
local comp_by_name = {}
|
local comp_by_name = {} ---@type table<string, Component>
|
||||||
for _, cc in ipairs(components) do comp_by_name[cc.name] = cc end
|
for _, cc in ipairs(components) do comp_by_name[cc.name] = cc end ---@type integer, Component
|
||||||
local cache = {}
|
local cache = {} ---@type table<string, integer> -- bag: memo; -1 in-progress sentinel
|
||||||
local counts = {}
|
local counts = {} ---@type table<string, integer> -- bag: bare name -> word count
|
||||||
for _, c in ipairs(components) do
|
for _, c in ipairs(components) do ---@type integer, Component
|
||||||
counts[c.name] = word_count_rec(c.name, comp_by_name, wc, cache)
|
counts[c.name] = word_count_rec(c.name, comp_by_name, wc, cache)
|
||||||
end
|
end
|
||||||
return counts
|
return counts
|
||||||
@@ -334,102 +435,87 @@ end
|
|||||||
-- Always walk the original `MipsAtomComp_` body via `cc.body_tokens`.
|
-- Always walk the original `MipsAtomComp_` body via `cc.body_tokens`.
|
||||||
-- ═══════════════════════════════════════════
|
-- ═══════════════════════════════════════════
|
||||||
|
|
||||||
--- (internal) Recursive cycle-cost derivation. Sum `latency[ident]` per emitted instruction in the component body,
|
--- (internal) One walk of a component body that fills both `cycle_cost` and `gp0_contrib`.
|
||||||
--- recursing through nested `mac_*` calls (so `mac_format_g4_color`'s cost = 4 × `mac_pack_color_word`'s cost).
|
--- Cycle: sum `isa.cycles` / `gte.cycles` / `latency[ident]` / 1 per leaf, recurse `mac_*`.
|
||||||
--- Special rule: `mac_yield`'s cost = 0 (per `lottes_tape.h:125-130` "the runtime cost lands in the next atom's prologue").
|
--- `mac_yield` cycle_cost is 0 (runtime cost lands in the next atom's prologue); its gp0 still comes from the token walk.
|
||||||
|
--- GP0: count `gte_sw` and `store_word` / `store_half` / `store_byte` that target `R_PrimCursor` / `O_(Poly_` / `r_prim_cursor` / `r_primitive_cursor` / `r_base`.
|
||||||
|
--- `insert_ot_tag*` gp0_contrib is 0; cycle still comes from the body walk.
|
||||||
|
--- Missing component: cycle 1, gp0 0.
|
||||||
--- @param name string -- component bare name (e.g. "yield", "pack_color_word")
|
--- @param name string -- component bare name (e.g. "yield", "pack_color_word")
|
||||||
--- @param comp_by_name table<string, Component>
|
--- @param comp_by_name table<string, Component>
|
||||||
--- @param latency table<string, integer>
|
--- @param latency table<string, integer> -- bag: ident -> cycle cost
|
||||||
--- @param cache table<string, integer> -- shared memoization; `-1` sentinel detects cycles
|
--- @param cache ComponentMetaMap
|
||||||
--- @return integer
|
--- @return ComponentMeta
|
||||||
local function cycle_cost_rec(name, comp_by_name, latency, cache)
|
local function component_meta_rec(name, comp_by_name, latency, cache)
|
||||||
if cache[name] ~= nil then return cache[name] end
|
if cache[name] ~= nil then return cache[name] end
|
||||||
cache[name] = -1
|
cache[name] = { cycle_cost = -1, gp0_contrib = -1 }
|
||||||
local cc = comp_by_name[name]
|
local cc = comp_by_name[name] ---@type Component|nil
|
||||||
local n
|
local cycle_cost ---@type integer
|
||||||
|
local gp0_contrib ---@type integer
|
||||||
if cc then
|
if cc then
|
||||||
if name == "yield" then
|
local skip_cycle = (name == "yield") ---@type boolean
|
||||||
-- mac_yield's cost is 0 by convention (the runtime cost lands in the next atom's prologue).
|
local skip_gp0 = name:match("^insert_ot_tag") ~= nil ---@type boolean
|
||||||
n = 0
|
cycle_cost = 0
|
||||||
else
|
gp0_contrib = 0
|
||||||
n = 0
|
if not skip_cycle or not skip_gp0 then
|
||||||
local tokens = cc.body_tokens
|
local tokens = cc.body_tokens ---@type BodyToken[]
|
||||||
for _, t in ipairs(tokens) do
|
for _, t in ipairs(tokens) do ---@type integer, BodyToken
|
||||||
local trimmed = t.tok
|
local trimmed = t.tok ---@type string
|
||||||
if trimmed ~= "" then
|
if trimmed ~= "" then
|
||||||
local ident = duffle.read_ident(trimmed, 1)
|
local ident = duffle.read_ident(trimmed, 1) ---@type string|nil
|
||||||
if ident and ident:sub(1, MAC_PREFIX_LEN) == MAC_PREFIX then
|
if ident and ident:sub(1, MAC_PREFIX_LEN) == MAC_PREFIX then
|
||||||
-- Nested `mac_X(...)` call: recurse.
|
local nested = ident:sub(MAC_PREFIX_LEN + 1) ---@type string
|
||||||
local nested = ident:sub(MAC_PREFIX_LEN + 1)
|
local nested_meta = component_meta_rec(nested, comp_by_name, latency, cache) ---@type ComponentMeta
|
||||||
n = n + cycle_cost_rec(nested, comp_by_name, latency, cache)
|
if not skip_cycle then
|
||||||
else
|
cycle_cost = cycle_cost + nested_meta.cycle_cost
|
||||||
-- Leaf instruction or pseudo-macro. Look up in INSTRUCTION_LATENCY; default 1.
|
|
||||||
n = n + (latency[ident] or 1)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
if not skip_gp0 then
|
||||||
|
gp0_contrib = gp0_contrib + nested_meta.gp0_contrib
|
||||||
end
|
end
|
||||||
else
|
else
|
||||||
n = 1
|
if not skip_cycle then
|
||||||
|
local isa = duffle.instr(ident) ---@type InstructionRow|nil
|
||||||
|
local gte = duffle.gte(ident) ---@type GteCommandRow|nil
|
||||||
|
cycle_cost = cycle_cost + ((isa and isa.cycles) or (gte and gte.cycles) or latency[ident] or 1)
|
||||||
end
|
end
|
||||||
cache[name] = n
|
if not skip_gp0 then
|
||||||
return n
|
if ident == "gte_sw" then
|
||||||
end
|
gp0_contrib = gp0_contrib + 1
|
||||||
|
|
||||||
--- (internal) Recursive GP0 prim-buffer contribution. Count `store_word` / `store_half` / `store_byte`
|
|
||||||
--- calls in the component body that target `R_PrimCursor` (these are the RAM-side prim-buffer words the macro contributes), recursing through nested `mac_*` calls.
|
|
||||||
--- Only `R_PrimCursor`-targeting stores count. Stores targeting other registers (e.g. `R_OtBase`, heap pointers) are not prim-buffer contributions.
|
|
||||||
--- @param name string
|
|
||||||
--- @param comp_by_name table<string, Component>
|
|
||||||
--- @param cache table<string, integer>
|
|
||||||
--- @return integer
|
|
||||||
local function gp0_contrib_rec(name, comp_by_name, cache)
|
|
||||||
if cache[name] ~= nil then return cache[name] end
|
|
||||||
cache[name] = -1
|
|
||||||
local cc = comp_by_name[name]
|
|
||||||
local n
|
|
||||||
if cc then
|
|
||||||
n = 0
|
|
||||||
local tokens = cc.body_tokens
|
|
||||||
for _, t in ipairs(tokens) do
|
|
||||||
local trimmed = t.tok
|
|
||||||
if trimmed ~= "" then
|
|
||||||
local ident = duffle.read_ident(trimmed, 1)
|
|
||||||
if ident and ident:sub(1, MAC_PREFIX_LEN) == MAC_PREFIX then
|
|
||||||
-- Nested `mac_X(...)` call: recurse.
|
|
||||||
local nested = ident:sub(MAC_PREFIX_LEN + 1)
|
|
||||||
n = n + gp0_contrib_rec(nested, comp_by_name, cache)
|
|
||||||
elseif ident == "store_word" or ident == "store_half" or ident == "store_byte" then
|
elseif ident == "store_word" or ident == "store_half" or ident == "store_byte" then
|
||||||
if trimmed:find("R_PrimCursor", 1, true) then
|
if trimmed:find("R_PrimCursor", 1, true)
|
||||||
n = n + 1
|
or trimmed:find("O_(Poly_", 1, true)
|
||||||
|
or trimmed:find("r_prim_cursor", 1, true)
|
||||||
|
or trimmed:find("r_primitive_cursor", 1, true)
|
||||||
|
or trimmed:find("r_base", 1, true)
|
||||||
|
then
|
||||||
|
gp0_contrib = gp0_contrib + 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
else
|
else
|
||||||
n = 0
|
cycle_cost = 1
|
||||||
|
gp0_contrib = 0
|
||||||
end
|
end
|
||||||
cache[name] = n
|
cache[name] = { cycle_cost = cycle_cost, gp0_contrib = gp0_contrib }
|
||||||
return n
|
return cache[name]
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Compute `cycle_cost` + `gp0_contrib` for every component in `components` in a single pass.
|
--- Compute `cycle_cost` + `gp0_contrib` for every component in `components` in a single pass.
|
||||||
--- Memoization cache is built ONCE (per source) and shared across both helpers so that
|
--- One memoization cache; a nested `mac_Y` inside a `mac_X` body computes both fields once.
|
||||||
--- a nested `mac_Y` reference inside a `mac_X` body computes its values once.
|
|
||||||
--- @param components Component[]
|
--- @param components Component[]
|
||||||
--- @param latency table<string, integer>
|
--- @param latency table<string, integer> -- bag: ident -> cycle cost
|
||||||
--- @return table<string, {cycle_cost=integer, gp0_contrib=integer}>
|
--- @return ComponentMetaMap
|
||||||
local function compute_components_metadata(components, latency)
|
local function compute_components_metadata(components, latency)
|
||||||
local comp_by_name = {}
|
local comp_by_name = {} ---@type table<string, Component>
|
||||||
for _, cc in ipairs(components) do comp_by_name[cc.name] = cc end
|
for _, cc in ipairs(components) do comp_by_name[cc.name] = cc end ---@type integer, Component
|
||||||
local cc_cache = {}
|
local cache = {} ---@type ComponentMetaMap
|
||||||
local gc_cache = {}
|
local out = {} ---@type ComponentMetaMap
|
||||||
local out = {}
|
for _, c in ipairs(components) do ---@type integer, Component
|
||||||
for _, c in ipairs(components) do
|
out[c.name] = component_meta_rec(c.name, comp_by_name, latency, cache)
|
||||||
out[c.name] = {
|
|
||||||
cycle_cost = cycle_cost_rec(c.name, comp_by_name, latency, cc_cache),
|
|
||||||
gp0_contrib = gp0_contrib_rec(c.name, comp_by_name, gc_cache),
|
|
||||||
}
|
|
||||||
end
|
end
|
||||||
return out
|
return out
|
||||||
end
|
end
|
||||||
@@ -443,11 +529,11 @@ end
|
|||||||
--- @param s string
|
--- @param s string
|
||||||
--- @return string[]
|
--- @return string[]
|
||||||
local function split_comment_lines(s)
|
local function split_comment_lines(s)
|
||||||
local out = {}
|
local out = {} ---@type string[]
|
||||||
local pos = 1
|
local pos = 1 ---@type integer
|
||||||
local s_len = #s
|
local s_len = #s ---@type integer
|
||||||
while pos <= s_len do
|
while pos <= s_len do
|
||||||
local nl = s:find("\n", pos, true)
|
local nl = s:find("\n", pos, true) ---@type integer|nil
|
||||||
if not nl then
|
if not nl then
|
||||||
out[#out + 1] = s:sub(pos)
|
out[#out + 1] = s:sub(pos)
|
||||||
break
|
break
|
||||||
@@ -466,41 +552,120 @@ end
|
|||||||
--- @param args_str string|nil
|
--- @param args_str string|nil
|
||||||
--- @return string
|
--- @return string
|
||||||
local function signature_from_args(args_str)
|
local function signature_from_args(args_str)
|
||||||
local arg_names = extract_arg_names(args_str)
|
local names = formal_arg_names(args_str) ---@type string[]|nil
|
||||||
if arg_names and #arg_names > 0 then
|
if names then
|
||||||
-- Drop the leading `ab` (atom-builder) first arg if present.
|
return table.concat(names, ", ")
|
||||||
-- Convention: `MipsAtomComp_Proc_` components always declare `ab` as the first function-arg
|
|
||||||
-- (type `MipsAtomBuilder_R`), mirroring the macro signature in `lottes_tape.h`.
|
|
||||||
if arg_names[1] == "ab" then
|
|
||||||
table.remove(arg_names, 1)
|
|
||||||
end
|
|
||||||
if #arg_names > 0 then
|
|
||||||
return table.concat(arg_names, ", ")
|
|
||||||
end
|
|
||||||
return "..." -- `ab` was the only arg; fall through to variadic
|
|
||||||
end
|
end
|
||||||
return "..."
|
return "..."
|
||||||
end
|
end
|
||||||
|
|
||||||
--- Strip the trailing `" \"` (space + backslash) line continuation from the last body line.
|
--- Strip the trailing `" \"` (space + backslash) line continuation from the last body line.
|
||||||
--- The last 2 chars are always that pair.
|
--- The last 2 chars are always that pair.
|
||||||
|
--- @param lines string[]
|
||||||
|
--- @return nil
|
||||||
local function strip_trailing_continuation(lines)
|
local function strip_trailing_continuation(lines)
|
||||||
local last = lines[#lines]
|
local last = lines[#lines] ---@type string
|
||||||
if last:sub(-2) == " \\" then
|
if last:sub(-2) == " \\" then
|
||||||
lines[#lines] = last:sub(1, -3)
|
lines[#lines] = last:sub(1, -3)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
--- Classify a token as a "pure delay marker token" (a delay-marker identifier with no following instruction — only whitespace and/or block comments).
|
||||||
|
--- Examples that match:
|
||||||
|
--- * `GteDelay_` → marker alone
|
||||||
|
--- * `GteDelay_ /* RT diagonal: D1 = a.x... */` → marker + block comment
|
||||||
|
--- * `GteDelay_ /* RT diagonal: ... */\n\t` → marker + comment + trailing whitespace
|
||||||
|
--- Examples that DO NOT match (these contain a real instruction after the marker and must be preserved verbatim so the instruction still gets emitted):
|
||||||
|
--- * `GteDelay_ nop2`
|
||||||
|
--- * `GteDelay_ add_si(r.dst_ptr, r.scratch, dst_offset)`
|
||||||
|
---
|
||||||
|
--- Why this classification matters: the metaprogram emits tokens separated by `,` and joins them with `\<newline>` line continuations. After C preprocessor
|
||||||
|
--- phase 2 (line splicing), the macro body collapses to a single logical line.
|
||||||
|
--- Each delay-marker identifier expands to empty (its definition `#define GteDelay_ // ...` consumes the `//` line comment during preprocessing
|
||||||
|
--- of the definition itself, leaving an empty replacement list).
|
||||||
|
--- When a token is purely a delay marker with only a trailing comment, the `,` the metaprogram normally adds before
|
||||||
|
--- each token-after-the-first brackets empty content and produces the syntax error `,,` (`expected expression before ',' token`) at C compile.
|
||||||
|
--- The metaprogram therefore emits such tokens WITHOUT the leading `,` (see `token_skips_leading_comma`) —
|
||||||
|
--- but the marker + trailing comment are still emitted verbatim so the annotation is preserved in `gen/macs.h`.
|
||||||
|
--- @param tok string -- a single token from split_top_level_commas (already trimmed at the start, may contain trailing whitespace + block comment)
|
||||||
|
--- @return boolean
|
||||||
|
local function is_pure_delay_marker_token(tok)
|
||||||
|
local markers = duffle.DELAY_MARKERS ---@type table<string, boolean> -- bag: delay-marker ident -> true
|
||||||
|
if type(markers) ~= "table" then return false end
|
||||||
|
|
||||||
|
-- Identify a leading delay-marker identifier (e.g. `GteDelay_`).
|
||||||
|
local ident_end = 1 ---@type integer
|
||||||
|
while ident_end <= #tok do
|
||||||
|
local ch = tok:sub(ident_end, ident_end) ---@type string
|
||||||
|
if ch:match("[%w_]") then
|
||||||
|
ident_end = ident_end + 1
|
||||||
|
else
|
||||||
|
break
|
||||||
|
end
|
||||||
|
end
|
||||||
|
local ident = tok:sub(1, ident_end - 1) ---@type string
|
||||||
|
if not markers[ident] then return false end
|
||||||
|
|
||||||
|
-- Walk the remainder: only whitespace and block comments are allowed.
|
||||||
|
local scan = ident_end ---@type integer
|
||||||
|
while scan <= #tok do
|
||||||
|
local ch = tok:sub(scan, scan) ---@type string
|
||||||
|
if ch:match("%s") then
|
||||||
|
scan = scan + 1
|
||||||
|
elseif ch == "/" and tok:sub(scan + 1, scan + 1) == "*" then
|
||||||
|
local close = tok:find("*/", scan + 2, true) ---@type integer|nil
|
||||||
|
if not close then return false end
|
||||||
|
scan = close + 2
|
||||||
|
else
|
||||||
|
-- Non-whitespace, non-block-comment content: a real instruction
|
||||||
|
-- follows the marker (e.g. `GteDelay_ nop2`); keep this token intact.
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return true
|
||||||
|
end
|
||||||
|
|
||||||
|
--- Classify a token's "leading comma requirement".
|
||||||
|
--- Pure delay-marker tokens (`GteDelay_` / `LdSlot_` / `BdSlot_` / `DmaSlot_`
|
||||||
|
--- followed by whitespace + optional block comment and NOTHING ELSE) expand
|
||||||
|
--- to empty at C preprocessor time. Emitting them WITHOUT the leading `,`
|
||||||
|
--- separator that the metaprogram normally adds before each token after the
|
||||||
|
--- first keeps exactly one `,` between the surrounding real expressions in the spliced macro body:
|
||||||
|
--- * before this rule: `<tok1> ,\t<gdelay> ,\t<tok3>` → after expansion
|
||||||
|
--- `<tok1> , /* comment */ , <tok3>` → `,,` syntax error.
|
||||||
|
--- * after this rule: `<tok1> \t<gdelay> ,\t<tok3>` → after expansion
|
||||||
|
--- `<tok1> /* comment */ , <tok3>` → `<tok1>, <tok3>` — valid.
|
||||||
|
---
|
||||||
|
--- Tokens like `GteDelay_ nop2` keep the leading `,`
|
||||||
|
--- (the marker is followed by a real instruction, so the marker + instruction together need the separator on the LEFT to land between two real expressions).
|
||||||
|
--- @param tok string
|
||||||
|
--- @return boolean -- true if the token needs NO leading `,` separator.
|
||||||
|
local function token_skips_leading_comma(tok)
|
||||||
|
return is_pure_delay_marker_token(tok)
|
||||||
|
end
|
||||||
|
|
||||||
--- Emit the `#define mac_X(sig) \<newline>\t<tok1> \<newline>,\t<tok2> ...` block.
|
--- Emit the `#define mac_X(sig) \<newline>\t<tok1> \<newline>,\t<tok2> ...` block.
|
||||||
--- Converts `//` line comments to `/* */` block comments in each token so they don't break the C macro `\` line continuations.
|
--- Converts `//` line comments to `/* */` block comments in each token so they don't break the C macro `\` line continuations.
|
||||||
|
---
|
||||||
|
--- Pure delay-marker tokens (`GteDelay_` / `LdSlot_` / `BdSlot_` / `DmaSlot_` with only a trailing block comment, no real instruction) are emitted WITHOUT a leading `,` separator;
|
||||||
|
--- the annotation IS preserved in the generated header
|
||||||
|
--- (so the comment + marker remain visible to anyone reading `gen/macs.h`), but the C preprocessor expands the marker to empty, so leaving the `,`
|
||||||
|
--- separator out is what stops the `,,` syntax error. See `token_skips_leading_comma` for the contract.
|
||||||
|
--- @param lines string[]
|
||||||
|
--- @param c Component
|
||||||
|
--- @param sig string
|
||||||
|
--- @param tokens string[]
|
||||||
|
--- @return nil
|
||||||
local function emit_macro_body(lines, c, sig, tokens)
|
local function emit_macro_body(lines, c, sig, tokens)
|
||||||
for tok_idx = 1, #tokens do
|
for tok_idx = 1, #tokens do ---@type integer
|
||||||
tokens[tok_idx] = convert_line_comments_to_block(tokens[tok_idx])
|
tokens[tok_idx] = convert_line_comments_to_block(tokens[tok_idx])
|
||||||
end
|
end
|
||||||
|
if #tokens == 0 then return end
|
||||||
lines[#lines + 1] = "#define mac_" .. c.name .. "(" .. sig .. ") \\"
|
lines[#lines + 1] = "#define mac_" .. c.name .. "(" .. sig .. ") \\"
|
||||||
lines[#lines + 1] = "\t" .. tokens[1] .. " \\"
|
lines[#lines + 1] = "\t" .. tokens[1] .. " \\"
|
||||||
for tok_idx = 2, #tokens do
|
for tok_idx = 2, #tokens do ---@type integer
|
||||||
lines[#lines + 1] = ",\t" .. tokens[tok_idx] .. " \\"
|
local sep = token_skips_leading_comma(tokens[tok_idx]) and "\t" or ",\t" ---@type string
|
||||||
|
lines[#lines + 1] = sep .. tokens[tok_idx] .. " \\"
|
||||||
end
|
end
|
||||||
strip_trailing_continuation(lines)
|
strip_trailing_continuation(lines)
|
||||||
end
|
end
|
||||||
@@ -511,11 +676,10 @@ end
|
|||||||
--- The marker is a single line, the comment comes next, and the `#define` line follows. The `debug_skip` stamp is scanner-owned
|
--- The marker is a single line, the comment comes next, and the `#define` line follows. The `debug_skip` stamp is scanner-owned
|
||||||
--- (`a.debug_skip == true` on the declaration record); the components pass projects it directly.
|
--- (`a.debug_skip == true` on the declaration record); the components pass projects it directly.
|
||||||
--- @param c Component
|
--- @param c Component
|
||||||
--- @param components Component[]
|
--- @param counts table<string, integer> -- bag: bare component name -> word count
|
||||||
--- @param wc table<string, integer>
|
|
||||||
--- @return string[] -- list of lines for this component
|
--- @return string[] -- list of lines for this component
|
||||||
local function build_component_lines(c, counts)
|
local function build_component_lines(c, counts)
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
|
|
||||||
-- Marker comment: emitted once for every skipped component.
|
-- Marker comment: emitted once for every skipped component.
|
||||||
-- The marker is scanner-owned (declared by `atom_dbg_skip` immediately before the declaration in the source);
|
-- The marker is scanner-owned (declared by `atom_dbg_skip` immediately before the declaration in the source);
|
||||||
@@ -525,16 +689,16 @@ local function build_component_lines(c, counts)
|
|||||||
end
|
end
|
||||||
|
|
||||||
if c.comment and c.comment ~= "" then
|
if c.comment and c.comment ~= "" then
|
||||||
for _, line in ipairs(split_comment_lines(c.comment)) do
|
for _, line in ipairs(split_comment_lines(c.comment)) do ---@type integer, string
|
||||||
lines[#lines + 1] = line
|
lines[#lines + 1] = line
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
local tokens = duffle.split_top_level_commas(c.body)
|
local tokens = duffle.split_top_level_commas(c.body) ---@type string[]
|
||||||
for i = 1, #tokens do tokens[i] = duffle.trim(tokens[i]) end
|
for i = 1, #tokens do tokens[i] = duffle.trim(tokens[i]) end ---@type integer
|
||||||
local sig = signature_from_args(c.args)
|
local sig = signature_from_args(c.args) ---@type string
|
||||||
-- Direct lookup against the per-source precomputed `counts` table (built once by count_all_components).
|
-- Direct lookup against the per-source precomputed `counts` table (built once by count_all_components).
|
||||||
local n = counts[c.name]
|
local n = counts[c.name] ---@type integer
|
||||||
|
|
||||||
if n > 0 then
|
if n > 0 then
|
||||||
emit_macro_body(lines, c, sig, tokens)
|
emit_macro_body(lines, c, sig, tokens)
|
||||||
@@ -557,11 +721,11 @@ end
|
|||||||
--- @param sources SourceFile[] -- Sources contributing to this directory (for the header comment)
|
--- @param sources SourceFile[] -- Sources contributing to this directory (for the header comment)
|
||||||
--- @return string[]
|
--- @return string[]
|
||||||
local function header_boilerplate(dir, sources)
|
local function header_boilerplate(dir, sources)
|
||||||
local source_lines = { "// Directory: " .. duffle.to_absolute_path(dir) .. "/" }
|
local source_lines = { "// Directory: " .. duffle.to_absolute_path(dir) .. "/" } ---@type string[]
|
||||||
for _, src in ipairs(sources) do
|
for _, src in ipairs(sources) do ---@type integer, SourceFile
|
||||||
source_lines[#source_lines + 1] = "// source: " .. duffle.to_absolute_path(src.path)
|
source_lines[#source_lines + 1] = "// source: " .. duffle.to_absolute_path(src.path)
|
||||||
end
|
end
|
||||||
local source_blob = table.concat(source_lines, "\n")
|
local source_blob = table.concat(source_lines, "\n") ---@type string
|
||||||
return {
|
return {
|
||||||
-- #pragma once wrapped in #ifdef INTELLISENSE_DIRECTIVES, matching the convention in lottes_tape.h.
|
-- #pragma once wrapped in #ifdef INTELLISENSE_DIRECTIVES, matching the convention in lottes_tape.h.
|
||||||
-- The build does manual unity includes (the user controls include order), so the pragma is only active for IDE/tooling.
|
-- The build does manual unity includes (the user controls include order), so the pragma is only active for IDE/tooling.
|
||||||
@@ -589,8 +753,8 @@ end
|
|||||||
--- @return string -- Output directory
|
--- @return string -- Output directory
|
||||||
--- @return string -- Full output path
|
--- @return string -- Full output path
|
||||||
local function compute_macs_h_path(dir)
|
local function compute_macs_h_path(dir)
|
||||||
local out_dir = dir .. "/" .. GEN_SUBDIR
|
local out_dir = dir .. "/" .. GEN_SUBDIR ---@type string
|
||||||
local out_path = out_dir .. "/" .. MACS_FILENAME
|
local out_path = out_dir .. "/" .. MACS_FILENAME ---@type string
|
||||||
return out_dir, out_path
|
return out_dir, out_path
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -600,20 +764,20 @@ end
|
|||||||
--- @param dir string -- Absolute source directory
|
--- @param dir string -- Absolute source directory
|
||||||
--- @param sources SourceFile[] -- Sources contributing to this directory (for the header comment)
|
--- @param sources SourceFile[] -- Sources contributing to this directory (for the header comment)
|
||||||
--- @param components Component[] -- Aggregated components from all sources in this directory
|
--- @param components Component[] -- Aggregated components from all sources in this directory
|
||||||
--- @param counts table<string, integer> -- Precomputed word counts (from count_all_components)
|
--- @param counts table<string, integer> -- bag: bare component name -> word count
|
||||||
--- @return string|nil -- Path to the written file (nil if no components)
|
--- @return string|nil -- Path to the written file (nil if no components)
|
||||||
local function emit_component_macros_h(ctx, dir, sources, components, counts)
|
local function emit_component_macros_h(ctx, dir, sources, components, counts)
|
||||||
if #components == 0 then return nil end
|
if #components == 0 then return nil end
|
||||||
local out_dir, out_path = compute_macs_h_path(dir)
|
local out_dir, out_path = compute_macs_h_path(dir) ---@type string, string
|
||||||
local lines = header_boilerplate(dir, sources)
|
local lines = header_boilerplate(dir, sources) ---@type string[]
|
||||||
|
|
||||||
for _, c in ipairs(components) do
|
for _, c in ipairs(components) do ---@type integer, Component
|
||||||
for _, l in ipairs(build_component_lines(c, counts)) do
|
for _, l in ipairs(build_component_lines(c, counts)) do ---@type integer, string
|
||||||
lines[#lines + 1] = l
|
lines[#lines + 1] = l
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
local content = table.concat(lines, "\n") .. "\n"
|
local content = table.concat(lines, "\n") .. "\n" ---@type string
|
||||||
duffle.ensure_dir(out_dir)
|
duffle.ensure_dir(out_dir)
|
||||||
duffle.write_file_lf(out_path, content)
|
duffle.write_file_lf(out_path, content)
|
||||||
print(string.format(" -> %s", out_path))
|
print(string.format(" -> %s", out_path))
|
||||||
@@ -626,59 +790,55 @@ end
|
|||||||
|
|
||||||
--- (internal) Extend `corpus.word_counts` with this source's component macros so offsets sees them without re-reading the file.
|
--- (internal) Extend `corpus.word_counts` with this source's component macros so offsets sees them without re-reading the file.
|
||||||
--- First declaration wins: a later caller's count is dropped (the existing entry from the first source is preserved).
|
--- First declaration wins: a later caller's count is dropped (the existing entry from the first source is preserved).
|
||||||
--- @param corpus table -- the corpus
|
--- @param corpus Corpus
|
||||||
--- @param components Component[]
|
--- @param components Component[]
|
||||||
--- @param counts table<string, integer> -- precomputed word counts (from count_all_components)
|
--- @param counts table<string, integer> -- bag: bare component name -> word count
|
||||||
|
--- @return nil
|
||||||
local function update_canonical_word_counts(corpus, components, counts)
|
local function update_canonical_word_counts(corpus, components, counts)
|
||||||
local wc = corpus.word_counts
|
local wc = corpus.word_counts ---@type WordCounts
|
||||||
for _, c in ipairs(components) do
|
for _, c in ipairs(components) do ---@type integer, Component
|
||||||
local key = "mac_" .. c.name
|
local key = "mac_" .. c.name ---@type string
|
||||||
if wc[key] == nil then
|
if wc[key] == nil then
|
||||||
wc[key] = counts[c.name]
|
wc[key] = counts[c.name]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
--- @class ComponentDef
|
--- (internal) Populate `corpus.components` with this source's one component row per bare name.
|
||||||
--- @field name string -- Bare name (without ac_/mac_ prefix)
|
|
||||||
--- @field line integer -- Definition source line (line of `MipsAtomComp_(ac_X)` / `MipsAtomComp_Proc_(ac_X, ...)`)
|
|
||||||
--- @field path string -- Absolute source path of the definition
|
|
||||||
--- @field kind string -- "comp_bare" | "comp_proc" (atom_proc is NOT a component)
|
|
||||||
--- @field debug_skip boolean -- Mirror of the scanner-owned `a.debug_skip`; consumers read this directly
|
|
||||||
|
|
||||||
--- (internal) Populate `corpus.components` with this source's components-by-name map.
|
|
||||||
--- First declaration wins; later declarations of the same bare name are dropped and recorded as a collision via `corpus.collisions` (kind = "component").
|
--- First declaration wins; later declarations of the same bare name are dropped and recorded as a collision via `corpus.collisions` (kind = "component").
|
||||||
--- The pass does NOT write to `ctx.shared.components`.
|
--- The pass does NOT write to `ctx.shared.components`.
|
||||||
--- No parallel skip map is built here; consumers that need the per-component skip state read `corpus.components[name].debug_skip` directly.
|
--- No parallel skip map is built here; consumers that need the per-component skip state read `corpus.components[name].debug_skip` directly.
|
||||||
--- The `cycle_cost` + `gp0_contrib` fields are populated from `metadata[c.name]` (computed by `compute_components_metadata` against the original `MipsAtomComp_` body).
|
--- The `cycle_cost` + `gp0_contrib` fields are populated from `metadata[c.name]` (computed by `compute_components_metadata` against the original `MipsAtomComp_` body).
|
||||||
--- @param corpus table -- the corpus
|
--- @param corpus Corpus
|
||||||
--- @param src SourceFile
|
--- @param src SourceFile
|
||||||
--- @param components Component[]
|
--- @param components Component[]
|
||||||
--- @param metadata table<string, {cycle_cost=integer, gp0_contrib=integer}>
|
--- @param metadata ComponentMetaMap
|
||||||
local function update_canonical_components(corpus, src, components, metadata)
|
--- @param scan SourceScan
|
||||||
local rel_path = src.path:gsub("\\", "/")
|
--- @return nil
|
||||||
for _, c in ipairs(components) do
|
local function update_canonical_components(corpus, src, components, metadata, scan)
|
||||||
|
local rel_path = src.path:gsub("\\", "/") ---@type string
|
||||||
|
local line_of = scan and scan.line_of ---@type (fun(pos: integer): integer)|nil
|
||||||
|
for _, c in ipairs(components) do ---@type integer, Component
|
||||||
-- Keyed by bare name (e.g. `yield`, `load_tri_indices`).
|
-- Keyed by bare name (e.g. `yield`, `load_tri_indices`).
|
||||||
-- The atoms_source_map pass looks up components by bare name from the corpus;
|
-- The atoms_source_map pass looks up components by bare name from the corpus;
|
||||||
-- `mac_` prefix lives at the call-site identifier and is stripped before lookup.
|
-- `mac_` prefix lives at the call-site identifier and is stripped before lookup.
|
||||||
local m = metadata and metadata[c.name] or nil
|
local m = metadata and metadata[c.name] or nil ---@type ComponentMeta|nil
|
||||||
if corpus.components[c.name] == nil then
|
if corpus.components[c.name] == nil then
|
||||||
corpus.components[c.name] = {
|
c.path = rel_path
|
||||||
name = c.name,
|
c.source = src.path
|
||||||
line = c.line,
|
c.line_of = line_of
|
||||||
path = rel_path,
|
c.kind = c.kind or "comp_bare"
|
||||||
kind = c.kind or "comp_bare",
|
c.debug_skip = c.debug_skip == true
|
||||||
debug_skip = c.debug_skip == true,
|
c.cycle_cost = m and m.cycle_cost or nil
|
||||||
cycle_cost = m and m.cycle_cost or nil,
|
c.gp0_contrib = m and m.gp0_contrib or nil
|
||||||
gp0_contrib = m and m.gp0_contrib or nil,
|
corpus.components[c.name] = c
|
||||||
}
|
|
||||||
else
|
else
|
||||||
-- A second declaration of the same bare name: record a typed collision so static-analysis + the report can surface it.
|
-- A second declaration of the same bare name: record a typed collision so static-analysis + the report can surface it.
|
||||||
-- Identical-shape declarations (same path + line) reuse the first-wins entry without a collision record.
|
-- Identical-shape declarations (same path + line) reuse the first-wins entry without a collision record.
|
||||||
local existing = corpus.components[c.name]
|
local existing = corpus.components[c.name] ---@type Component
|
||||||
if existing.path ~= rel_path or existing.line ~= c.line then
|
if existing.path ~= rel_path or existing.line ~= c.line then
|
||||||
local kind = c.kind or "comp_bare"
|
local kind = c.kind or "comp_bare" ---@type string
|
||||||
local first_kind = existing.kind or "comp_bare"
|
local first_kind = existing.kind or "comp_bare" ---@type string
|
||||||
corpus.collisions[#corpus.collisions + 1] = {
|
corpus.collisions[#corpus.collisions + 1] = {
|
||||||
kind = "component",
|
kind = "component",
|
||||||
name = c.name,
|
name = c.name,
|
||||||
@@ -692,38 +852,15 @@ local function update_canonical_components(corpus, src, components, metadata)
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
--- (internal) Populate `corpus.component_body_index` with this source's body index entries.
|
|
||||||
--- First declaration wins; later declarations are dropped (no separate collision record: the components collision is already surfaced by `update_canonical_components`).
|
|
||||||
--- The pass writes to `corpus.component_body_index` only (the corpus owns this projection).
|
|
||||||
--- @param corpus table -- the corpus
|
|
||||||
--- @param src SourceFile
|
|
||||||
--- @param components Component[]
|
|
||||||
--- @param scan table -- the SourceScan payload (for line_of)
|
|
||||||
local function update_canonical_component_body_index(corpus, src, components, scan)
|
|
||||||
local line_of = scan and scan.line_of
|
|
||||||
for _, c in ipairs(components) do
|
|
||||||
if corpus.component_body_index[c.name] == nil then
|
|
||||||
corpus.component_body_index[c.name] = {
|
|
||||||
body_tokens = c.body_tokens,
|
|
||||||
body_off = c.body_off,
|
|
||||||
line_of = line_of,
|
|
||||||
source = src.path,
|
|
||||||
declaration = c.line,
|
|
||||||
kind = c.kind,
|
|
||||||
}
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @return PassResult
|
--- @return PassResult
|
||||||
function M.run(ctx)
|
function M.run(ctx)
|
||||||
local outputs = {}
|
local outputs = {} ---@type MacsOutput[]
|
||||||
local errors = {}
|
local errors = {} ---@type Finding[]
|
||||||
local warnings = {}
|
local warnings = {} ---@type Finding[]
|
||||||
|
|
||||||
-- Corpus ownership gate.
|
-- Corpus ownership gate.
|
||||||
local corpus = ctx.shared and ctx.shared.corpus
|
local corpus = ctx.shared and ctx.shared.corpus ---@type Corpus|nil
|
||||||
if type(corpus) ~= "table" then
|
if type(corpus) ~= "table" then
|
||||||
error("components.run requires ctx.shared.corpus.", 0)
|
error("components.run requires ctx.shared.corpus.", 0)
|
||||||
end
|
end
|
||||||
@@ -738,41 +875,39 @@ function M.run(ctx)
|
|||||||
|
|
||||||
-- Projection ownership:
|
-- Projection ownership:
|
||||||
-- * `corpus.word_counts["mac_"..name]` — current component count
|
-- * `corpus.word_counts["mac_"..name]` — current component count
|
||||||
-- * `corpus.components[name]` — bare-name component definition
|
-- * `corpus.components[name]` — one row: body, line_of, source, cost
|
||||||
-- * `corpus.component_body_index[name]` — body / line_of / source index
|
|
||||||
-- The pass writes to the corpus only; consumers read from the corpus directly.
|
-- The pass writes to the corpus only; consumers read from the corpus directly.
|
||||||
|
|
||||||
-- Per-directory aggregation: every source in the same directory contributes to one `gen/macs.h`.
|
-- Per-directory aggregation: every source in the same directory contributes to one `gen/macs.h`.
|
||||||
-- The directory itself is the namespace. `corpus.sources_by_dir` preserves source-order within each bucket (matches `corpus.source_order`).
|
-- The directory itself is the namespace. `corpus.sources_by_dir` preserves source-order within each bucket (matches `corpus.source_order`).
|
||||||
local sources_by_dir = corpus.sources_by_dir or duffle.group_sources_by_dir(corpus.source_order)
|
local sources_by_dir = corpus.sources_by_dir or duffle.group_sources_by_dir(corpus.source_order) ---@type table<string, SourceFile[]>
|
||||||
for dir, sources in pairs(sources_by_dir) do
|
for dir, sources in pairs(sources_by_dir) do ---@type string, SourceFile[]
|
||||||
-- Aggregate components from every source in this directory.
|
-- Aggregate components from every source in this directory.
|
||||||
-- `project_components` returns nil for sources with no `MipsAtomComp_` declarations; we skip those.
|
-- `project_components` returns nil for sources with no `MipsAtomComp_` declarations; we skip those.
|
||||||
local aggregated_components = {}
|
local aggregated_components = {} ---@type Component[]
|
||||||
local metadata_per_source = {}
|
local metadata_per_source = {} ---@type table<SourceFile, ComponentMetaMap>
|
||||||
for _, src in ipairs(sources) do
|
for _, src in ipairs(sources) do ---@type integer, SourceFile
|
||||||
local per_source = project_components(src.text, src.scan) or {}
|
local per_source = project_components(src.text, src.scan) or {} ---@type Component[]
|
||||||
for _, c in ipairs(per_source) do
|
for _, c in ipairs(per_source) do ---@type integer, Component
|
||||||
aggregated_components[#aggregated_components + 1] = c
|
aggregated_components[#aggregated_components + 1] = c
|
||||||
end
|
end
|
||||||
if #per_source > 0 then
|
if #per_source > 0 then
|
||||||
metadata_per_source[src] = compute_components_metadata(per_source, duffle.INSTRUCTION_LATENCY)
|
metadata_per_source[src] = compute_components_metadata(per_source, {})
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
if #aggregated_components > 0 then
|
if #aggregated_components > 0 then
|
||||||
-- Compute word counts across the aggregated set. `corpus.word_counts` carries the
|
-- Compute word counts across the aggregated set. `corpus.word_counts` carries the
|
||||||
-- same-source + prior-directory entries so the recursive lookup sees both.
|
-- same-source + prior-directory entries so the recursive lookup sees both.
|
||||||
local counts = count_all_components(aggregated_components, corpus.word_counts)
|
local counts = count_all_components(aggregated_components, corpus.word_counts) ---@type table<string, integer> -- bag: bare name -> word count
|
||||||
local macs_path = emit_component_macros_h(ctx, dir, sources, aggregated_components, counts)
|
local macs_path = emit_component_macros_h(ctx, dir, sources, aggregated_components, counts) ---@type string|nil
|
||||||
if macs_path then
|
if macs_path then
|
||||||
outputs[#outputs + 1] = { macs_h = macs_path }
|
outputs[#outputs + 1] = { macs_h = macs_path }
|
||||||
-- Populate the projections AFTER disk emission (byte-identical `.macs.h` contract).
|
-- Populate the projections AFTER disk emission (byte-identical `.macs.h` contract).
|
||||||
update_canonical_word_counts(corpus, aggregated_components, counts)
|
update_canonical_word_counts(corpus, aggregated_components, counts)
|
||||||
for _, src in ipairs(sources) do
|
for _, src in ipairs(sources) do ---@type integer, SourceFile
|
||||||
local per_source = project_components(src.text, src.scan) or {}
|
local per_source = project_components(src.text, src.scan) or {} ---@type Component[]
|
||||||
if #per_source > 0 then
|
if #per_source > 0 then
|
||||||
update_canonical_components(corpus, src, per_source, metadata_per_source[src])
|
update_canonical_components(corpus, src, per_source, metadata_per_source[src], src.scan)
|
||||||
update_canonical_component_body_index(corpus, src, per_source, src.scan)
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
+929
-609
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,13 @@
|
|||||||
--- passes/emission_model.lua: Per-atom emission projection.
|
--- passes/emission_model.lua: Per-atom emission projection.
|
||||||
---
|
---
|
||||||
--- The `emission-model` pass owns `atom.paths`, the canonical per-atom mutable surface for atoms and raw atoms with bodies in `ctx.shared.corpus.source_order`.
|
--- The `emission-model` pass owns `atom.paths`, the canonical per-atom mutable surface for atoms and raw atoms with bodies in `ctx.shared.corpus.source_order`.
|
||||||
--- For each atom, the pass invokes `duffle.project_emission(body_text, component_index, word_counts, components)`.
|
--- For each atom, the pass invokes `duffle.project_emission(body_text, components, word_counts, components)`.
|
||||||
--- It stores the ordered `items` stream plus the dense `word_events` / `markers` / `invocations` views on `atom.paths`.
|
--- It stores the ordered `items` stream plus the dense `word_events` / `markers` / `invocations` views on `atom.paths`.
|
||||||
---
|
---
|
||||||
--- Public boundary:
|
--- Public boundary:
|
||||||
--- * `M.run(ctx)` is the only entry point.
|
--- * `M.run(ctx)` is the only entry point.
|
||||||
--- * The pass returns `{outputs = {}, errors = ..., warnings = ...}`.
|
--- * The pass returns `{outputs = {}, errors = ..., warnings = ...}`.
|
||||||
--- Pass kind = `validation` → `PASS_KIND_STOP_ON_ERROR.validation` preserves the existing build-stopping policy.
|
--- Pass kind = `validation`. Findings record on the result; the orchestrator does not exit non-zero.
|
||||||
---
|
---
|
||||||
--- Source-order discipline:
|
--- Source-order discipline:
|
||||||
--- * `corpus.source_order` sets the source-record order.
|
--- * `corpus.source_order` sets the source-record order.
|
||||||
@@ -26,13 +26,94 @@
|
|||||||
---
|
---
|
||||||
--- `passes.scan_source` strips its private `_code_macros` / `_code_macro_bodies` tables before this pass runs.
|
--- `passes.scan_source` strips its private `_code_macros` / `_code_macro_bodies` tables before this pass runs.
|
||||||
|
|
||||||
local M = {}
|
--- @class BodyToken
|
||||||
|
--- @field tok string
|
||||||
|
--- @field rel integer
|
||||||
|
|
||||||
|
--- @class EmissionItem
|
||||||
|
--- @field kind string
|
||||||
|
--- @field encoder string|nil
|
||||||
|
--- @field args string[]|nil
|
||||||
|
--- @field i integer|nil
|
||||||
|
--- @field word_count integer|nil
|
||||||
|
--- @field line integer|nil
|
||||||
|
--- @field call_text string|nil
|
||||||
|
--- @field root_call_text string|nil
|
||||||
|
--- @field invocation_ids integer[]|nil
|
||||||
|
--- @field outermost_invocation_id integer|nil
|
||||||
|
--- @field gpr_keys string[]|nil
|
||||||
|
--- @field ident string|nil
|
||||||
|
--- @field isa_kind string|nil
|
||||||
|
--- @field nop_words integer|nil
|
||||||
|
--- @field is_yield boolean|nil
|
||||||
|
--- @field is_load boolean|nil
|
||||||
|
--- @field is_branch boolean|nil
|
||||||
|
--- @field is_unconditional_jump boolean|nil
|
||||||
|
--- @field is_terminal_jump boolean|nil
|
||||||
|
--- @field gp0_shape string|nil
|
||||||
|
--- @field name string|nil
|
||||||
|
--- @field target string|nil
|
||||||
|
--- @field word_index integer|nil
|
||||||
|
--- @field consuming_encoder string|nil
|
||||||
|
--- @field consuming_arg_pos integer|nil
|
||||||
|
--- @field invocation_id integer|nil
|
||||||
|
|
||||||
|
--- @class WordEvent
|
||||||
|
--- @field i integer
|
||||||
|
--- @field encoder string
|
||||||
|
--- @field args string[]
|
||||||
|
--- @field def_path string
|
||||||
|
--- @field def_line integer
|
||||||
|
--- @field call_text string|nil
|
||||||
|
--- @field root_call_text string|nil
|
||||||
|
--- @field invocation_ids integer[]
|
||||||
|
--- @field outermost_invocation_id integer
|
||||||
|
--- @field word_count integer
|
||||||
|
--- @field gpr_keys string[]|nil
|
||||||
|
--- @field ident string
|
||||||
|
--- @field kind string
|
||||||
|
--- @field nop_words integer
|
||||||
|
--- @field is_yield boolean
|
||||||
|
--- @field is_load boolean
|
||||||
|
--- @field is_branch boolean
|
||||||
|
--- @field is_unconditional_jump boolean
|
||||||
|
--- @field is_terminal_jump boolean
|
||||||
|
--- @field gp0_shape string|nil
|
||||||
|
--- @field body_line integer|nil
|
||||||
|
--- @field call_line integer|nil
|
||||||
|
--- @field call_path string|nil
|
||||||
|
|
||||||
|
--- @class EmissionMarker
|
||||||
|
--- @field kind string
|
||||||
|
--- @field name string
|
||||||
|
--- @field line integer
|
||||||
|
--- @field word_index integer
|
||||||
|
--- @field target string|nil
|
||||||
|
--- @field consuming_encoder string|nil
|
||||||
|
--- @field consuming_arg_pos integer|nil
|
||||||
|
|
||||||
|
-- Finding: see ps1_meta.lua
|
||||||
|
|
||||||
|
--- @class AtomPaths
|
||||||
|
--- @field tokens BodyToken[]
|
||||||
|
--- @field line_in_body table<integer, integer> -- bag: body byte offset -> 1-based line
|
||||||
|
--- @field items EmissionItem[]
|
||||||
|
--- @field word_events WordEvent[]
|
||||||
|
--- @field markers EmissionMarker[]
|
||||||
|
--- @field invocations InvocationRecord[]
|
||||||
|
--- @field errors Finding[]
|
||||||
|
--- @field warnings Finding[]
|
||||||
|
|
||||||
|
--- @class EmissionModelPass
|
||||||
|
--- @field run fun(ctx: PassCtx): PassResult
|
||||||
|
|
||||||
|
local M = {} ---@type EmissionModelPass
|
||||||
|
|
||||||
-- ─────────────────────────────────────────────────────────────────────────
|
-- ─────────────────────────────────────────────────────────────────────────
|
||||||
-- Bootstrap: load `duffle_paths.lua` via debug.getinfo so the module works standalone (run as `luajit passes/emission_model.lua`) and when require'd from the orchestrator.
|
-- Bootstrap: load `duffle_paths.lua` via debug.getinfo so the module works standalone (run as `luajit passes/emission_model.lua`) and when require'd from the orchestrator.
|
||||||
-- ─────────────────────────────────────────────────────────────────────────
|
-- ─────────────────────────────────────────────────────────────────────────
|
||||||
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
|
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" ---@type string
|
||||||
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") ---@type DuffleExport
|
||||||
|
|
||||||
-- ─────────────────────────────────────────────────────────────────────────
|
-- ─────────────────────────────────────────────────────────────────────────
|
||||||
-- Helpers
|
-- Helpers
|
||||||
@@ -45,12 +126,17 @@ local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
|||||||
-- * ROOT invocations (`inv.parent_id == 0`) receive body-relative `call_line` values directly from `M.LineIndex(body_text)` in the walker.
|
-- * ROOT invocations (`inv.parent_id == 0`) receive body-relative `call_line` values directly from `M.LineIndex(body_text)` in the walker.
|
||||||
-- The source `line_of` closure supplies physical lines at the close site, so this function converts each root value exactly once.
|
-- The source `line_of` closure supplies physical lines at the close site, so this function converts each root value exactly once.
|
||||||
-- * INNER invocations (`inv.parent_id ~= 0`) receive physical `call_line` values directly from the COMPONENT's `line_of` in the walker.
|
-- * INNER invocations (`inv.parent_id ~= 0`) receive physical `call_line` values directly from the COMPONENT's `line_of` in the walker.
|
||||||
-- Recursive descent forwards that closure through `corpus.component_body_index[name].line_of`; those values arrive physical and remain unchanged.
|
-- Recursive descent forwards that closure through `corpus.components[name].line_of`; those values arrive physical and remain unchanged.
|
||||||
--
|
--
|
||||||
-- After this function, every `inv.call_line` is physical. DWARF and provenance output read it directly.
|
-- After this function, every `inv.call_line` is physical. DWARF and provenance output read it directly.
|
||||||
-- The word-event loop forwards the already-physical `outer_inv.call_line` into `we.call_line` for words inside an invocation.
|
-- The word-event loop forwards the already-physical `outer_inv.call_line` into `we.call_line` for words inside an invocation.
|
||||||
|
--- @param projection EmissionProjection
|
||||||
|
--- @param atom_record AtomEntry
|
||||||
|
--- @param src SourceFile
|
||||||
|
--- @param corpus Corpus
|
||||||
|
--- @return nil
|
||||||
local function stamp_root_provenance(projection, atom_record, src, corpus)
|
local function stamp_root_provenance(projection, atom_record, src, corpus)
|
||||||
local root_line_of = src.scan and src.scan.line_of
|
local root_line_of = src.scan and src.scan.line_of ---@type (fun(pos: integer): integer)|nil
|
||||||
assert(type(root_line_of) == "function"
|
assert(type(root_line_of) == "function"
|
||||||
, "emission_model: src.scan.line_of is required (canonical LineIndex closure over the source text) to stamp physical provenance")
|
, "emission_model: src.scan.line_of is required (canonical LineIndex closure over the source text) to stamp physical provenance")
|
||||||
assert(type(atom_record.body_off) == "number"
|
assert(type(atom_record.body_off) == "number"
|
||||||
@@ -58,26 +144,29 @@ local function stamp_root_provenance(projection, atom_record, src, corpus)
|
|||||||
-- `root_body_line` is the physical source line of the ATOM HEADER byte containing the opening `{`; that byte is one byte BEFORE `atom_record.body_off`.
|
-- `root_body_line` is the physical source line of the ATOM HEADER byte containing the opening `{`; that byte is one byte BEFORE `atom_record.body_off`.
|
||||||
-- The walker assigns line 2 to the body's first content line because line 1 is the trailing `\n` after `{`. Body-text line k therefore maps to `root_body_line + (k - 1)`.
|
-- The walker assigns line 2 to the body's first content line because line 1 is the trailing `\n` after `{`. Body-text line k therefore maps to `root_body_line + (k - 1)`.
|
||||||
-- `body_off - 1` points at the opening `{`, whose line index identifies the header line. `body_off` points after `{` and would shift every word row forward by one line.
|
-- `body_off - 1` points at the opening `{`, whose line index identifies the header line. `body_off` points after `{` and would shift every word row forward by one line.
|
||||||
local root_body_line = root_line_of(atom_record.body_off - 1) or atom_record.line or 0
|
local root_body_line = root_line_of(atom_record.body_off - 1) or atom_record.line or 0 ---@type integer
|
||||||
local component_index = corpus.component_body_index or {}
|
local components = corpus.components or {} ---@type table<string, Component>
|
||||||
local word_items = {}
|
local word_items = {} ---@type EmissionItem[]
|
||||||
|
|
||||||
for _, item in ipairs(projection.items) do
|
for _, item in ipairs(projection.items) do ---@type integer, EmissionItem
|
||||||
if item.kind == "word" then word_items[#word_items + 1] = item end
|
if item.kind == "word" then word_items[#word_items + 1] = item end
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Resolve one word's physical body line, where the byte containing that word appears in source.
|
-- Resolve one word's physical body line, where the byte containing that word appears in source.
|
||||||
-- * Component expansions carry `invocation_ids`; the component's full-file `line_of` leaves `item.line` physical.
|
-- * Component expansions carry `invocation_ids`; the component's full-file `line_of` leaves `item.line` physical.
|
||||||
-- * Raw tokens in the root atom body carry an empty `invocation_ids` list and a body-relative `item.line`; convert them here.
|
-- * Raw tokens in the root atom body carry an empty `invocation_ids` list and a body-relative `item.line`; convert them here.
|
||||||
|
--- @param event WordEvent
|
||||||
|
--- @param item EmissionItem
|
||||||
|
--- @return integer
|
||||||
local function body_line_for(event, item)
|
local function body_line_for(event, item)
|
||||||
local ids = event.invocation_ids or {}
|
local ids = event.invocation_ids or {} ---@type integer[]
|
||||||
-- The innermost open invocation identifies which line index the walker used.
|
-- The innermost open invocation identifies which line index the walker used.
|
||||||
-- A component `line_of` makes `item.line` physical; the atom's `body_text` line index makes it body-relative.
|
-- A component `line_of` makes `item.line` physical; the atom's `body_text` line index makes it body-relative.
|
||||||
if ids and #ids > 0 then
|
if ids and #ids > 0 then
|
||||||
local inner_id = ids[#ids]
|
local inner_id = ids[#ids] ---@type integer
|
||||||
local inner_inv = inner_id and projection.invocations[inner_id]
|
local inner_inv = inner_id and projection.invocations[inner_id] ---@type InvocationRecord|nil
|
||||||
if inner_inv then
|
if inner_inv then
|
||||||
local component = component_index[inner_inv.component_name]
|
local component = components[inner_inv.component_name] ---@type Component|nil
|
||||||
if component and component.line_of then
|
if component and component.line_of then
|
||||||
-- Walker used `comp.line_of`, which is the source's physical LineIndex. item.line is already physical.
|
-- Walker used `comp.line_of`, which is the source's physical LineIndex. item.line is already physical.
|
||||||
return item.line or 0
|
return item.line or 0
|
||||||
@@ -92,8 +181,8 @@ local function stamp_root_provenance(projection, atom_record, src, corpus)
|
|||||||
-- Stamp the root source path onto invocation records whose `call_path` the walker left empty.
|
-- Stamp the root source path onto invocation records whose `call_path` the walker left empty.
|
||||||
-- The walker passes `body_entry.source` to `emit_invoke_begin`; `M.project_emission` creates the root `body_entry` with source `""`, leaving its `call_path` empty.
|
-- The walker passes `body_entry.source` to `emit_invoke_begin`; `M.project_emission` creates the root `body_entry` with source `""`, leaving its `call_path` empty.
|
||||||
-- This stamp gives every invocation a physical `call_path` matching `passes/atoms_source_map.lua`'s in-memory provenance projection.
|
-- This stamp gives every invocation a physical `call_path` matching `passes/atoms_source_map.lua`'s in-memory provenance projection.
|
||||||
local root_path = src.path or ""
|
local root_path = src.path or "" ---@type string
|
||||||
for _, inv in ipairs(projection.invocations) do
|
for _, inv in ipairs(projection.invocations) do ---@type integer, InvocationRecord
|
||||||
if inv.call_path == nil or inv.call_path == "" then
|
if inv.call_path == nil or inv.call_path == "" then
|
||||||
inv.call_path = root_path
|
inv.call_path = root_path
|
||||||
end
|
end
|
||||||
@@ -102,7 +191,7 @@ local function stamp_root_provenance(projection, atom_record, src, corpus)
|
|||||||
-- Normalize `inv.call_line` to a physical source line.
|
-- Normalize `inv.call_line` to a physical source line.
|
||||||
-- * ROOT invocations (`parent_id == 0`) carry body-relative `call_line` values from `M.LineIndex(body_text)`; convert them once with `root_body_line`.
|
-- * ROOT invocations (`parent_id == 0`) carry body-relative `call_line` values from `M.LineIndex(body_text)`; convert them once with `root_body_line`.
|
||||||
-- * INNER invocations (`parent_id ~= 0`) carry physical `call_line` values from the component's `line_of`; retain them unchanged.
|
-- * INNER invocations (`parent_id ~= 0`) carry physical `call_line` values from the component's `line_of`; retain them unchanged.
|
||||||
for _, inv in ipairs(projection.invocations) do
|
for _, inv in ipairs(projection.invocations) do ---@type integer, InvocationRecord
|
||||||
if inv.parent_id == 0 then
|
if inv.parent_id == 0 then
|
||||||
inv.call_line = (root_body_line or 0) + (inv.call_line or 1) - 1
|
inv.call_line = (root_body_line or 0) + (inv.call_line or 1) - 1
|
||||||
end
|
end
|
||||||
@@ -111,14 +200,14 @@ local function stamp_root_provenance(projection, atom_record, src, corpus)
|
|||||||
-- Build `body_lines` for each invocation.
|
-- Build `body_lines` for each invocation.
|
||||||
-- `atoms_source_map` and `dwarf_injection` read `inv.body_lines[k]` directly from the invocation record created here.
|
-- `atoms_source_map` and `dwarf_injection` read `inv.body_lines[k]` directly from the invocation record created here.
|
||||||
-- Component words already carry physical `item.line` values from the walker's COMPONENT line index, so `body_line_for` returns them unchanged.
|
-- Component words already carry physical `item.line` values from the walker's COMPONENT line index, so `body_line_for` returns them unchanged.
|
||||||
for _, inv in ipairs(projection.invocations) do
|
for _, inv in ipairs(projection.invocations) do ---@type integer, InvocationRecord
|
||||||
local sw = inv.start_word
|
local sw = inv.start_word ---@type integer
|
||||||
local ew = inv.end_word
|
local ew = inv.end_word ---@type integer
|
||||||
local bls = {}
|
local bls = {} ---@type integer[]
|
||||||
for i = sw, ew do
|
for i = sw, ew do ---@type integer
|
||||||
local it = projection.items and projection.items[i]
|
local it = projection.items and projection.items[i] ---@type EmissionItem|nil
|
||||||
if it and it.kind == "word" then
|
if it and it.kind == "word" then
|
||||||
local fake_event = { invocation_ids = { inv.id } }
|
local fake_event = { invocation_ids = { inv.id } } ---@type WordEvent
|
||||||
bls[#bls + 1] = body_line_for(fake_event, it) or 0
|
bls[#bls + 1] = body_line_for(fake_event, it) or 0
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
@@ -128,15 +217,15 @@ local function stamp_root_provenance(projection, atom_record, src, corpus)
|
|||||||
-- Resolve each `word_event`'s physical `body_line` and `call_line`.
|
-- Resolve each `word_event`'s physical `body_line` and `call_line`.
|
||||||
-- For words inside an invocation, `we.call_line` identifies the OUTER atom source line containing the `mac_X(...)` token that triggered expansion.
|
-- For words inside an invocation, `we.call_line` identifies the OUTER atom source line containing the `mac_X(...)` token that triggered expansion.
|
||||||
-- The root-invocation conversion above makes every `inv.call_line` physical; forward it directly and use each raw word's `body_line` as the fallback.
|
-- The root-invocation conversion above makes every `inv.call_line` physical; forward it directly and use each raw word's `body_line` as the fallback.
|
||||||
for index, we in ipairs(projection.word_events) do
|
for index, we in ipairs(projection.word_events) do ---@type integer, WordEvent
|
||||||
local item = word_items[index] or {}
|
local item = word_items[index] or {} ---@type EmissionItem
|
||||||
local body_line = body_line_for(we, item)
|
local body_line = body_line_for(we, item) ---@type integer
|
||||||
item.line = body_line
|
item.line = body_line
|
||||||
we.body_line = body_line
|
we.body_line = body_line
|
||||||
|
|
||||||
local call_line = body_line
|
local call_line = body_line ---@type integer
|
||||||
local outer_id = we.outermost_invocation_id or 0
|
local outer_id = we.outermost_invocation_id or 0 ---@type integer
|
||||||
local outer_inv = projection.invocations[outer_id]
|
local outer_inv = projection.invocations[outer_id] ---@type InvocationRecord|nil
|
||||||
if outer_inv then
|
if outer_inv then
|
||||||
-- `outer_inv.call_line` is physical after the conversion loop above, so use it directly.
|
-- `outer_inv.call_line` is physical after the conversion loop above, so use it directly.
|
||||||
call_line = outer_inv.call_line
|
call_line = outer_inv.call_line
|
||||||
@@ -151,13 +240,46 @@ end
|
|||||||
|
|
||||||
-- Project one atom record into `atom.paths`.
|
-- Project one atom record into `atom.paths`.
|
||||||
-- Mutates the atom record in-place and returns the projection (for pass-level error/warning accumulation).
|
-- Mutates the atom record in-place and returns the projection (for pass-level error/warning accumulation).
|
||||||
|
--- @param atom_record AtomEntry
|
||||||
|
--- @param src SourceFile
|
||||||
|
--- @param corpus Corpus
|
||||||
|
--- @return EmissionProjection
|
||||||
local function project_atom(atom_record, src, corpus)
|
local function project_atom(atom_record, src, corpus)
|
||||||
local body = atom_record.body or ""
|
local body = atom_record.body or "" ---@type string
|
||||||
local wc = corpus.word_counts or {}
|
local wc = corpus.word_counts or {} ---@type WordCounts
|
||||||
local cbi = corpus.component_body_index or {}
|
local comps = corpus.components or {} ---@type table<string, Component>
|
||||||
|
local schema = nil ---@type RegUseSchema|nil
|
||||||
|
if atom_record.reg_use_schema_name then
|
||||||
|
schema = corpus.reg_use_schemas and corpus.reg_use_schemas[atom_record.reg_use_schema_name]
|
||||||
|
end
|
||||||
-- That construction site stamps `invocation.debug_skip` while appending each record to `proj.invocations`.
|
-- That construction site stamps `invocation.debug_skip` while appending each record to `proj.invocations`.
|
||||||
local proj = duffle.project_emission(body, cbi, wc, corpus.components)
|
local proj = duffle.project_emission(body, comps, wc, comps, { ---@type EmissionProjection
|
||||||
local paths = {
|
reg_use_schema = schema,
|
||||||
|
reg_use_param = atom_record.reg_use_param_name,
|
||||||
|
atom_name = atom_record.name,
|
||||||
|
schema_name = atom_record.reg_use_schema_name,
|
||||||
|
})
|
||||||
|
if atom_record.reg_use_schema_name and not schema then
|
||||||
|
proj.errors[#proj.errors + 1] = {
|
||||||
|
kind = "error",
|
||||||
|
check = "reguse_missing_schema",
|
||||||
|
msg = string.format("RegUse schema %q is missing", atom_record.reg_use_schema_name),
|
||||||
|
schema_name = atom_record.reg_use_schema_name,
|
||||||
|
}
|
||||||
|
end
|
||||||
|
for _, err in ipairs(corpus.reg_use_errors or {}) do ---@type integer, RegUseError
|
||||||
|
if err.schema_name == atom_record.reg_use_schema_name then
|
||||||
|
proj.errors[#proj.errors + 1] = {
|
||||||
|
kind = "error",
|
||||||
|
check = err.kind,
|
||||||
|
line = err.line or err.source_line or 0,
|
||||||
|
msg = err.msg or "",
|
||||||
|
source = err.source or err.source_file,
|
||||||
|
schema_name = err.schema_name,
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
local paths = { ---@type AtomPaths
|
||||||
tokens = atom_record.body_tokens or {},
|
tokens = atom_record.body_tokens or {},
|
||||||
line_in_body = duffle.build_body_line_index(body),
|
line_in_body = duffle.build_body_line_index(body),
|
||||||
items = proj.items,
|
items = proj.items,
|
||||||
@@ -179,35 +301,42 @@ end
|
|||||||
--- @param ctx PassCtx -- { shared = { corpus = ... }, out_root, ... }
|
--- @param ctx PassCtx -- { shared = { corpus = ... }, out_root, ... }
|
||||||
--- @return PassResult
|
--- @return PassResult
|
||||||
function M.run(ctx)
|
function M.run(ctx)
|
||||||
local outputs = {}
|
local outputs = {} ---@type PassOutputEntry[]
|
||||||
local errors = {}
|
local errors = {} ---@type Finding[]
|
||||||
local warnings = {}
|
local warnings = {} ---@type Finding[]
|
||||||
|
|
||||||
local corpus = ctx and ctx.shared and ctx.shared.corpus
|
local corpus = ctx and ctx.shared and ctx.shared.corpus ---@type Corpus|nil
|
||||||
if type(corpus) ~= "table" then error("emission_model: ctx.shared.corpus is required (canonical projection)", 0) end
|
if type(corpus) ~= "table" then error("emission_model: ctx.shared.corpus is required (canonical projection)", 0) end
|
||||||
if type(corpus.source_order) ~= "table" then error("emission_model: ctx.shared.corpus.source_order is required", 0) end
|
if type(corpus.source_order) ~= "table" then error("emission_model: ctx.shared.corpus.source_order is required", 0) end
|
||||||
|
|
||||||
-- Project once, collect errors + warnings for one atom.
|
-- Project once, collect errors + warnings for one atom.
|
||||||
-- Kind must be one of: atom | atom_proc | raw_atom | comp_bare | comp_proc.
|
-- Kind must be one of: atom | atom_proc | raw_atom | comp_bare | comp_proc.
|
||||||
|
--- @param atom AtomEntry
|
||||||
|
--- @param src SourceFile
|
||||||
|
--- @return nil
|
||||||
local function process_atom(atom, src)
|
local function process_atom(atom, src)
|
||||||
if not (atom and atom.body) then return end
|
if not (atom and atom.body) then return end
|
||||||
local kind = atom.kind
|
local kind = atom.kind ---@type string
|
||||||
if kind ~= "atom" and kind ~= "atom_proc" and kind ~= "raw_atom" and kind ~= "comp_bare" and kind ~= "comp_proc" then
|
if kind ~= "atom" and kind ~= "atom_proc" and kind ~= "raw_atom" and kind ~= "comp_bare" and kind ~= "comp_proc" then
|
||||||
return
|
return
|
||||||
end
|
end
|
||||||
local proj = project_atom(atom, src, corpus)
|
local proj = project_atom(atom, src, corpus) ---@type EmissionProjection
|
||||||
for _, e in ipairs(proj.errors) do
|
for _, e in ipairs(proj.errors) do ---@type integer, Finding
|
||||||
-- Preserve `kind` (cycle / count_mismatch / unbalanced) so readers dispatch on the diagnostic class and leave the message string as display text.
|
-- Finding.kind is severity. Finding.check holds the diagnostic code
|
||||||
|
-- (cycle / count_mismatch / unbalanced / reguse_*).
|
||||||
errors[#errors + 1] = {
|
errors[#errors + 1] = {
|
||||||
kind = e.kind,
|
kind = "error",
|
||||||
|
check = e.check,
|
||||||
line = e.line,
|
line = e.line,
|
||||||
msg = e.msg,
|
msg = e.msg,
|
||||||
source = e.source or src.path,
|
source = e.source or src.path,
|
||||||
|
schema_name = e.schema_name,
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
for _, w in ipairs(proj.warnings) do
|
for _, w in ipairs(proj.warnings) do ---@type integer, Finding
|
||||||
warnings[#warnings + 1] = {
|
warnings[#warnings + 1] = {
|
||||||
kind = w.kind,
|
kind = "warning",
|
||||||
|
check = w.check,
|
||||||
line = w.line,
|
line = w.line,
|
||||||
msg = w.msg,
|
msg = w.msg,
|
||||||
}
|
}
|
||||||
@@ -217,12 +346,12 @@ function M.run(ctx)
|
|||||||
-- Walk `corpus.source_order`; within each source, visit atoms followed by raw_atoms.
|
-- Walk `corpus.source_order`; within each source, visit atoms followed by raw_atoms.
|
||||||
-- Recognized kinds (atom | atom_proc | raw_atom | comp_bare | comp_proc) each receive the atom.paths projection via duffle.project_emission.
|
-- Recognized kinds (atom | atom_proc | raw_atom | comp_bare | comp_proc) each receive the atom.paths projection via duffle.project_emission.
|
||||||
-- Components are macros inlined into atom bodies; focused tests and isolated component analyses consume atom.paths directly.
|
-- Components are macros inlined into atom bodies; focused tests and isolated component analyses consume atom.paths directly.
|
||||||
for _, src in ipairs(corpus.source_order) do
|
for _, src in ipairs(corpus.source_order) do ---@type integer, SourceFile
|
||||||
local scan = src.scan or {}
|
local scan = src.scan or {} ---@type SourceScan
|
||||||
for _, atom in ipairs(scan.atoms or {}) do
|
for _, atom in ipairs(scan.atoms or {}) do ---@type integer, AtomEntry
|
||||||
process_atom(atom, src)
|
process_atom(atom, src)
|
||||||
end
|
end
|
||||||
for _, atom in ipairs(scan.raw_atoms or {}) do
|
for _, atom in ipairs(scan.raw_atoms or {}) do ---@type integer, AtomEntry
|
||||||
process_atom(atom, src)
|
process_atom(atom, src)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
+114
-88
@@ -1,20 +1,14 @@
|
|||||||
--- passes/offsets.lua — Branch-offset generator.
|
--- passes/offsets.lua — Branch-offset generator.
|
||||||
---
|
---
|
||||||
--- Reads the pre-scanned SourceScan payload (produced once upstream by `duffle.scan_source`)
|
--- Reads the pre-scanned SourceScan payload (produced once upstream by `duffle.scan_source`)
|
||||||
--- for `MipsAtom_(name)` and `MipsCode code_<name>` declarations, computes the word offset
|
--- for `MipsAtom_(name)` and leftover `MipsCode code_*` declarations, computes the word offset
|
||||||
|
--- (ELF symbol is the C ident; raw `code_*` is leftover, not the atom rule)
|
||||||
--- from each `atom_offset(F, T)` marker to its target `atom_label(T)` declaration, and emits
|
--- from each `atom_offset(F, T)` marker to its target `atom_label(T)` declaration, and emits
|
||||||
--- `gen/offsets.h` with one `#define _atom_offset_F_T = N` per branch.
|
--- `gen/offsets.h` with one `#define _atom_offset_F_T = N` per branch.
|
||||||
---
|
---
|
||||||
--- Per-directory aggregation: every source in the same directory contributes to the same `gen/offsets.h`.
|
--- Per-directory aggregation: every source in the same directory contributes to the same `gen/offsets.h`.
|
||||||
--- The directory itself is the namespace; the filename does not repeat the module name.
|
--- The directory itself is the namespace; the filename does not repeat the module name.
|
||||||
---
|
---
|
||||||
--- (Task 12.16 note: atom-namespaced enum names — e.g., `atom_offset__normalize_v3s4__srav_path__aligned_done` —
|
|
||||||
--- were considered to prevent cross-atom label collisions, but the C-side `atom_offset(F, T)` macro in
|
|
||||||
--- `code/duffle/dsl.atom.h` doesn't know the current atom_name at expansion time, so any namespacing
|
|
||||||
--- on the metaprogram side breaks the C build. Reverted. The C-side would need a per-atom
|
|
||||||
--- `CURRENT_ATOM` #define (set by `MipsAtom_`/`MipsAtom_Proc_` macros) plus an updated `atom_offset`
|
|
||||||
--- macro that uses it. That's a coordinated refactor — deferred to a future track.)
|
|
||||||
---
|
|
||||||
--- The offset is `target_word - branch_word - 1` (the standard MIPS branch-immediate encoding: branch_offset = relative_pc_in_words - 1).
|
--- The offset is `target_word - branch_word - 1` (the standard MIPS branch-immediate encoding: branch_offset = relative_pc_in_words - 1).
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -26,41 +20,25 @@
|
|||||||
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
|
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
|
||||||
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works both standalone + when require'd).
|
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works both standalone + when require'd).
|
||||||
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
|
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
|
||||||
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
|
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" ---@type string
|
||||||
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") ---@type DuffleExport
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Constants
|
-- Constants
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
-- Offset macro/enum naming prefixes (the emitted header uses these).
|
-- Offset macro/enum naming prefixes (the emitted header uses these).
|
||||||
local OFFSET_MACRO_PREFIX = "_atom_offset_"
|
local OFFSET_MACRO_PREFIX = "_atom_offset_" ---@type string
|
||||||
local OFFSET_ENUM_PREFIX = "atom_offset_"
|
local OFFSET_ENUM_PREFIX = "atom_offset_" ---@type string
|
||||||
|
|
||||||
-- Column width for the `#define _atom_offset_F_T = N` alignment.
|
-- Column width for the `#define _atom_offset_F_T = N` alignment.
|
||||||
local OFFSET_MACRO_COL = 44
|
local OFFSET_MACRO_COL = 44 ---@type integer
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Type declarations
|
-- Type declarations
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- @class SourceFile
|
-- SourceFile, PassCtx, PassResult: see ps1_meta.lua
|
||||||
--- @field path string -- Absolute path to the source file
|
|
||||||
--- @field text string -- Full source text
|
|
||||||
--- @field dir string -- Directory containing the source
|
|
||||||
--- @field basename string -- Filename without extension
|
|
||||||
--- @field scan table -- Pre-scanned SourceScan payload (from duffle.scan_source)
|
|
||||||
|
|
||||||
--- @class PassCtx
|
|
||||||
--- @field shared table -- Cross-pass shared state
|
|
||||||
--- @field shared.corpus table -- Corpus projection
|
|
||||||
--- @field shared.word_counts table
|
|
||||||
--- @field out_root string -- Output root (e.g. "build/gen")
|
|
||||||
|
|
||||||
--- @class PassResult
|
|
||||||
--- @field outputs table[] -- {kind=, path=} entries describing emit files
|
|
||||||
--- @field errors table[] -- {line=, msg=} entries; build-stops
|
|
||||||
--- @field warnings table[] -- {line=, msg=} entries; build-succeeds
|
|
||||||
|
|
||||||
--- @class BranchOffset
|
--- @class BranchOffset
|
||||||
--- @field tag string -- Marker tag (e.g. "F" in `atom_offset(F, T)`)
|
--- @field tag string -- Marker tag (e.g. "F" in `atom_offset(F, T)`)
|
||||||
@@ -75,6 +53,32 @@ local OFFSET_MACRO_COL = 44
|
|||||||
--- @field total_words integer -- Total word count of the atom body
|
--- @field total_words integer -- Total word count of the atom body
|
||||||
--- @field offsets BranchOffset[] -- Per-branch offset list
|
--- @field offsets BranchOffset[] -- Per-branch offset list
|
||||||
|
|
||||||
|
--- @class OffsetBranch
|
||||||
|
--- @field tag string
|
||||||
|
--- @field target string
|
||||||
|
--- @field branch_word integer
|
||||||
|
--- @field consuming_encoder string|nil
|
||||||
|
--- @field consuming_arg_pos integer|nil
|
||||||
|
--- @field line integer|nil
|
||||||
|
|
||||||
|
--- @class MarkerProjectState
|
||||||
|
--- @field labels table<string, integer> -- bag: label name -> word index
|
||||||
|
--- @field branches OffsetBranch[]
|
||||||
|
|
||||||
|
--- @class OffsetConst
|
||||||
|
--- @field macro_name string
|
||||||
|
--- @field enum_name string
|
||||||
|
--- @field value integer
|
||||||
|
|
||||||
|
--- @class OffsetOutput
|
||||||
|
--- @field offsets_h string
|
||||||
|
|
||||||
|
--- @class OffsetsPass
|
||||||
|
--- @field run fun(ctx: PassCtx): PassResult
|
||||||
|
|
||||||
|
--- @class AtomEntry
|
||||||
|
--- @field paths AtomPaths|nil
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Canonical marker projection
|
-- Canonical marker projection
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
@@ -82,10 +86,16 @@ local OFFSET_MACRO_COL = 44
|
|||||||
-- MARKER_PROJECTORS is the marker-kind data table.
|
-- MARKER_PROJECTORS is the marker-kind data table.
|
||||||
-- The emission-model pass already records marker word positions + consuming-instruction context;
|
-- The emission-model pass already records marker word positions + consuming-instruction context;
|
||||||
-- this pass only projects those records into the label/branch lookup shape needed by offset computation.
|
-- this pass only projects those records into the label/branch lookup shape needed by offset computation.
|
||||||
local MARKER_PROJECTORS = {
|
local MARKER_PROJECTORS = { ---@type table<string, fun(state: MarkerProjectState, marker: EmissionMarker): nil>
|
||||||
|
--- @param state MarkerProjectState
|
||||||
|
--- @param marker EmissionMarker
|
||||||
|
--- @return nil
|
||||||
label = function(state, marker)
|
label = function(state, marker)
|
||||||
state.labels[marker.name] = marker.word_index
|
state.labels[marker.name] = marker.word_index
|
||||||
end,
|
end,
|
||||||
|
--- @param state MarkerProjectState
|
||||||
|
--- @param marker EmissionMarker
|
||||||
|
--- @return nil
|
||||||
offset = function(state, marker)
|
offset = function(state, marker)
|
||||||
state.branches[#state.branches + 1] = {
|
state.branches[#state.branches + 1] = {
|
||||||
tag = marker.name,
|
tag = marker.name,
|
||||||
@@ -99,12 +109,13 @@ local MARKER_PROJECTORS = {
|
|||||||
|
|
||||||
--- Project canonical marker records into the two lookup tables used by the offset renderer.
|
--- Project canonical marker records into the two lookup tables used by the offset renderer.
|
||||||
--- No source text, body text, or body token is inspected.
|
--- No source text, body text, or body token is inspected.
|
||||||
--- @param markers table[] -- atom.paths.markers
|
--- @param markers EmissionMarker[]
|
||||||
--- @return table<string, integer>, table[]
|
--- @return table<string, integer>
|
||||||
|
--- @return OffsetBranch[]
|
||||||
local function project_markers(markers)
|
local function project_markers(markers)
|
||||||
local state = { labels = {}, branches = {} }
|
local state = { labels = {}, branches = {} } ---@type MarkerProjectState
|
||||||
for _, marker in ipairs(markers or {}) do
|
for _, marker in ipairs(markers or {}) do ---@type integer, EmissionMarker
|
||||||
local project = MARKER_PROJECTORS[marker.kind]
|
local project = MARKER_PROJECTORS[marker.kind] ---@type (fun(state: MarkerProjectState, marker: EmissionMarker): nil)|nil
|
||||||
if project then project(state, marker) end
|
if project then project(state, marker) end
|
||||||
end
|
end
|
||||||
return state.labels, state.branches
|
return state.labels, state.branches
|
||||||
@@ -123,38 +134,47 @@ end
|
|||||||
--- For cross-module `j`/`jal` (atom body in one module, target in another), the linker emits a `R_MIPS_26` relocation against the lower 26 bits; the upper 4 bits come from the PC of the delay slot following the `j`.
|
--- For cross-module `j`/`jal` (atom body in one module, target in another), the linker emits a `R_MIPS_26` relocation against the lower 26 bits; the upper 4 bits come from the PC of the delay slot following the `j`.
|
||||||
--- The metaprogram doesn't know either at compile time, so the emitted value is the relative word offset that the duffle `enc_i` macro places in the immediate field; the toolchain handles the rest.
|
--- The metaprogram doesn't know either at compile time, so the emitted value is the relative word offset that the duffle `enc_i` macro places in the immediate field; the toolchain handles the rest.
|
||||||
--- `jump_reg` / `call_reg` / `jump_link` -> ERROR. Register-form jumps have no offset field; `atom_offset` is invalid.
|
--- `jump_reg` / `call_reg` / `jump_link` -> ERROR. Register-form jumps have no offset field; `atom_offset` is invalid.
|
||||||
---
|
--- missing `consuming_encoder` -> ERROR. A lone top-level `atom_offset` is not a branch.
|
||||||
--- Top-level `atom_offset(F, T)` markers (where the marker is the entire token — `consuming_encoder` == nil) default to `branch_*` behavior (relative offset).
|
|
||||||
--- This preserves backward compatibility for any top-level marker that may exist outside a control-transfer instruction.
|
|
||||||
--- @param labels table<string, integer>
|
--- @param labels table<string, integer>
|
||||||
--- @param branches table[]
|
--- @param branches OffsetBranch[]
|
||||||
|
--- @param errors Finding[]
|
||||||
--- @return BranchOffset[]
|
--- @return BranchOffset[]
|
||||||
local function compute_offsets(labels, branches)
|
local function compute_offsets(labels, branches, errors)
|
||||||
local results = {}
|
local results = {} ---@type BranchOffset[]
|
||||||
for _, br in ipairs(branches) do
|
for _, br in ipairs(branches) do ---@type integer, OffsetBranch
|
||||||
local target = labels[br.target]
|
local target = labels[br.target] ---@type integer|nil
|
||||||
if not target then
|
if not target then
|
||||||
error("Branch target '" .. br.target .. "' has no atom_label (at word " .. br.branch_word .. ")")
|
errors[#errors + 1] = {
|
||||||
end
|
line = br.line or 0,
|
||||||
local consuming = br.consuming_encoder
|
msg = "Branch target '" .. br.target .. "' has no atom_label (at word " .. br.branch_word .. ")",
|
||||||
local offset
|
}
|
||||||
if consuming == "jump_reg" or consuming == "call_reg" or consuming == "jump_link" then
|
else
|
||||||
-- Register-form jumps have no offset field. `atom_offset` cannot be used here.
|
local consuming = br.consuming_encoder ---@type string|nil
|
||||||
error("atom_offset cannot be used with " .. consuming
|
if consuming == nil or consuming == "" then
|
||||||
.. " (register-form jumps have no offset field); at word " .. br.branch_word)
|
errors[#errors + 1] = {
|
||||||
end
|
line = br.line or 0,
|
||||||
-- All other consuming instructions (including `branch_*`, `jump`, `call_addr`, and nil for top-level markers) use the same relative offset value.
|
msg = "atom_offset requires a consuming encoder (branch_*, jump, call_addr); top-level atom_offset is invalid; at word " .. br.branch_word,
|
||||||
|
}
|
||||||
|
elseif consuming == "jump_reg" or consuming == "call_reg" or consuming == "jump_link" then
|
||||||
|
errors[#errors + 1] = {
|
||||||
|
line = br.line or 0,
|
||||||
|
msg = "atom_offset cannot be used with " .. consuming
|
||||||
|
.. " (register-form jumps have no offset field); at word " .. br.branch_word,
|
||||||
|
}
|
||||||
|
else
|
||||||
|
-- Consuming instructions with an offset field (`branch_*`, `jump`, `call_addr`) use the same relative offset value.
|
||||||
-- The MIPS encoding differs per opcode but the duffle `enc_i` macro handles the truncation to the immediate-field width.
|
-- The MIPS encoding differs per opcode but the duffle `enc_i` macro handles the truncation to the immediate-field width.
|
||||||
offset = target - br.branch_word - 1
|
|
||||||
results[#results + 1] = {
|
results[#results + 1] = {
|
||||||
target = br.target,
|
target = br.target,
|
||||||
tag = br.tag,
|
tag = br.tag,
|
||||||
branch_word = br.branch_word,
|
branch_word = br.branch_word,
|
||||||
offset = offset,
|
offset = target - br.branch_word - 1,
|
||||||
consuming_encoder = br.consuming_encoder,
|
consuming_encoder = br.consuming_encoder,
|
||||||
consuming_arg_pos = br.consuming_arg_pos,
|
consuming_arg_pos = br.consuming_arg_pos,
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
return results
|
return results
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -168,7 +188,7 @@ end
|
|||||||
|
|
||||||
--- (internal) Build a constant-table entry `{macro_name, enum_name, value}` from a BranchOffset.
|
--- (internal) Build a constant-table entry `{macro_name, enum_name, value}` from a BranchOffset.
|
||||||
--- @param bo BranchOffset
|
--- @param bo BranchOffset
|
||||||
--- @return table
|
--- @return OffsetConst
|
||||||
local function make_offset_const(bo)
|
local function make_offset_const(bo)
|
||||||
return {
|
return {
|
||||||
macro_name = OFFSET_MACRO_PREFIX .. bo.tag .. "_" .. bo.target,
|
macro_name = OFFSET_MACRO_PREFIX .. bo.tag .. "_" .. bo.target,
|
||||||
@@ -180,20 +200,21 @@ end
|
|||||||
--- (internal) Emit one atom's offset constants + enum into the lines buffer.
|
--- (internal) Emit one atom's offset constants + enum into the lines buffer.
|
||||||
--- @param add fun(s: string)
|
--- @param add fun(s: string)
|
||||||
--- @param atom AtomData
|
--- @param atom AtomData
|
||||||
|
--- @return nil
|
||||||
local function emit_atom_offsets(add, atom)
|
local function emit_atom_offsets(add, atom)
|
||||||
if #atom.offsets == 0 then return end
|
if #atom.offsets == 0 then return end
|
||||||
add("// --- atom: " .. atom.name .. " (" .. atom.total_words .. " words) ---")
|
add("// --- atom: " .. atom.name .. " (" .. atom.total_words .. " words) ---")
|
||||||
add("")
|
add("")
|
||||||
local consts = {}
|
local consts = {} ---@type OffsetConst[]
|
||||||
for _, r in ipairs(atom.offsets) do
|
for _, r in ipairs(atom.offsets) do ---@type integer, BranchOffset
|
||||||
consts[#consts + 1] = make_offset_const(r)
|
consts[#consts + 1] = make_offset_const(r)
|
||||||
end
|
end
|
||||||
for _, c in ipairs(consts) do
|
for _, c in ipairs(consts) do ---@type integer, OffsetConst
|
||||||
add("#define " .. pad_right(c.macro_name, OFFSET_MACRO_COL) .. " " .. c.value)
|
add("#define " .. pad_right(c.macro_name, OFFSET_MACRO_COL) .. " " .. c.value)
|
||||||
end
|
end
|
||||||
add("")
|
add("")
|
||||||
add("enum {")
|
add("enum {")
|
||||||
for _, c in ipairs(consts) do
|
for _, c in ipairs(consts) do ---@type integer, OffsetConst
|
||||||
add(" " .. c.enum_name .. " = " .. c.macro_name .. ",")
|
add(" " .. c.enum_name .. " = " .. c.macro_name .. ",")
|
||||||
end
|
end
|
||||||
add("};")
|
add("};")
|
||||||
@@ -201,19 +222,21 @@ local function emit_atom_offsets(add, atom)
|
|||||||
end
|
end
|
||||||
|
|
||||||
--- Generate the per-directory .offsets.h header.
|
--- Generate the per-directory .offsets.h header.
|
||||||
--- @param dir string -- the absolute source directory
|
--- @param dir string
|
||||||
--- @param sources table[] -- sources contributing to this directory (for the header comment)
|
--- @param sources SourceFile[]
|
||||||
--- @param atoms_data AtomData[]
|
--- @param atoms_data AtomData[]
|
||||||
--- @return string
|
--- @return string
|
||||||
local function generate_header(dir, sources, atoms_data)
|
local function generate_header(dir, sources, atoms_data)
|
||||||
local dir_basename = duffle.basename_no_ext(dir)
|
local dir_basename = duffle.basename_no_ext(dir) ---@type string
|
||||||
|
|
||||||
local lines = {}
|
local lines = {} ---@type string[]
|
||||||
|
--- @param s string
|
||||||
|
--- @return nil
|
||||||
local function add(s) lines[#lines + 1] = s end
|
local function add(s) lines[#lines + 1] = s end
|
||||||
|
|
||||||
add("// Auto-generated by ps1_meta.lua (passes/offsets.lua) — DO NOT EDIT")
|
add("// Auto-generated by ps1_meta.lua (passes/offsets.lua) — DO NOT EDIT")
|
||||||
add("// Directory: " .. dir:gsub("/", "\\") .. "\\")
|
add("// Directory: " .. dir:gsub("/", "\\") .. "\\")
|
||||||
for _, src in ipairs(sources) do
|
for _, src in ipairs(sources) do ---@type integer, SourceFile
|
||||||
add("// source: " .. src.path:gsub("/", "\\"))
|
add("// source: " .. src.path:gsub("/", "\\"))
|
||||||
end
|
end
|
||||||
add("#pragma once")
|
add("#pragma once")
|
||||||
@@ -221,7 +244,7 @@ local function generate_header(dir, sources, atoms_data)
|
|||||||
add("#pragma region " .. dir_basename)
|
add("#pragma region " .. dir_basename)
|
||||||
add("")
|
add("")
|
||||||
add("")
|
add("")
|
||||||
for _, atom in ipairs(atoms_data) do
|
for _, atom in ipairs(atoms_data) do ---@type integer, AtomData
|
||||||
emit_atom_offsets(add, atom)
|
emit_atom_offsets(add, atom)
|
||||||
end
|
end
|
||||||
add("#pragma endregion " .. dir_basename)
|
add("#pragma endregion " .. dir_basename)
|
||||||
@@ -229,36 +252,39 @@ local function generate_header(dir, sources, atoms_data)
|
|||||||
return table.concat(lines, "\n") .. "\n"
|
return table.concat(lines, "\n") .. "\n"
|
||||||
end
|
end
|
||||||
|
|
||||||
local M = {}
|
local M = {} ---@type OffsetsPass
|
||||||
|
|
||||||
--- (internal) Aggregate atoms from every source in one directory, render the per-directory `offsets.h`.
|
--- (internal) Aggregate atoms from every source in one directory, render the per-directory `offsets.h`.
|
||||||
--- Returns the offsets_h path if a header was written, or nil.
|
--- Returns the offsets_h path if a header was written, or nil.
|
||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @param dir string -- the absolute source directory
|
--- @param dir string
|
||||||
--- @param sources SourceFile[] -- sources in this directory
|
--- @param sources SourceFile[]
|
||||||
--- @return string|nil -- the offsets_h path
|
--- @param errors Finding[]
|
||||||
local function process_directory(ctx, dir, sources)
|
--- @return string|nil
|
||||||
local atoms_data = {}
|
local function process_directory(ctx, dir, sources, errors)
|
||||||
|
local atoms_data = {} ---@type AtomData[]
|
||||||
|
|
||||||
|
--- @param atom AtomEntry
|
||||||
|
--- @return nil
|
||||||
local function append_atom(atom)
|
local function append_atom(atom)
|
||||||
local paths = atom and atom.paths
|
local paths = atom and atom.paths ---@type AtomPaths|nil
|
||||||
if not paths then return end
|
if not paths then return end
|
||||||
local labels, branches = project_markers(paths.markers)
|
local labels, branches = project_markers(paths.markers) ---@type table<string, integer>, OffsetBranch[]
|
||||||
atoms_data[#atoms_data + 1] = {
|
atoms_data[#atoms_data + 1] = {
|
||||||
name = atom.raw_name or atom.name,
|
name = atom.raw_name or atom.name,
|
||||||
total_words = #(paths.word_events or {}),
|
total_words = #(paths.word_events or {}),
|
||||||
offsets = compute_offsets(labels, branches),
|
offsets = compute_offsets(labels, branches, errors),
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
|
|
||||||
for _, src in ipairs(sources) do
|
for _, src in ipairs(sources) do ---@type integer, SourceFile
|
||||||
local scan = src.scan or {}
|
local scan = src.scan or {} ---@type SourceScan
|
||||||
for _, atom in ipairs(scan.atoms or {}) do append_atom(atom) end
|
for _, atom in ipairs(scan.atoms or {}) do append_atom(atom) end ---@type integer, AtomEntry
|
||||||
for _, atom in ipairs(scan.raw_atoms or {}) do append_atom(atom) end
|
for _, atom in ipairs(scan.raw_atoms or {}) do append_atom(atom) end ---@type integer, AtomEntry
|
||||||
end
|
end
|
||||||
if #atoms_data == 0 then return nil end
|
if #atoms_data == 0 then return nil end
|
||||||
|
|
||||||
local out_path = dir .. "/gen/offsets.h"
|
local out_path = dir .. "/gen/offsets.h" ---@type string
|
||||||
duffle.ensure_dir(duffle.dirname(out_path))
|
duffle.ensure_dir(duffle.dirname(out_path))
|
||||||
duffle.write_file(out_path, generate_header(dir, sources, atoms_data))
|
duffle.write_file(out_path, generate_header(dir, sources, atoms_data))
|
||||||
return out_path
|
return out_path
|
||||||
@@ -270,11 +296,11 @@ end
|
|||||||
--- @param ctx PassCtx
|
--- @param ctx PassCtx
|
||||||
--- @return PassResult
|
--- @return PassResult
|
||||||
function M.run(ctx)
|
function M.run(ctx)
|
||||||
local outputs = {}
|
local outputs = {} ---@type OffsetOutput[]
|
||||||
local errors = {}
|
local errors = {} ---@type Finding[]
|
||||||
local warnings = {}
|
local warnings = {} ---@type Finding[]
|
||||||
|
|
||||||
local corpus = ctx.shared and ctx.shared.corpus
|
local corpus = ctx.shared and ctx.shared.corpus ---@type Corpus|nil
|
||||||
if type(corpus) ~= "table" then
|
if type(corpus) ~= "table" then
|
||||||
error("offsets.run requires ctx.shared.corpus", 0)
|
error("offsets.run requires ctx.shared.corpus", 0)
|
||||||
end
|
end
|
||||||
@@ -283,9 +309,9 @@ function M.run(ctx)
|
|||||||
end
|
end
|
||||||
|
|
||||||
-- Per-directory aggregation: every source in the same directory contributes to one `gen/offsets.h`.
|
-- Per-directory aggregation: every source in the same directory contributes to one `gen/offsets.h`.
|
||||||
local sources_by_dir = corpus.sources_by_dir or duffle.group_sources_by_dir(corpus.source_order)
|
local sources_by_dir = corpus.sources_by_dir or duffle.group_sources_by_dir(corpus.source_order) ---@type table<string, SourceFile[]>
|
||||||
for dir, sources in pairs(sources_by_dir) do
|
for dir, sources in pairs(sources_by_dir) do ---@type string, SourceFile[]
|
||||||
local out_path = process_directory(ctx, dir, sources)
|
local out_path = process_directory(ctx, dir, sources, errors) ---@type string|nil
|
||||||
if out_path then
|
if out_path then
|
||||||
outputs[#outputs + 1] = { offsets_h = out_path }
|
outputs[#outputs + 1] = { offsets_h = out_path }
|
||||||
end
|
end
|
||||||
|
|||||||
+883
-332
File diff suppressed because it is too large
Load Diff
+1867
-543
File diff suppressed because it is too large
Load Diff
+2472
-1088
File diff suppressed because it is too large
Load Diff
@@ -4,13 +4,13 @@
|
|||||||
--- 1. **Public utility** `M.count_token_words(token, wc)`: Used by `passes/offsets.lua`, `passes/annotation.lua`, and other passes.
|
--- 1. **Public utility** `M.count_token_words(token, wc)`: Used by `passes/offsets.lua`, `passes/annotation.lua`, and other passes.
|
||||||
--- 2. **Pass entry** `M.run(ctx)`: Loads the authored `word_count.metadata.h` into `ctx.shared.corpus.word_counts` for downstream passes.
|
--- 2. **Pass entry** `M.run(ctx)`: Loads the authored `word_count.metadata.h` into `ctx.shared.corpus.word_counts` for downstream passes.
|
||||||
--- The generated `.macs.h` files are OUTPUT artifacts and are NOT inputs to this pass;
|
--- The generated `.macs.h` files are OUTPUT artifacts and are NOT inputs to this pass;
|
||||||
--- Current component counts are owned by `passes/components.lua` (which populates `corpus.word_counts` and `corpus.component_body_index`
|
--- Current component counts are owned by `passes/components.lua` (which populates `corpus.word_counts` and `corpus.components`
|
||||||
--- AFTER computing each current count from the just-built body + `corpus.word_counts`).
|
--- AFTER computing each current count from the just-built body + `corpus.word_counts`).
|
||||||
---
|
---
|
||||||
--- **Canonical contract**:
|
--- **Canonical contract**:
|
||||||
--- * `ctx.shared.corpus.word_counts` is the count table.
|
--- * `ctx.shared.corpus.word_counts` is the count table.
|
||||||
--- * `corpus.word_counts` is the sole count table. Consumers read `corpus.word_counts` directly.
|
--- * `corpus.word_counts` is the sole count table. Consumers read `corpus.word_counts` directly.
|
||||||
--- * `ctx.shared.components` and `ctx.shared.component_body_index` are NOT created by this pass (projections only).
|
--- * `ctx.shared.components` is NOT created by this pass (projections only).
|
||||||
--- * No `.macs.h` recursive discovery (no `scan_dir`, no scan cache, no `_invalidate_scan_cache`).
|
--- * No `.macs.h` recursive discovery (no `scan_dir`, no scan cache, no `_invalidate_scan_cache`).
|
||||||
---
|
---
|
||||||
--- **Conventions**: tabs (1/level), EmmyLua annotations, no regex,
|
--- **Conventions**: tabs (1/level), EmmyLua annotations, no regex,
|
||||||
@@ -23,44 +23,28 @@
|
|||||||
-- Bootstrap: load `scripts/duffle_paths.lua` (sets package.path + package.cpath).
|
-- Bootstrap: load `scripts/duffle_paths.lua` (sets package.path + package.cpath).
|
||||||
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
|
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
|
||||||
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
|
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
|
||||||
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
|
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./" ---@type string
|
||||||
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
|
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua") ---@type DuffleExport
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Type declarations
|
-- Type declarations
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- @class WordCounts
|
--- @class WordCounts
|
||||||
--- @field [string] integer -- macro name -> word count
|
--- @field [string] integer -- bag: macro name -> word count
|
||||||
|
|
||||||
--- @class SourceFile
|
--- @class WordCountEval
|
||||||
--- @field path string -- absolute path to the source file
|
--- @field count_token_words fun(token: string, wc: WordCounts): integer
|
||||||
--- @field text string -- the full source text
|
--- @field run fun(ctx: PassCtx): PassResult
|
||||||
--- @field dir string -- the directory containing the source
|
|
||||||
--- @field basename string -- filename without extension
|
|
||||||
|
|
||||||
--- @class PassCtx
|
-- SourceFile, PassCtx, PassResult: see ps1_meta.lua
|
||||||
--- @field sources SourceFile[] -- all source files in the build
|
-- DuffleExport: see duffle.lua (facade returned by duffle_paths.lua)
|
||||||
--- @field metadata_path string -- path to word_count.metadata.h
|
|
||||||
--- @field shared table -- cross-pass shared state
|
|
||||||
--- @field shared.corpus table -- canonical corpus (required)
|
|
||||||
--- @field shared.corpus.word_counts WordCounts -- canonical count table (populated by this pass)
|
|
||||||
--- @field out_root string -- output root (e.g. "build/gen")
|
|
||||||
--- @field project_root string -- project root (e.g. "code/")
|
|
||||||
--- @field upstream table<string, table> -- per-pass upstream outputs
|
|
||||||
--- @field flags table -- CLI flags
|
|
||||||
--- @field verbose boolean -- if true, log diagnostic info
|
|
||||||
|
|
||||||
--- @class PassResult
|
|
||||||
--- @field outputs table[] -- {kind=, path=} entries describing emit files
|
|
||||||
--- @field errors table[] -- {line=, msg=} entries; build-stops
|
|
||||||
--- @field warnings table[] -- {line=, msg=} entries; build-succeeds
|
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Module exports
|
-- Module exports
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
local M = {}
|
local M = {} ---@type WordCountEval
|
||||||
|
|
||||||
-- ┌────────────────────────────────────────────────────────────────────┐
|
-- ┌────────────────────────────────────────────────────────────────────┐
|
||||||
-- │ Shared utility: count_token_words │
|
-- │ Shared utility: count_token_words │
|
||||||
@@ -74,12 +58,12 @@ local M = {}
|
|||||||
--- @param wc WordCounts -- the shared word-count table
|
--- @param wc WordCounts -- the shared word-count table
|
||||||
--- @return integer
|
--- @return integer
|
||||||
function M.count_token_words(token, wc)
|
function M.count_token_words(token, wc)
|
||||||
local s = duffle.trim(token)
|
local s = duffle.trim(token) ---@type string
|
||||||
if s == "" then return 0 end
|
if s == "" then return 0 end
|
||||||
local name, after = duffle.read_ident(s, 1)
|
local name, after = duffle.read_ident(s, 1) ---@type string|nil, integer
|
||||||
if not name then return 1 end
|
if not name then return 1 end
|
||||||
if wc[name] then return wc[name] end
|
if wc[name] then return wc[name] end
|
||||||
local paren_pos = duffle.skip_ws_and_cmt(s, after)
|
local paren_pos = duffle.skip_ws_and_cmt(s, after) ---@type integer
|
||||||
if s:sub(paren_pos, paren_pos) == "(" then
|
if s:sub(paren_pos, paren_pos) == "(" then
|
||||||
io.stderr:write(" warning: unknown macro '" .. name .. "', assuming 1 word\n")
|
io.stderr:write(" warning: unknown macro '" .. name .. "', assuming 1 word\n")
|
||||||
end
|
end
|
||||||
@@ -105,7 +89,7 @@ end
|
|||||||
--- @return PassResult
|
--- @return PassResult
|
||||||
function M.run(ctx)
|
function M.run(ctx)
|
||||||
-- 1. Canonical-corpus ownership gate.
|
-- 1. Canonical-corpus ownership gate.
|
||||||
local corpus = ctx.shared and ctx.shared.corpus
|
local corpus = ctx.shared and ctx.shared.corpus ---@type Corpus|nil
|
||||||
if type(corpus) ~= "table" then
|
if type(corpus) ~= "table" then
|
||||||
error("word_count_eval.run requires ctx.shared.corpus (canonical corpus). The fixture must install the corpus before running this pass.", 0)
|
error("word_count_eval.run requires ctx.shared.corpus (canonical corpus). The fixture must install the corpus before running this pass.", 0)
|
||||||
end
|
end
|
||||||
@@ -117,7 +101,7 @@ function M.run(ctx)
|
|||||||
|
|
||||||
-- 3. Load authored metadata. Generated .macs.h files are NOT scanned
|
-- 3. Load authored metadata. Generated .macs.h files are NOT scanned
|
||||||
-- (the pass computes their counts from the just-built bodies after disk emission; see passes/components.lua).
|
-- (the pass computes their counts from the just-built bodies after disk emission; see passes/components.lua).
|
||||||
local wc = duffle.load_word_counts(ctx.metadata_path)
|
local wc = duffle.load_word_counts(ctx.metadata_path) ---@type WordCounts
|
||||||
|
|
||||||
-- 4. Assign the count table. ONE assignment, no copy. The assignment creates no secondary alias.
|
-- 4. Assign the count table. ONE assignment, no copy. The assignment creates no secondary alias.
|
||||||
corpus.word_counts = wc
|
corpus.word_counts = wc
|
||||||
|
|||||||
+241
-158
@@ -19,8 +19,8 @@
|
|||||||
-- fall back to `debug.getinfo(1, "S").source` when this file is being dofile()'d or require()'d (in which case `arg[0]` is the *caller's* path).
|
-- fall back to `debug.getinfo(1, "S").source` when this file is being dofile()'d or require()'d (in which case `arg[0]` is the *caller's* path).
|
||||||
-- That single statement: (a) sets `package.path` + `package.cpath`, (b) at the bottom returns `require("duffle")`.
|
-- That single statement: (a) sets `package.path` + `package.cpath`, (b) at the bottom returns `require("duffle")`.
|
||||||
-- So the dofile's return value is the duffle module.
|
-- So the dofile's return value is the duffle module.
|
||||||
local _is_entry_script = arg and arg[0] and arg[0]:match("ps1_meta%.lua$") ~= nil
|
local _is_entry_script = arg and arg[0] and arg[0]:match("ps1_meta%.lua$") ~= nil ---@type boolean
|
||||||
local _bootstrap_src
|
local _bootstrap_src ---@type string
|
||||||
if _is_entry_script then
|
if _is_entry_script then
|
||||||
_bootstrap_src = arg[0]
|
_bootstrap_src = arg[0]
|
||||||
else
|
else
|
||||||
@@ -28,26 +28,26 @@ else
|
|||||||
-- strip the leading "@" so the directory match works in both cases.
|
-- strip the leading "@" so the directory match works in both cases.
|
||||||
_bootstrap_src = debug.getinfo(1, "S").source:sub(2)
|
_bootstrap_src = debug.getinfo(1, "S").source:sub(2)
|
||||||
end
|
end
|
||||||
local duffle = dofile((_bootstrap_src:match("(.*[/\\])") or "./") .. "duffle_paths.lua")
|
local duffle = dofile((_bootstrap_src:match("(.*[/\\])") or "./") .. "duffle_paths.lua") ---@type DuffleExport
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Constants
|
-- Constants
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
-- Exit codes (per the --help text and the post-build summary convention).
|
-- Exit codes (per the --help text and the post-build summary convention).
|
||||||
local EXIT_OK = 0
|
local EXIT_OK = 0 ---@type integer
|
||||||
local EXIT_VALIDATION_ERRORS = 1
|
local EXIT_VALIDATION_ERRORS = 1 ---@type integer
|
||||||
local EXIT_INTERNAL_ERROR = 2
|
local EXIT_INTERNAL_ERROR = 2 ---@type integer
|
||||||
|
|
||||||
-- Default --out-root value if not provided.
|
-- Default --out-root value if not provided.
|
||||||
local DEFAULT_OUT_ROOT = "build/gen"
|
local DEFAULT_OUT_ROOT = "build/gen" ---@type string
|
||||||
|
|
||||||
-- Sentinel for "all passes" in `PASS_FLAG_TO_NAME`. Distinguishes `--all` from the per-pass flags (which map to individual pass names).
|
-- Sentinel for "all passes" in `PASS_FLAG_TO_NAME`. Distinguishes `--all` from the per-pass flags (which map to individual pass names).
|
||||||
local ALL_PASSES_SENTINEL = "__all__"
|
local ALL_PASSES_SENTINEL = "__all__" ---@type string
|
||||||
|
|
||||||
-- Sentinel key for the pass-flag dispatcher in `FLAG_HANDLERS`.
|
-- Sentinel key for the pass-flag dispatcher in `FLAG_HANDLERS`.
|
||||||
-- The actual pass names are looked up via `PASS_FLAG_TO_NAME`, not direct dispatch, so this key never matches a real flag.
|
-- The actual pass names are looked up via `PASS_FLAG_TO_NAME`, not direct dispatch, so this key never matches a real flag.
|
||||||
local PASS_FLAG_DISPATCH_KEY = "__pass__"
|
local PASS_FLAG_DISPATCH_KEY = "__pass__" ---@type string
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- Type declarations
|
-- Type declarations
|
||||||
@@ -60,29 +60,98 @@ local PASS_FLAG_DISPATCH_KEY = "__pass__"
|
|||||||
--- @field deps string[] -- Names of upstream passes
|
--- @field deps string[] -- Names of upstream passes
|
||||||
--- @field groups string[]? -- OPTIONAL build-phase groups this pass is a root of (e.g. { "pre-link" }, { "post-link" }); absent ⇒ dependency-only
|
--- @field groups string[]? -- OPTIONAL build-phase groups this pass is a root of (e.g. { "pre-link" }, { "post-link" }); absent ⇒ dependency-only
|
||||||
|
|
||||||
--- @class SourceFile
|
--- @class Corpus
|
||||||
--- @field path string -- Absolute path to the source file
|
--- @field unity_root string|nil
|
||||||
--- @field text string -- Full source text
|
--- @field project_root string
|
||||||
--- @field dir string -- Directory containing the source
|
--- @field code_root string
|
||||||
--- @field basename string -- Filename without extension
|
--- @field source_order SourceFile[]
|
||||||
|
--- @field sources_by_path table<Path, SourceFile>
|
||||||
|
--- @field sources_by_dir table<string, SourceFile[]>
|
||||||
|
--- @field atoms_by_name table<AtomName, AtomEntry>
|
||||||
|
--- @field binds_by_name table<string, BindsEntry>
|
||||||
|
--- @field atom_infos AtomInfoEntry[]
|
||||||
|
--- @field register_alias_registry table<string, AliasEntry>
|
||||||
|
--- @field type_name_registry table<string, TypeNameEntry>
|
||||||
|
--- @field atom_views table<AtomName, AtomViewEntry>
|
||||||
|
--- @field atom_ctxs table<AtomName, AtomCtxEntry>
|
||||||
|
--- @field atom_phases table<string, AtomPhaseGroup>
|
||||||
|
--- @field word_counts WordCounts
|
||||||
|
--- @field components table<string, Component>
|
||||||
|
--- @field atom_bundles table<string, AtomBundle>|nil
|
||||||
|
--- @field tape_emits TapeEmit[]|nil
|
||||||
|
--- @field collisions CorpusCollision[]
|
||||||
|
--- @field resolver SourceResolver
|
||||||
|
--- @field component_atom_infos AtomInfoEntry[]|nil
|
||||||
|
--- @field atom_auto_regs table<AtomName, table<string, string>>|nil
|
||||||
|
--- @field phase_auto_regs table<string, table<string, string>>|nil
|
||||||
|
--- @field reg_use_schemas table<string, RegUseSchema>|nil
|
||||||
|
--- @field reg_use_errors RegUseError[]|nil
|
||||||
|
--- @field static_analysis_results table<string, AtomAnalysis>|nil
|
||||||
|
--- @field tape_chains table<string, TapeChain>|nil
|
||||||
|
|
||||||
|
--- @class PassShared
|
||||||
|
--- @field corpus Corpus
|
||||||
|
|
||||||
|
--- @class PassFlags
|
||||||
|
--- @field gdb_runtime boolean|nil
|
||||||
|
--- @field dwarf_injection boolean|nil
|
||||||
|
--- @field elf_path string|nil
|
||||||
|
|
||||||
--- @class PassCtx
|
--- @class PassCtx
|
||||||
--- @field metadata_path string -- Path to word_count.metadata.h
|
--- @field metadata_path string -- Path to word_count.metadata.h
|
||||||
--- @field shared table -- Cross-pass shared state
|
--- @field shared PassShared -- Cross-pass shared state
|
||||||
--- @field shared.corpus table -- Authored-source/project projection
|
|
||||||
--- @field out_root string -- Output root (e.g. "build/gen")
|
--- @field out_root string -- Output root (e.g. "build/gen")
|
||||||
--- @field project_root string -- PS1 repository root
|
--- @field project_root string -- PS1 repository root
|
||||||
--- @field flags table -- CLI flags + per-pass stash
|
--- @field flags PassFlags -- CLI flags + per-pass stash
|
||||||
--- @field verbose boolean -- If true, log diagnostic info
|
--- @field verbose boolean -- If true, log diagnostic info
|
||||||
|
|
||||||
|
--- CheckName: see static_analysis.lua. AtomName: see duffle.lua.
|
||||||
--- @class Finding
|
--- @class Finding
|
||||||
--- @field line integer -- Source line (or 0 for pass-level)
|
--- @field line integer
|
||||||
--- @field msg string -- Finding message
|
--- @field msg string
|
||||||
|
--- @field kind string|nil -- error | warning | info
|
||||||
|
--- @field atom AtomName|nil
|
||||||
|
--- @field check CheckName|nil
|
||||||
|
--- @field source string|nil -- optional; emit/reguse path
|
||||||
|
--- @field schema_name string|nil -- optional; emit/reguse
|
||||||
|
|
||||||
|
--- @class PassScratch
|
||||||
|
--- @field corpus Corpus|nil
|
||||||
|
--- @field info_by_atom table<string, AtomInfoEntry>|nil
|
||||||
|
--- @field binds_index table<string, BindsEntry>|nil
|
||||||
|
--- @field atom_index table<string, AtomEntry>|nil
|
||||||
|
--- @field annot_counts table<string, integer>|nil -- bag
|
||||||
|
--- @field types table<string, RegTypeDefault>|nil
|
||||||
|
--- @field atom_views table<string, AtomViewEntry>|nil
|
||||||
|
--- @field seen_defaults table<string, integer>|nil -- bag
|
||||||
|
--- @field seen_field table<string, integer>|nil -- bag
|
||||||
|
--- @field _scan SourceScan|nil
|
||||||
|
--- @field word_counts WordCounts|nil
|
||||||
|
--- @field register_alias_registry table<string, AliasEntry>|nil
|
||||||
|
--- @field type_name_registry table<string, TypeNameEntry>|nil
|
||||||
|
--- @field type_occurrences RegTypeOccurrence[]|nil
|
||||||
|
--- @field atom_infos_list AtomInfoEntry[]|nil
|
||||||
|
--- @field binds_list BindsEntry[]|nil
|
||||||
|
--- @field unknown_seen table<string, integer>|nil -- bag
|
||||||
|
--- @field atoms AtomEntry[]|nil
|
||||||
|
--- @field components_by_name table<string, Component>|nil
|
||||||
|
--- @field atoms_by_name table<string, AtomEntry>|nil
|
||||||
|
--- @field tape_chains table<string, string[]>|nil
|
||||||
|
--- @field source_order SourceFile[]|nil
|
||||||
|
--- @field component_atom_infos AtomInfoEntry[]|nil
|
||||||
|
--- @field atom_infos_all AtomInfoEntry[]|nil
|
||||||
|
--- @field gte_cr_alias_groups GteCrAliasGroup[]|nil
|
||||||
|
--- @field line_for_word_event (fun(ev: WordEvent): integer)|nil
|
||||||
|
|
||||||
|
--- @class PassOutputEntry
|
||||||
|
--- @field kind string
|
||||||
|
--- @field path string
|
||||||
|
|
||||||
--- @class PassResult
|
--- @class PassResult
|
||||||
--- @field outputs PassOutputEntry[] -- Emitted file paths
|
--- @field outputs PassOutputEntry[]
|
||||||
--- @field errors Finding[] -- Build-stops (per-pass kind policy)
|
--- @field errors Finding[] -- Build-stops (per-pass kind policy)
|
||||||
--- @field warnings Finding[] -- Informational
|
--- @field warnings Finding[] -- Informational
|
||||||
|
--- @field info Finding[]|nil -- static_analysis only
|
||||||
|
|
||||||
--- @class ParsedArgs
|
--- @class ParsedArgs
|
||||||
--- @field requested_set string[] -- Pass names to run (explicit --all expanded)
|
--- @field requested_set string[] -- Pass names to run (explicit --all expanded)
|
||||||
@@ -92,6 +161,18 @@ local PASS_FLAG_DISPATCH_KEY = "__pass__"
|
|||||||
--- @field out_root string -- --out-root value (default "build/gen")
|
--- @field out_root string -- --out-root value (default "build/gen")
|
||||||
--- @field project_root string -- PS1 repository root (derived from metadata by default)
|
--- @field project_root string -- PS1 repository root (derived from metadata by default)
|
||||||
--- @field verbose boolean -- If true, log diagnostic info
|
--- @field verbose boolean -- If true, log diagnostic info
|
||||||
|
--- @field flags PassFlags|nil -- Per-pass stash; copied onto PassCtx.flags
|
||||||
|
|
||||||
|
--- @alias FlagHandler fun(args: ParsedArgs, argv: string[]|nil, arg_idx: integer|nil): integer|nil
|
||||||
|
|
||||||
|
--- @class PassModule
|
||||||
|
--- @field run fun(ctx: PassCtx): PassResult
|
||||||
|
|
||||||
|
--- @class Ps1MetaMod
|
||||||
|
--- @field PASSES table<string, PassDescriptor>
|
||||||
|
--- @field PASS_KIND_STOP_ON_ERROR table<string, boolean>
|
||||||
|
--- @field parse_args fun(argv: string[]): ParsedArgs
|
||||||
|
--- @field build_ctx fun(args: ParsedArgs): PassCtx
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- PASSES Table
|
-- PASSES Table
|
||||||
@@ -104,7 +185,7 @@ local PASS_FLAG_DISPATCH_KEY = "__pass__"
|
|||||||
-- A row without a `groups` entry is dependency-only: it runs only when a transitive dep requests it,
|
-- A row without a `groups` entry is dependency-only: it runs only when a transitive dep requests it,
|
||||||
-- but it remains directly requestable through its explicit CLI flag (e.g. --atoms-source-map, --scan-source).
|
-- but it remains directly requestable through its explicit CLI flag (e.g. --atoms-source-map, --scan-source).
|
||||||
|
|
||||||
local PASSES = {
|
local PASSES = { ---@type table<string, PassDescriptor>
|
||||||
["scan-source"] = {
|
["scan-source"] = {
|
||||||
module = "passes.scan_source",
|
module = "passes.scan_source",
|
||||||
kind = "shared", deps = {},
|
kind = "shared", deps = {},
|
||||||
@@ -142,8 +223,7 @@ local PASSES = {
|
|||||||
},
|
},
|
||||||
["static-analysis"] = {
|
["static-analysis"] = {
|
||||||
module = "passes.static_analysis",
|
module = "passes.static_analysis",
|
||||||
-- "diagnostic" — every `error`/`warning` finding is written to the report file;
|
-- "diagnostic" — every `error`/`warning` finding is written to the report file.
|
||||||
-- The orchestrator does NOT exit non-zero on these findings (see PASS_KIND_STOP_ON_ERROR).
|
|
||||||
-- Report severity is independent from process exit policy.
|
-- Report severity is independent from process exit policy.
|
||||||
kind = "diagnostic",
|
kind = "diagnostic",
|
||||||
deps = {"scan-source", "word-counts", "components", "emission-model"},
|
deps = {"scan-source", "word-counts", "components", "emission-model"},
|
||||||
@@ -175,10 +255,10 @@ local PASSES = {
|
|||||||
--- @param group_name string -- Build-phase group ("pre-link" | "post-link")
|
--- @param group_name string -- Build-phase group ("pre-link" | "post-link")
|
||||||
--- @return string[] -- Sorted root pass names belonging to that group
|
--- @return string[] -- Sorted root pass names belonging to that group
|
||||||
local function roots_for_group(group_name)
|
local function roots_for_group(group_name)
|
||||||
local names = {}
|
local names = {} ---@type string[]
|
||||||
for name, pass in pairs(PASSES) do
|
for name, pass in pairs(PASSES) do ---@type string, PassDescriptor
|
||||||
if pass.groups then
|
if pass.groups then
|
||||||
for _, g in ipairs(pass.groups) do
|
for _, g in ipairs(pass.groups) do ---@type integer, string
|
||||||
if g == group_name then
|
if g == group_name then
|
||||||
names[#names + 1] = name
|
names[#names + 1] = name
|
||||||
break
|
break
|
||||||
@@ -195,27 +275,25 @@ end
|
|||||||
--- cannot silently fall through to pre-link (or any other default) and dispatch nothing.
|
--- cannot silently fall through to pre-link (or any other default) and dispatch nothing.
|
||||||
--- @param args ParsedArgs
|
--- @param args ParsedArgs
|
||||||
--- @param group_name string
|
--- @param group_name string
|
||||||
|
--- @return nil
|
||||||
local function request_roots_for_group(args, group_name)
|
local function request_roots_for_group(args, group_name)
|
||||||
local roots = roots_for_group(group_name)
|
local roots = roots_for_group(group_name) ---@type string[]
|
||||||
if #roots == 0 then
|
if #roots == 0 then
|
||||||
error(string.format("ps1_meta: build-phase group %q has zero roots in PASSES; check PASSES rows for a `groups = { %q }` field"
|
error(string.format("ps1_meta: build-phase group %q has zero roots in PASSES; check PASSES rows for a `groups = { %q }` field"
|
||||||
, group_name, group_name))
|
, group_name, group_name))
|
||||||
end
|
end
|
||||||
for _, name in ipairs(roots) do
|
for _, name in ipairs(roots) do ---@type integer, string
|
||||||
args.requested_set[#args.requested_set + 1] = name
|
args.requested_set[#args.requested_set + 1] = name
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Pass-kind taxonomy: Which kinds stop the build on errors?
|
-- Pass-kind taxonomy: findings always print. No pass kind stops the build.
|
||||||
--
|
|
||||||
-- Report severity is independent from process exit policy.
|
-- Report severity is independent from process exit policy.
|
||||||
-- A "diagnostic" pass still writes every `error`/`warning` finding into its report file,
|
-- Adding a new pass kind requires listing it here explicitly; an unknown kind must not silently fall back to "true".
|
||||||
-- but `report_validation_errors` returns early for non-stopping kinds, so nothing is printed to stderr and the orchestrator does not exit non-zero.
|
local PASS_KIND_STOP_ON_ERROR = { ---@type table<string, boolean> -- bag: pass kind -> stop-on-error
|
||||||
-- Adding a new pass kind requires listing it here explicitly; An unknown kind must not silently fall back to "true".
|
|
||||||
local PASS_KIND_STOP_ON_ERROR = {
|
|
||||||
["shared"] = false,
|
["shared"] = false,
|
||||||
["header-output"] = true,
|
["header-output"] = false,
|
||||||
["validation"] = true,
|
["validation"] = false,
|
||||||
["diagnostic"] = false,
|
["diagnostic"] = false,
|
||||||
["report"] = false,
|
["report"] = false,
|
||||||
}
|
}
|
||||||
@@ -224,7 +302,7 @@ local PASS_KIND_STOP_ON_ERROR = {
|
|||||||
-- Per-pass flags (e.g. --word-counts); phase flags (--pre-link, --post-link, --all) are within FLAG_HANDLERS because they own side effects or invoke group-derivation logic.
|
-- Per-pass flags (e.g. --word-counts); phase flags (--pre-link, --post-link, --all) are within FLAG_HANDLERS because they own side effects or invoke group-derivation logic.
|
||||||
-- dwarf-injection is *also* a per-pass opt-in flag, but its selection + opt-in state are both owned by the explicit FLAG_HANDLERS entry below
|
-- dwarf-injection is *also* a per-pass opt-in flag, but its selection + opt-in state are both owned by the explicit FLAG_HANDLERS entry below
|
||||||
-- (it sets args.flags.dwarf_injection and appends "dwarf-injection" to requested_set), so it is intentionally absent from this table.
|
-- (it sets args.flags.dwarf_injection and appends "dwarf-injection" to requested_set), so it is intentionally absent from this table.
|
||||||
local PASS_FLAG_TO_NAME = {
|
local PASS_FLAG_TO_NAME = { ---@type table<string, string> -- bag: CLI flag -> pass name or ALL_PASSES_SENTINEL
|
||||||
["--word-counts"] = "word-counts",
|
["--word-counts"] = "word-counts",
|
||||||
["--components"] = "components",
|
["--components"] = "components",
|
||||||
["--validate"] = "annotation",
|
["--validate"] = "annotation",
|
||||||
@@ -239,24 +317,26 @@ local PASS_FLAG_TO_NAME = {
|
|||||||
--- Append every pass name to args.requested_set.
|
--- Append every pass name to args.requested_set.
|
||||||
--- Names are derived from PASSES (no parallel name list); used by --all and by any caller that wants the full closure.
|
--- Names are derived from PASSES (no parallel name list); used by --all and by any caller that wants the full closure.
|
||||||
--- @param args ParsedArgs
|
--- @param args ParsedArgs
|
||||||
|
--- @return nil
|
||||||
local function request_all_passes(args)
|
local function request_all_passes(args)
|
||||||
local names = {}
|
local names = {} ---@type string[]
|
||||||
for name in pairs(PASSES) do names[#names + 1] = name end
|
for name in pairs(PASSES) do names[#names + 1] = name end ---@type string
|
||||||
table.sort(names)
|
table.sort(names)
|
||||||
for _, n in ipairs(names) do
|
for _, n in ipairs(names) do ---@type integer, string
|
||||||
args.requested_set[#args.requested_set + 1] = n
|
args.requested_set[#args.requested_set + 1] = n
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Per-flag handlers. Each handler takes (args, argv, arg_idx) and returns the new arg_idx (so multi-arg flags like --source FILE advance it).
|
-- Per-flag handlers. Each handler takes (args, argv, arg_idx) and returns the new arg_idx (so multi-arg flags like --source FILE advance it).
|
||||||
-- Returning nil + os.exit() handles termination flags (--help).
|
-- Returning nil + os.exit() handles termination flags (--help).
|
||||||
local FLAG_HANDLERS = {}
|
local FLAG_HANDLERS = {} ---@type table<string, FlagHandler>
|
||||||
|
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
-- CLI parsing
|
-- CLI parsing
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- Print the CLI usage to stdout and exit 0.
|
--- Print the CLI usage to stdout and exit 0.
|
||||||
|
--- @return nil
|
||||||
local function print_help()
|
local function print_help()
|
||||||
io.write([[
|
io.write([[
|
||||||
ps1_meta.lua - Tape-atom metaprogram orchestrator
|
ps1_meta.lua - Tape-atom metaprogram orchestrator
|
||||||
@@ -295,8 +375,7 @@ COMMON_FLAGS:
|
|||||||
--help Show this help and exit
|
--help Show this help and exit
|
||||||
|
|
||||||
EXIT CODES:
|
EXIT CODES:
|
||||||
0 All requested passes succeeded
|
0 Ran. Findings print on stderr and in the report; they do not fail the process.
|
||||||
1 Validation errors found
|
|
||||||
2 Metaprogram internal error
|
2 Metaprogram internal error
|
||||||
|
|
||||||
EXAMPLES:
|
EXAMPLES:
|
||||||
@@ -306,7 +385,7 @@ EXAMPLES:
|
|||||||
]])
|
]])
|
||||||
end
|
end
|
||||||
|
|
||||||
local FLAG_VALUE_NAMES = {
|
local FLAG_VALUE_NAMES = { ---@type table<string, string> -- bag: flag -> value metavar
|
||||||
["--source"] = "FILE",
|
["--source"] = "FILE",
|
||||||
["--unity-root"] = "FILE",
|
["--unity-root"] = "FILE",
|
||||||
["--metadata"] = "PATH",
|
["--metadata"] = "PATH",
|
||||||
@@ -315,9 +394,14 @@ local FLAG_VALUE_NAMES = {
|
|||||||
["--elf"] = "PATH",
|
["--elf"] = "PATH",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
--- @param argv string[]
|
||||||
|
--- @param arg_idx integer
|
||||||
|
--- @param flag string
|
||||||
|
--- @return string
|
||||||
|
--- @return integer
|
||||||
local function require_flag_value(argv, arg_idx, flag)
|
local function require_flag_value(argv, arg_idx, flag)
|
||||||
local value = argv[arg_idx + 1]
|
local value = argv[arg_idx + 1] ---@type string|nil
|
||||||
local next_known = type(value) == "string"
|
local next_known = type(value) == "string" ---@type boolean
|
||||||
and (FLAG_HANDLERS[value] ~= nil or PASS_FLAG_TO_NAME[value] ~= nil)
|
and (FLAG_HANDLERS[value] ~= nil or PASS_FLAG_TO_NAME[value] ~= nil)
|
||||||
if value == nil or next_known then
|
if value == nil or next_known then
|
||||||
io.stderr:write("ps1_meta: " .. flag .. " requires " .. FLAG_VALUE_NAMES[flag] .. "\n")
|
io.stderr:write("ps1_meta: " .. flag .. " requires " .. FLAG_VALUE_NAMES[flag] .. "\n")
|
||||||
@@ -331,49 +415,81 @@ end
|
|||||||
-- Populated AFTER print_help so the --help handler can reference it as an upvalue (Lua resolves locals at closure-call time,
|
-- Populated AFTER print_help so the --help handler can reference it as an upvalue (Lua resolves locals at closure-call time,
|
||||||
-- but if the closure is defined before the local, it falls back to _G).
|
-- but if the closure is defined before the local, it falls back to _G).
|
||||||
|
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @return nil
|
||||||
FLAG_HANDLERS["--help"] = function(args) print_help(); os.exit(0) end
|
FLAG_HANDLERS["--help"] = function(args) print_help(); os.exit(0) end
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @return nil
|
||||||
FLAG_HANDLERS["--verbose"] = function(args) args.verbose = true end
|
FLAG_HANDLERS["--verbose"] = function(args) args.verbose = true end
|
||||||
|
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @param argv string[]
|
||||||
|
--- @param arg_idx integer
|
||||||
|
--- @return integer
|
||||||
FLAG_HANDLERS["--source"] = function(args, argv, arg_idx)
|
FLAG_HANDLERS["--source"] = function(args, argv, arg_idx)
|
||||||
local value, value_idx = require_flag_value(argv, arg_idx, "--source")
|
local value, value_idx = require_flag_value(argv, arg_idx, "--source") ---@type string, integer
|
||||||
args.sources[#args.sources + 1] = value
|
args.sources[#args.sources + 1] = value
|
||||||
return value_idx
|
return value_idx
|
||||||
end
|
end
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @param argv string[]
|
||||||
|
--- @param arg_idx integer
|
||||||
|
--- @return integer
|
||||||
FLAG_HANDLERS["--unity-root"] = function(args, argv, arg_idx)
|
FLAG_HANDLERS["--unity-root"] = function(args, argv, arg_idx)
|
||||||
local value, value_idx = require_flag_value(argv, arg_idx, "--unity-root")
|
local value, value_idx = require_flag_value(argv, arg_idx, "--unity-root") ---@type string, integer
|
||||||
args.unity_root = value
|
args.unity_root = value
|
||||||
return value_idx
|
return value_idx
|
||||||
end
|
end
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @param argv string[]
|
||||||
|
--- @param arg_idx integer
|
||||||
|
--- @return integer
|
||||||
FLAG_HANDLERS["--metadata"] = function(args, argv, arg_idx)
|
FLAG_HANDLERS["--metadata"] = function(args, argv, arg_idx)
|
||||||
local value, value_idx = require_flag_value(argv, arg_idx, "--metadata")
|
local value, value_idx = require_flag_value(argv, arg_idx, "--metadata") ---@type string, integer
|
||||||
args.metadata = value
|
args.metadata = value
|
||||||
return value_idx
|
return value_idx
|
||||||
end
|
end
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @param argv string[]
|
||||||
|
--- @param arg_idx integer
|
||||||
|
--- @return integer
|
||||||
FLAG_HANDLERS["--out-root"] = function(args, argv, arg_idx)
|
FLAG_HANDLERS["--out-root"] = function(args, argv, arg_idx)
|
||||||
local value, value_idx = require_flag_value(argv, arg_idx, "--out-root")
|
local value, value_idx = require_flag_value(argv, arg_idx, "--out-root") ---@type string, integer
|
||||||
args.out_root = value
|
args.out_root = value
|
||||||
return value_idx
|
return value_idx
|
||||||
end
|
end
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @param argv string[]
|
||||||
|
--- @param arg_idx integer
|
||||||
|
--- @return integer
|
||||||
FLAG_HANDLERS["--project-root"] = function(args, argv, arg_idx)
|
FLAG_HANDLERS["--project-root"] = function(args, argv, arg_idx)
|
||||||
local value, value_idx = require_flag_value(argv, arg_idx, "--project-root")
|
local value, value_idx = require_flag_value(argv, arg_idx, "--project-root") ---@type string, integer
|
||||||
args.project_root = value
|
args.project_root = value
|
||||||
return value_idx
|
return value_idx
|
||||||
end
|
end
|
||||||
|
|
||||||
-- Per-pass stash flags. Read by `passes/atoms_source_map.lua` to opt into the post-link gdb-runtime emission.
|
-- Per-pass stash flags. Read by `passes/atoms_source_map.lua` to opt into the post-link gdb-runtime emission.
|
||||||
-- Same shape as the existing per-flag handlers. mutates `args.flags` (which propagates into `ctx.flags`).
|
-- Same shape as the existing per-flag handlers. mutates `args.flags` (which propagates into `ctx.flags`).
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @return nil
|
||||||
FLAG_HANDLERS["--gdb-runtime"] = function(args)
|
FLAG_HANDLERS["--gdb-runtime"] = function(args)
|
||||||
args.flags = args.flags or {}
|
args.flags = args.flags or {}
|
||||||
args.flags.gdb_runtime = true
|
args.flags.gdb_runtime = true
|
||||||
end
|
end
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @param argv string[]
|
||||||
|
--- @param arg_idx integer
|
||||||
|
--- @return integer
|
||||||
FLAG_HANDLERS["--elf"] = function(args, argv, arg_idx)
|
FLAG_HANDLERS["--elf"] = function(args, argv, arg_idx)
|
||||||
local value, value_idx = require_flag_value(argv, arg_idx, "--elf")
|
local value, value_idx = require_flag_value(argv, arg_idx, "--elf") ---@type string, integer
|
||||||
args.flags = args.flags or {}
|
args.flags = args.flags or {}
|
||||||
args.flags.elf_path = value
|
args.flags.elf_path = value
|
||||||
return value_idx
|
return value_idx
|
||||||
end
|
end
|
||||||
-- Enable DWARF injection (default OFF). Opts in to the post-link pass and sets the flag in one shot.
|
-- Enable DWARF injection (default OFF). Opts in to the post-link pass and sets the flag in one shot.
|
||||||
-- The explicit handler below owns both selection and opt-in state, so --dwarf-injection is intentionally absent from PASS_FLAG_TO_NAME.
|
-- The explicit handler below owns both selection and opt-in state, so --dwarf-injection is intentionally absent from PASS_FLAG_TO_NAME.
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @return nil
|
||||||
FLAG_HANDLERS["--dwarf-injection"] = function(args)
|
FLAG_HANDLERS["--dwarf-injection"] = function(args)
|
||||||
args.flags = args.flags or {}
|
args.flags = args.flags or {}
|
||||||
args.flags.dwarf_injection = true
|
args.flags.dwarf_injection = true
|
||||||
@@ -381,12 +497,16 @@ FLAG_HANDLERS["--dwarf-injection"] = function(args)
|
|||||||
end
|
end
|
||||||
-- Build-phase flags: --pre-link and --post-link request the roots of their declared groups (see roots_for_group).
|
-- Build-phase flags: --pre-link and --post-link request the roots of their declared groups (see roots_for_group).
|
||||||
-- topo_sort closes transitive deps from those roots; dispatch_passes runs every pass in the resolved closure without phase-filtering.
|
-- topo_sort closes transitive deps from those roots; dispatch_passes runs every pass in the resolved closure without phase-filtering.
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @return nil
|
||||||
FLAG_HANDLERS["--pre-link"] = function(args)
|
FLAG_HANDLERS["--pre-link"] = function(args)
|
||||||
request_roots_for_group(args, "pre-link")
|
request_roots_for_group(args, "pre-link")
|
||||||
end
|
end
|
||||||
-- Batch post-link phase: gdb-runtime + dwarf-injection in one luajit cold start.
|
-- Batch post-link phase: gdb-runtime + dwarf-injection in one luajit cold start.
|
||||||
-- Sets the same opt-in flags as --gdb-runtime + --dwarf-injection and selects the post-link build-phase group.
|
-- Sets the same opt-in flags as --gdb-runtime + --dwarf-injection and selects the post-link build-phase group.
|
||||||
-- elf is required; parse_args enforces it after all flags are parsed.
|
-- elf is required; parse_args enforces it after all flags are parsed.
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @return nil
|
||||||
FLAG_HANDLERS["--post-link"] = function(args)
|
FLAG_HANDLERS["--post-link"] = function(args)
|
||||||
args.flags = args.flags or {}
|
args.flags = args.flags or {}
|
||||||
args.flags.gdb_runtime = true
|
args.flags.gdb_runtime = true
|
||||||
@@ -397,8 +517,11 @@ end
|
|||||||
-- `--dwarf-injection` also emits atom-local debug data.
|
-- `--dwarf-injection` also emits atom-local debug data.
|
||||||
|
|
||||||
-- Pass-flag handler. Reads the closed-set table, expands --all, appends to requested_set.
|
-- Pass-flag handler. Reads the closed-set table, expands --all, appends to requested_set.
|
||||||
|
--- @param args ParsedArgs
|
||||||
|
--- @param a string
|
||||||
|
--- @return nil
|
||||||
FLAG_HANDLERS[PASS_FLAG_DISPATCH_KEY] = function(args, a)
|
FLAG_HANDLERS[PASS_FLAG_DISPATCH_KEY] = function(args, a)
|
||||||
local name = PASS_FLAG_TO_NAME[a]
|
local name = PASS_FLAG_TO_NAME[a] ---@type string|nil
|
||||||
if name == ALL_PASSES_SENTINEL then
|
if name == ALL_PASSES_SENTINEL then
|
||||||
request_all_passes(args)
|
request_all_passes(args)
|
||||||
return
|
return
|
||||||
@@ -410,7 +533,7 @@ end
|
|||||||
--- @param argv string[]
|
--- @param argv string[]
|
||||||
--- @return ParsedArgs
|
--- @return ParsedArgs
|
||||||
local function parse_args(argv)
|
local function parse_args(argv)
|
||||||
local args = {
|
local args = { ---@type ParsedArgs
|
||||||
requested_set = {},
|
requested_set = {},
|
||||||
sources = {},
|
sources = {},
|
||||||
unity_root = nil,
|
unity_root = nil,
|
||||||
@@ -420,10 +543,10 @@ local function parse_args(argv)
|
|||||||
verbose = false,
|
verbose = false,
|
||||||
}
|
}
|
||||||
|
|
||||||
local pos = 1
|
local pos = 1 ---@type integer
|
||||||
while pos <= #argv do
|
while pos <= #argv do
|
||||||
local a = argv[pos]
|
local a = argv[pos] ---@type string
|
||||||
local handler = FLAG_HANDLERS[a]
|
local handler = FLAG_HANDLERS[a] ---@type FlagHandler|nil
|
||||||
if handler then
|
if handler then
|
||||||
pos = handler(args, argv, pos) or pos
|
pos = handler(args, argv, pos) or pos
|
||||||
elseif PASS_FLAG_TO_NAME[a] then
|
elseif PASS_FLAG_TO_NAME[a] then
|
||||||
@@ -448,14 +571,14 @@ local function parse_args(argv)
|
|||||||
-- `<repo>/code/duffle/word_count.metadata.h` is the canonical metadata location.
|
-- `<repo>/code/duffle/word_count.metadata.h` is the canonical metadata location.
|
||||||
-- `project_root` names `<repo>`; the resolver derives `<project_root>/code` separately.
|
-- `project_root` names `<repo>`; the resolver derives `<project_root>/code` separately.
|
||||||
if not args.project_root then
|
if not args.project_root then
|
||||||
local metadata_dir = duffle.dirname(duffle.normalize_path(args.metadata))
|
local metadata_dir = duffle.dirname(duffle.normalize_path(args.metadata)) ---@type string
|
||||||
local code_root = duffle.dirname(metadata_dir)
|
local code_root = duffle.dirname(metadata_dir) ---@type string
|
||||||
args.project_root = duffle.dirname(code_root)
|
args.project_root = duffle.dirname(code_root)
|
||||||
else
|
else
|
||||||
args.project_root = duffle.normalize_path(args.project_root)
|
args.project_root = duffle.normalize_path(args.project_root)
|
||||||
end
|
end
|
||||||
|
|
||||||
local has_unity = type(args.unity_root) == "string" and args.unity_root ~= ""
|
local has_unity = type(args.unity_root) == "string" and args.unity_root ~= "" ---@type boolean
|
||||||
if has_unity and #args.sources > 0 then
|
if has_unity and #args.sources > 0 then
|
||||||
io.stderr:write("ps1_meta: --unity-root FILE and --source FILE are mutually exclusive\n")
|
io.stderr:write("ps1_meta: --unity-root FILE and --source FILE are mutually exclusive\n")
|
||||||
os.exit(EXIT_INTERNAL_ERROR)
|
os.exit(EXIT_INTERNAL_ERROR)
|
||||||
@@ -468,10 +591,10 @@ local function parse_args(argv)
|
|||||||
-- Post-link opt-ins (--gdb-runtime, --dwarf-injection) write output that depends on the linked ELF.
|
-- Post-link opt-ins (--gdb-runtime, --dwarf-injection) write output that depends on the linked ELF.
|
||||||
-- Without --elf the metaprogram can't satisfy those requests, so refuse loud and early.
|
-- Without --elf the metaprogram can't satisfy those requests, so refuse loud and early.
|
||||||
-- This covers the explicit --post-link batch, --dwarf-injection by itself, and --gdb-runtime by itself.
|
-- This covers the explicit --post-link batch, --dwarf-injection by itself, and --gdb-runtime by itself.
|
||||||
local flags = args.flags or {}
|
local flags = args.flags or {} ---@type PassFlags
|
||||||
local elf_path = flags.elf_path
|
local elf_path = flags.elf_path ---@type string|nil
|
||||||
local has_elf = type(elf_path) == "string" and #elf_path > 0
|
local has_elf = type(elf_path) == "string" and #elf_path > 0 ---@type boolean
|
||||||
local post_links = flags.gdb_runtime or flags.dwarf_injection
|
local post_links = flags.gdb_runtime or flags.dwarf_injection ---@type boolean
|
||||||
if post_links and not has_elf then
|
if post_links and not has_elf then
|
||||||
io.stderr:write("ps1_meta: --elf PATH is required for post-link output\n")
|
io.stderr:write("ps1_meta: --elf PATH is required for post-link output\n")
|
||||||
os.exit(EXIT_INTERNAL_ERROR)
|
os.exit(EXIT_INTERNAL_ERROR)
|
||||||
@@ -490,9 +613,9 @@ end
|
|||||||
--- @param args ParsedArgs
|
--- @param args ParsedArgs
|
||||||
--- @return PassCtx
|
--- @return PassCtx
|
||||||
local function build_ctx(args)
|
local function build_ctx(args)
|
||||||
local normalized_project_root = duffle.normalize_path(args.project_root)
|
local normalized_project_root = duffle.normalize_path(args.project_root) ---@type string
|
||||||
local project_root = normalized_project_root
|
local project_root = normalized_project_root ---@type string
|
||||||
local project_root_is_absolute = normalized_project_root:match("^%a:/")
|
local project_root_is_absolute = normalized_project_root:match("^%a:/") ---@type boolean
|
||||||
or normalized_project_root:sub(1, 2) == "//"
|
or normalized_project_root:sub(1, 2) == "//"
|
||||||
or normalized_project_root:sub(1, 1) == "/"
|
or normalized_project_root:sub(1, 1) == "/"
|
||||||
if not project_root_is_absolute then
|
if not project_root_is_absolute then
|
||||||
@@ -503,9 +626,9 @@ local function build_ctx(args)
|
|||||||
-- Do not route POSIX/UNC/drive-absolute paths through to_absolute_path.
|
-- Do not route POSIX/UNC/drive-absolute paths through to_absolute_path.
|
||||||
duffle.canonical_path_key(project_root)
|
duffle.canonical_path_key(project_root)
|
||||||
end
|
end
|
||||||
local resolution
|
local resolution ---@type Corpus
|
||||||
if args.unity_root then
|
if args.unity_root then
|
||||||
local ok_resolve, resolved = pcall(duffle.resolve_source_corpus, {
|
local ok_resolve, resolved = pcall(duffle.resolve_source_corpus, { ---@type boolean, Corpus|string
|
||||||
unity_root = args.unity_root,
|
unity_root = args.unity_root,
|
||||||
project_root = project_root,
|
project_root = project_root,
|
||||||
})
|
})
|
||||||
@@ -515,59 +638,18 @@ local function build_ctx(args)
|
|||||||
end
|
end
|
||||||
resolution = resolved
|
resolution = resolved
|
||||||
else
|
else
|
||||||
local source_order = {}
|
local ok_exact, exact = pcall(duffle.resolve_exact_sources, { ---@type boolean, Corpus|string
|
||||||
local sources_by_path = {}
|
sources = args.sources,
|
||||||
local resolver = {
|
project_root = project_root,
|
||||||
resolved = {},
|
})
|
||||||
skipped = {},
|
if not ok_exact then
|
||||||
shadowed = {},
|
io.stderr:write("ps1_meta: cannot resolve --source: " .. tostring(exact) .. "\n")
|
||||||
}
|
|
||||||
for _, input_path in ipairs(args.sources) do
|
|
||||||
local path = duffle.normalize_path(input_path)
|
|
||||||
local key_ok, key_or_error = pcall(duffle.canonical_path_key, path)
|
|
||||||
if not key_ok then
|
|
||||||
error("ps1_meta: invalid --source " .. input_path .. ": " .. tostring(key_or_error), 0)
|
|
||||||
end
|
|
||||||
local file = io.open(path, "r")
|
|
||||||
if not file then
|
|
||||||
io.stderr:write("ps1_meta: cannot open --source " .. input_path .. "\n")
|
|
||||||
os.exit(EXIT_INTERNAL_ERROR)
|
os.exit(EXIT_INTERNAL_ERROR)
|
||||||
end
|
end
|
||||||
local text = file:read("*a")
|
resolution = exact
|
||||||
file:close()
|
|
||||||
|
|
||||||
local source = {
|
|
||||||
path = path,
|
|
||||||
text = text,
|
|
||||||
dir = duffle.dirname(path),
|
|
||||||
basename = duffle.basename_no_ext(path),
|
|
||||||
}
|
|
||||||
source_order[#source_order + 1] = source
|
|
||||||
local key = key_or_error
|
|
||||||
if not sources_by_path[key] then sources_by_path[key] = source end
|
|
||||||
resolver.resolved[#resolver.resolved + 1] = {
|
|
||||||
include_path = path,
|
|
||||||
include_text = nil,
|
|
||||||
root_source = nil,
|
|
||||||
root_line = nil,
|
|
||||||
candidate_a = path,
|
|
||||||
candidate_b = nil,
|
|
||||||
selected_path = path,
|
|
||||||
disposition = "exact",
|
|
||||||
}
|
|
||||||
end
|
|
||||||
resolution = {
|
|
||||||
unity_root = nil,
|
|
||||||
project_root = project_root,
|
|
||||||
code_root = duffle.normalize_path(project_root .. "/code"),
|
|
||||||
source_order = source_order,
|
|
||||||
sources_by_path = sources_by_path,
|
|
||||||
sources_by_dir = duffle.group_sources_by_dir(source_order),
|
|
||||||
resolver = resolver,
|
|
||||||
}
|
|
||||||
end
|
end
|
||||||
|
|
||||||
local corpus = {
|
local corpus = { ---@type Corpus
|
||||||
unity_root = resolution.unity_root,
|
unity_root = resolution.unity_root,
|
||||||
project_root = resolution.project_root,
|
project_root = resolution.project_root,
|
||||||
code_root = resolution.code_root,
|
code_root = resolution.code_root,
|
||||||
@@ -584,11 +666,12 @@ local function build_ctx(args)
|
|||||||
atom_phases = {},
|
atom_phases = {},
|
||||||
word_counts = {},
|
word_counts = {},
|
||||||
components = {},
|
components = {},
|
||||||
component_body_index = {},
|
atom_bundles = {},
|
||||||
|
tape_emits = {},
|
||||||
collisions = {},
|
collisions = {},
|
||||||
resolver = resolution.resolver,
|
resolver = resolution.resolver,
|
||||||
}
|
}
|
||||||
local ctx = {
|
local ctx = { ---@type PassCtx
|
||||||
metadata_path = args.metadata,
|
metadata_path = args.metadata,
|
||||||
shared = { corpus = corpus },
|
shared = { corpus = corpus },
|
||||||
out_root = args.out_root,
|
out_root = args.out_root,
|
||||||
@@ -617,15 +700,15 @@ end
|
|||||||
--- Keeping these blocks local makes the topological sort self-contained.
|
--- Keeping these blocks local makes the topological sort self-contained.
|
||||||
local function topo_sort(passes, requested_set)
|
local function topo_sort(passes, requested_set)
|
||||||
-- Dependency closure: include every pass transitively required by `requested_set`.
|
-- Dependency closure: include every pass transitively required by `requested_set`.
|
||||||
local needed = {}
|
local needed = {} ---@type table<string, boolean> -- bag: pass name -> needed
|
||||||
for _, name in ipairs(requested_set) do needed[name] = true end
|
for _, name in ipairs(requested_set) do needed[name] = true end ---@type integer, string
|
||||||
local changed = true
|
local changed = true ---@type boolean
|
||||||
while changed do
|
while changed do
|
||||||
changed = false
|
changed = false
|
||||||
for name, _ in pairs(needed) do
|
for name, _ in pairs(needed) do ---@type string, boolean
|
||||||
local pass = passes[name]
|
local pass = passes[name] ---@type PassDescriptor
|
||||||
if not pass then error("unknown pass '" .. name .. "' requested") end
|
if not pass then error("unknown pass '" .. name .. "' requested") end
|
||||||
for _, dep in ipairs(pass.deps) do
|
for _, dep in ipairs(pass.deps) do ---@type integer, string
|
||||||
if not needed[dep] then
|
if not needed[dep] then
|
||||||
needed[dep] = true
|
needed[dep] = true
|
||||||
changed = true
|
changed = true
|
||||||
@@ -635,10 +718,10 @@ local function topo_sort(passes, requested_set)
|
|||||||
end
|
end
|
||||||
|
|
||||||
-- In-degree calculation: count each needed pass's needed dependencies.
|
-- In-degree calculation: count each needed pass's needed dependencies.
|
||||||
local in_degree = {}
|
local in_degree = {} ---@type table<string, integer> -- bag: pass name -> in-degree
|
||||||
for name, _ in pairs(needed) do in_degree[name] = 0 end
|
for name, _ in pairs(needed) do in_degree[name] = 0 end ---@type string, boolean
|
||||||
for name, _ in pairs(needed) do
|
for name, _ in pairs(needed) do ---@type string, boolean
|
||||||
for _, dep in ipairs(passes[name].deps) do
|
for _, dep in ipairs(passes[name].deps) do ---@type integer, string
|
||||||
if needed[dep] then
|
if needed[dep] then
|
||||||
in_degree[name] = in_degree[name] + 1
|
in_degree[name] = in_degree[name] + 1
|
||||||
end
|
end
|
||||||
@@ -646,21 +729,21 @@ local function topo_sort(passes, requested_set)
|
|||||||
end
|
end
|
||||||
|
|
||||||
-- Ready-queue seeding: add zero-in-degree passes in deterministic order.
|
-- Ready-queue seeding: add zero-in-degree passes in deterministic order.
|
||||||
local ready = {}
|
local ready = {} ---@type string[]
|
||||||
for name, deg in pairs(in_degree) do
|
for name, deg in pairs(in_degree) do ---@type string, integer
|
||||||
if deg == 0 then ready[#ready + 1] = name end
|
if deg == 0 then ready[#ready + 1] = name end
|
||||||
end
|
end
|
||||||
table.sort(ready)
|
table.sort(ready)
|
||||||
|
|
||||||
-- Ready-queue drain: decrement dependents when each pass is emitted.
|
-- Ready-queue drain: decrement dependents when each pass is emitted.
|
||||||
-- Newly-zero-degree passes are inserted back into the ready queue (kept sorted).
|
-- Newly-zero-degree passes are inserted back into the ready queue (kept sorted).
|
||||||
local order = {}
|
local order = {} ---@type string[]
|
||||||
while #ready > 0 do
|
while #ready > 0 do
|
||||||
local just_finished = table.remove(ready, 1)
|
local just_finished = table.remove(ready, 1) ---@type string
|
||||||
order[#order + 1] = just_finished
|
order[#order + 1] = just_finished
|
||||||
for name, _ in pairs(needed) do
|
for name, _ in pairs(needed) do ---@type string, boolean
|
||||||
if name ~= just_finished then
|
if name ~= just_finished then
|
||||||
for _, dep in ipairs(passes[name].deps) do
|
for _, dep in ipairs(passes[name].deps) do ---@type integer, string
|
||||||
if dep == just_finished then
|
if dep == just_finished then
|
||||||
in_degree[name] = in_degree[name] - 1
|
in_degree[name] = in_degree[name] - 1
|
||||||
if in_degree[name] == 0 then
|
if in_degree[name] == 0 then
|
||||||
@@ -676,10 +759,10 @@ local function topo_sort(passes, requested_set)
|
|||||||
-- Cycle detection: if `order` doesn't include all needed passes, some are stuck with in_degree > 0
|
-- Cycle detection: if `order` doesn't include all needed passes, some are stuck with in_degree > 0
|
||||||
-- (the cycle closed on itself before Kahn could process them).
|
-- (the cycle closed on itself before Kahn could process them).
|
||||||
-- Without this check, a fully-closed cycle (e.g. A -> B -> A) would silently return an empty order list, leaving the orchestrator to dispatch nothing.
|
-- Without this check, a fully-closed cycle (e.g. A -> B -> A) would silently return an empty order list, leaving the orchestrator to dispatch nothing.
|
||||||
local needed_count = 0
|
local needed_count = 0 ---@type integer
|
||||||
for _ in pairs(needed) do needed_count = needed_count + 1 end -- count hash entries; Lua's #t doesn't work
|
for _ in pairs(needed) do needed_count = needed_count + 1 end ---@type string -- count hash entries; Lua's #t doesn't work
|
||||||
if #order ~= needed_count then
|
if #order ~= needed_count then
|
||||||
for name, deg in pairs(in_degree) do
|
for name, deg in pairs(in_degree) do ---@type string, integer
|
||||||
if deg > 0 then
|
if deg > 0 then
|
||||||
error("dependency cycle detected involving pass '" .. name .. "'")
|
error("dependency cycle detected involving pass '" .. name .. "'")
|
||||||
end
|
end
|
||||||
@@ -693,19 +776,19 @@ end
|
|||||||
-- Main Orchestrator
|
-- Main Orchestrator
|
||||||
-- ════════════════════════════════════════════════════════════════════════════
|
-- ════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
--- (internal) If the pass's kind is in PASS_KIND_STOP_ON_ERROR and it reported errors, write each error to stderr.
|
--- (internal) Write every pass error to stderr.
|
||||||
--- Returns true if any validation errors were reported.
|
--- Returns true only when the pass kind still stops the build.
|
||||||
--- @param pass_name string
|
--- @param pass_name string
|
||||||
--- @param pass PassDescriptor
|
--- @param pass PassDescriptor
|
||||||
--- @param result PassResult
|
--- @param result PassResult
|
||||||
--- @return boolean
|
--- @return boolean
|
||||||
local function report_validation_errors(pass_name, pass, result)
|
local function report_validation_errors(pass_name, pass, result)
|
||||||
local has_errors = result.errors and #result.errors > 0
|
local has_errors = result.errors and #result.errors > 0 ---@type boolean
|
||||||
if not (has_errors and PASS_KIND_STOP_ON_ERROR[pass.kind]) then return false end
|
if not has_errors then return false end
|
||||||
for _, e in ipairs(result.errors) do
|
for _, e in ipairs(result.errors) do ---@type integer, Finding
|
||||||
io.stderr:write(string.format("[%s] line %d: %s\n", pass_name, e.line or 0, e.msg or ""))
|
io.stderr:write(string.format("[%s] line %d: %s\n", pass_name, e.line or 0, e.msg or ""))
|
||||||
end
|
end
|
||||||
return true
|
return PASS_KIND_STOP_ON_ERROR[pass.kind] == true
|
||||||
end
|
end
|
||||||
|
|
||||||
--- (internal) Run each pass in `order` in topological sequence.
|
--- (internal) Run each pass in `order` in topological sequence.
|
||||||
@@ -713,11 +796,11 @@ end
|
|||||||
--- @param order string[]
|
--- @param order string[]
|
||||||
--- @return boolean -- true if any validation errors were reported
|
--- @return boolean -- true if any validation errors were reported
|
||||||
local function dispatch_passes(ctx, order)
|
local function dispatch_passes(ctx, order)
|
||||||
local had_errors = false
|
local had_errors = false ---@type boolean
|
||||||
for _, pass_name in ipairs(order) do
|
for _, pass_name in ipairs(order) do ---@type integer, string
|
||||||
local pass = PASSES[pass_name]
|
local pass = PASSES[pass_name] ---@type PassDescriptor
|
||||||
local mod = require(pass.module)
|
local mod = require(pass.module) ---@type PassModule
|
||||||
local result = mod.run(ctx)
|
local result = mod.run(ctx) ---@type PassResult
|
||||||
if report_validation_errors(pass_name, pass, result) then
|
if report_validation_errors(pass_name, pass, result) then
|
||||||
had_errors = true
|
had_errors = true
|
||||||
end
|
end
|
||||||
@@ -727,16 +810,16 @@ end
|
|||||||
|
|
||||||
--- Main entry point. Runs the requested passes in dep-topological order.
|
--- Main entry point. Runs the requested passes in dep-topological order.
|
||||||
--- @param argv string[]
|
--- @param argv string[]
|
||||||
|
--- @return nil
|
||||||
local function main(argv)
|
local function main(argv)
|
||||||
local ok, err = pcall(function()
|
local ok, err = pcall(function() ---@type boolean, string|nil
|
||||||
local args = parse_args(argv)
|
local args = parse_args(argv) ---@type ParsedArgs
|
||||||
local ctx = build_ctx(args)
|
local ctx = build_ctx(args) ---@type PassCtx
|
||||||
|
|
||||||
local requested = args.requested_set
|
local requested = args.requested_set ---@type string[]
|
||||||
local closed = topo_sort(PASSES, requested)
|
local closed = topo_sort(PASSES, requested) ---@type string[]
|
||||||
|
|
||||||
local had_errors = dispatch_passes(ctx, closed)
|
dispatch_passes(ctx, closed)
|
||||||
if had_errors then os.exit(EXIT_VALIDATION_ERRORS) end
|
|
||||||
end)
|
end)
|
||||||
|
|
||||||
if not ok then
|
if not ok then
|
||||||
@@ -750,7 +833,7 @@ end
|
|||||||
-- Module export for in-process consumers (tests that dofile this script).
|
-- Module export for in-process consumers (tests that dofile this script).
|
||||||
-- The conditional `main(...)` call below only fires when this file is invoked as the entry script (arg[0] ends in "ps1_meta.lua");
|
-- The conditional `main(...)` call below only fires when this file is invoked as the entry script (arg[0] ends in "ps1_meta.lua");
|
||||||
-- in dofile() mode (test's arg[0] does not match), main() is skipped and the chunk returns `_M` to the caller.
|
-- in dofile() mode (test's arg[0] does not match), main() is skipped and the chunk returns `_M` to the caller.
|
||||||
local _M = {
|
local _M = { ---@type Ps1MetaMod
|
||||||
PASSES = PASSES,
|
PASSES = PASSES,
|
||||||
PASS_KIND_STOP_ON_ERROR = PASS_KIND_STOP_ON_ERROR,
|
PASS_KIND_STOP_ON_ERROR = PASS_KIND_STOP_ON_ERROR,
|
||||||
parse_args = parse_args,
|
parse_args = parse_args,
|
||||||
|
|||||||
+14
-25
@@ -91,11 +91,9 @@ if (-not (Test-Path -LiteralPath $path_pcsx_packages)) {
|
|||||||
New-Item -ItemType Directory -Path $path_pcsx_packages -Force | Out-Null
|
New-Item -ItemType Directory -Path $path_pcsx_packages -Force | Out-Null
|
||||||
}
|
}
|
||||||
|
|
||||||
# Download anything missing. Skip the package entirely if its dir already has
|
# Download anything missing.
|
||||||
# any contents (the legacy packages.config style means the targets file
|
# Skip the package entirely if its dir already has any contents (the legacy packages.config style means the targets file location varies per package
|
||||||
# location varies per package — `luajit.native` puts it at build/native/,
|
# — `luajit.native` puts it at build/native/, `glfw` puts it elsewhere — so we can't probe a specific path; just check whether the dir is non-empty).
|
||||||
# `glfw` puts it elsewhere — so we can't probe a specific path; just check
|
|
||||||
# whether the dir is non-empty).
|
|
||||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||||
foreach ($pkg in $required_packages.Values) {
|
foreach ($pkg in $required_packages.Values) {
|
||||||
$pkgDir = Join-Path $path_pcsx_packages ('{0}.{1}' -f $pkg.id, $pkg.version)
|
$pkgDir = Join-Path $path_pcsx_packages ('{0}.{1}' -f $pkg.id, $pkg.version)
|
||||||
@@ -122,24 +120,18 @@ foreach ($pkg in $required_packages.Values) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
|
||||||
# isoffi.lua size guard — `core.vcxproj` #includes src/core/isoffi.lua into
|
# isoffi.lua size guard — `core.vcxproj` #includes src/core/isoffi.lua into luaiso.cc via the `-- lualoader, R"EOF(...)EOF"` trick.
|
||||||
# luaiso.cc via the `-- lualoader, R"EOF(...)EOF"` trick. The raw string
|
# The raw string literal between R"EOF(-- and -- )EOF" must stay under ~16,379 bytes or MSVC (19.44) fails with C2026 (its actual raw-string limit is 16,384, minus 5 bytes for the `-- lualoader, ` prefix).
|
||||||
# literal between R"EOF(-- and -- )EOF" must stay under ~16,379 bytes or
|
# If the upstream file grows past that, trim it: remove license header, trailing whitespace, blank separators, inline comments, and shrink 4-space indent to 2-space.
|
||||||
# MSVC (19.44) fails with C2026 (its actual raw-string limit is 16,384,
|
|
||||||
# minus 5 bytes for the `-- lualoader, ` prefix). If the upstream file
|
|
||||||
# grows past that, trim it: remove license header, trailing whitespace,
|
|
||||||
# blank separators, inline comments, and shrink 4-space indent to 2-space.
|
|
||||||
# Idempotent — only writes when the raw string exceeds the limit.
|
# Idempotent — only writes when the raw string exceeds the limit.
|
||||||
# ════════════════════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════
|
||||||
$path_isoffi = join-path $path_pcsx_redux 'src\core\isoffi.lua'
|
$path_isoffi = join-path $path_pcsx_redux 'src\core\isoffi.lua'
|
||||||
if (Test-Path -LiteralPath $path_isoffi) {
|
if (Test-Path -LiteralPath $path_isoffi) {
|
||||||
$content = Get-Content -LiteralPath $path_isoffi -Raw -Encoding utf8
|
$content = Get-Content -LiteralPath $path_isoffi -Raw -Encoding utf8
|
||||||
$startMarker = $content.IndexOf('R"EOF(--')
|
$startMarker = $content.IndexOf('R"EOF(--')
|
||||||
$endMarker = $content.IndexOf('-- )EOF"')
|
$endMarker = $content.IndexOf('-- )EOF"')
|
||||||
$literalLen = if ($startMarker -ge 0 -and $endMarker -gt $startMarker) {
|
$literalLen = if ($startMarker -ge 0 -and $endMarker -gt $startMarker) { $endMarker - ($startMarker + 8) } else { -1 }
|
||||||
$endMarker - ($startMarker + 8)
|
|
||||||
} else { -1 }
|
|
||||||
# Effective MSVC raw-string limit for the lualoader prefix is 16379 bytes.
|
# Effective MSVC raw-string limit for the lualoader prefix is 16379 bytes.
|
||||||
if ($literalLen -gt 16379) {
|
if ($literalLen -gt 16379) {
|
||||||
Write-Host "isoffi.lua raw string is $literalLen bytes (>16379); trimming for MSVC C2026 limit."
|
Write-Host "isoffi.lua raw string is $literalLen bytes (>16379); trimming for MSVC C2026 limit."
|
||||||
@@ -168,8 +160,7 @@ if (Test-Path -LiteralPath $path_isoffi) {
|
|||||||
$newLines += $line
|
$newLines += $line
|
||||||
}
|
}
|
||||||
($newLines -join "`n") | Out-File -LiteralPath $path_isoffi -Encoding utf8 -NoNewline
|
($newLines -join "`n") | Out-File -LiteralPath $path_isoffi -Encoding utf8 -NoNewline
|
||||||
$newLen = ((Get-Content -LiteralPath $path_isoffi -Raw -Encoding utf8) `
|
$newLen = ((Get-Content -LiteralPath $path_isoffi -Raw -Encoding utf8) -replace '.*R"EOF\(--', '' -replace '-- \)EOF".*', '').Length
|
||||||
-replace '.*R"EOF\(--', '' -replace '-- \)EOF".*', '').Length
|
|
||||||
Write-Host "isoffi.lua trimmed: $literalLen -> $newLen bytes of raw string content."
|
Write-Host "isoffi.lua trimmed: $literalLen -> $newLen bytes of raw string content."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,13 +222,11 @@ $lfs_dll_import = join-path $luajit_lib_dir 'libluajit-5.1.dll.a'
|
|||||||
|
|
||||||
$path_openbios = join-path $path_pcsx_redux 'src\mips\openbios'
|
$path_openbios = join-path $path_pcsx_redux 'src\mips\openbios'
|
||||||
|
|
||||||
# Wipe stale *.dep files across src\mips. These cache absolute paths to the
|
# Wipe stale *.dep files across src\mips.
|
||||||
# GCC headers directory; if the toolchain was upgraded (e.g. v14.2.0 → v16.1.0)
|
# These cache absolute paths to the GCC headers directory; if the toolchain was upgraded (e.g. v14.2.0 → v16.1.0)
|
||||||
# Make reads the stale paths and aborts with "no rule to make target .../stddef.h".
|
# Make reads the stale paths and aborts with "no rule to make target .../stddef.h".
|
||||||
# `make clean` in openbios only clears its own dir — subdirs like
|
# `make clean` in openbios only clears its own dir — subdirs like common/crt0/, modplayer/, and shell/ keep their stale .dep files.
|
||||||
# common/crt0/, modplayer/, and shell/ keep their stale .dep files. Easier to
|
# Easier to just delete the lot before each build than to teach every Makefile about deepclean recursion.
|
||||||
# just delete the lot before each build than to teach every Makefile about
|
|
||||||
# deepclean recursion.
|
|
||||||
Get-ChildItem -Path (join-path $path_pcsx_redux 'src\mips') -Recurse -Filter '*.dep' -ErrorAction SilentlyContinue |
|
Get-ChildItem -Path (join-path $path_pcsx_redux 'src\mips') -Recurse -Filter '*.dep' -ErrorAction SilentlyContinue |
|
||||||
ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force }
|
ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force }
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user