Matching techniques¶
Source shapes and compiler behaviours found while matching the game's functions with ee-gcc 3.2, one entry each, with the function that showed it. The list was collected during the recovery runs of November 2026, so some entries are phrased as advice to the person matching a function.
Historical search scripts are available in the parent of commit ee3346987. ProgressHandler includes the tools for the remaining game fallback.
The first entries are owner decisions of 13 November 2026; docs/development/READABILITY.md is the standard they belong to.
- An unnamed local is acceptable when it holds one real value the body uses
(a reference to an array element, a member copied once, a pointer read once)
and it makes the function exact. CRagdoll2::Move matched with
ParticleProperty &particleProperty = m_aParticleProperty[i];and MoveTarget withfloat tx = tracker.x;. Still no dead locals and no casts added only to steer the compiler. - PS2 functions may use the typed PS2 intrinsics in src/engine/system/_ps2/ (mmi.h: ZPor, ZPxor, ZPceqh, ZPpacb, ZPcpyld, ZPcpyud, ZMovz; addscaled.h: ZAddScaled; prefetch.h: ZPrefetch). Do not write new inline assembly.
- A loop whose counter is compared unsigned (
sltiu) and is not reversed usually compares against a sizeof expression or an unsigned bound; GCC 3.2 only reverses loops on a signed<. - If-conversion hoists the return-value store of a
return CONST;block that has a single predecessor, which moves the result register. Inverting the last test so the return is shared with another path fixed ZHitman3::CanSyringe (20 -> 0). - A file-local static helper that reads a member often stands in for an original
member inline accessor (
pActor->GetEndPosReqTime()made ZEnterElevator::UpdatePosition exact). Prefer adding the accessor to the class. - Functions at address >= 0x4381f8 sit in the reference's inline-function groups: in the original they were header inlines or templates, even where our source defines them out of line.
- Register ties between two locals follow global-alloc priority
floor_log2(refs) * frequency / live_length * size. Rewriting a tail asif (x) {...} else { return false; } return true;changes live lengths without changing code in AllocateBufferPath. - For a function with no draft or a draft scoring over 300: do not tune the old draft. Rebuild the body statement by statement from tools/lines.py (one source line per statement, in line order) and tools/debug_context.py (every named local in its scope), using tools/m2c_draft.py only as a reading aid. Write the draft first, commit it, then iterate.
- Byte-assembled values (bit readers, packed ints) build the result one statement
at a time in the result variable (
r = p[0]; r |= p[1] << 8; ...); a single OR-expression folds differently (StreamPacker 1037 -> 377 from this alone).(a << 3) + (b << 3)keeps two shifts;a * 8 + b * 8folds to(a + b) * 8. - Before tuning a draft, look for a matched sibling with the same name in another
class or unit (
grep -rn "Name(" src); copying its expression forms made the 5-argument ZHumanState::Blend and the static CheckBloodSplatter exact at once. - Every enum type is its own alias set in GCC 3.2. A field typed with a stand-in or duplicate enum (a global copy of a nested enum) changes which loads are reused. Check the field's type against analysis/recovered-types.h and the mangled names; typing sContainerEntry::m_eActionType as ZHM3ActionControl::EHM3Action made ZGui::ClassFrameUpdate (5,684 bytes) exact.
- A do-while whose decrement-and-test reads
sw; lw; bnezhas two--lRunssites in the source, one in an earlyif (...) { --lRuns; continue; }(ZSoundGraph::TestRooms 1601 -> 40 from this alone). - Two
move $sX, $v0copies of one call result are a chained assignment in the source (pOrig = pItem = GetItem(...)); two statements let CSE merge the locals. - A loop that tests at the top and falls from the first call into the second is
(bFirst && GetFirst()) || GetNext(), not a?:. constlocals never share a stack slot with a freed temporary in GCC 3.2. If a struct local sits above its own initializer's temporaries or skips a slot the next statement reuses, declare itconst(ActorCollision 81 -> 3 from this).- When the original saves more callee-saved registers than it uses and both branches end alike, write the final statement in each branch; GCC merges them.
- One instruction tagged with two source lines (
:143 :149) is the same statement written at the end of both if/else arms and merged by GCC. - A loop whose invariant loads stay inside it, with a
bc1tlthat jumps past the back-branch, has abreakafter the flag store (ProcessLight 281 -> 87). - A
div.sby what looks like a literal (2.0, 4.0) is a non-const local such asint iSubSteps = 2;: a literal divisor always folds to a multiply, and the debug record drops the local after propagating it (MoveRagdoll 2547 -> 0). - A walk written
for (p = Next(); p; p = Next())has two call sites before GCC merges them; those extra references raise p's register priority. - A null test kept after the pointer was already dereferenced is a test of a second
variable holding the same pointer (e.g.
ZHM3ItemWeapon *pWeapon = static_cast<ZHM3ItemWeapon *>(pItem);used for every later statement); GCC deletes the null check on the dereferenced one (ControlWeapon 280 -> 146). - GS register words: Sony's SCE_GS_SET_* field form with an
(unsigned long)cast on each field reproduces the original's extend-then-OR sequences; a 32-bit shift before widening compiles differently from a 64-bit shift after it. - A bool inline that sets 1 before its tests is
if (a) return true; return b;, notreturn a || b;. - GCC 3.2 turns a loop into a down-counter only when the counter is incremented
once; two
i++in the body keep the original's up-count withslti. - Getter loads placed before a call while the arithmetic comes after it mean the source held the results in locals declared in that load order.
- A non-inline getter called with its result unused is
ZASSERT(Getter());(compiled-out assert; owner-accepted). - A return value copied to $v0 once at the end (via $t7) where yours goes straight to $v0 at each return: one return reads a member instead of the local (copy propagation then cannot merge them); ZItem::SetItemOwner.
- A switch's default block position follows the highest jump-table entry pointing
at it: an explicit case group with the default body, written after
default:, reproduces it (ActOnCurrentAction). if (!A || !B) {...}lets CSE reuse a loaded value the original reloads; an earlyif (A && B) return X;stops it.- A redundant
if (n)around a counted loop can flip which variable is kept in a register and which goes to the stack; try removing it (GetStripsInsideBox). - GCC 3.2 checks an uninstantiated template's inline budget at zero statements, so the first caller always inlines it. A user-written
{}constructor/destructor in a header instantiates member templates during parsing and loses that free pass; compiler-generated ones keep it (ZDictionary_Serializerlib D1/D0). - Saved registers can trade places when two locals tie in allocation priority. Inspect the allocator’s weighted frequencies as well as live lengths.
In
ZGUITable::Setup, reading the member directly changes which local gets the register. - Two look-alike local arrays in separate stack slots: check their
type_idindebug_context.py --json. Different type numbers mean separately declared array types (uint32 a[] = {...}vsuint32 a[4]), each its own alias set, so no slot sharing (SaveBoundTrees). - A shared
return falseblock placed too late: read the.31.bbrodump fromcompile_unit.py --dump B; nest the code so the failing test falls through to the final return as the original does (CalcColiLort). - New approved intrinsics (13 Nov):
ZCross(pResult, v0, v1)(engine/system/_ps2/cross.h, six contiguousmula.s/msub.s) andZDot(fResult, v0, v1)(reference output; a stack temporary beside each stored component is the sign).TransferCamAndExitsis on the inline-asm list. - A draft exact with
-f=-fno-gcse: dump withtools/compile_unit.py <unit> -D NON_MATCHING --dump Gand grep the .gcse file for COPY-PROP/CONST-PROP to see which copy the original kept. The readability standard records the evidenced dead store inZTextCredits::Update. CHUNKFILE::ChildCountnow tests the whole size word twice; four CHUNKFILE callers became exact, so recheck any draft that walks chunks.- Packet words built from
intarithmetic take the signedVIFCODE_DIRECTenum; theuint32PACKET_DIRECTadds a zero extension (FillRegion). Write oneAddRegper source line betweenBeginCntPacketandEndPacket, and a one-line clamp with nozmath.hline as a ternary on that line. - A placement
operator newwithoutthrow()drops the original's null test after placement new; define itthrow()instead of hand-writingif (p). A loop tested at the top withb headat the bottom isfor (;;) { if (!n--) break; ... }; anywhile/forwith a condition gets rotated. - An if / else-if / else-break chain on a flag: give the flag its initial value at the declaration, or GCC drops the second compare (lPackBits = 8). When the original stores the first DMA word directly and reloads a stack array for the rest, copy from the array (
lCurrentDelta[i]), not the scalars just stored. - Returns going through
$a0instead of writing$v0directly, with an in-loopreturn x;moved out of the loop: look for an earlyif (r) return r;the original did not have. Writeif (!r) { ... }and one finalreturn r;(GetClosestGuard; STRREFTAB::FindStr is the same shape). - A loop whose early exit branches back to the loop's own test is a
continue, not abreak; one wrong word there shows up as register differences across the whole loop (UpdateActiveMarks). - Per-loop range registers in the original that your build lacks: check where the enclosing block starts. Declaring the loop locals inside the
ifthat holds the loops makes the live-range pass split them as the original does (UpdateText). - GCC 3.2 never shares a temporary stack slot for a type with a reference or const member; a derived wrapper type is exempt.
ZFixedSizeMemoryManager<T>::Iterator(typed, derived) is now in fixed_size_memory_manager.h and fixed two oversized SaveObject frames. - Jump threading links two tests only when they compare the same variable, and it runs before copy propagation: test the variable the original tests (AddBaseGeoms).
- A
?:that is an operand of|is rewritten by constant folding; when the original computes it separately, make it its own statement (uTTE = bWithSign ? 0 : USN; uTTE |= ...;, UnpackAndFixAlign). - A surviving copy of a
ZDotresult (mov.safter the madd) means the original reused a scratch float:fLength = ZDot(...); fDot = fLength;thenif (fLength < fDot) fDot = fLength;per extra dot (CheckMoveObjectTorso). - zmath.h lines 1664-1666 are the in-place
vadd(a, b):v3copy(dst, src); vadd(dst, d);(FrameUpdate). An increment block that jumps into the middle of the call before a loop means an unrotatedfor (;;) { if (!x) break; ... }. Alui %hi(global)reload the original has and you lack points to a ternary or a two-return inline between the uses. - What looks like a scheduling difference can be wrong constants: when two switch cases share code in your build but not in the original, compare every immediate the cases pass (SetupMemoryBuffers).
tools/mutate.py --loosefound ReadPS2SystemFile's local. $t4-$t7rotation of temporaries is the local allocator ranking refs / live span in scheduler order; how a later call's result is assigned changes that order (GetSysMemPixInterpolated: one statement per line-table line in every group).- Debug-record scopes are block boundaries: a scope that starts right after a test and holds one local means
if (p) { T local; ... }with that local declared first, notif (!p) continue;(AddButtonGraphic). - A store GCC merged from both arms of an if (crossjump tail) means each arm wrote it in the source; a shared temporary in its place drops references and swaps registers (CreateWinFaces). Earlier failed attempts may only have failed because of another wrong statement: retry them after each fix.
- "Scheduler/register tie" residue is often a wrong source shape. QuickSort (108 -> 0) needed a real tail-recursive call instead of a loop, the classic
if (iL <= iR) { swap; iL++; iR--; }partition, and a uint32 seed. This compiler hands block-local temporaries out from$t7downward. Allocation-priority probe scripts: the historical experiment (prio.sh). - A repeated
andi 0xffon a bool tested twice need not be an inline accessor: GCC reuses the first load when no path between the tests stores the field, which an if / else-if chain whose storing branches return gives you (UpdateBaseActions). - A duplicated statement in both arms that GCC crossjumps after reload costs no code but adds references before allocation, raising that variable's priority; use it when the line table shows the statement in each arm (Findclosestcharactertype).
- A local the debug record keeps in a saved register across a final call means the original assigned it from that call and returned it (
pRef = AddStart(...); return pRef;), with the declaration at the top of the enclosing block (AddBig). - A load that tools/lines.py tags with an earlier test's line belongs to that test's condition:
if (a || b) { if (a) ...; return; }rather than two separate ifs (PlaySpeech). - No pointer locals in the debug record means the original reused a parameter or existing pointer to walk (
for (pChunkFile = pChunkFile->FirstChild(); lCount; lCount--) ... pChunkFile = pChunkFile->Next();); a new local loses the CSE of inline loads (ZAnimTemplatesNames::Init). - Branch direction inside a loop can depend on code before the loop: GCC's loop pass moves a
{ ...; break; }block out of the loop (flipping the branch) only when an unconditional jump survives at function level. A?:leaves one,x = b; if (c) x = a;does not. Sign: the break code sits outside every debug scope of the loop (Toggle 77 -> 0). Earlier notes of the kind "block reached only by a taken branch, cannot be steered" may be this. - An unused saved FP register (
$f21save with no use) is not a compiler artefact to accept: a clamp written as a five-line if/else through pDst/pSrc reproduces it (ModifySpotLight 18 -> 0). Retry drafts parked on that note. - A bool already true then set by
sltu; sltiu 1is an if-convertedif (a < b) flag = false;;flag = a >= b;givesxori 1(ZPS2Video::Init). - Check each referenced data chunk in
check_unit.py. A matching instruction can still reference an incorrect string, float or table. - A "scheduler tie" in a call's argument order can be a statement placed before the call that the original put after the block's last call (pHit = 0 after the restore calls; ZKnifeThrower::FrameUpdate 3,972 bytes, 15 -> 0).
- A value kept in one register into a later block can be an unnamed local the debug record lost (GCC drops debug entries of deleted locals):
uint32 lNrTriangles = (end - start) / 9; ... lNrCorners = lNrTriangles * 3;instead oflNrCorners *= 3(UpdateCamera). If disabling a pass (-fno-gcse,-fno-cse-follow-jumps) makes the draft exact, the original source blocked that pass: look for the statement shape that does. - Direct field copies of one struct are reordered freely (TBAA: distinct fields never alias); a copy through a pointer-taking helper (
v2copy(dst, src)) stays behind earlier float and byte stores (ZWINOBJ::CopyData). - An inlined header loop must use the same form as an already-exact out-of-line copy of that inline elsewhere in the tree; find it with grep before trying variants (
delete m_Entries[i++]in Clear, Exchange). - A loop counter missing from the debug record can still be its own for-init local: reusing a function-level variable assigned elsewhere keeps its
= 0in the guard block (delay-slot difference). The record drops for-init counters (GetClosestComponent). - An exact allocation-priority tie is broken by pseudo number (creation order). Declaring a local at its first assignment instead of at the top gives it a later pseudo number without changing the debug record (CheckCornerCover).
- A local the original keeps in an argument register ($f12, $a1) is usually passed as that argument somewhere: assign it, then pass it (
fSteerAngle = vMovement[1]; mrotaxis(-fSteerAngle, fSteerAngle, ...), TurnWheelsLocal). - A pointer the compiler steps through a loop where the original indexes is GCC's giv rewrite; it is skipped when the loop exceeds the size cutoff in the loop dump (second loop pass decides). An inline the original had (e.g. IsBaseGeomOfType forwarding to IsGeomType) can supply the missing size (UpdateLightListForGeom).
- A compare that lines.py tags with an inline's own header line (zmath.h:679) was written inside that call's expression:
if (ZDot(a, b) < 0.0f) continue;, not a separate fDot statement (WantControl). - A line-table line holding only a field load (maybe a constant) and nothing else is a compiled-out
ZASSERT(field >= 0.0f); the leftover load/constant is reused by later tests (TestGraph). - Read the reference's branch targets before calling anything a scheduling tie: a branch that skips a call means the call sits inside that if-block (MapInside 12 -> 0).
- A header inline whose body differs from IOI's shows as fewer debug block numbers in the original than in our build around each inlined call; reading a member into a local first (
ZBoneModifyBase *pBoneModify = m_pBoneModify;in ZLNKOBJ::GetBoneMatPos) can change the scheduler and allocation downstream (CheckShootableItem). - A field's declared type sets its alias set even when it compiles to the same load:
uint16 g_zoffset(from the debug record) instead of uint8 moved a store into place (ZGeometryDecal::Create). Check every member and global type against the debug record when stores are out of order. - Owner approved (13 Nov): a statement duplicated in both arms of a test is fine when it reproduces the original's allocation and the neighbouring code or line table supports the shape (docs/development/READABILITY.md). ColorFVTOIU and GenQuadruple are on the inline-asm list (tasks/f0319).
- Zero-init stores landing a call too early: a local pointer to a stack object held across that call (
const ZMirrorTransferSetup *pMirrorSetup = &Entry.m_Setup;used later) takes the free scheduling slot; reload deletes it so it costs no code (DrawMirror). Declare flag locals with initialisers in line-table order. - Hand-written vector component lines where the line table shows zmath.h lines (1664-1674 vadd/vsub/v3copy, 1732-1742): use the inlines; their vres parameter adds address references that set allocation (AddSingleDecal). zdmachain.h BeginCntPacket now builds the tag as lId << 28 (main, from): recheck DMA packet drafts.
- A frame address the original recomputes right before each use (
addiu $x, $sp, N) points to a pointer initialised to the array early (_SPath *pCurrentPath = Pathes;), not a hoist; -Os skips loop-invariant motion (TestRooms). - GCC 3.2 keeps a numbered debug block for an if or compound statement whenever a nested scope declares a local. Compare the reference's block numbers with a -g compile of your draft (the historical experiment) to see early returns vs enclosing ifs and fall-through vs else (CanHitmanOperateGenericAction).
- Instructions the scheduler hoisted before a call still carry the debug scope of the statement they came from: a shift placed before SetFrameBuffer but scoped inside the TEX0 AddReg means the source did the shift in that argument (DrawShadowReceivers 4,112 bytes).
- Arguments the line table tags with the .cpp line, not a header, were direct fields (
kStart.m_vPos), not an accessor (Position()) (FindComponentPathAStar 4,040 bytes). A header bit test on its own header line is a named accessor (IsLooping(),HasAutoDelete()), not a shared TestConFlag(n): a reused parameter constant changes later blocks (GetDeletedSounds).a + bvsb + ain float adds is kept by GCC: write the original's operand order. - Repeating a cleanup call at every exit (
RRunRunDelRef + continue at each Add exit) costs no code once crossjumped after reload, but raises that object's allocation priority; one statement per line-table line for the tests (GetAudiable 2,376 bytes). - An early exit whose branch delay slot holds a copy of the final return's first instruction jumps into that return: one shared return, not two. Reload rotates spare registers, so an extra return block can shift a constant into a register a loop clobbers (BlendPalettes). Plain zero stores of uint128 get GCC's own por; an asm por local reorders stores.
- Operand order inside a multiply in a header inline matters (
m_lNumBones * lFrameNumber, Bones() in humanflow.h): swapped operands alone gave a $t4/$t5 swap (CalculateInterpolatedBones). - When a sum's operand order and load order can't both match, split its constant into its natural parts (
21 + ... + 1instead of 0x16): combine folds them and re-sorts the other operands (PrimInstanceCreateScatter). - A frame larger than the original by an unreferenced gap that the debug record does not name is a compiled-out debug buffer of that size (
char szDebugText[0x10];), declared in the block the gap belongs to; at function scope it can land wrong (Strangulate::Update 44 -> 0). - Speculative assignments overwritten in nested ifs vs an else-if chain with one assignment per arm give different allocations; follow the line table. A message send the line table tags with a message header is that header's inline Send... function (SendM02_DrinkAphro, ZHM3LevelControlM02::Command 80 -> 0).
- A call result copied to a saved register before its beqz (instead of testing $v0) means other branches land on that test: the block sits after an enclosing if's closing brace, not inside it (ActivateRagdollOrAnim 61 -> 0). PlaySpeechResourceWithFilter's if (!pSource) residue may be the same with the opposite sign.
- A store the original does once where the debug record scopes its local inside the innermost block: write the store in every arm (GCC merges them); OR terms of a packed index go highest bit first (CreateInitialFlowInstances 94 -> 0; brute-force script the historical experiment).
- The duplicate-statement trick cuts both ways: a statement written in two arms counts twice for allocation even though GCC merges it. If the original has one copy (no separate debug scope per copy, merged line-table lines), write it once after the test and
continue;on the other path (ZOldViewPS2::Draw). - An inline-asm result (ZDot) the original computes before a branch, where your draft computes it after: the source held it in a local assigned before the branch; GCSE and sched1 never move an asm across a branch (ClipAndGetTriangles 57 -> 0). Debug block numbers follow the final scheduled order, so they do not show statement order inside one basic block.
- A
trueconstant held in a saved register for several byte stores across calls is an inline bool setter's parameter (UseColi(true), recovered-types.h names it); write the setter call, not the field store (CanUnpackSniper 68 -> 0). - One call among identical twin call sites whose argument constant (
mtc1 $zero,$f12) comes before the vtable load: the source passed a local set before the enclosing test (V1 fTime = 0.0f; if (...) RemoveAimTarget(fTime, 0);); it also stops GCC crossjumping the whole twin block (ControlWeapon 146 -> 0). - Drafts can carry real logic errors (a condition that sends one case down the wrong branch, a block that ends too late) that look like allocation noise in the score: check behaviour against the reference's branches before tuning (ZOSD::DrawBufferViewUpdate 186 -> 0).
- Reload hands constant-pool addresses out in turn ($t6/$t7), skipping a register still live; one off-by-one there shifts every later constant. A constant computed once at function scope (
const float fMaxTurnAngle = DegToRad(10.0f);) instead of inline at each call changes scheduling enough to fix it. the historical experiment lists reload registers in order (RunGuide 96 -> 0). - zmath.h:628 lines in the line table before a vector's first writes are
vreset(v);calls the draft lacks; adding them fixed a whole-function $fp/$s7 swap (FindLieDownGeom 127 -> 0). Copy loop forms from already-exact siblings (FindSitDownGeom). - A
const boolin the debug record whose test sits on one line-table line is one||/&&initialiser, not an if/else-if assignment chain (MakeLocations 54 -> 0). - Locals the debug record scopes to a block around a loop (
{ int leg; int baseid; for (...) }) let the live-range pass split there and place their init stores after the block's last call; this was StateFit's "scheduling barrier" (269 -> 10). - Look for an exact sibling with the same name in another class first (ZHM3Actor::PlayFootStep matched by copying ZHitman3::PlayFootStep's GetAudioResource wrapper and if-block ending).
- An add.s operand swap together with a register swap on its result can mean the original repeated the expression (
fAttenuation + fPanin each test and use) instead of assigning it; GCC keeps the repeated sum in an unnamed temporary (ZSoundSpline::FrameUpdate 174 -> 0). - A register "preference" (
;; N preferences: Rin the .greg dump) can be the residue rather than a priority tie: a loop shapedfor (;;) { ... else break; }makes the live-range pass skip it, and a copy's preference then spreads to other loops. Use the loop form the line table and scopes show (while (cond) { if ... else ... }; CCutSequenceList::FrameUpdate 117 -> 0). - Operand order of a mult inside a header inline (ZFlowBytePlane::Get:
SizeX() * ly + lx) decides the whole address chain's registers; check header inlines' operand order against the reference's mult (UpdateBoneArrayInstance 77 -> 0). - Line-table loop shape: one line tagged on both the init and the test is a
for; two tags on one test, or a removed line number on a later block (:2048 :2055), mean a duplicate test the compiler merged (if (foundOne) break;inside, thenif (foundOne) {...} else {...}after). A do-while that compiles the same can still shift live ranges (FindPath 41 -> 0). - A
neg.stagged with the function's own line beside inlined helper code is a separatex = -x;statement, not part of the inline (ZHumanState::Mirror 81 -> 0). - An empty line inside a header inline's line range is room for a two-line if/else:
if (b) m_Inside = 1; else m_Inside = 0;in ZLocation::Set splits the block so CSE keeps a later store going through the pointer (MoveNodeConstrained 57 -> 0). - A variable listed again in the debug record with
[only ...]ranges over a loop is a live-range copy of itself: the original stepped it inside the loop (pPlanes += 4;), not indexed it (CalcTransferMatrixAndClipPlanes 230 -> 0). - A non-null case that branches to an out-of-line block jumping back into the null path's tests is jump threading between consecutive early exits: write one
if (...) continue;per line-table line, not one combined condition (MapUBHoldAnimsToIdx 146 -> 0). uint64in the original isunsigned long(mangled m): a global typed that way shares Add64's alias set and keeps packet stores in order (UpdateLight).- TIMETYPE compares the line table tags with timetype.h:19 (the float constructor) take
0.0f, not0(line 32 is the int constructor); the float constant then stays in a register and shifts reload's scratch choices across the function (ClassFrameUpdate 225 -> 4). - Two uint32 fields share an alias set, so a read of one before a store to the other fixes the order; read it into a local at the top if the original does (Animation::Model::Init 178 -> 0).
- Each mula/madda/madd dot product in the original is ZDot even when its operands are already in registers; a plain C sum allocates differently (FlushLightBuffer 201 -> 140).
- A clamp written
if (r > c) r = c;vsr = r < c ? r : c;both give min.s, but the if form leaves a label that stops CSE extending, dropping a copy and shifting every later reload register; try the ternary when a whole loop's $t5/$t6/$t7 are off by one (StraightenGates 109 -> 0). - New intrinsics ZMinTo/ZMaxTo (minmax.h): one min.s/max.s whose output is an lvalue (array element). Sign: one unnamed stack temporary per element and stores GCC would otherwise drop around a box expansion (CRigidBody::Move). Real logic errors (a wrong source vector in v3copy) can masquerade as 30 register-tie marks.
- A loop condition with a comma expression (
while (skip(), isalpha(*p))) is entered by a jump from outside, which makes the live-range pass reject the loop; writefor (skip(); isalpha(*p); skip())(SimpleXML::getElement 170 -> 0). - A loop left last in the function by an early return gets split by the live-range pass (a copy of this before it); writing the early exit as an else arm after the loop makes the pass reject it as the original did (ActiveAnimation::LoadSave 78 -> 0).
- A function tail the line table gives one statement per line is a single
return a && b && !c;expression per line, not a chain ofif (...) return false;blocks; the shared return-false block's placement follows from that (IsAimingAtTarget 197 -> 0). - TIMETYPE::secs is an int, so a frame-time read after uint32 stores must wait for them; that can raise unrelated multiplies' scheduling priority. If the original reads the time early, hold it in a
const float fFrameTime = g_pSysInterface->FrameTime;local (AddParticlesHeader 395 -> 0). - An if / else-if / else chain that assigns a selector (
lModel = 2 / 1 / 0) instead of a nested or speculative form changes which loads GCC hoists out of a loop; a chain endingelse if (x == 0)lets other values skip to the shared tail (ZPoseModel::GetWeight 297 -> 0). Real behaviour bugs (a missing divide on one exit) show up here too. - A whole-function register shift by one ($t5 where the original has $t4 everywhere) usually comes from one statement shape that changes reload's spill set; find the first block where it starts (CreatePrettyLightsBuffer 249 -> 142 from one loop-2 statement).
- GCC 3.2 unrolls away an innermost loop that runs once; a surviving one-pass loop (
for (int p = 0; p < 1; p++)) held an inner one-pass loop. An extra register copy of an outer counter used for one address is the leftover of an inner index sum (p + s) (ZSysInputPS2 ctor 134 -> 0). c.lt.s; bc1flaround a final assignment isif (x < c) continue; target = p;, notif (x >= c) target = p;. Two early returns that share an epilogue placed right after the second test are oneif (!p || !IsType(p)) return false;(CanHitmanStrangleInElevator 206 -> 0).- A single guarded store (
if (Count() > 0) a[0].x = ...) may be the original's loop that breaks on its first pass (an IOI bug kept as is); the loop keeps a later reload of this into $a0 (CFormationController::Command 47 -> 0). - A
%hi(global)reload mid-condition means the original split one || chain into two ifs with the same early-return body (GCC merges the bodies) (DemoGameplayCallback). - Unused lines at the top of a switch in the line table can hold a
default:block with the same body as a later case; GCC merges them after reload, but reload's $t5/$t6/$t7 rotation follows the pre-merge order, so every case's registers shift (MusicCallBackEvent03). - A switch case that leaves by
breakto one sharedreturn X;after the switch, instead of returning in the case, keeps the return register unset until the end; write out empty trailing cases that set the switch bound (MusicCallBackLocation01 298 -> 0). - Child-node walks in octree code:
if (pChild) { int bLast; do { ...; bLast = pChild->IsLast(); pChild++; } while (!bLast); }controls whether the live-range pass splits the loop, as the original (RemapObjects/GetObjects/CheckPoint).!(id & 1) ? x - h : x + hgives xori/andi/movz. - A component missing from a vector op (no x subtract) can be a vsub/vadd against a vset vector whose component is 0.0f, folded away under unsafe-math: write the inline calls, not per-component maths (ZHM3LevelControlM05::Animate).
- Block reordering in this compiler follows fallthrough order only (the live-range pass strips branch-probability notes). Epilogue placement right after an entry branch comes from declaring the locals inside that if-block; a debug block covering only the epilogue comes from the scope that was last in the source (ZENVIRONMENT::ClassInit 104 -> 0).
- A branch back to an outer loop that the line table gives its own line is a
break;out of an innerwhile (RRun._RunPtr) { ...; break; }, not an if (ZROOM::FreeDynamicGeomList). - A parameter kept in its argument register with a copy at loop entry means the source indexed it (
for (int i = 0; s[i] != 0 && ...;) f(s[i++]);) rather than stepping it; the record drops the for-init counter. The live-range pass never splits a loop with a break or ana && btest at the bottom (zstring::CStrToUTF8). - A file-local helper the debug signature marks static must be static: GCC 3.2 then treats calls to it as const and CSE reuses a load across the call (CopyArgs).
- A TIMETYPE local whose stores carry the copy-constructor line (not operator=) is declared with its value (
TIMETYPE t = FrameTime - start + x;), not default-constructed then assigned (ZParamAnim::FrameUpdate). - A header line tagging several call sites is an accessor (checkvisible.h:451 = ZCheckVisible::Instance()); calling through it can break a local-alloc qty_compare tie (ZHM3ActorStrangleInElevator::Execute).
- Closing statements the line table shows only once can still be written in each continuing path; GCC merges the copies into one tail, but before that the extra block contents change call-argument scheduling ($t0 before $a2/$a3 at RegisterZMsg sites; ZHM3Boid::FollowWaypoints).
- Under unsafe-math even
640.0f / 640.0ffolds to the float just below 1.0f; constants one ULP below round values mean a division in the source (ZTTFONT::SetDataHandle:512.0f / 640.0f : 640.0f / 640.0f). - Store-order residue can be the wrong struct type over the same bytes: alias sets come from declared types, so use the struct recovered-types.h names for that memory (SMallocBlockHeader vs SMallocHeader; ZMalloc::AddBlock).
- GCC never fills an unannulled delay slot with a load that can fault, from either side; a
bnezwith anlwin its slot means the load sat before the branch in the source (CEVENTCONTROLLER::GetNextActor). GCC 3.2's inliner substitutes a constant argument only for aconstparameter: an inline whose branch on a parameter should fold needsconst(ZRTStringHeader ctor). - A field the debug record types
const T *constmust be const and set in the initialiser list; that changes store order (ZMessageResolver ctor). - A product used twice that the debug record gives no local is written twice (
uNumBones * 3); GCC shares it as the original does (AddMoreBones 177 -> 0). - An
xori r,r,0next to sltiu/movz/movn means the if was converted to set-on-condition in the late ce pass: one branch held a dead store (compiled-out leftover) or two insns combine merges (SF_CheckTimeout). the historical experiment has a batch harness that compiles many variants in one file. - Header inlines that wrap a library call (a SplineLen3 around sqrt) may be the library inline itself in the original: zmath.h:238-239 lines are ZSqrt, so call ZSqrt directly (ParametricCurve::ToSplineTimeFrom 180 -> 0). Check return values on edge paths for logic errors (returned ts instead of 1.0f).
- Two cases that share one failure body (
case NONE: default:) instead ofa != 0 && a == Kkeep both compares; writing a store in both arms of a test stops movn conversion; a switch without default where the original has none (ZCDRecover 246 -> 0). A branch can carry the line of its delay-slot instruction: use the compare constant to place the test. - OR-ing bits into a uint16 local delays conditional-move creation until after combine, which keeps the original's
xori t,t,0(ZHFlow state ScheduledUpdates). A loop-invariant constant load hoisted in the original means a local (float fObstacleMargin = 30.0f;): -Os never hoists. - A return inside a loop body makes the live-range pass skip that loop; if
-fno-live-rangemakes every register match, look for the original's in-loop return (GetSaveDir 184 -> 0).if (New) {...} return x;vsif (!New) return x;changes which register holds the return and the prologue order. - How a loop's tests are split between the while condition and break tests in the body decides the copied exit test and crossjump that put the loop body after the epilogue (ZELEVATORBOUND::CalcCenSize 211 -> 0).
- An inlined helper whose debug record keeps only some parameters had literals for the others (
vset(p, 0.0f, 0.0f, 0.0f)); passing a variable leaves a copy the compiler reuses elsewhere (ZHitman3::OnProjectileHit 117 -> 0). - GCC 3.2 keeps an inline's line on everything after it in the same argument: if an op on the inline's result is tagged with the outer call's line in the original but with the inline's line in your -g build, the original called the inline in an earlier statement (
const uint32 lFogAdd = FloatAsBits(...);; PrimInstanceCreate 128 -> 0; the historical experiment). - If a near-miss draft is exact with
-f=-fno-sched-interblock, the original exceeded the interblock limits (more than 10 blocks or ~100 insns): look for a missing branch, e.g. a second identical call in a nested if/else that GCC merges later (ZMardiGrassHFlow::CalculateNewState 160 -> 0). - After a call, once 33 memory refs are pending GCC's scheduler makes the next store depend on all of them: constructor store order follows the exact source store sequence (brute-force script the historical experiment ZPostFilterAnimEvent ctor). A branch that needs its own
return x;at the line table's line keeps a ternary result in $v0 (PostLoad). - A register difference can be caused by a statement many lines earlier: register preferences propagate through copy and OR chains, so find the first earlier insn writing the original's register (the historical experiment shim forces preferences to test a hypothesis; UploadTexture's TEX0 fixed via the BITBLTBUF word 25 lines earlier).
- A const pointer local (
const ZFlow32Plane *p = ...) keeps a separate copy that changes how copy propagation rewrites later reads, so GCSE stops treating two reads as one; GCC then deletes the local and its debug entry, which is why the record lacks it (CollectAllVisibleLinks: draft exact only with -fno-gcse before). - Hand-written DMA packets (
BeginPacket(); Add32(DMA_TAG_CNT); Add32(0); Add64(...)) where the debug record shows the packet API's inline scopes (lTransferDMATag/lId, lReg/lValue) must use BeginCntPacket/AddReg/EndPacket: same instructions, but the tag id lives in a pseudo and changes sched1's free slots (DrawNormalMapped 14 -> 0). - Taking the address of any local (a
const T &x = Get();reference) blocks every tail call in the function in this GCC, and the local can still end up in a register: use it when the original makes no tail calls where you expect them (ZLNKOBJ::ClassInit). Early-returnif (m && m != this) { Base::F(); return; }instead of nested!m || m == thiskeeps two loads of m. - Plain field loads at the start of an IOI asm block into the registers GCC hands out first ($t7/$t6, $f0-$f2) are compiler-loaded asm input operands, not loads inside the asm; operand order matters (ZCloth::DrawIt 5 -> 0; the historical experiment dumps allocno preferences).
- Top-level const parameters on an inline helper (
const float *const pM) change GCC 3.2's argument substitution and so the evaluation order of address computations; zmath.h ZMatrixTransformMul now has them (ZHFlow::UpdateBones). One function-level loop counter shared by two loops can let sched1 move the second loop's init above a call (CalcProjectedFloat). - Owner decisions 14 Nov:
ZTRACE(...)(engine/system/zassert.h) is IOI's compiled-out debug output, an emptywhile (0) { }whose deleted loop leaves loop notes that block sched1 and the live-range pass. Use it only where the line table shows code-less source lines at that spot and the barrier measurably helps (SetSubBoxes, CalcBonesFromMotion, UpdateLight leads). Accepted shapes: a folded if/else on a just-stored value with a deadZDebugBreak()arm (ZActor::Initialize); reconstructed leftover loops the line table shows (PrimInstanceCreateWaterPatch). - If turning off
-fexpensive-optimizationsmakes a draft exact, a literal call argument was a variable in the original (float fWindScale = 0.25f;declared with nearby locals, not const); GCC copies literals into a temporary (ZCloth::ApplyWind). - A literal 64-bit packet term that reaches bit 31 (
static_cast<uint64>(2048 << 4) << 16) becomes a sign-extended constant in GCC 3.2 and sets the top 32 bits: build it with ZDMAChain::RegisterField(value, shift) (SetupMaterial). - A loop test on a sentinel local (
int32 iLockedBuffer = -1; while (iLockedBuffer < 0) {... break; }) gives GCSE an exit path that keeps a copy alive, then gets deleted as always-true: no code left (nativeReadOL 21 -> 0; draft was exact with -fno-gcse). - One condition the line table spreads over two lines is a nested if, not a multi-line && (a multi-line statement takes only its first line); both else arms may then repeat the same code, which GCC merges after allocation but which lowers another value's priority first (ControlUseOneAlone 35 -> 0).
- Several locals starting at the same constant are CSE copies of one value; which is zeroed first decides which stays the loop guard's register (
uint32 iFlags = 0; if (...) iFlags = 0x40;vs starting at 0x40; GetDeadBodyFlags). A bool local tested in an if loses the original'sandi 0xff: test the expression directly (PlaySpeechResourceWithFilter). - Switch cases with identical bodies the line table lists separately (one body line per case) are separate case blocks GCC merges late; the extra block lengthens live ranges before allocation (UpdateWeaponInfo). Split only the ones the line table shows.
- A struct copy the original does as a uint128 + uint64 + uint32 sequence comes from typed copies (mmi.h uint128) in that order (BlendQuats). A pointer stepped by hand on two paths (
p++; continue;andp++;at the body end) instead of in the for increment gives it two more references before allocation; GCC merges them later (SetSubBoxes 51 -> 0 without ZTRACE). A line tag at a loop head can be a merged-awaycontinue's line, not a compiled-out loop. - GCC records a register preference for an OR's result from its first operand only: grouping
a | (b | c)vs(a | b) | cdecides which register a packet word gets and can shift a whole loop's registers by one (TextureSwitchInDot3Pass 90 -> 0). - A small int set once to a constant and passed to many calls, with
lirematerialised before each use and absent from the debug record, is a named local (int iStand = 0; int iWalk = 1;): GCC spills it as a constant equivalence. ZHM3ActorMovesets::Initialize 593 -> 54; the scheduler also reverses the last pair of a run of same-shape calls, so write them in ascending order. - A dead
x = cond ? a : b;on a code-less line, overwritten later and deleted by flow before sched1, ends both CSE passes at its join label without blocking scheduling; ZTRACE ends only the first CSE pass and also blocks sched1. Use only on a code-less line between the store and the reload (ZTextCredits::Update 142 -> 0; accepted for ZTextCredits::Update). - A threshold the debug record names as a local (
fPrcMinForMovement) is a non-const local initialised to the literal; a plain literal lets its load hoist next to an earlier call (IsMoveBlocked 14 -> 0). An earlyif (!x) return false;can be an enclosingif (x) { ...; return false; } return false;(WantControl 16 -> 0, found by mutate.py). - One local reused for two meanings in a header inline (scale it, then reassign) shares one pseudo across both paths; give each path its own local when the original keeps them in different registers (ZPackedData::GetDataAtIndex, _RecalculateCheckSum 30 -> 0).
- A max stored to a member and then reloaded is
m = a; if (b > m) m = b;with conditional stores to the member, not?:: the if is converted only after combine, past the cse pass that would drop the reload (InitZoomPanLimits 37 -> 0). - A field read through a const pointer is reloaded in each arm of a later ternary; through a non-const pointer it is loaded once before the branch and passes its register preference to the ternary temporary (CalcBoneLightSources 14 -> 0 with a non-const pLight). Check the pointer constness before trying address-taking or slot tricks.
- A local assigned in two blocks becomes a global-alloc pseudo with its own register; reusing an earlier local for a later value (
len = vlen(v);) reproduces amov.s $f6,$f0copy that a fresh local loses (LnSphColl 25 -> 0). - A block of code-less lines before a call can be the first arm of an if/else whose arms make the same call: GCC merges them after allocation, but until then the test splits blocks, stops sched1 hoisting zero-inits above the calls, and makes the result variable live across blocks (CalcBonesFromMotion 207 -> 0). ZTRACE also blocks sched2 and made it worse.
- When two partial fixes each score worse or equal alone, try them together: line-table declaration order plus a direct member read (no getter when the line has no header tag) moved both stores before the load in sched1 and fixed the $t6/$t7 reload parity (ZHM3ObjectivesBrief::Setup 36 -> 0).
- A line tagged twice around an untagged instruction (lwc1 on line N, then an earlier-line op, then c.lt.s on line N) means a load from a later statement was scheduled into the gap and taken by the delay-slot filler: move that statement above the early return (WaitForOtherActor 39 -> 0; the historical experiment finds the pattern).
- Compare the draft's -g block numbering with the original's $LBB numbers to find chained calls that were a named local (
ZHM3CameraBase *pCamera = ...; pCamera->GetYaw()) and ZAbs of an expression that was stored first and then abs-ed in place (UpdateViewPosition 26 -> 0; the historical experiment). - Before calling a $sN swap a priority tie, check the line table for a header tag on the member loads: an inline accessor (
GetControllers().Clear()for zsndobj.h:283) changed both the loads and the allocation (CopyControllersFrom 30 -> 0). - A local missing from the debug record whose load and use are on separate lines can be an address-taken local (
*reinterpret_cast<uint32 *>(&f)): GCC 3.2 drops ADDRESSOF homes from stabs. An inline call on the right of*p++ = ...costs a copy of p (CreatePrettyLightsBuffer 142 -> 0; the historical experiment lists emitted locals). - Base REF2Ptr is
if (ref-- == 0) return 0;then REF2IndexInBlock/REF2ID on the zero-based value (fixed_size_memory_manager.h): FreeRef, ConvEventRefToPtr and GeomRefToBasePtr exact. A header inline that decrements inside the test explains a CSE-deleted null test. - After an early
if (!x) return;, jump1 simplifies a branch-over-branch and deletes the deadret = thiscopies of an inlined TIMETYPE::operator=, so cse merges the g_pSysInterface reloads; an enclosingif (x) { ... }keeps them (SetupBloodTrail 24 -> 0). Try the enclosing form whenever a TIMETYPE reload is missing. - Before deep allocation work on a draft, check its logic against the line table: GetSndVolume (109 -> 0) had a statement outside the if it belonged to. A loop that restarts the search is tail recursion (
return GetPlayableSound(iIndex, 0);). - A loop with a run of code-less lines and unwanted live-range copies of saved registers around it: one ZTRACE on those lines makes the range pass skip the loop (ZHumanBoid::Collision 130 -> 0, lines 851-916).
- A definition written void whose debug signature returns a value changes callers: the call no longer sets $v0, which shifts sched2 ties (ZPS2Setup::EnableFieldAliasing is bool with no return statement; ZRenderPS2::Init 21 -> 0). the historical experiment lists such definitions; ZCDASClose in cdread.cpp is the other one.
- A loop GCC reverses still keeps its source direction in the preheader: if the pointer increment carries the for line (not the index statement), the source counted up and indexed from the counter (
for (leg = 0, baseid = 0; leg < 2; leg++),m_Quats[4 + leg]); StateFit 10 -> 0. - A walker init that survives allocation (
move $s2,$sptagged with the for line) means the loop indexed through a pointer local (const float *pCorners2D = Corners2D;then&pCorners2D[a]); direct array indexing folds the init away (CalcCameraExit 67 -> 0). - A do/while(0) with a bValid flag and breaks leaves an extra
$v0 = 0; plainreturn false;exits with the shared final test written at the end of both arms (GCC merges them) give the original (IsLocalGuidePosValid 22 -> 0). - A wrapper inline the debug record does not list on the class is invented; call the real target directly with the accessors the line table tags (ZGUIList::Setup 197 -> 10).
if (*psz)andif (psz[0])compile differently. - A local built in two steps (also MixPalettes 15 -> 0 by scaling each stage value in place before the blend; FormatText 11 -> 0 with
int32 lMaxWidth = iWidth; lMaxWidth *= fScale;) (uint32 lId2 = (uint32)p; lId2 |= lListType;) keeps a plain copy until combine, which adds references to the pseudo in the first life pass and raises its allocation priority; a way to break a near priority tie without changing code (RemoveBaseGeoms 19 -> 0). - One of two similar pointers reloaded while the other is merged: the reloaded one is address-taken in the original (a const reference to it,
T *const &pSecond = p2;), so GCSE treats its reads as different expressions (SetDualFrame 54 -> 0). - In one long basic block of calls, sched1 hoists constant loads into call gaps by priority; each named constant local adds an invisible hoist ahead of a literal. Switching some arguments between named locals and literals reorders that queue (Initialize 54 -> 0).
- A
bwhose delay slot holds a copy of its target's first insn (and jumps to target+4) right after a min.s/max.s/abs.s means that op is IOI asm (ZMinTo/ZMaxTo/ZAbs): reorg never moves asm into a slot (CollideCapsuleAndTriangle 34 -> 0; scan script in the historical experiment). - Slot order and block order that disagree in a switch: the dispatch may be nested ifs (
if (t == A || t == B) { if (t == A) {...} else {...} } else {...}); jump threading sends the t == B path straight to its arm (FlushLightBuffer 78 -> 0). - Identical case bodies in a header inline (one return per case, merged after reload) add pre-reload insns where only some values are live and lower their allocation priority (CHUNKFILE::GetFileLen; AllocSequence 17 -> 0 plus 4 destructors). Extra inline nesting adds block notes but no insns, so it does not change priorities.
- Two-statement trick limit: it only raises a value that is a register copy or a multiply combine can fold; a float loaded from memory gains no references (ProgressHandler stays 7).
- A flag word written
x = C; if (!cond) x = 0;vsx = 0; if (cond) x |= C;: in the OR form update_equiv_regs moves the constant down to its use, which shifts other copies one insn earlier in local-alloc numbering and flips a qty tie (CalcStripChainStartValues 8 -> 0). Write flag words the way the rest of the function does. - TOOL: the historical experiment is an LD_PRELOAD qsort shim that reads or edits sched1 priority and register weight per insn or forces one insn above another; use it to check in minutes whether one scheduling decision is the whole residue (ApplyCurvesFilter: one tie = 310 points).
- TOOL: the historical experiment simulates local-alloc register filling ($t7 down to $v0, a value shares the register of a source operand that dies in the same insn) from the dump2.so priority list; check a guessed priority or lifetime change before writing source. Add64 stores can move past uint32 global accesses in sched1, Add32 stores cannot.
- An array index that loop.c must not strength-reduce at -Os is written with a count recomputed inside the loop (
m_Data[iFirst + i + (iLast - iFirst)]); a later CSE folds it back toi + iLast(vectorS::erase, _RemoveEvents 85 -> 0). - TOOL: the historical experiment forces sched1 decisions by matching insns on RTL content rather than uid, so a forcing survives mutate.py/permute.py source changes; use it to search for the source of one decision while forcing another.
- Asm min shortens sched1 chains: an asm insn has cost 1 and every dependence into it is free, so IOI asm ZMinTo/ZMaxTo can reorder a whole block; four epsilon clamps as ZMinTo made AddPrimToDMAChain 313 -> 0. the historical experiment forces a full sched1 order per source from an .ord file.
- Locals the debug record cannot show: an unallocated local has no stab and a scope whose only insn was deleted leaves no block, so code-less lines between asserts can hold locals that move set insns into another block and free issue slots (ApplyCurvesFilter 310 -> 0 with pFrameIncreaseRef/pTexIncreaseRef locals). Check 64-bit constant halves against the original pool.
- A cut-down copy of an exact sibling keeps the sibling's expressions over a local flag that is always true (
bool bGotPalette = true;then the sibling's ternaries): the nested ternary on a local constant leaves no code but ends a CSE1 path (DrawFrontSprite 305 -> 0, copy of AddGifChainTexture). const bool is folded by the front end and does not work.