From 57c8dcf76f7baefe88790d34733b0584f9565222 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Mon, 16 Nov 2026 15:45:29 -0800 Subject: [PATCH 01/14] Linearize blocks on a per-funclet basis. The block order is set in SetBlockSequence using the WasmDfs produced dfs tree to perform a loop-aware RPO traversal. Blocks are partitioned per funclet during the traversal, resulting in relative LaRPO for each funclet. --- src/coreclr/jit/regallocwasm.cpp | 127 +++++++++++++++++++++++++++++++ src/coreclr/jit/regallocwasm.h | 20 +++++ 2 files changed, 147 insertions(+) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index f8e8f516557732..9a7d45d0f5a0a4 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -9,6 +9,7 @@ #include "regallocwasm.h" #include "lower.h" // for LowerRange() +#include "fgwasm.h" RegAllocInterface* GetRegisterAllocator(Compiler* compiler) { @@ -33,6 +34,7 @@ PhaseStatus WasmRegAlloc::doRegisterAllocation() IdentifyCandidates(); CollectReferences(); + BuildIntervals(); ResolveReferences(); PublishAllocationResults(); @@ -1009,6 +1011,131 @@ regNumber WasmRegAlloc::RequestInternalRegister(GenTree* node, var_types type) return reg; } +//------------------------------------------------------------------------ +// SetBlockSequence: set the block sequence partitioned by funclet. +// +// The result will be stored in each funclet's m_blockOrder. Each funclet's block order +// follows a (relative) loop-aware reverse postorder. +// +void WasmRegAlloc::SetBlockSequence() +{ + FgWasm fgWasm(m_compiler); + + bool hasBlocksOnlyReachableViaEH; + FlowGraphDfsTree* dfsTree = fgWasm.WasmDfs(hasBlocksOnlyReachableViaEH); + assert(!hasBlocksOnlyReachableViaEH); // fgWasmEHFlow should have handled blocks only reachable via EH + + BitVecTraits visitedTraits(m_compiler->fgBBNumMax + 1, m_compiler); + BitVec visited = BitVecOps::MakeEmpty(&visitedTraits); + auto visitBlock = [&](BasicBlock* block) { + if (BitVecOps::IsMember(&visitedTraits, visited, block->bbNum)) + { + return; + } + + int funcletIdx = m_compiler->bbFuncletRegionOf(block); + PerFuncletData* const funcletData = m_perFuncletData[funcletIdx]; + funcletData->m_blockOrder.push_back(block); + + BitVecOps::AddElemD(&visitedTraits, visited, block->bbNum); + }; + + FlowGraphNaturalLoops* loops = FlowGraphNaturalLoops::Find(dfsTree); + m_compiler->fgVisitBlocksInLoopAwareRPO(dfsTree, loops, visitBlock); + + // Ensure we visit any blocks not reached by the loop-aware RPO traversal. + for (BasicBlock* block : m_compiler->Blocks()) + { + visitBlock(block); + } + + JITDUMP("Block order:\n"); + for (const FuncInfoDsc* const funcInfo : m_compiler->Funcs()) + { + JITDUMP("Funclet %u:\n", funcInfo->GetFuncletIdx(m_compiler)); + unsigned count = 0; + for (BasicBlock* block : funcInfo->Blocks(m_compiler)) + { + count++; + } + const auto& blockOrder = m_perFuncletData[funcInfo->GetFuncletIdx(m_compiler)]->m_blockOrder; + assert(count == blockOrder.size()); + + BitVecTraits traits(m_compiler->fgBBNumMax + 1, m_compiler); + BitVec funcBlocks = BitVecOps::MakeEmpty(&traits); + for (BasicBlock* block : funcInfo->Blocks(m_compiler)) + { + BitVecOps::AddElemD(&traits, funcBlocks, block->bbNum); + } + + for (unsigned i = 0; i < count; i++) + { + assert(BitVecOps::IsMember(&traits, funcBlocks, blockOrder[i]->bbNum)); + JITDUMP(" BB%02u\n", blockOrder[i]->bbNum); + } + } +} + +void WasmRegAlloc::BuildIntervals() +{ + SetBlockSequence(); + for (FuncInfoDsc* const funcInfo : m_compiler->Funcs()) + { + m_currentFunclet = funcInfo->GetFuncletIdx(m_compiler); + PerFuncletData* const funcletData = m_perFuncletData[m_currentFunclet]; + assert(m_compiler->lvaTrackedCount == funcletData->m_intervals.size()); + BuildFuncIntervals(funcInfo, funcletData); + } +} + +void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData) +{ + struct PendingLclUse + { + GenTree* UseNode; + unsigned int trackedLcl; + }; + + auto isIntervalCandidate = [&](LclVarDsc* varDsc) { + if (varDsc->lvIsRegCandidate()) + { + // Don't permit params or SP/FP locals to be tracked interval candidates; + regNumber reg = varDsc->GetRegNum(); + assert(genIsValidReg(reg)); + return !varDsc->lvIsParam && reg != funcletData->m_fpReg && reg != funcletData->m_spReg; + } + return false; + }; + + for (unsigned i = 0; i < m_compiler->lvaTrackedCount; i++) + { + LclVarDsc* varDsc = m_compiler->lvaGetDescByTrackedIndex(i); + + Interval* interval = nullptr; + if (isIntervalCandidate(varDsc)) + { + regNumber virtReg = varDsc->GetRegNum(); + interval = new (m_compiler->getAllocator(CMK_LSRA)) Interval(); + interval->start = INT_MAX; + interval->end = INT_MIN; + interval->virtReg = virtReg; + } + funcletData->m_intervals[i] = interval; + } + + unsigned pos = 0; + for (BasicBlock* const block : funcletData->m_blockOrder) + { + JITDUMP("Processing block [%06u]\n", block->bbNum); + for (GenTree* tree : LIR::AsRange(block)) + { + JITDUMP("%d: ", pos); + DISPNODE(tree); + pos++; + } + } +} + //------------------------------------------------------------------------ // ResolveReferences: Translate virtual registers to physical ones (WASM locals). // diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index 07863cc2fccadd..411fc8c8641e4d 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -73,6 +73,14 @@ struct VirtualRegReferences VirtualRegReferences* Prev = nullptr; }; +struct Interval +{ + int start; + int end; + regNumber virtReg; + WasmValueType type; +}; + class WasmRegAlloc : public RegAllocInterface { Compiler* m_compiler; @@ -93,6 +101,8 @@ class WasmRegAlloc : public RegAllocInterface , m_lastVirtualRegRefsCount(0) , m_virtualRegRefs(nullptr) , m_physicalRegAssignments(comp->lvaTrackedCount, REG_STK, comp->getAllocator(CMK_LSRA)) + , m_intervals(comp->lvaTrackedCount, nullptr, comp->getAllocator(CMK_LSRA)) + , m_blockOrder(comp->getAllocator(CMK_LSRA)) { } @@ -114,6 +124,12 @@ class WasmRegAlloc : public RegAllocInterface // Map from local tracked index to phys reg for that local, in this funclet. // jitstd::vector m_physicalRegAssignments; + + // Map from local tracked index to live interval for this local, in this funclet + jitstd::vector m_intervals; + + // Block iteration order for this funclet (initialized later) + jitstd::vector m_blockOrder; }; jitstd::vector m_perFuncletData; @@ -167,6 +183,10 @@ class WasmRegAlloc : public RegAllocInterface regNumber RequestInternalRegister(GenTree* node, var_types type); void ConsumeTemporaryRegForOperand(GenTree* operand DEBUGARG(const char* reason)); + void SetBlockSequence(); + void BuildIntervals(); + void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); + void ResolveReferences(); void PublishAllocationResults(); From b62f9c791977cfdc5c8d841013af66a08e6b7fe6 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Tue, 17 Nov 2026 17:32:01 -0800 Subject: [PATCH 02/14] WIP build live local intervals in wasm regalloc --- src/coreclr/jit/regallocwasm.cpp | 155 ++++++++++++++++++++++++++++++- src/coreclr/jit/regallocwasm.h | 1 + 2 files changed, 153 insertions(+), 3 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index 9a7d45d0f5a0a4..e5561ffadaef02 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1086,13 +1086,30 @@ void WasmRegAlloc::BuildIntervals() assert(m_compiler->lvaTrackedCount == funcletData->m_intervals.size()); BuildFuncIntervals(funcInfo, funcletData); } + + DumpIntervals(); +} + +GenTree* getNonContainedUser(GenTree* node, LIR::Range& blockRange) +{ + GenTree* useNode = node; + LIR::Use treeUse; + bool foundUse; + do + { + foundUse = blockRange.TryGetUse(useNode, &treeUse); + useNode = treeUse.User(); + assert(foundUse); + } while (useNode->isContained()); + + return useNode; } void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData) { struct PendingLclUse { - GenTree* UseNode; + GenTree* UserNode; unsigned int trackedLcl; }; @@ -1123,19 +1140,151 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun funcletData->m_intervals[i] = interval; } + auto updateIntervalStart = [&](unsigned trackedIdx, unsigned pos) { + Interval* interval = funcletData->m_intervals[trackedIdx]; + if (interval != nullptr) + { + int prev = interval->start; + interval->start = min(interval->start, static_cast(pos)); + if (interval->start != prev) + { + JITDUMP("V%02u start: %d -> %d\n", m_compiler->lvaTrackedIndexToLclNum(trackedIdx), prev, interval->start); + } + } + }; + + auto updateIntervalEnd = [&](unsigned trackedIdx, unsigned pos) { + Interval* interval = funcletData->m_intervals[trackedIdx]; + if (interval != nullptr) + { + int prev = interval->end; + interval->end = max(interval->end, static_cast(pos)); + if (interval->end != prev) + { + JITDUMP("V%02u end: %d -> %d\n", m_compiler->lvaTrackedIndexToLclNum(trackedIdx), prev, interval->end); + } + } + }; + + auto updateIntervalStarts = [&](VARSET_TP toUpdate, unsigned pos) { + VarSetOps::Iter iter(m_compiler, toUpdate); + unsigned trackedIdx; + while (iter.NextElem(&trackedIdx)) + { + updateIntervalStart(trackedIdx, pos); + } + }; + + auto updateIntervalEnds = [&](VARSET_TP toUpdate, unsigned pos) { + VarSetOps::Iter iter(m_compiler, toUpdate); + unsigned trackedIdx; + while (iter.NextElem(&trackedIdx)) + { + updateIntervalEnd(trackedIdx, pos); + } + }; + + JITDUMP("----------------------------------------\n"); + JITDUMP("Building intervals for funclet %u\n", m_currentFunclet); + JITDUMP("----------------------------------------\n"); + ArrayStack pendingMultipleUse(m_compiler->getAllocator(CMK_LSRA)); + unsigned pos = 0; for (BasicBlock* const block : funcletData->m_blockOrder) { - JITDUMP("Processing block [%06u]\n", block->bbNum); + m_currentBlock = block; + + JITDUMPEXEC(block->dspBlockHeader()); + JITDUMP("liveIn="); + dumpConvertedVarSet(m_compiler, block->bbLiveIn); + JITDUMP("\n"); + + // Potentially update the start points of any intervals live at block entry. + updateIntervalStarts(block->bbLiveIn, pos); + for (GenTree* tree : LIR::AsRange(block)) { - JITDUMP("%d: ", pos); + JITDUMP("%10u: ", pos); DISPNODE(tree); + // Check for and consume any multiple-use local reads used by this node; + // if a read of a reg candidate is MultiplyUsed its underlying local lifetime must extend through the node + // that consumes it, since it won't get a separate temp. + while (!pendingMultipleUse.Empty() && tree == pendingMultipleUse.TopRef().UserNode) + { + + if (tree->isContained()) + { + JITDUMP("TREE IS CONTAINED\n"); + } + PendingLclUse pendingUse = pendingMultipleUse.Pop(); + updateIntervalEnd(pendingUse.trackedLcl, pos); + } + + if (tree->OperIsLocal()) + { + GenTreeLclVarCommon* lcl = tree->AsLclVarCommon(); + LclVarDsc* dsc = m_compiler->lvaGetDesc(lcl->GetLclNum()); + + if (isIntervalCandidate(dsc)) + { + assert(dsc->lvIsInReg()); + assert(tree->OperIs(GT_STORE_LCL_VAR, GT_LCL_VAR)); + assert(!tree->isContained()); + + if (tree->OperIs(GT_STORE_LCL_VAR)) + { + updateIntervalStart(dsc->lvVarIndex, pos); + // Update the interval end here too, in case this is a dead store + // and we never have a use (TODO: could we check flags to determine if it's a dead store?) + updateIntervalEnd(dsc->lvVarIndex, pos); + } + else if (tree->OperIs(GT_LCL_VAR)) + { + if ((tree->gtLIRFlags & LIR::Flags::MultiplyUsed) != 0) + { + GenTree* user = getNonContainedUser(tree, CurrentRange()); + pendingMultipleUse.Push({user, dsc->lvVarIndex}); + } + else if ((tree->gtFlags & GTF_VAR_DEATH) != 0) + { + // Last use; extend the var's interval to end here; + updateIntervalEnd(dsc->lvVarIndex, pos); + } + } + } + } + + if (tree == CurrentRange().LastNode()) + { + updateIntervalEnds(block->bbLiveOut, pos); + } + pos++; } } } +void WasmRegAlloc::DumpIntervals() +{ + JITDUMP("Final intervals:\n") + for (FuncInfoDsc* const funcInfo : m_compiler->Funcs()) + { + PerFuncletData* funcletData = m_perFuncletData[funcInfo->GetFuncletIdx(m_compiler)]; + JITDUMP("Funclet %u:\n", funcInfo->GetFuncletIdx(m_compiler)); + for (unsigned trackedIdx = 0; trackedIdx < funcletData->m_intervals.size(); trackedIdx++) + { + Interval* interval = funcletData->m_intervals[trackedIdx]; + if (interval == nullptr) + { + continue; + } + + JITDUMP("V%02u: [%d, %d]\n", + m_compiler->lvaTrackedIndexToLclNum(trackedIdx), interval->start, interval->end); + } + } +} + //------------------------------------------------------------------------ // ResolveReferences: Translate virtual registers to physical ones (WASM locals). // diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index 411fc8c8641e4d..dc39e606c1e4c6 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -186,6 +186,7 @@ class WasmRegAlloc : public RegAllocInterface void SetBlockSequence(); void BuildIntervals(); void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); + void DumpIntervals(); void ResolveReferences(); From ab5d4160fe6d0d646e47b4c27a43d53f069793f2 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Wed, 18 Nov 2026 16:50:08 -0800 Subject: [PATCH 03/14] Also exclude paramRegTarget locals from being candidates; Null out empty intervals in funclets; Improve interval dump; --- src/coreclr/jit/regallocwasm.cpp | 90 ++++++++++++++++++-------------- src/coreclr/jit/regallocwasm.h | 15 ++++-- 2 files changed, 63 insertions(+), 42 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index e5561ffadaef02..cfe6083c26984a 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1094,7 +1094,7 @@ GenTree* getNonContainedUser(GenTree* node, LIR::Range& blockRange) { GenTree* useNode = node; LIR::Use treeUse; - bool foundUse; + bool foundUse; do { foundUse = blockRange.TryGetUse(useNode, &treeUse); @@ -1105,6 +1105,19 @@ GenTree* getNonContainedUser(GenTree* node, LIR::Range& blockRange) return useNode; } +bool WasmRegAlloc::isIntervalCandidate(LclVarDsc* varDsc, PerFuncletData* funcletData) +{ + if (varDsc->lvIsRegCandidate()) + { + // Don't permit params or SP/FP locals to be tracked interval candidates; + regNumber reg = varDsc->GetRegNum(); + assert(genIsValidReg(reg)); + return !varDsc->lvIsParam && !varDsc->lvIsParamRegTarget && reg != funcletData->m_fpReg && + reg != funcletData->m_spReg; + } + return false; +} + void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData) { struct PendingLclUse @@ -1113,29 +1126,14 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun unsigned int trackedLcl; }; - auto isIntervalCandidate = [&](LclVarDsc* varDsc) { - if (varDsc->lvIsRegCandidate()) - { - // Don't permit params or SP/FP locals to be tracked interval candidates; - regNumber reg = varDsc->GetRegNum(); - assert(genIsValidReg(reg)); - return !varDsc->lvIsParam && reg != funcletData->m_fpReg && reg != funcletData->m_spReg; - } - return false; - }; - for (unsigned i = 0; i < m_compiler->lvaTrackedCount; i++) { - LclVarDsc* varDsc = m_compiler->lvaGetDescByTrackedIndex(i); - - Interval* interval = nullptr; - if (isIntervalCandidate(varDsc)) + LclVarDsc* varDsc = m_compiler->lvaGetDescByTrackedIndex(i); + Interval* interval = nullptr; + if (isIntervalCandidate(varDsc, funcletData)) { regNumber virtReg = varDsc->GetRegNum(); - interval = new (m_compiler->getAllocator(CMK_LSRA)) Interval(); - interval->start = INT_MAX; - interval->end = INT_MIN; - interval->virtReg = virtReg; + interval = new (m_compiler->getAllocator(CMK_LSRA_Interval)) Interval(virtReg); } funcletData->m_intervals[i] = interval; } @@ -1144,11 +1142,12 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun Interval* interval = funcletData->m_intervals[trackedIdx]; if (interval != nullptr) { - int prev = interval->start; + int prev = interval->start; interval->start = min(interval->start, static_cast(pos)); if (interval->start != prev) { - JITDUMP("V%02u start: %d -> %d\n", m_compiler->lvaTrackedIndexToLclNum(trackedIdx), prev, interval->start); + JITDUMP("V%02u start: %d -> %d\n", m_compiler->lvaTrackedIndexToLclNum(trackedIdx), prev, + interval->start); } } }; @@ -1157,7 +1156,7 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun Interval* interval = funcletData->m_intervals[trackedIdx]; if (interval != nullptr) { - int prev = interval->end; + int prev = interval->end; interval->end = max(interval->end, static_cast(pos)); if (interval->end != prev) { @@ -1168,7 +1167,7 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun auto updateIntervalStarts = [&](VARSET_TP toUpdate, unsigned pos) { VarSetOps::Iter iter(m_compiler, toUpdate); - unsigned trackedIdx; + unsigned trackedIdx; while (iter.NextElem(&trackedIdx)) { updateIntervalStart(trackedIdx, pos); @@ -1177,7 +1176,7 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun auto updateIntervalEnds = [&](VARSET_TP toUpdate, unsigned pos) { VarSetOps::Iter iter(m_compiler, toUpdate); - unsigned trackedIdx; + unsigned trackedIdx; while (iter.NextElem(&trackedIdx)) { updateIntervalEnd(trackedIdx, pos); @@ -1196,7 +1195,7 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun JITDUMPEXEC(block->dspBlockHeader()); JITDUMP("liveIn="); - dumpConvertedVarSet(m_compiler, block->bbLiveIn); + JITDUMPEXEC(dumpConvertedVarSet(m_compiler, block->bbLiveIn)); JITDUMP("\n"); // Potentially update the start points of any intervals live at block entry. @@ -1211,21 +1210,16 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun // that consumes it, since it won't get a separate temp. while (!pendingMultipleUse.Empty() && tree == pendingMultipleUse.TopRef().UserNode) { - - if (tree->isContained()) - { - JITDUMP("TREE IS CONTAINED\n"); - } PendingLclUse pendingUse = pendingMultipleUse.Pop(); updateIntervalEnd(pendingUse.trackedLcl, pos); } - if (tree->OperIsLocal()) + if (tree->OperIsLocal()) { GenTreeLclVarCommon* lcl = tree->AsLclVarCommon(); - LclVarDsc* dsc = m_compiler->lvaGetDesc(lcl->GetLclNum()); + LclVarDsc* dsc = m_compiler->lvaGetDesc(lcl->GetLclNum()); - if (isIntervalCandidate(dsc)) + if (isIntervalCandidate(dsc, funcletData)) { assert(dsc->lvIsInReg()); assert(tree->OperIs(GT_STORE_LCL_VAR, GT_LCL_VAR)); @@ -1235,7 +1229,8 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun { updateIntervalStart(dsc->lvVarIndex, pos); // Update the interval end here too, in case this is a dead store - // and we never have a use (TODO: could we check flags to determine if it's a dead store?) + // and we never have a use + // TODO: could we check flags to determine if it's a dead store? updateIntervalEnd(dsc->lvVarIndex, pos); } else if (tree->OperIs(GT_LCL_VAR)) @@ -1256,12 +1251,27 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun if (tree == CurrentRange().LastNode()) { + JITDUMP("liveOut="); + JITDUMPEXEC(dumpConvertedVarSet(m_compiler, block->bbLiveOut)) + JITDUMP("\n"); + // Extend interval ends to the end of the block for live-out locals updateIntervalEnds(block->bbLiveOut, pos); } pos++; } } + + // Remove empty intervals which correspond to virtual registers that were never used in this funclet. + for (int i = 0; i < funcletData->m_intervals.size(); i++) + { + Interval* interval = funcletData->m_intervals[i]; + if (interval != nullptr && interval->start > interval->end) + { + assert(interval->start == INT_MAX && interval->end == INT_MIN); + funcletData->m_intervals[i] = nullptr; + } + } } void WasmRegAlloc::DumpIntervals() @@ -1273,14 +1283,18 @@ void WasmRegAlloc::DumpIntervals() JITDUMP("Funclet %u:\n", funcInfo->GetFuncletIdx(m_compiler)); for (unsigned trackedIdx = 0; trackedIdx < funcletData->m_intervals.size(); trackedIdx++) { - Interval* interval = funcletData->m_intervals[trackedIdx]; + unsigned lclNum = m_compiler->lvaTrackedIndexToLclNum(trackedIdx); + const LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum); + Interval* interval = funcletData->m_intervals[trackedIdx]; if (interval == nullptr) { continue; } - JITDUMP("V%02u: [%d, %d]\n", - m_compiler->lvaTrackedIndexToLclNum(trackedIdx), interval->start, interval->end); + JITDUMP("Interval %2u: (V%02u) %s range:[%d, %d] virtReg:$%u:%s%s\n", trackedIdx, lclNum, + varTypeName(varDsc->TypeGet()), interval->start, interval->end, WasmRegToIndex(interval->virtReg), + WasmValueTypeName(WasmRegToType(interval->virtReg)), + varDsc->lvWasmGCWriteThru ? " (GCWriteThru)" : ""); } } } diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index dc39e606c1e4c6..d4b973390783bc 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -75,10 +75,16 @@ struct VirtualRegReferences struct Interval { - int start; - int end; - regNumber virtReg; - WasmValueType type; + int start; + int end; + regNumber virtReg; + + Interval(regNumber virtReg) + : start(INT_MAX) + , end(INT_MIN) + , virtReg(virtReg) + { + } }; class WasmRegAlloc : public RegAllocInterface @@ -146,6 +152,7 @@ class WasmRegAlloc : public RegAllocInterface #endif // TRACK_LSRA_STATS bool isRegCandidate(LclVarDsc* varDsc); + bool isIntervalCandidate(LclVarDsc* varDsc, PerFuncletData* funcletData); bool isContainableMemoryOp(GenTree* node); void checkForDNER(unsigned lclNum, LclVarDsc* varDsc); From 9bcb578c203490949267fe3a971dcddb667c628e Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Wed, 18 Nov 2026 17:10:39 -0800 Subject: [PATCH 04/14] Remove block sequence computation and re-use block order from fgWasmControlFlow --- src/coreclr/jit/regallocwasm.cpp | 83 ++++---------------------------- src/coreclr/jit/regallocwasm.h | 5 -- 2 files changed, 10 insertions(+), 78 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index cfe6083c26984a..626ea5d9e0caef 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1011,74 +1011,8 @@ regNumber WasmRegAlloc::RequestInternalRegister(GenTree* node, var_types type) return reg; } -//------------------------------------------------------------------------ -// SetBlockSequence: set the block sequence partitioned by funclet. -// -// The result will be stored in each funclet's m_blockOrder. Each funclet's block order -// follows a (relative) loop-aware reverse postorder. -// -void WasmRegAlloc::SetBlockSequence() -{ - FgWasm fgWasm(m_compiler); - - bool hasBlocksOnlyReachableViaEH; - FlowGraphDfsTree* dfsTree = fgWasm.WasmDfs(hasBlocksOnlyReachableViaEH); - assert(!hasBlocksOnlyReachableViaEH); // fgWasmEHFlow should have handled blocks only reachable via EH - - BitVecTraits visitedTraits(m_compiler->fgBBNumMax + 1, m_compiler); - BitVec visited = BitVecOps::MakeEmpty(&visitedTraits); - auto visitBlock = [&](BasicBlock* block) { - if (BitVecOps::IsMember(&visitedTraits, visited, block->bbNum)) - { - return; - } - - int funcletIdx = m_compiler->bbFuncletRegionOf(block); - PerFuncletData* const funcletData = m_perFuncletData[funcletIdx]; - funcletData->m_blockOrder.push_back(block); - - BitVecOps::AddElemD(&visitedTraits, visited, block->bbNum); - }; - - FlowGraphNaturalLoops* loops = FlowGraphNaturalLoops::Find(dfsTree); - m_compiler->fgVisitBlocksInLoopAwareRPO(dfsTree, loops, visitBlock); - - // Ensure we visit any blocks not reached by the loop-aware RPO traversal. - for (BasicBlock* block : m_compiler->Blocks()) - { - visitBlock(block); - } - - JITDUMP("Block order:\n"); - for (const FuncInfoDsc* const funcInfo : m_compiler->Funcs()) - { - JITDUMP("Funclet %u:\n", funcInfo->GetFuncletIdx(m_compiler)); - unsigned count = 0; - for (BasicBlock* block : funcInfo->Blocks(m_compiler)) - { - count++; - } - const auto& blockOrder = m_perFuncletData[funcInfo->GetFuncletIdx(m_compiler)]->m_blockOrder; - assert(count == blockOrder.size()); - - BitVecTraits traits(m_compiler->fgBBNumMax + 1, m_compiler); - BitVec funcBlocks = BitVecOps::MakeEmpty(&traits); - for (BasicBlock* block : funcInfo->Blocks(m_compiler)) - { - BitVecOps::AddElemD(&traits, funcBlocks, block->bbNum); - } - - for (unsigned i = 0; i < count; i++) - { - assert(BitVecOps::IsMember(&traits, funcBlocks, blockOrder[i]->bbNum)); - JITDUMP(" BB%02u\n", blockOrder[i]->bbNum); - } - } -} - void WasmRegAlloc::BuildIntervals() { - SetBlockSequence(); for (FuncInfoDsc* const funcInfo : m_compiler->Funcs()) { m_currentFunclet = funcInfo->GetFuncletIdx(m_compiler); @@ -1188,14 +1122,19 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun JITDUMP("----------------------------------------\n"); ArrayStack pendingMultipleUse(m_compiler->getAllocator(CMK_LSRA)); + // Note: This phase should run after fgWasmControlFlow, so can expect each funclet's blocks to be ordered in + // a Wasm-compatible loop-aware RPO unsigned pos = 0; - for (BasicBlock* const block : funcletData->m_blockOrder) + for (BasicBlock* const block : funcInfo->Blocks(m_compiler)) { m_currentBlock = block; JITDUMPEXEC(block->dspBlockHeader()); JITDUMP("liveIn="); JITDUMPEXEC(dumpConvertedVarSet(m_compiler, block->bbLiveIn)); + JITDUMP(" "); + JITDUMP("liveOut="); + JITDUMPEXEC(dumpConvertedVarSet(m_compiler, block->bbLiveOut)); JITDUMP("\n"); // Potentially update the start points of any intervals live at block entry. @@ -1205,9 +1144,9 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun { JITDUMP("%10u: ", pos); DISPNODE(tree); - // Check for and consume any multiple-use local reads used by this node; - // if a read of a reg candidate is MultiplyUsed its underlying local lifetime must extend through the node - // that consumes it, since it won't get a separate temp. + // Consume any multiple-use local reads used by this node; + // if a read of a reg candidate is MultiplyUsed, its underlying local lifetime must extend through the node + // that consumes it since it won't get a separate temp. while (!pendingMultipleUse.Empty() && tree == pendingMultipleUse.TopRef().UserNode) { PendingLclUse pendingUse = pendingMultipleUse.Pop(); @@ -1251,9 +1190,6 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun if (tree == CurrentRange().LastNode()) { - JITDUMP("liveOut="); - JITDUMPEXEC(dumpConvertedVarSet(m_compiler, block->bbLiveOut)) - JITDUMP("\n"); // Extend interval ends to the end of the block for live-out locals updateIntervalEnds(block->bbLiveOut, pos); } @@ -1268,6 +1204,7 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun Interval* interval = funcletData->m_intervals[i]; if (interval != nullptr && interval->start > interval->end) { + // An empty interval should always be one that was never set assert(interval->start == INT_MAX && interval->end == INT_MIN); funcletData->m_intervals[i] = nullptr; } diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index d4b973390783bc..37b1aca992b5e2 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -108,7 +108,6 @@ class WasmRegAlloc : public RegAllocInterface , m_virtualRegRefs(nullptr) , m_physicalRegAssignments(comp->lvaTrackedCount, REG_STK, comp->getAllocator(CMK_LSRA)) , m_intervals(comp->lvaTrackedCount, nullptr, comp->getAllocator(CMK_LSRA)) - , m_blockOrder(comp->getAllocator(CMK_LSRA)) { } @@ -133,9 +132,6 @@ class WasmRegAlloc : public RegAllocInterface // Map from local tracked index to live interval for this local, in this funclet jitstd::vector m_intervals; - - // Block iteration order for this funclet (initialized later) - jitstd::vector m_blockOrder; }; jitstd::vector m_perFuncletData; @@ -190,7 +186,6 @@ class WasmRegAlloc : public RegAllocInterface regNumber RequestInternalRegister(GenTree* node, var_types type); void ConsumeTemporaryRegForOperand(GenTree* operand DEBUGARG(const char* reason)); - void SetBlockSequence(); void BuildIntervals(); void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); void DumpIntervals(); From e74183107a42a9a367a9705d2971ad9329e683dd Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Thu, 19 Nov 2026 14:16:23 -0800 Subject: [PATCH 05/14] Don't use GTF_VAR_DEATH flag to detect last use --- src/coreclr/jit/regallocwasm.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index 626ea5d9e0caef..ea2e935c8f9c24 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1179,9 +1179,9 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun GenTree* user = getNonContainedUser(tree, CurrentRange()); pendingMultipleUse.Push({user, dsc->lvVarIndex}); } - else if ((tree->gtFlags & GTF_VAR_DEATH) != 0) + else { - // Last use; extend the var's interval to end here; + // Ordinary single-use local var read; extend the var's interval to potentially end here updateIntervalEnd(dsc->lvVarIndex, pos); } } @@ -1213,7 +1213,8 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun void WasmRegAlloc::DumpIntervals() { - JITDUMP("Final intervals:\n") + JITDUMP("Final intervals:\n"); + JITDUMP("----------------\n") for (FuncInfoDsc* const funcInfo : m_compiler->Funcs()) { PerFuncletData* funcletData = m_perFuncletData[funcInfo->GetFuncletIdx(m_compiler)]; From c6da498a299d62aa7730d0764e6cbbf76c6edf2d Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Nov 2026 09:41:13 -0800 Subject: [PATCH 06/14] Fix emtpy interval loop iv type --- src/coreclr/jit/regallocwasm.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index ea2e935c8f9c24..91e3bba3a67cd6 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1199,7 +1199,7 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun } // Remove empty intervals which correspond to virtual registers that were never used in this funclet. - for (int i = 0; i < funcletData->m_intervals.size(); i++) + for (size_t i = 0; i < funcletData->m_intervals.size(); i++) { Interval* interval = funcletData->m_intervals[i]; if (interval != nullptr && interval->start > interval->end) From 6e838f81a95c38b3ccd5619b98b17964d8f7ac42 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Nov 2026 15:46:12 -0800 Subject: [PATCH 07/14] WIP: refactor ABI reg assignments and don't pre-set DeclaredCount; Temporarily disable allocation for temporary registers --- src/coreclr/jit/regallocwasm.cpp | 211 +++++++++++++++---------------- src/coreclr/jit/regallocwasm.h | 1 + 2 files changed, 100 insertions(+), 112 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index 91e3bba3a67cd6..d0bdbed06aecc0 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1237,6 +1237,50 @@ void WasmRegAlloc::DumpIntervals() } } +unsigned int WasmRegAlloc::ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spVirtReg, regNumber fpVirtReg) +{ + unsigned int indexBase = 0; + switch (funcInfo->funKind) + { + case FuncKind::FUNC_ROOT: + { + for (unsigned argLclNum = 0; argLclNum < m_compiler->info.compArgsCount; argLclNum++) + { + const ABIPassingInformation& abiInfo = m_compiler->lvaGetParameterABIInfo(argLclNum); + for (const ABIPassingSegment& segment : abiInfo.Segments()) + { + if (segment.IsPassedInRegister()) + { + WasmValueType argType; + regNumber argReg = segment.GetRegister(); + unsigned argIndex = UnpackWasmReg(argReg, &argType); + indexBase = max(indexBase, argIndex + 1); + } + } + } + } + break; + + case FuncKind::FUNC_HANDLER: + case FuncKind::FUNC_FILTER: + { + assert(spVirtReg != REG_NA && fpVirtReg != REG_NA && spVirtReg != fpVirtReg); + EHblkDsc* const ehDsc = funcInfo->GetEHDesc(m_compiler); + + // Filter funclets take an additional argument for the exception object. Otherwise, + // the only args for a funclet should be (SP, FP) = (local 0, local 1) + indexBase = ehDsc->HasCatchHandler() ? 3 : 2; + } + + break; + + default: + unreached(); + } + + return indexBase; +} + //------------------------------------------------------------------------ // ResolveReferences: Translate virtual registers to physical ones (WASM locals). // @@ -1250,11 +1294,11 @@ void WasmRegAlloc::ResolveReferences() regNumber* Regs; unsigned Count; }; - TemporaryRegBank temporaryRegMap[static_cast(WasmValueType::Count)]; + TemporaryRegBank temporaryRegBankByType[static_cast(WasmValueType::Count)]; for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { TemporaryRegStack& temporaryRegs = m_temporaryRegs[static_cast(type)]; - TemporaryRegBank& allocatedTemporaryRegs = temporaryRegMap[static_cast(type)]; + TemporaryRegBank& allocatedTemporaryRegs = temporaryRegBankByType[static_cast(type)]; assert((temporaryRegs.Count == 0) && "Some temporary regs were not consumed/released"); allocatedTemporaryRegs.Count = temporaryRegs.MaxCount; @@ -1289,97 +1333,44 @@ void WasmRegAlloc::ResolveReferences() // m_currentFunclet = funcInfo->GetFuncletIdx(m_compiler); - PhysicalRegBank virtToPhysRegMap[static_cast(WasmValueType::Count)]; - for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) - { - VirtualRegStack& virtRegs = m_virtualRegs[static_cast(type)]; - PhysicalRegBank& physRegs = virtToPhysRegMap[static_cast(type)]; - physRegs.DeclaredCount = virtRegs.Count(); - } + PhysicalRegBank regBankByType[static_cast(WasmValueType::Count)]{}; - unsigned indexBase = 0; const bool inFunclet = funcInfo->funKind != FuncKind::FUNC_ROOT; PerFuncletData* const data = m_perFuncletData[m_currentFunclet]; regNumber const spVirtReg = data->m_spReg; regNumber const fpVirtReg = data->m_fpReg; + unsigned indexBase = ComputeIndexBase(funcInfo, spVirtReg, fpVirtReg); - switch (funcInfo->funKind) - { - case FuncKind::FUNC_ROOT: + auto isABIReg = [&](regNumber virtReg, LclVarDsc* varDsc) { + if (virtReg == spVirtReg || virtReg == fpVirtReg) { - for (unsigned argLclNum = 0; argLclNum < m_compiler->info.compArgsCount; argLclNum++) - { - const ABIPassingInformation& abiInfo = m_compiler->lvaGetParameterABIInfo(argLclNum); - for (const ABIPassingSegment& segment : abiInfo.Segments()) - { - if (segment.IsPassedInRegister()) - { - WasmValueType argType; - regNumber argReg = segment.GetRegister(); - unsigned argIndex = UnpackWasmReg(argReg, &argType); - indexBase = max(indexBase, argIndex + 1); - - LclVarDsc* argVarDsc = m_compiler->lvaGetDesc(argLclNum); - if (canReuseAbiReg(argVarDsc->GetRegNum(), argReg) || - (argLclNum == m_compiler->lvaWasmSpArg)) - { - assert(abiInfo.HasExactlyOneRegisterSegment()); - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - - const ParameterRegisterLocalMapping* mapping = - m_compiler->FindParameterRegisterLocalMappingByRegister(argReg); - if ((mapping != nullptr) && - canReuseAbiReg(m_compiler->lvaGetDesc(mapping->LclNum)->GetRegNum(), argReg)) - { - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - } - } - } + return true; } - break; - - case FuncKind::FUNC_HANDLER: - case FuncKind::FUNC_FILTER: + if ((varDsc != nullptr) && varDsc->lvIsRegArg && !varDsc->lvIsStructField) { - // TODO-WASM: add ABI information for funclets? - // - WasmValueType argType = TypeToWasmValueType(TYP_I_IMPL); - - if (spVirtReg != REG_NA) - { - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - - if ((fpVirtReg != REG_NA) && (fpVirtReg != spVirtReg)) - { - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - - EHblkDsc* const ehDsc = funcInfo->GetEHDesc(m_compiler); - indexBase = ehDsc->HasCatchHandler() ? 3 : 2; + return true; } + if ((varDsc != nullptr) && varDsc->lvIsParamRegTarget) + { + return true; + } + return false; + }; - break; - - default: - unreached(); - } + // Create a new phys reg in the regbank for the given virtReg + auto allocPhysReg = [&](regNumber virtReg) { + WasmValueType type = WasmRegToType(virtReg); + unsigned physRegIndex = regBankByType[static_cast(type)].Index++; + regBankByType[static_cast(type)].DeclaredCount++; + regNumber physReg = MakeWasmReg(physRegIndex, type); + return physReg; + }; - for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + auto allocABIReg = [&](regNumber virtReg, LclVarDsc* varDsc) { - PhysicalRegBank& physRegs = virtToPhysRegMap[static_cast(type)]; - physRegs.IndexBase = indexBase; - physRegs.Index = indexBase; - indexBase += physRegs.DeclaredCount; - } + assert(isABIReg(virtReg, varDsc)); - // Allocate all our virtual registers to physical ones. - // - auto allocPhysReg = [&](regNumber virtReg, LclVarDsc* varDsc) { regNumber physReg = REG_NA; - if (!inFunclet) { // ABI registers in the main method @@ -1421,11 +1412,11 @@ void WasmRegAlloc::ResolveReferences() } } + // If we couldn't reuse a the ABI parameter register, allocate + // a new phys reg now if (physReg == REG_NA) { - WasmValueType type = WasmRegToType(virtReg); - unsigned physRegIndex = virtToPhysRegMap[static_cast(type)].Index++; - physReg = MakeWasmReg(physRegIndex, type); + physReg = allocPhysReg(virtReg); } assert(genIsValidReg(physReg)); @@ -1440,50 +1431,44 @@ void WasmRegAlloc::ResolveReferences() // if (spVirtReg != REG_NA) { - data->m_spReg = allocPhysReg(spVirtReg, m_compiler->lvaGetDesc(m_compiler->lvaWasmSpArg)); + data->m_spReg = allocABIReg(spVirtReg, m_compiler->lvaGetDesc(m_compiler->lvaWasmSpArg)); } if (fpVirtReg != REG_NA) { - data->m_fpReg = (spVirtReg == fpVirtReg) ? data->m_spReg : allocPhysReg(fpVirtReg, nullptr); + data->m_fpReg = (spVirtReg == fpVirtReg) ? data->m_spReg : allocABIReg(fpVirtReg, nullptr); } - // Do likewise for the enregistered locals. - // - // Note we do not update the LclVarDsc here. - // - // We will update the LclVarDsc at the end of this method to be the assignments - // for the main method. - // - // Then when codegen calls back to the allocator via recordVarLocationsAtStartOfBB - // we will either verify the assignments are correct for the block, or update them - // using the per-funclet mappings kept in the per-funclet m_physicalRegAssignments. - // - for (unsigned varIndex = 0; varIndex < m_compiler->lvaTrackedCount; varIndex++) + // Allocate non-FP/SP param registers + for (unsigned lclNum = 0; lclNum < m_compiler->lvaCount; lclNum++) { - unsigned lclNum = m_compiler->lvaTrackedIndexToLclNum(varIndex); LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum); - - if (lclNum == m_compiler->lvaWasmSpArg) - { - // Allocation was handled above. - } - else if (!varDsc->lvIsRegCandidate()) - { - continue; - } - else + if (varDsc->lvIsRegCandidate()) { - allocPhysReg(varDsc->GetRegNum(), varDsc); + regNumber virtReg = varDsc->GetRegNum(); + assert(genIsValidReg(virtReg)); + if (virtReg == spVirtReg || virtReg == fpVirtReg) + { + continue; + } + + if (isABIReg(virtReg, varDsc)) + { + regNumber reg = allocABIReg(virtReg, varDsc); + assert(genIsValidReg(reg)); + } } } + + // Allocate temporary regs to physical regs for each wasm value type for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { - TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; + TemporaryRegBank& regs = temporaryRegBankByType[static_cast(type)]; for (unsigned i = 0; i < regs.Count; i++) { - regs.Regs[i] = allocPhysReg(regs.Regs[i], nullptr); + // TODO: allocate temp regs +// regs.Regs[i] = allocPhysReg(regs.Regs[i], nullptr); } } @@ -1517,7 +1502,7 @@ void WasmRegAlloc::ResolveReferences() assert(!node->OperIsLocal() || !m_compiler->lvaGetDesc(node->AsLclVarCommon())->lvIsRegCandidate()); WasmValueType type; unsigned index = UnpackWasmReg(node->GetRegNum(), &type); - physReg = temporaryRegMap[static_cast(type)].Regs[index]; + physReg = temporaryRegBankByType[static_cast(type)].Regs[index]; } if (physReg != REG_NA) @@ -1536,7 +1521,7 @@ void WasmRegAlloc::ResolveReferences() { WasmValueType type; unsigned index = UnpackWasmReg(internalRegs->GetAt(i), &type); - regNumber physReg = temporaryRegMap[static_cast(type)].Regs[index]; + regNumber physReg = temporaryRegBankByType[static_cast(type)].Regs[index]; internalRegs->SetAt(i, physReg); } } @@ -1554,7 +1539,7 @@ void WasmRegAlloc::ResolveReferences() for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { - PhysicalRegBank& physRegs = virtToPhysRegMap[static_cast(type)]; + PhysicalRegBank& physRegs = regBankByType[static_cast(type)]; assert(physRegs.Index <= physRegs.IndexBase + physRegs.DeclaredCount); if (physRegs.DeclaredCount != 0) { @@ -1573,6 +1558,8 @@ void WasmRegAlloc::ResolveReferences() } } + // TODO: increment the indexBase for each declared physical register type. + // Set all lcl var assignments to the main method's allocations. // const jitstd::vector& mainFuncAssignment = m_perFuncletData[ROOT_FUNC_IDX]->m_physicalRegAssignments; diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index 37b1aca992b5e2..756d86586126a5 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -187,6 +187,7 @@ class WasmRegAlloc : public RegAllocInterface void ConsumeTemporaryRegForOperand(GenTree* operand DEBUGARG(const char* reason)); void BuildIntervals(); + unsigned int ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spVirtReg, regNumber fpVirtReg); void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); void DumpIntervals(); From dd7ed958958bfc6a541aafa63cb6d35d3511f165 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Fri, 20 Nov 2026 17:35:58 -0800 Subject: [PATCH 08/14] WIP assign phys regs to intervals; temp allocation and local desc reg num resolution still not updated --- src/coreclr/jit/priorityqueue.h | 5 ++ src/coreclr/jit/regallocwasm.cpp | 107 ++++++++++++++++++++++++++----- src/coreclr/jit/regallocwasm.h | 22 +++++++ 3 files changed, 117 insertions(+), 17 deletions(-) diff --git a/src/coreclr/jit/priorityqueue.h b/src/coreclr/jit/priorityqueue.h index dc51f0efdea0f6..b3f8b4a74d1524 100644 --- a/src/coreclr/jit/priorityqueue.h +++ b/src/coreclr/jit/priorityqueue.h @@ -18,6 +18,11 @@ class PriorityQueue { } + const int Size() const + { + return static_cast(data.size()); + } + const T& Top() const { assert(!data.empty()); diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index d0bdbed06aecc0..c746f43773117b 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#include "algorithm.h" #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop @@ -1281,6 +1282,71 @@ unsigned int WasmRegAlloc::ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spV return indexBase; } +void WasmRegAlloc::AssignIntervals(jitstd::vector* intervals, PhysicalRegBank* regBankMap) +{ + struct PhysRegPool + { + jitstd::vector* Regs; + }; + + PhysRegPool physRegPoolMap[static_cast(WasmValueType::Count)]{}; + for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + { + physRegPoolMap[static_cast(type)].Regs = new (m_compiler->getAllocator(CMK_LSRA)) jitstd::vector(m_compiler->getAllocator(CMK_LSRA)); + } + + auto numAvail = [&](WasmValueType type) + { + return physRegPoolMap[static_cast(type)].Regs->size(); + }; + + auto nextReg = [&](WasmValueType type) + { + jitstd::vector* regs = physRegPoolMap[static_cast(type)].Regs; + assert(!regs->empty()); + regNumber reg = regs->back(); + regs->pop_back(); + return reg; + }; + + auto laterEnd = [](Interval* a, Interval* b) { + return a->end > b->end; + }; + PriorityQueue activeQueue(m_compiler->getAllocator(CMK_LSRA), laterEnd); + + auto expireOld = [&](Interval* current) { + while (activeQueue.Size() > 0 && activeQueue.Top()->end <= current->start) + { + JITDUMP("Expiring interval [%d, %d]:virtReg%d\n", activeQueue.Top()->start, activeQueue.Top()->end, activeQueue.Top()->virtReg); + Interval* interval = activeQueue.Top(); + activeQueue.Pop(); + assert(genIsValidReg(interval->physReg)); + physRegPoolMap[static_cast(WasmRegToType(interval->virtReg))].Regs->push_back(interval->physReg); + } + }; + + jitstd::sort(intervals->begin(), intervals->end(), [](Interval* a, Interval* b) { + return a->start < b->start; + }); + + for (Interval* interval : *intervals) + { + JITDUMP("Assigning reg for interval: [%d, %d]:virtReg %d\n", interval->start, interval->end, interval->virtReg); + expireOld(interval); + WasmValueType type = WasmRegToType(interval->virtReg); + if (numAvail(type) == 0) + { + interval->physReg = regBankMap[static_cast(type)].AllocPhysReg(interval->virtReg); + } + else + { + interval->physReg = nextReg(type); + } + + activeQueue.Push(interval); + } +} + //------------------------------------------------------------------------ // ResolveReferences: Translate virtual registers to physical ones (WASM locals). // @@ -1314,13 +1380,6 @@ void WasmRegAlloc::ResolveReferences() } } - struct PhysicalRegBank - { - unsigned DeclaredCount; - unsigned IndexBase; - unsigned Index; - }; - auto canReuseAbiReg = [](regNumber virtReg, regNumber abiReg) { return genIsValidReg(virtReg) && (WasmRegToType(virtReg) == WasmRegToType(abiReg)); }; @@ -1357,15 +1416,6 @@ void WasmRegAlloc::ResolveReferences() return false; }; - // Create a new phys reg in the regbank for the given virtReg - auto allocPhysReg = [&](regNumber virtReg) { - WasmValueType type = WasmRegToType(virtReg); - unsigned physRegIndex = regBankByType[static_cast(type)].Index++; - regBankByType[static_cast(type)].DeclaredCount++; - regNumber physReg = MakeWasmReg(physRegIndex, type); - return physReg; - }; - auto allocABIReg = [&](regNumber virtReg, LclVarDsc* varDsc) { assert(isABIReg(virtReg, varDsc)); @@ -1416,7 +1466,7 @@ void WasmRegAlloc::ResolveReferences() // a new phys reg now if (physReg == REG_NA) { - physReg = allocPhysReg(virtReg); + physReg = regBankByType[static_cast(WasmRegToType(virtReg))].AllocPhysReg(virtReg); } assert(genIsValidReg(physReg)); @@ -1460,6 +1510,29 @@ void WasmRegAlloc::ResolveReferences() } } + // At this point, physRegBankByType should reflect the declaration count necessary for all locals needed to home + // ABI parameters. Each local index remains relative to the IndexBase, which is unset at this point. We can't set it + // until we know how many locals we will actually need. Therefore, the below regNum assignments for enregistered locals + // represent Wasm-type relative local indices. Assign (index relative) physical registers to each interval + jitstd::vector* intervals = new (m_compiler->getAllocator(CMK_LSRA)) jitstd::vector(m_compiler->getAllocator()); + for (size_t i = 0; i < intervals->size(); i++) + { + if (data->m_intervals[i] != nullptr) + { + intervals->push_back(data->m_intervals[i]); + } + } + AssignIntervals(intervals, regBankByType); + + // + // We will update the LclVarDsc at the end of this method to be the assignments + // for the main method. + // + // Then when codegen calls back to the allocator via recordVarLocationsAtStartOfBB + // we will either verify the assignments are correct for the block, or update them + // using the per-funclet mappings kept in the per-funclet m_physicalRegAssignments. + // + // Allocate temporary regs to physical regs for each wasm value type for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index 756d86586126a5..75a8da5adad169 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -78,11 +78,13 @@ struct Interval int start; int end; regNumber virtReg; + regNumber physReg; Interval(regNumber virtReg) : start(INT_MAX) , end(INT_MIN) , virtReg(virtReg) + , physReg(REG_NA) { } }; @@ -191,9 +193,29 @@ class WasmRegAlloc : public RegAllocInterface void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); void DumpIntervals(); + struct PhysicalRegBank + { + unsigned DeclaredCount; + unsigned IndexBase; + unsigned Index; + + + // Create a new phys reg in the regbank for the given virtReg + regNumber AllocPhysReg(regNumber virtReg) { + WasmValueType type = WasmRegToType(virtReg); + unsigned physRegIndex = Index++; + DeclaredCount++; + regNumber physReg = MakeWasmReg(physRegIndex, type); + return physReg; + } + + }; + void ResolveReferences(); + void AssignIntervals(jitstd::vector* intervals, PhysicalRegBank* regBankByType); void PublishAllocationResults(); + }; using RegAllocImpl = WasmRegAlloc; From c01960db6e1c12b3eeea353f0fab40b63fb8dabc Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Mon, 23 Nov 2026 13:58:41 -0800 Subject: [PATCH 09/14] Introduce `isRelative` bit on Wasm regNum as a debug check to indicate whether a local created by the allocator has its indexBase added. Resolve IndexBase's and map created locals to their resolved indices. Assert that the isRelative bit doesn't survive on any tracked locals once they are assigned physRegs. Also, jit-format and rename some of the reg map structure temps. --- src/coreclr/jit/regallocwasm.cpp | 160 ++++++++++++++++++---------- src/coreclr/jit/regallocwasm.h | 50 ++++----- src/coreclr/jit/registeropswasm.cpp | 59 +++++++--- src/coreclr/jit/registeropswasm.h | 6 +- 4 files changed, 175 insertions(+), 100 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index c746f43773117b..e8577c5763eec6 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1068,7 +1068,7 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun if (isIntervalCandidate(varDsc, funcletData)) { regNumber virtReg = varDsc->GetRegNum(); - interval = new (m_compiler->getAllocator(CMK_LSRA_Interval)) Interval(virtReg); + interval = new (m_compiler->getAllocator(CMK_LSRA_Interval)) Interval(virtReg, i); } funcletData->m_intervals[i] = interval; } @@ -1270,7 +1270,7 @@ unsigned int WasmRegAlloc::ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spV // Filter funclets take an additional argument for the exception object. Otherwise, // the only args for a funclet should be (SP, FP) = (local 0, local 1) - indexBase = ehDsc->HasCatchHandler() ? 3 : 2; + indexBase = ehDsc->HasCatchHandler() ? 3 : 2; } break; @@ -1282,30 +1282,30 @@ unsigned int WasmRegAlloc::ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spV return indexBase; } -void WasmRegAlloc::AssignIntervals(jitstd::vector* intervals, PhysicalRegBank* regBankMap) +void WasmRegAlloc::AssignIntervals(jitstd::vector& intervals, PhysicalRegBank* regBankMap) { - struct PhysRegPool - { - jitstd::vector* Regs; - }; - - PhysRegPool physRegPoolMap[static_cast(WasmValueType::Count)]{}; + jitstd::list* physRegPoolMap[static_cast(WasmValueType::Count)]{}; for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { - physRegPoolMap[static_cast(type)].Regs = new (m_compiler->getAllocator(CMK_LSRA)) jitstd::vector(m_compiler->getAllocator(CMK_LSRA)); + physRegPoolMap[static_cast(type)] = + new (m_compiler->getAllocator(CMK_LSRA)) jitstd::list(m_compiler->getAllocator(CMK_LSRA)); } - auto numAvail = [&](WasmValueType type) - { - return physRegPoolMap[static_cast(type)].Regs->size(); + auto releaseIntervalReg = [&](Interval* interval) { + assert(genIsValidReg(interval->physReg)); + WasmValueType type = WasmRegToType(interval->physReg); + physRegPoolMap[static_cast(type)]->push_back(interval->physReg); }; - auto nextReg = [&](WasmValueType type) - { - jitstd::vector* regs = physRegPoolMap[static_cast(type)].Regs; + auto numAvail = [&](WasmValueType type) { + return physRegPoolMap[static_cast(type)]->size(); + }; + + auto nextReg = [&](WasmValueType type) { + jitstd::list* regs = physRegPoolMap[static_cast(type)]; assert(!regs->empty()); - regNumber reg = regs->back(); - regs->pop_back(); + regNumber reg = regs->front(); + regs->pop_front(); return reg; }; @@ -1317,31 +1317,35 @@ void WasmRegAlloc::AssignIntervals(jitstd::vector* intervals, Physica auto expireOld = [&](Interval* current) { while (activeQueue.Size() > 0 && activeQueue.Top()->end <= current->start) { - JITDUMP("Expiring interval [%d, %d]:virtReg%d\n", activeQueue.Top()->start, activeQueue.Top()->end, activeQueue.Top()->virtReg); + JITDUMP("Expiring interval [%d, %d]:virtReg $%d\n", activeQueue.Top()->start, activeQueue.Top()->end, + WasmRegToIndex(activeQueue.Top()->virtReg)); Interval* interval = activeQueue.Top(); activeQueue.Pop(); assert(genIsValidReg(interval->physReg)); - physRegPoolMap[static_cast(WasmRegToType(interval->virtReg))].Regs->push_back(interval->physReg); + releaseIntervalReg(interval); } }; - jitstd::sort(intervals->begin(), intervals->end(), [](Interval* a, Interval* b) { + jitstd::sort(intervals.begin(), intervals.end(), [](Interval* a, Interval* b) { return a->start < b->start; }); - for (Interval* interval : *intervals) + for (Interval* interval : intervals) { - JITDUMP("Assigning reg for interval: [%d, %d]:virtReg %d\n", interval->start, interval->end, interval->virtReg); + assert(interval->physReg == REG_NA && genIsValidReg(interval->virtReg)); expireOld(interval); WasmValueType type = WasmRegToType(interval->virtReg); if (numAvail(type) == 0) { - interval->physReg = regBankMap[static_cast(type)].AllocPhysReg(interval->virtReg); + interval->physReg = + regBankMap[static_cast(type)].AllocPhysReg(interval->virtReg, /*relative=*/true); } else { interval->physReg = nextReg(type); } + JITDUMP("Assigning (relative) reg for interval: [%d, %d]:virtReg $%d = $%d\n", interval->start, interval->end, + WasmRegToIndex(interval->virtReg), WasmRegToIndex(interval->physReg)); activeQueue.Push(interval); } @@ -1360,11 +1364,11 @@ void WasmRegAlloc::ResolveReferences() regNumber* Regs; unsigned Count; }; - TemporaryRegBank temporaryRegBankByType[static_cast(WasmValueType::Count)]; + TemporaryRegBank temporaryRegMap[static_cast(WasmValueType::Count)]; for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { TemporaryRegStack& temporaryRegs = m_temporaryRegs[static_cast(type)]; - TemporaryRegBank& allocatedTemporaryRegs = temporaryRegBankByType[static_cast(type)]; + TemporaryRegBank& allocatedTemporaryRegs = temporaryRegMap[static_cast(type)]; assert((temporaryRegs.Count == 0) && "Some temporary regs were not consumed/released"); allocatedTemporaryRegs.Count = temporaryRegs.MaxCount; @@ -1392,7 +1396,7 @@ void WasmRegAlloc::ResolveReferences() // m_currentFunclet = funcInfo->GetFuncletIdx(m_compiler); - PhysicalRegBank regBankByType[static_cast(WasmValueType::Count)]{}; + PhysicalRegBank physRegMap[static_cast(WasmValueType::Count)]{}; const bool inFunclet = funcInfo->funKind != FuncKind::FUNC_ROOT; PerFuncletData* const data = m_perFuncletData[m_currentFunclet]; @@ -1416,8 +1420,7 @@ void WasmRegAlloc::ResolveReferences() return false; }; - auto allocABIReg = [&](regNumber virtReg, LclVarDsc* varDsc) - { + auto allocABIReg = [&](regNumber virtReg, LclVarDsc* varDsc) { assert(isABIReg(virtReg, varDsc)); regNumber physReg = REG_NA; @@ -1454,11 +1457,11 @@ void WasmRegAlloc::ResolveReferences() // ABI registers in the funclets if (virtReg == spVirtReg) { - physReg = MakeWasmReg(0, TypeToWasmValueType(TYP_I_IMPL)); + physReg = MakeWasmReg(0, TypeToWasmValueType(TYP_I_IMPL), /*relative=*/false); } else if (virtReg == fpVirtReg) { - physReg = MakeWasmReg(1, TypeToWasmValueType(TYP_I_IMPL)); + physReg = MakeWasmReg(1, TypeToWasmValueType(TYP_I_IMPL), /*relative=*/false); } } @@ -1466,7 +1469,8 @@ void WasmRegAlloc::ResolveReferences() // a new phys reg now if (physReg == REG_NA) { - physReg = regBankByType[static_cast(WasmRegToType(virtReg))].AllocPhysReg(virtReg); + physReg = physRegMap[static_cast(WasmRegToType(virtReg))].AllocPhysReg(virtReg, + /*relative=*/true); } assert(genIsValidReg(physReg)); @@ -1510,41 +1514,83 @@ void WasmRegAlloc::ResolveReferences() } } - // At this point, physRegBankByType should reflect the declaration count necessary for all locals needed to home - // ABI parameters. Each local index remains relative to the IndexBase, which is unset at this point. We can't set it - // until we know how many locals we will actually need. Therefore, the below regNum assignments for enregistered locals - // represent Wasm-type relative local indices. Assign (index relative) physical registers to each interval - jitstd::vector* intervals = new (m_compiler->getAllocator(CMK_LSRA)) jitstd::vector(m_compiler->getAllocator()); - for (size_t i = 0; i < intervals->size(); i++) - { - if (data->m_intervals[i] != nullptr) - { - intervals->push_back(data->m_intervals[i]); - } - } - AssignIntervals(intervals, regBankByType); - - // - // We will update the LclVarDsc at the end of this method to be the assignments - // for the main method. + // At this point, physRegBankByType should reflect the declaration count necessary for any extra locals needed + // for ABI parameters. Each local index remains relative to the IndexBase, which is unset at this point. We + // can't set it until we know how many locals we will actually need. Once we have the final local count, we will + // resolve the indices to their actual physical register assignments. At this point we will update the LclVarDsc + // at the end of this method to be the assignments for the main method. // // Then when codegen calls back to the allocator via recordVarLocationsAtStartOfBB // we will either verify the assignments are correct for the block, or update them // using the per-funclet mappings kept in the per-funclet m_physicalRegAssignments. // + // Assign registers to intervals to assign homes for the enregistered locals + jitstd::vector intervals(m_compiler->getAllocator(CMK_LSRA)); + for (size_t i = 0; i < data->m_intervals.size(); i++) + { + if (data->m_intervals[i] != nullptr) + { + intervals.push_back(data->m_intervals[i]); + } + } + AssignIntervals(intervals, physRegMap); // Allocate temporary regs to physical regs for each wasm value type for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { - TemporaryRegBank& regs = temporaryRegBankByType[static_cast(type)]; + TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; for (unsigned i = 0; i < regs.Count; i++) { - // TODO: allocate temp regs -// regs.Regs[i] = allocPhysReg(regs.Regs[i], nullptr); + regs.Regs[i] = physRegMap[static_cast(type)].AllocPhysReg(regs.Regs[i], /*relative=*/true); } } + // At this point, we know how many physical registers are needed for the number of enregistered locals + + // temporary registers; We can now adjust the IndexBase for each local group to reflect the actual number of + // physical registers needed, and re-write the index-relative local indices to reflect the final physical + // register indices. + + for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + { + PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; + physRegs.IndexBase = indexBase; // iteration 0: pre-computed index base from the number of ABI registers + physRegs.Index += indexBase; + indexBase += physRegs.DeclaredCount; + JITDUMP("Type: %s, IndexBase: %d, Index: %d, DeclaredCount: %d\n", WasmValueTypeName(type), + physRegs.IndexBase, physRegs.Index, physRegs.DeclaredCount); + } + + for (Interval* interval : intervals) + { + assert(genIsValidReg(interval->physReg)); + PhysicalRegBank& physRegs = physRegMap[static_cast(WasmRegToType(interval->physReg))]; + interval->physReg = ResolveRegOffset(interval->physReg, physRegs.IndexBase); + data->m_physicalRegAssignments[interval->trackedIdx] = interval->physReg; + } + + for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + { + TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; + PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; + for (unsigned i = 0; i < regs.Count; i++) + { + regs.Regs[i] = ResolveRegOffset(regs.Regs[i], physRegs.IndexBase); + } + } + + if (data->m_spReg != REG_NA && genIsRelativeReg(data->m_spReg)) + { + data->m_spReg = + ResolveRegOffset(data->m_spReg, physRegMap[static_cast(WasmValueType::I)].IndexBase); + } + + if (data->m_fpReg != REG_NA && genIsRelativeReg(data->m_fpReg)) + { + data->m_fpReg = + ResolveRegOffset(data->m_fpReg, physRegMap[static_cast(WasmValueType::I)].IndexBase); + } + // Now remap all remaining virtual register references. unsigned refsCount = data->m_lastVirtualRegRefsCount; for (VirtualRegReferences* refs = data->m_virtualRegRefs; refs != nullptr; refs = refs->Prev) @@ -1575,11 +1621,12 @@ void WasmRegAlloc::ResolveReferences() assert(!node->OperIsLocal() || !m_compiler->lvaGetDesc(node->AsLclVarCommon())->lvIsRegCandidate()); WasmValueType type; unsigned index = UnpackWasmReg(node->GetRegNum(), &type); - physReg = temporaryRegBankByType[static_cast(type)].Regs[index]; + physReg = temporaryRegMap[static_cast(type)].Regs[index]; } if (physReg != REG_NA) { + assert(!genIsRelativeReg(physReg)); node->SetRegNum(physReg); } @@ -1594,7 +1641,7 @@ void WasmRegAlloc::ResolveReferences() { WasmValueType type; unsigned index = UnpackWasmReg(internalRegs->GetAt(i), &type); - regNumber physReg = temporaryRegBankByType[static_cast(type)].Regs[index]; + regNumber physReg = temporaryRegMap[static_cast(type)].Regs[index]; internalRegs->SetAt(i, physReg); } } @@ -1612,7 +1659,7 @@ void WasmRegAlloc::ResolveReferences() for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { - PhysicalRegBank& physRegs = regBankByType[static_cast(type)]; + PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; assert(physRegs.Index <= physRegs.IndexBase + physRegs.DeclaredCount); if (physRegs.DeclaredCount != 0) { @@ -1631,8 +1678,6 @@ void WasmRegAlloc::ResolveReferences() } } - // TODO: increment the indexBase for each declared physical register type. - // Set all lcl var assignments to the main method's allocations. // const jitstd::vector& mainFuncAssignment = m_perFuncletData[ROOT_FUNC_IDX]->m_physicalRegAssignments; @@ -1643,6 +1688,7 @@ void WasmRegAlloc::ResolveReferences() if (genIsValidReg(assignedReg)) { + assert(!genIsRelativeReg(assignedReg)); varDsc->SetRegNum(mainFuncAssignment[varIndex]); // While register allocations are fixed per-funclet, they are unlikely diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index 75a8da5adad169..bb8e5d3083ad5d 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -78,12 +78,16 @@ struct Interval int start; int end; regNumber virtReg; + unsigned trackedIdx; + + // Assigned later by the allocator regNumber physReg; - Interval(regNumber virtReg) + Interval(regNumber virtReg, unsigned trackedIdx) : start(INT_MAX) , end(INT_MIN) , virtReg(virtReg) + , trackedIdx(trackedIdx) , physReg(REG_NA) { } @@ -155,6 +159,23 @@ class WasmRegAlloc : public RegAllocInterface void checkForDNER(unsigned lclNum, LclVarDsc* varDsc); private: + struct PhysicalRegBank + { + unsigned DeclaredCount; + unsigned IndexBase; + unsigned Index; + + // Create a new phys reg in the regbank for the given virtReg + regNumber AllocPhysReg(regNumber virtReg, bool relative) + { + WasmValueType type = WasmRegToType(virtReg); + unsigned physRegIndex = Index++; + DeclaredCount++; + regNumber physReg = MakeWasmReg(physRegIndex, type, relative); + return physReg; + } + }; + LIR::Range& CurrentRange(); void IdentifyCandidates(); @@ -188,34 +209,15 @@ class WasmRegAlloc : public RegAllocInterface regNumber RequestInternalRegister(GenTree* node, var_types type); void ConsumeTemporaryRegForOperand(GenTree* operand DEBUGARG(const char* reason)); - void BuildIntervals(); + void BuildIntervals(); unsigned int ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spVirtReg, regNumber fpVirtReg); - void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); - void DumpIntervals(); - - struct PhysicalRegBank - { - unsigned DeclaredCount; - unsigned IndexBase; - unsigned Index; - - - // Create a new phys reg in the regbank for the given virtReg - regNumber AllocPhysReg(regNumber virtReg) { - WasmValueType type = WasmRegToType(virtReg); - unsigned physRegIndex = Index++; - DeclaredCount++; - regNumber physReg = MakeWasmReg(physRegIndex, type); - return physReg; - } - - }; + void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); + void DumpIntervals(); void ResolveReferences(); - void AssignIntervals(jitstd::vector* intervals, PhysicalRegBank* regBankByType); + void AssignIntervals(jitstd::vector& intervals, PhysicalRegBank* regBankByType); void PublishAllocationResults(); - }; using RegAllocImpl = WasmRegAlloc; diff --git a/src/coreclr/jit/registeropswasm.cpp b/src/coreclr/jit/registeropswasm.cpp index 112520dd9928b1..8023cee5242063 100644 --- a/src/coreclr/jit/registeropswasm.cpp +++ b/src/coreclr/jit/registeropswasm.cpp @@ -8,9 +8,12 @@ using RegNumUnderlyingType = regNumberSmall; static const RegNumUnderlyingType WASM_REG_TYPE_BITS = 3; +static const RegNumUnderlyingType WASM_REG_REL_BITS = 1; static const RegNumUnderlyingType WASM_REG_TYPE_SHIFT = 8 * sizeof(RegNumUnderlyingType) - WASM_REG_TYPE_BITS; +static const RegNumUnderlyingType WASM_REG_REL_SHIFT = WASM_REG_TYPE_SHIFT - WASM_REG_REL_BITS; static const RegNumUnderlyingType WASM_REG_TYPE_MASK = ~0u << WASM_REG_TYPE_SHIFT; -static const unsigned WASM_LOCAL_INDEX_LIMIT = WASM_REG_TYPE_MASK; +static const RegNumUnderlyingType WASM_REG_REL_MASK = ((1u << WASM_REG_REL_BITS) - 1) << WASM_REG_REL_SHIFT; +static const unsigned WASM_LOCAL_INDEX_LIMIT = WASM_REG_REL_MASK - 1; static_assert(sizeof(RegNumUnderlyingType) >= sizeof(unsigned)); static_assert(((static_cast(WasmValueType::Count) - 1) >> WASM_REG_TYPE_BITS) == 0); @@ -20,15 +23,24 @@ static_assert(((static_cast(WasmValueType::Count) - 1) >> // // Arguments: // index - The index of the WASM local -// type - Its type, must be directly mappable to the WASM type system +// type - Its type +// isRelative - Whether the index is relative to some base (default: false) // // Return Value: // 'regNumber' representing a tuple of '(index, type)'. // -regNumber MakeWasmReg(unsigned index, var_types type) +regNumber MakeWasmReg(unsigned index, WasmValueType type, bool isRelative) { - WasmValueType wasmType = TypeToWasmValueType(type); - return MakeWasmReg(index, wasmType); + assert((WasmValueType::Invalid < type) && (type < WasmValueType::Count)); + + // WASM engines have a much smaller limit on the number of locals (50K) than this. + if ((index & WASM_REG_TYPE_MASK) != 0) + { + IMPL_LIMITATION("Too many locals"); + } + RegNumUnderlyingType regValue = index | (isRelative ? (1u << WASM_REG_REL_SHIFT) : 0) | + (static_cast(type) << WASM_REG_TYPE_SHIFT); + return static_cast(regValue); } //------------------------------------------------------------------------ @@ -36,22 +48,20 @@ regNumber MakeWasmReg(unsigned index, var_types type) // // Arguments: // index - The index of the WASM local -// type - Its type +// type - Its type, must be directly mappable to the WASM type system +// isRelative - Whether the index is relative to a base (default: false) // // Return Value: // 'regNumber' representing a tuple of '(index, type)'. // -regNumber MakeWasmReg(unsigned index, WasmValueType type) +// Notes: +// isRelative is only used by the wasm register allocator to indicate whether a local +// is relative to an index base. This is because we don't know the exact final counts of locals while allocating. +// It has no effect on the actual encoding of the register number outside the allocator. +regNumber MakeWasmReg(unsigned index, var_types type, bool isRelative) { - assert((WasmValueType::Invalid < type) && (type < WasmValueType::Count)); - - // WASM engines have a much smaller limit on the number of locals (50K) than this. - if ((index & WASM_REG_TYPE_MASK) != 0) - { - IMPL_LIMITATION("Too many locals"); - } - RegNumUnderlyingType regValue = index | (static_cast(type) << WASM_REG_TYPE_SHIFT); - return static_cast(regValue); + WasmValueType wasmType = TypeToWasmValueType(type); + return MakeWasmReg(index, wasmType, isRelative); } //------------------------------------------------------------------------ @@ -174,7 +184,22 @@ unsigned UnpackWasmReg(regNumber reg, WasmValueType* pType) { *pType = static_cast(regValue >> WASM_REG_TYPE_SHIFT); } - return regValue & ~WASM_REG_TYPE_MASK; + return regValue & ~WASM_REG_TYPE_MASK & ~WASM_REG_REL_MASK; +} + +bool genIsRelativeReg(regNumber reg) +{ + RegNumUnderlyingType regValue = static_cast(reg); + return (regValue & WASM_REG_REL_MASK) != 0; +} + +regNumber ResolveRegOffset(regNumber reg, unsigned offset) +{ + assert(genIsRelativeReg(reg)); + WasmValueType type; + unsigned index = UnpackWasmReg(reg, &type); + index += offset; + return MakeWasmReg(index, type, false); } //------------------------------------------------------------------------ diff --git a/src/coreclr/jit/registeropswasm.h b/src/coreclr/jit/registeropswasm.h index 6c12d31a6003d8..0ce83a6f394d13 100644 --- a/src/coreclr/jit/registeropswasm.h +++ b/src/coreclr/jit/registeropswasm.h @@ -25,14 +25,16 @@ inline WasmValueType& operator++(WasmValueType& type) return type = static_cast(static_cast(type) + 1); } -regNumber MakeWasmReg(unsigned index, var_types type); -regNumber MakeWasmReg(unsigned index, WasmValueType type); +regNumber MakeWasmReg(unsigned index, var_types type, bool relative = false); +regNumber MakeWasmReg(unsigned index, WasmValueType type, bool relative = false); +regNumber ResolveRegOffset(regNumber reg, unsigned offset); WasmValueType TypeToWasmValueType(var_types type); WasmValueType ActualTypeToWasmValueType(var_types type); const char* WasmValueTypeName(WasmValueType type); unsigned UnpackWasmReg(regNumber reg, WasmValueType* pType = nullptr); unsigned WasmRegToIndex(regNumber reg); WasmValueType WasmRegToType(regNumber reg); +bool genIsRelativeReg(regNumber reg); bool genIsValidReg(regNumber reg); bool genIsValidIntReg(regNumber reg); bool genIsValidIntOrFakeReg(regNumber reg); From ce63153868d939fcba4a10d31f099c8503d71c4a Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Mon, 23 Nov 2026 16:33:23 -0800 Subject: [PATCH 10/14] Add Wasm Regalloc targeted tests --- src/tests/JIT/Directed/Directed_1.csproj | 1 + .../JIT/Directed/WasmRegalloc/WasmRegalloc.cs | 469 ++++++++++++++++++ .../Directed/WasmRegalloc/WasmRegalloc.csproj | 9 + 3 files changed, 479 insertions(+) create mode 100644 src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.cs create mode 100644 src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.csproj diff --git a/src/tests/JIT/Directed/Directed_1.csproj b/src/tests/JIT/Directed/Directed_1.csproj index 3e258f1253cd89..40ba526f2f39ea 100644 --- a/src/tests/JIT/Directed/Directed_1.csproj +++ b/src/tests/JIT/Directed/Directed_1.csproj @@ -18,6 +18,7 @@ + diff --git a/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.cs b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.cs new file mode 100644 index 00000000000000..aae471d357d78c --- /dev/null +++ b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.cs @@ -0,0 +1,469 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.CompilerServices; +using Xunit; + +public class WasmRegalloc +{ + private sealed class Box + { + public Box Next; + public int A; + public int B; + } + + private struct SingleFloat + { + public float Value; + } + + [Theory] + [InlineData(1, 0)] + [InlineData(5, 4)] + [InlineData(10, 8)] + [InlineData(-3, 0)] + [InlineData(0, 0)] + public static void ConditionalBackedge(int n, int expected) + { + if (n == 0) + { + Assert.Throws(() => ConditionalBackedgeMultiUse(n)); + } + else + { + Assert.Equal(expected, ConditionalBackedgeMultiUse(n)); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int ConditionalBackedgeMultiUse(int n) + { + int sum = 0; + for (int i = 0; i < n; i++) + { + sum += i; + } + + int result = sum / n; + return result + result; + } + + [Theory] + [InlineData(4, 7, 28)] + [InlineData(-4, -7, 28)] + [InlineData(-4, 7, int.MaxValue)] + [InlineData(int.MaxValue, 1, int.MaxValue)] + [InlineData(46341, 46341, int.MaxValue)] + [InlineData(int.MinValue, -1, int.MaxValue)] + public static void CheckedConversion(int a, int b, int expected) + { + Assert.Equal(expected, EHNonEH(a, b)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int EHNonEH(int a, int b) + { + uint value; + try + { + value = checked((uint)(a * b)); + } + catch (OverflowException) + { + return int.MaxValue; + } + + return (int)value; + } + + [Theory] + [InlineData(0, false, 23)] + [InlineData(1, false, 40)] + [InlineData(2, false, 57)] + [InlineData(1, true, 34)] + public static void ContainedTree(int index, bool alias, int expected) + { + Box first = new Box { A = 17, B = -1 }; + Box second = alias ? first : new Box { A = 23, B = -2 }; + first.Next = second; + Box[] boxes = { first, first, first }; + Assert.Equal(expected, CandidateInContainedTree(boxes, index)); + Assert.Equal(expected, second.B); + Assert.Equal(17, first.A); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int CandidateInContainedTree(Box[] boxes, int k) + { + Box p = boxes[k]; + Box q = p.Next; + int a = p.A; + q.B = a * k + q.A; + return q.B; + } + + [Theory] + [InlineData(0, 0)] + [InlineData(5, 50)] + [InlineData(-7, 98)] + public static void ContainedStore(int seed, int expected) + { + Box sentinel = new Box { B = -1 }; + Box destination = new Box { B = -2 }; + StoreCandidate(new Box[] { sentinel, destination }, 1, seed); + Assert.Equal(expected, destination.B); + Assert.Equal(-1, sentinel.B); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void StoreCandidate(Box[] boxes, int index, int seed) + { + Box destination = boxes[index]; + // The CSE definition on the RHS must not reuse the still-needed store base. + destination.B = checked(seed * seed + seed * seed); + } + + [Theory] + [InlineData(41, 5, 8)] + [InlineData(-41, 5, -8)] + [InlineData(int.MinValue, 1, int.MinValue)] + [InlineData(int.MinValue, -1, 0)] + [InlineData(1, 0, 0)] + public static void SignedDivision(int numerator, int denominator, int quotient) + { + if (denominator == 0) + { + Assert.Throws(() => DivideCandidate(numerator, denominator)); + } + else if (denominator == -1 && numerator == int.MinValue) + { + Assert.Throws(() => DivideCandidate(numerator, denominator)); + } + else + { + Assert.Equal(quotient, DivideCandidate(numerator, denominator)); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int DivideCandidate(int numerator, int denominator) + { + int divisor = Opaque(denominator); + int dividend = Opaque(numerator); + return dividend / divisor; + } + + [Theory] + [InlineData(11, 101L, 1.5f, 2.25, 262.75)] + [InlineData(-5, -11L, -1.5f, 0.25, 1.75)] + public static void ABIHomeRetention(int i, long l, float f, double d, double expected) + { + int home = 7; + Box box = new Box { A = 3, B = 5 }; + Assert.Equal(expected, RetainABIHomes(i, l, f, d, box, ref home)); + Assert.Equal(12, home); + Assert.Equal(f + i, RetainPromotedHome(new SingleFloat { Value = f }, i)); + Assert.Equal(2 * (i + 13), AddressExposedHome(i)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static double RetainABIHomes(int i, long l, float f, double d, Box box, ref int home) + { + i += box.A; + l += home; + f += i; + d += l; + home += box.B; + return Opaque(i) + l + f + d + home + box.A; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static float RetainPromotedHome(SingleFloat value, int delta) + { + return value.Value + Opaque(delta); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int AddressExposedHome(int argument) + { + Mutate(ref argument); + return argument + Opaque(argument); + } + + [Theory] + [InlineData(0, 25004)] + [InlineData(1, 134124)] + [InlineData(2, 29145)] + [InlineData(3, 53034)] + public static void FuncletHomes(int scenario, int expected) + { + Assert.Equal(expected, MultipleFunclets(scenario)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int MultipleFunclets(int scenario) + { + int shared = Opaque(17); + int trace = 0; + try + { + try + { + ThrowForScenario(scenario); + shared += Opaque(3); + } + catch (DivideByZeroException) when (CheckFilter(scenario, ref trace)) + { + int a = Opaque(11); + long b = Opaque(101L); + shared += a + (int)b; + trace = trace * 10 + 2; + } + catch (OverflowException) + { + float c = Opaque(13.5f); + double d = Opaque(17.5); + shared += (int)(c + d); + trace = trace * 10 + 3; + } + finally + { + shared += Opaque(5); + trace = trace * 10 + 4; + } + } + catch (DivideByZeroException) + { + shared += Opaque(7); + trace = trace * 10 + 5; + } + + return shared * 1000 + trace; + } + + [Theory] + [InlineData(3, 2, 45, 69)] + [InlineData(-5, 7, 29, 34)] + [InlineData(11, 32, 61, 139)] + public static void FrameHomes(int seed, int length, int fixedExpected, int dynamicExpected) + { + Assert.Equal(fixedExpected, FixedFrame(seed)); + Assert.Equal(dynamicExpected, DynamicFrame(seed, length)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int FixedFrame(int seed) + { + int home = seed; + Mutate(ref home); + int saved = Opaque(home); + Mutate(ref home); + return saved + home; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int DynamicFrame(int seed, int length) + { + ArgumentOutOfRangeException.ThrowIfLessThan(length, 2); + ArgumentOutOfRangeException.ThrowIfGreaterThan(length, 32); + int home = seed; + Mutate(ref home); + Span buffer = stackalloc int[length]; + for (int i = 0; i < buffer.Length; i++) + { + buffer[i] = home + i; + } + + int saved = Opaque(home); + buffer[0] += Opaque(seed + 1); + return saved + buffer[0] + buffer[length - 1] + home; + } + + [Theory] + [InlineData(0, 2, 69364)] + [InlineData(0, 32, 69364)] + [InlineData(1, 2, 190484)] + [InlineData(1, 7, 190484)] + [InlineData(2, 7, 215584)] + [InlineData(3, 2, 91705)] + [InlineData(3, 32, 91705)] + public static void DynamicFuncletHomes(int scenario, int length, int expected) + { + Assert.Equal(expected, MultipleFuncletsLocalloc(scenario, length)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int MultipleFuncletsLocalloc(int scenario, int length) + { + ArgumentOutOfRangeException.ThrowIfLessThan(length, 2); + ArgumentOutOfRangeException.ThrowIfGreaterThan(length, 32); + Span buffer = stackalloc int[length]; + buffer[0] = 11; + buffer[length - 1] = 23; + int shared = Opaque(19); + int trace = 0; + try + { + try + { + buffer[0] += Opaque(scenario); + ThrowForScenario(scenario); + shared += buffer[length - 1]; + } + catch (DivideByZeroException) + { + int a = Opaque(buffer[0]); + int b = Opaque(shared); + shared = a * a + b; + trace = 2; + } + finally + { + buffer[length - 1] += Opaque(3); + shared += buffer[length - 1]; + trace = trace * 10 + 4; + } + } + catch (OverflowException) + { + long value = Opaque((long)shared); + shared = (int)(value * 2); + trace = trace * 10 + 5; + } + + return shared * 1000 + buffer[0] * 100 + buffer[length - 1] * 10 + trace; + } + + [Theory] + [InlineData(3, 103, 72, 115, -53, 261.5)] + [InlineData(-5, 671, -72, -5, -77, 197.5)] + public static void IntervalBoundaries( + int seed, int disjointExpected, int overlapExpected, int firstExpected, int secondExpected, double banksExpected) + { + Assert.Equal(disjointExpected, DisjointIntervals(seed)); + Assert.Equal(overlapExpected, OverlappingIntervals(seed)); + Assert.Equal(firstExpected, BranchIntervals(seed, true)); + Assert.Equal(secondExpected, BranchIntervals(seed, false)); + Assert.Equal(banksExpected, TypedIntervals(seed)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int DisjointIntervals(int seed) + { + int a = Opaque(seed); + int b = a * a + 1; + return b * b + Opaque(seed); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int OverlappingIntervals(int seed) + { + int a = Opaque(seed); + int b = Opaque(seed + 1); + int c = a * a + b; + int d = Opaque(seed + 2); + return c * d + a + b; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int BranchIntervals(int seed, bool first) + { + int a = Opaque(seed); + int b = first ? Opaque(a + 5) : Opaque(a - 7); + int c = Opaque(seed + 11); + return a + b * c; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static double TypedIntervals(int seed) + { + int a = Opaque(seed); + long b = Opaque(seed + 101L); + float c = Opaque(seed + 0.5f); + double d = Opaque(seed + 0.25); + int a2 = Opaque(a + 7); + long b2 = Opaque(b + 11); + float c2 = Opaque(c + 3); + double d2 = Opaque(d + 13); + return a + a2 + b + b2 + c + c2 + d + d2; + } + + [Theory] + [InlineData(0, 58)] + [InlineData(1, 173)] + [InlineData(2, 248)] + [InlineData(3, 456)] + [InlineData(4, 757)] + public static void BackedgeIntervals(int count, int expected) + { + Assert.Equal(expected, LoopIntervals(count)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int LoopIntervals(int count) + { + int left = Opaque(3); + int right = Opaque(7); + for (int i = 0; i < count; i++) + { + int next = Opaque(left + i); + left = right + next; + right = next - i; + } + + return left * 17 + right; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool CheckFilter(int scenario, ref int trace) + { + trace = trace * 10 + 1; + return (scenario & 1) != 0; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ThrowForScenario(int scenario) + { + if (scenario is 1 or 2) + { + throw new DivideByZeroException(); + } + + if (scenario == 3) + { + throw new OverflowException(); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Mutate(ref int value) + { + value += 13; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int Opaque(int value) + { + return value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static long Opaque(long value) + { + return value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static float Opaque(float value) + { + return value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static double Opaque(double value) + { + return value; + } +} diff --git a/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.csproj b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.csproj new file mode 100644 index 00000000000000..be9a80a20865e4 --- /dev/null +++ b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.csproj @@ -0,0 +1,9 @@ + + + true + 1 + + + + + From 8a791df1ab028e1068ca72ded885531a6dbb5852 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Tue, 24 Nov 2026 14:55:32 -0800 Subject: [PATCH 11/14] Bug fixes: Ensure relative physregs are resolved against their offset in one place; Merge all reg assignments in funclets which do not exist in the root funclet into the root's assignments to match existing policy --- src/coreclr/jit/regallocwasm.cpp | 76 ++++++++++++++++++++--------- src/coreclr/jit/registeropswasm.cpp | 5 ++ 2 files changed, 58 insertions(+), 23 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index e8577c5763eec6..52462786ce2b12 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -10,7 +10,6 @@ #include "regallocwasm.h" #include "lower.h" // for LowerRange() -#include "fgwasm.h" RegAllocInterface* GetRegisterAllocator(Compiler* compiler) { @@ -50,6 +49,7 @@ PhaseStatus WasmRegAlloc::doRegisterAllocation() // bb - the basic block whose start is being processed // // Notes: + // This relies on m_currentFunclet to try and avoid work in some cases. // void WasmRegAlloc::recordVarLocationsAtStartOfBB(BasicBlock* bb) @@ -1388,6 +1388,21 @@ void WasmRegAlloc::ResolveReferences() return genIsValidReg(virtReg) && (WasmRegToType(virtReg) == WasmRegToType(abiReg)); }; + auto mergeAssignments = [&](int destIdx, int srcIdx){ + PerFuncletData* srcData = m_perFuncletData[srcIdx]; + PerFuncletData* destData = m_perFuncletData[destIdx]; + + for (unsigned i = 0; i < m_compiler->lvaTrackedCount; i++) + { + regNumber srcAssigned = srcData->m_physicalRegAssignments[i]; + regNumber destAssigned = destData->m_physicalRegAssignments[i]; + if (srcAssigned != REG_STK && destAssigned == REG_STK) + { + destData->m_physicalRegAssignments[i] = srcAssigned; + } + } + }; + // Resolve funclet by funclet, in reverse order, so that we process the main method region last. // for (FuncInfoDsc* const funcInfo : m_compiler->Funcs().Reverse()) @@ -1514,13 +1529,13 @@ void WasmRegAlloc::ResolveReferences() } } - // At this point, physRegBankByType should reflect the declaration count necessary for any extra locals needed - // for ABI parameters. Each local index remains relative to the IndexBase, which is unset at this point. We + // At this point, physRegMap should reflect the declaration count necessary for any extra locals needed + // for ABI parameters. Each local index remains relative to the final IndexBase, which is unset at this point. We // can't set it until we know how many locals we will actually need. Once we have the final local count, we will - // resolve the indices to their actual physical register assignments. At this point we will update the LclVarDsc - // at the end of this method to be the assignments for the main method. - // - // Then when codegen calls back to the allocator via recordVarLocationsAtStartOfBB + // resolve the indices to their actual physical register assignments. + // + // At the end of this method, we will update the LclVarDsc + // to be the assignments for the main method. Then when codegen calls back to the allocator via recordVarLocationsAtStartOfBB // we will either verify the assignments are correct for the block, or update them // using the per-funclet mappings kept in the per-funclet m_physicalRegAssignments. // @@ -1536,6 +1551,13 @@ void WasmRegAlloc::ResolveReferences() } AssignIntervals(intervals, physRegMap); + for (Interval* interval : intervals) + { + assert(genIsValidReg(interval->physReg)); + PhysicalRegBank& physRegs = physRegMap[static_cast(WasmRegToType(interval->physReg))]; + data->m_physicalRegAssignments[interval->trackedIdx] = interval->physReg; + } + // Allocate temporary regs to physical regs for each wasm value type for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { @@ -1546,7 +1568,7 @@ void WasmRegAlloc::ResolveReferences() } } - // At this point, we know how many physical registers are needed for the number of enregistered locals + + // At this point, we know how many physical registers are needed for ABI + enregistered locals + // temporary registers; We can now adjust the IndexBase for each local group to reflect the actual number of // physical registers needed, and re-write the index-relative local indices to reflect the final physical // register indices. @@ -1557,28 +1579,20 @@ void WasmRegAlloc::ResolveReferences() physRegs.IndexBase = indexBase; // iteration 0: pre-computed index base from the number of ABI registers physRegs.Index += indexBase; indexBase += physRegs.DeclaredCount; - JITDUMP("Type: %s, IndexBase: %d, Index: %d, DeclaredCount: %d\n", WasmValueTypeName(type), - physRegs.IndexBase, physRegs.Index, physRegs.DeclaredCount); } - for (Interval* interval : intervals) + // Resolve relative local -> physical register assignments to their actual physical register indices. + for (unsigned i = 0; i < data->m_physicalRegAssignments.size(); i++) { - assert(genIsValidReg(interval->physReg)); - PhysicalRegBank& physRegs = physRegMap[static_cast(WasmRegToType(interval->physReg))]; - interval->physReg = ResolveRegOffset(interval->physReg, physRegs.IndexBase); - data->m_physicalRegAssignments[interval->trackedIdx] = interval->physReg; - } - - for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) - { - TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; - PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; - for (unsigned i = 0; i < regs.Count; i++) + if (genIsRelativeReg(data->m_physicalRegAssignments[i])) { - regs.Regs[i] = ResolveRegOffset(regs.Regs[i], physRegs.IndexBase); + WasmValueType type = WasmRegToType(data->m_physicalRegAssignments[i]); + data->m_physicalRegAssignments[i] = ResolveRegOffset(data->m_physicalRegAssignments[i], physRegMap[static_cast(type)].IndexBase); } } + // Resolve SP and FP register relative offsets to their actual physical register indices if they haven't + // been adjusted already if (data->m_spReg != REG_NA && genIsRelativeReg(data->m_spReg)) { data->m_spReg = @@ -1591,6 +1605,17 @@ void WasmRegAlloc::ResolveReferences() ResolveRegOffset(data->m_fpReg, physRegMap[static_cast(WasmValueType::I)].IndexBase); } + // Resolve temporary register banks relative offsets to their actual physical register indices. + for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + { + TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; + PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; + for (unsigned i = 0; i < regs.Count; i++) + { + regs.Regs[i] = ResolveRegOffset(regs.Regs[i], physRegs.IndexBase); + } + } + // Now remap all remaining virtual register references. unsigned refsCount = data->m_lastVirtualRegRefsCount; for (VirtualRegReferences* refs = data->m_virtualRegRefs; refs != nullptr; refs = refs->Prev) @@ -1676,6 +1701,11 @@ void WasmRegAlloc::ResolveReferences() funcInfo->funWasmExnRefLocalIndex = indexBase; decls->push_back({WasmValueType::ExnRef, 1}); } + + // Copy any local -> reg mappings in this funclet to the root funclets if they don't exist there already. + // This allows us to ensure the root funclet knows about all reg assignments, + // even for locals which may not ever be used in the root funclet. + mergeAssignments(ROOT_FUNC_IDX, m_currentFunclet); } // Set all lcl var assignments to the main method's allocations. diff --git a/src/coreclr/jit/registeropswasm.cpp b/src/coreclr/jit/registeropswasm.cpp index 8023cee5242063..841bd81b97b342 100644 --- a/src/coreclr/jit/registeropswasm.cpp +++ b/src/coreclr/jit/registeropswasm.cpp @@ -269,6 +269,11 @@ const char* getRegName(regNumber reg) return "NA"; } + if (reg == REG_STK) + { + return "STK"; + } + // TODO-Wasm: remove this hardcoded list workaround by refactoring this API. // clang-format off static const char* const s_names[] = { From dfdc15e0f24a24a96dace07455e00e5b32217281 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Tue, 24 Nov 2026 16:04:32 -0800 Subject: [PATCH 12/14] jit-format --- src/coreclr/jit/regallocwasm.cpp | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index 52462786ce2b12..0216f1af22cc01 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1388,13 +1388,13 @@ void WasmRegAlloc::ResolveReferences() return genIsValidReg(virtReg) && (WasmRegToType(virtReg) == WasmRegToType(abiReg)); }; - auto mergeAssignments = [&](int destIdx, int srcIdx){ - PerFuncletData* srcData = m_perFuncletData[srcIdx]; + auto mergeAssignments = [&](int destIdx, int srcIdx) { + PerFuncletData* srcData = m_perFuncletData[srcIdx]; PerFuncletData* destData = m_perFuncletData[destIdx]; for (unsigned i = 0; i < m_compiler->lvaTrackedCount; i++) { - regNumber srcAssigned = srcData->m_physicalRegAssignments[i]; + regNumber srcAssigned = srcData->m_physicalRegAssignments[i]; regNumber destAssigned = destData->m_physicalRegAssignments[i]; if (srcAssigned != REG_STK && destAssigned == REG_STK) { @@ -1485,7 +1485,7 @@ void WasmRegAlloc::ResolveReferences() if (physReg == REG_NA) { physReg = physRegMap[static_cast(WasmRegToType(virtReg))].AllocPhysReg(virtReg, - /*relative=*/true); + /*relative=*/true); } assert(genIsValidReg(physReg)); @@ -1530,13 +1530,13 @@ void WasmRegAlloc::ResolveReferences() } // At this point, physRegMap should reflect the declaration count necessary for any extra locals needed - // for ABI parameters. Each local index remains relative to the final IndexBase, which is unset at this point. We - // can't set it until we know how many locals we will actually need. Once we have the final local count, we will - // resolve the indices to their actual physical register assignments. - // + // for ABI parameters. Each local index remains relative to the final IndexBase, which is unset at this point. + // We can't set it until we know how many locals we will actually need. Once we have the final local count, we + // will resolve the indices to their actual physical register assignments. + // // At the end of this method, we will update the LclVarDsc - // to be the assignments for the main method. Then when codegen calls back to the allocator via recordVarLocationsAtStartOfBB - // we will either verify the assignments are correct for the block, or update them + // to be the assignments for the main method. Then when codegen calls back to the allocator via + // recordVarLocationsAtStartOfBB we will either verify the assignments are correct for the block, or update them // using the per-funclet mappings kept in the per-funclet m_physicalRegAssignments. // @@ -1586,8 +1586,9 @@ void WasmRegAlloc::ResolveReferences() { if (genIsRelativeReg(data->m_physicalRegAssignments[i])) { - WasmValueType type = WasmRegToType(data->m_physicalRegAssignments[i]); - data->m_physicalRegAssignments[i] = ResolveRegOffset(data->m_physicalRegAssignments[i], physRegMap[static_cast(type)].IndexBase); + WasmValueType type = WasmRegToType(data->m_physicalRegAssignments[i]); + data->m_physicalRegAssignments[i] = ResolveRegOffset(data->m_physicalRegAssignments[i], + physRegMap[static_cast(type)].IndexBase); } } @@ -1703,7 +1704,7 @@ void WasmRegAlloc::ResolveReferences() } // Copy any local -> reg mappings in this funclet to the root funclets if they don't exist there already. - // This allows us to ensure the root funclet knows about all reg assignments, + // This allows us to ensure the root funclet knows about all reg assignments, // even for locals which may not ever be used in the root funclet. mergeAssignments(ROOT_FUNC_IDX, m_currentFunclet); } From 057b1e75581605f81b796cb8225325e952ba0027 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Wed, 25 Nov 2026 19:24:43 -0800 Subject: [PATCH 13/14] Fix edge case with dead store as last node in block; We could have a case where an interval's end is set to the last node position of a block due to its liveOut set, but the last position in said block contains a dead store followed by a BBJ_ALWAYS back edge. The dead store interferes then interferes with the liveOut local. Fix this by extending the endpoints of the liveOut set to pos + 1. This could push some locals' endpoints into an adjacent block where the locals are not already live, but that is ok because, assuming the liveOut was the "last use", the locals' intervals will still be expired before any interval starting at the first node in the block. --- src/coreclr/jit/regallocwasm.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index 0216f1af22cc01..74e1e6a05e6d8e 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1189,14 +1189,12 @@ void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* fun } } - if (tree == CurrentRange().LastNode()) - { - // Extend interval ends to the end of the block for live-out locals - updateIntervalEnds(block->bbLiveOut, pos); - } - pos++; } + + // Extend interval ends to the end of the block for live-out locals, + // and assign them pos + 1, where pos is the last position in the block + updateIntervalEnds(block->bbLiveOut, pos); } // Remove empty intervals which correspond to virtual registers that were never used in this funclet. From 5cf45f1a35ab160bbcbcd9684269f55ea99b7134 Mon Sep 17 00:00:00 2001 From: Adam Perlin Date: Tue, 1 Dec 2026 10:42:17 -0800 Subject: [PATCH 14/14] wasm regalloc: Use a total order for sorting intervals and comparing intervals in the priority queue --- src/coreclr/jit/regallocwasm.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index 74e1e6a05e6d8e..9627d6f8001a2d 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1308,8 +1308,10 @@ void WasmRegAlloc::AssignIntervals(jitstd::vector& intervals, Physica }; auto laterEnd = [](Interval* a, Interval* b) { - return a->end > b->end; + // Compare intervals by end first to expire old intervals earlier then by tracked index to break ties. + return (a->end != b->end) ? a->end > b->end : a->trackedIdx > b->trackedIdx; }; + PriorityQueue activeQueue(m_compiler->getAllocator(CMK_LSRA), laterEnd); auto expireOld = [&](Interval* current) { @@ -1325,7 +1327,8 @@ void WasmRegAlloc::AssignIntervals(jitstd::vector& intervals, Physica }; jitstd::sort(intervals.begin(), intervals.end(), [](Interval* a, Interval* b) { - return a->start < b->start; + // Sort intervals by start first to process earlier intervals first, then use tracked index to break ties. + return (a->start != b->start) ? a->start < b->start : a->trackedIdx < b->trackedIdx; }); for (Interval* interval : intervals)