From 8b975b86dcd106246fd203a851c4fa4509277148 Mon Sep 17 00:00:00 2001 From: Nino Floris Date: Sun, 29 Nov 2026 19:31:38 +0100 Subject: [PATCH 1/2] Reuse destination locals as CSE temporaries Keep the destination store and its SSA name when a single CSE definition feeds a local. For a local with multiple definitions, walk backwards from each replacement use to verify that the same store reaches it on every path. Preserve constant propagation for reused locals and use a fresh temp when the destination must remain visible to an exception handler. --- src/coreclr/jit/compiler.h | 4 +- src/coreclr/jit/optcse.cpp | 204 +++++++++++++++--- src/coreclr/jit/optcse.h | 2 +- src/tests/JIT/opt/CSE/StoreLocalTempReuse.cs | 79 +++++++ .../JIT/opt/CSE/StoreLocalTempReuse.csproj | 9 + 5 files changed, 265 insertions(+), 33 deletions(-) create mode 100644 src/tests/JIT/opt/CSE/StoreLocalTempReuse.cs create mode 100644 src/tests/JIT/opt/CSE/StoreLocalTempReuse.csproj diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index 9862f5639afd60..51165b3353d148 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -554,6 +554,7 @@ class LclVarDsc unsigned char lvInSsa : 1; // The variable is in SSA form (set by SsaBuilder) unsigned char lvIsCSE : 1; // Indicates if this LclVar is a CSE variable. + unsigned char lvIsCSEReuse : 1; // Existing local reused by CSE, retaining normal constant propagation. unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local. unsigned char lvHasILStoreOp : 1; // there is at least one STLOC or STARG on this local @@ -8120,7 +8121,8 @@ class Compiler // bool lclNumIsCSE(unsigned lclNum) const { - return lvaGetDesc(lclNum)->lvIsCSE; + const LclVarDsc* varDsc = lvaGetDesc(lclNum); + return varDsc->lvIsCSE && !varDsc->lvIsCSEReuse; } #ifdef DEBUG diff --git a/src/coreclr/jit/optcse.cpp b/src/coreclr/jit/optcse.cpp index f346f1cc869828..281f5a5dc138b6 100644 --- a/src/coreclr/jit/optcse.cpp +++ b/src/coreclr/jit/optcse.cpp @@ -5041,15 +5041,100 @@ bool CSE_HeuristicCommon::IsCompatibleType(var_types cseLclVarTyp, var_types exp } //------------------------------------------------------------------------ -// PerformCSE: takes a successful candidate and performs the appropriate replacements +// CseStoreReachesAllUses: Can each CSE use read the value written by store? // -// Arguments: -// successfulCandidate - cse candidate to perform -// -// It will replace all of the CSE defs with writes to a new "cse0" LclVar -// and will replace all of the CSE uses with reads of the "cse0" LclVar +static bool CseStoreReachesAllUses(Compiler* comp, CSEdsc* dsc, GenTreeLclVar* store) +{ + LclVarDsc* varDsc = comp->lvaGetDesc(store); + bool onlyDef = true; + for (unsigned i = 0; i < varDsc->lvPerSsaData.GetCount(); i++) + { + GenTreeLclVarCommon* def = varDsc->lvPerSsaData.GetSsaDefByIndex(i)->GetDefNode(); + if ((def != nullptr) && (def != store)) + { + onlyDef = false; + break; + } + } + // The single CSE definition already dominates the uses. + if (onlyDef) + { + return true; + } + if (comp->compHndBBtabCount > 0) + { + return false; + } + + // Pruned SSA can omit a phi where we are about to add a use. Check each incoming + // path back to its first store, including paths around backedges. + BitVecTraits traits(comp->compBasicBlockID, comp); + BitVec visited = BitVecOps::MakeEmpty(&traits); + ArrayStack pending(comp->getAllocator(CMK_CSE)); + const int useIndex = static_cast(dsc->csdIndex); + auto checkPrefix = [&](BasicBlock* block, Statement* stmt, GenTree* tree) { + while (stmt != nullptr) + { + for (; tree != nullptr; tree = tree->gtPrev) + { + if (tree->OperIsLocalStore() && (tree->AsLclVarCommon()->GetLclNum() == store->GetLclNum())) + { + return tree == store; + } + if (tree->gtCSEnum == useIndex) + { + // The earlier use has the same reaching value and is checked separately. + return true; + } + } + if (stmt == block->firstStmt()) + { + break; + } + stmt = stmt->GetPrevStmt(); + tree = stmt->GetRootNode(); + } + + if (block == comp->fgFirstBB) + { + return false; + } + for (FlowEdge* edge : block->PredEdges()) + { + BasicBlock* pred = edge->getSourceBlock(); + if (BitVecOps::TryAddElemD(&traits, visited, pred->bbID)) + { + pending.Push(pred); + } + } + return true; + }; + + for (treeStmtLst* use = &dsc->csdTreeList; use != nullptr; use = use->tslNext) + { + if ((use->tslTree->gtCSEnum == useIndex) && !checkPrefix(use->tslBlock, use->tslStmt, use->tslTree->gtPrev)) + { + return false; + } + } + while (!pending.Empty()) + { + BasicBlock* block = pending.Pop(); + Statement* stmt = block->lastStmt(); + if (!checkPrefix(block, stmt, (stmt == nullptr) ? nullptr : stmt->GetRootNode())) + { + return false; + } + } + return true; +} + +//------------------------------------------------------------------------ +// PerformCSE: Store definitions in a CSE temp or reusable destination local, +// replace uses with local reads, and update SSA where possible. // -// It will also put cse0 into SSA if there is just one def. +// Arguments: +// successfulCandidate - the candidate to transform // void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate) { @@ -5090,20 +5175,58 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate) #endif // DEBUG - // Allocate a CSE temp - // - unsigned cseLclVarNum = m_compiler->lvaGrabTemp(false DEBUGARG(grabTempMessage)); - var_types cseLclVarTyp = genActualType(successfulCandidate->Expr()->TypeGet()); + // Reuse the destination of a single CSE definition to avoid a temp and copy. + UseDefLocation reuseDef; + if ((dsc->csdDefCount == 1) && !successfulCandidate->IsSharedConst()) + { + for (treeStmtLst* defLst = &dsc->csdTreeList; defLst != nullptr; defLst = defLst->tslNext) + { + GenTree* const defExp = defLst->tslTree; + if (!IS_CSE_DEF(defExp->gtCSEnum)) + { + continue; + } + + // A STORE_LCL_VAR immediately follows its only operand in execution order. + GenTree* parent = defExp->gtNext; + if ((parent != nullptr) && parent->OperIs(GT_STORE_LCL_VAR) && (parent->AsLclVar()->Data() == defExp)) + { + GenTreeLclVar* store = parent->AsLclVar(); + LclVarDsc* varDsc = m_compiler->lvaGetDesc(store); + if (store->HasSsaName() && !varDsc->IsAddressExposed() && !varDsc->lvDoNotEnregister && + !(varDsc->lvTracked && varDsc->IsLiveInOutOfHandler()) && !varDsc->lvIsCSE && + !varTypeIsStruct(varDsc) && (varDsc->TypeGet() == genActualType(defExp->TypeGet())) && + CseStoreReachesAllUses(m_compiler, dsc, store)) + { + reuseDef = UseDefLocation(defLst->tslBlock, defLst->tslStmt, store); + } + } + break; + } + } + + unsigned cseLclVarNum = (reuseDef.Tree != nullptr) ? reuseDef.Tree->GetLclNum() + : m_compiler->lvaGrabTemp(false DEBUGARG(grabTempMessage)); + var_types cseLclVarTyp = genActualType(successfulCandidate->Expr()->TypeGet()); + LclVarDsc* const lclDsc = m_compiler->lvaGetDesc(cseLclVarNum); - LclVarDsc* const lclDsc = m_compiler->lvaGetDesc(cseLclVarNum); - if (cseLclVarTyp == TYP_STRUCT) + if (reuseDef.Tree != nullptr) { - m_compiler->lvaSetStruct(cseLclVarNum, successfulCandidate->Expr()->GetLayout(m_compiler), false); + JITDUMP("Using V%02u, which the definition is stored to, as the temp for " FMT_CSE "\n", cseLclVarNum, + dsc->csdIndex); + } + else + { + if (cseLclVarTyp == TYP_STRUCT) + { + m_compiler->lvaSetStruct(cseLclVarNum, successfulCandidate->Expr()->GetLayout(m_compiler), false); + } + lclDsc->lvType = cseLclVarTyp; } - lclDsc->lvType = cseLclVarTyp; - lclDsc->lvIsCSE = true; + lclDsc->lvIsCSE = true; + lclDsc->lvIsCSEReuse = reuseDef.Tree != nullptr; - // Record that we created a new LclVar for use as a CSE temp + // Record the CSE temp // m_addCSEcount++; m_compiler->optCSEcount++; @@ -5263,6 +5386,14 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate) } #endif // DEBUG + if (reuseDef.Tree != nullptr) + { + // The store that consumes the value is the definition. + reuseDef.Tree->gtCSEnum = exp->gtCSEnum; + exp->gtCSEnum = NO_CSE; + continue; + } + GenTree* val = exp; if (isSharedConst) { @@ -5339,7 +5470,8 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate) defUses.Emplace(blk, stmt, cseLclVar); } - bool insertIntoSsa = ssaBuilder.FinalizeDefs(); + IncrementalLiveInBuilder liveInBuilder(m_compiler); + bool insertIntoSsa = (reuseDef.Tree == nullptr) && ssaBuilder.FinalizeDefs(); // Start out by inserting all the uses we created as part of defs into SSA. if (insertIntoSsa) @@ -5347,7 +5479,8 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate) JITDUMP("Inserting each use created for defs into SSA\n"); for (UseDefLocation& defUse : defUses.BottomUpOrder()) { - InsertUseIntoSsa(ssaBuilder, defUse); + ssaBuilder.InsertUse(defUse); + AdoptReachingDefVN(defUse.Tree); } } @@ -5440,10 +5573,24 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate) ReplaceCSENode(stmt, exp, cse); - if (insertIntoSsa) + if (insertIntoSsa || (reuseDef.Tree != nullptr)) { - ValueNumPair oldLclVNP = cseLclVar->gtVNPair; - InsertUseIntoSsa(ssaBuilder, UseDefLocation(blk, stmt, cseLclVar)); + ValueNumPair oldLclVNP = cseLclVar->gtVNPair; + UseDefLocation useLoc(blk, stmt, cseLclVar); + if (reuseDef.Tree != nullptr) + { + unsigned ssaNum = reuseDef.Tree->GetSsaNum(); + JITDUMP("Inserting use [%06u] of V%02u d:%u into SSA\n", Compiler::dspTreeID(cseLclVar), cseLclVarNum, + ssaNum); + cseLclVar->SetSsaNum(ssaNum); + liveInBuilder.MarkLiveInBackwards(cseLclVarNum, useLoc, reuseDef); + m_compiler->lvaGetDesc(cseLclVar)->GetPerSsaData(ssaNum)->AddUse(blk); + } + else + { + ssaBuilder.InsertUse(useLoc); + } + AdoptReachingDefVN(cseLclVar); // Update conservative VN of comma node in case we changed // conservative VNs due to a new reaching def @@ -5508,19 +5655,14 @@ void CSE_HeuristicCommon::ReplaceCSENode(Statement* stmt, GenTree* exp, GenTree* } //------------------------------------------------------------------------ -// InsertUseIntoSsa: -// Insert a use into SSA form, updating its conservative VN to match its -// reaching definition in the process. +// AdoptReachingDefVN: +// Give a CSE temp use the value number of its reaching definition. // // Parameters: -// ssaBuilder - Incremental SSA builder that has already had definitions inserted -// useDefLoc - Location of the new use +// lcl - The use, already in SSA // -void CSE_HeuristicCommon::InsertUseIntoSsa(IncrementalSsaBuilder& ssaBuilder, const UseDefLocation& useDefLoc) +void CSE_HeuristicCommon::AdoptReachingDefVN(GenTreeLclVar* lcl) { - ssaBuilder.InsertUse(useDefLoc); - - GenTreeLclVar* lcl = useDefLoc.Tree; assert(lcl->HasSsaName()); LclVarDsc* lclDsc = m_compiler->lvaGetDesc(lcl); diff --git a/src/coreclr/jit/optcse.h b/src/coreclr/jit/optcse.h index 3d2def44ec635c..6afccb663048c0 100644 --- a/src/coreclr/jit/optcse.h +++ b/src/coreclr/jit/optcse.h @@ -117,7 +117,7 @@ class CSE_HeuristicCommon private: void ReplaceCSENode(Statement* stmt, GenTree* exp, GenTree* newNode); - void InsertUseIntoSsa(class IncrementalSsaBuilder& ssaBuilder, const struct UseDefLocation& useDefLoc); + void AdoptReachingDefVN(GenTreeLclVar* lcl); }; #ifdef DEBUG diff --git a/src/tests/JIT/opt/CSE/StoreLocalTempReuse.cs b/src/tests/JIT/opt/CSE/StoreLocalTempReuse.cs new file mode 100644 index 00000000000000..029137f80f84d3 --- /dev/null +++ b/src/tests/JIT/opt/CSE/StoreLocalTempReuse.cs @@ -0,0 +1,79 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.CompilerServices; +using Xunit; + +// Covers reusing a CSE definition's store local when the local has other +// definitions. Uses of each local are separated by control flow because +// consecutive reads let Roslyn forward the value through a stack dup, which +// the importer spills to a fresh lone-definition temp, and the shape under +// test never forms. + +namespace StoreLocalTempReuse +{ + public class StoreLocalTempReuse + { + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Consume(int value) + { + } + + // The store of a * a + a kills the earlier definition of x on every + // path to every use, so x is reusable as the CSE temp even though it + // has another definition. + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)] + private static int PriorDefKilledByStore(bool t, int a, int b) + { + int x = b + 1; + if (t) + { + Consume(x); + } + Consume(x); + x = a * a + a; + if (t) + { + Consume(x); + } + Consume(x); + return a * a + a; + } + + // The later definition of x sits on a path that does not dominate the + // final expression, and x is dead at the join, so pruned SSA has no + // phi there. x must not become the CSE temp: on the taken path it + // holds b + 3 when the final expression is evaluated. + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)] + private static int NonDominatingDefReachesUse(bool t, bool u, int a, int b) + { + int x = a * a + a; + if (t) + { + Consume(x); + } + Consume(x); + if (t) + { + x = b + 3; + if (u) + { + Consume(x); + } + Consume(x); + } + return a * a + a; + } + + [Fact] + public static void TestEntryPoint() + { + const int expected = 5 * 5 + 5; + Assert.Equal(expected, PriorDefKilledByStore(false, 5, 9)); + Assert.Equal(expected, PriorDefKilledByStore(true, 5, 9)); + Assert.Equal(expected, NonDominatingDefReachesUse(false, false, 5, 1000)); + Assert.Equal(expected, NonDominatingDefReachesUse(true, false, 5, 1000)); + Assert.Equal(expected, NonDominatingDefReachesUse(true, true, 5, 1000)); + } + } +} diff --git a/src/tests/JIT/opt/CSE/StoreLocalTempReuse.csproj b/src/tests/JIT/opt/CSE/StoreLocalTempReuse.csproj new file mode 100644 index 00000000000000..c677e927384fd0 --- /dev/null +++ b/src/tests/JIT/opt/CSE/StoreLocalTempReuse.csproj @@ -0,0 +1,9 @@ + + + None + True + + + + + From 3e2c7aa5c117a8fe7399a332e4436b95ed4e59da Mon Sep 17 00:00:00 2001 From: Nino Floris Date: Mon, 30 Nov 2026 21:11:04 +0100 Subject: [PATCH 2/2] Limit costly constant propagation from reused CSE locals Recognize reused destinations as CSE temps and handle their propagation in assertion propagation and VN folding. When a local has multiple stores and can stay in a register, keep the read if the constant costs more to materialize. Allow propagation when it can eliminate the only store or avoid a stack load. --- src/coreclr/jit/assertionprop.cpp | 76 +++++++++++++++++++++++++++++-- src/coreclr/jit/compiler.h | 3 +- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/src/coreclr/jit/assertionprop.cpp b/src/coreclr/jit/assertionprop.cpp index fe7e0e5f29c0e2..b7fcbc58bca12f 100644 --- a/src/coreclr/jit/assertionprop.cpp +++ b/src/coreclr/jit/assertionprop.cpp @@ -3477,6 +3477,50 @@ GenTree* Compiler::optVNBasedFoldConstExpr(BasicBlock* block, GenTree* parent, G } } +//------------------------------------------------------------------------------ +// lclHasSingleSsaStoreDef: Checks if a local in SSA has exactly one store definition +// +// Arguments: +// varDsc - the local's descriptor +// +// Returns: +// True if exactly one SSA definition has a defining store node +// +static bool lclHasSingleSsaStoreDef(LclVarDsc* varDsc) +{ + unsigned storeDefs = 0; + for (unsigned i = 0; i < varDsc->lvPerSsaData.GetCount(); i++) + { + if (varDsc->lvPerSsaData.GetSsaDefByIndex(i)->GetDefNode() != nullptr) + { + storeDefs++; + } + } + return storeDefs == 1; +} + +//------------------------------------------------------------------------------ +// isCheapIntegralConstant: Estimate the cost of substituting an integer constant +// +// Arguments: +// value - the constant's value +// +// Returns: +// True if the value is cheap enough on this target to replace a register read. +// +static bool isCheapIntegralConstant(ssize_t value) +{ +#if defined(TARGET_ARM64) + return emitter::emitIns_valid_imm_for_add(value, EA_8BYTE) || emitter::emitIns_valid_imm_for_mov(value, EA_8BYTE); +#elif defined(TARGET_AMD64) + return GenTreeIntConCommon::FitsInI32(value); +#elif defined(TARGET_X86) + return true; +#else + return (value >= -0x10000) && (value <= 0xFFFF); +#endif +} + //------------------------------------------------------------------------------ // optIsProfitableToSubstitute: Checks if value worth substituting to dest // @@ -3509,6 +3553,18 @@ bool Compiler::optIsProfitableToSubstitute(GenTree* dest, BasicBlock* destBlock, const GenTreeLclVar* lcl = dest->AsLclVar(); + // A reused local with multiple stores may stay in a register after this use is folded. + // Keep the register read if substituting the constant would materialize it again at greater cost. + LclVarDsc* const lclDsc = lvaGetDesc(lcl); + if (lclDsc->lvIsCSE && !lclDsc->lvDoNotEnregister && !lclDsc->lvHasLdAddrOp && !lclHasSingleSsaStoreDef(lclDsc)) + { + gtPrepareCost(value); + if (value->IsIconHandle() || (value->GetCostEx() > 1) || (value->GetCostSz() > 4)) + { + return false; + } + } + if (value->IsCnsVec()) { #if defined(FEATURE_HW_INTRINSICS) @@ -3614,9 +3670,20 @@ GenTree* Compiler::optConstantAssertionProp(const AssertionDsc& curAssertion, if (lclNumIsCSE(lclNum)) { + // Propagation can eliminate a single-store local or save a load from a stack local. + // For other reused locals, compare the cost of the immediate with a register read. + LclVarDsc* const varDsc = lvaGetDesc(lclNum); + bool cheapConst = false; + if ((curAssertion.GetOp2().GetKind() == O2K_CONST_INT) && !curAssertion.GetOp2().HasIconFlag()) + { + cheapConst = isCheapIntegralConstant((ssize_t)curAssertion.GetOp2().GetIntConstant()); + } + const bool reuseAllows = varDsc->lvIsCSEReuse && (cheapConst || varDsc->lvDoNotEnregister || + varDsc->lvHasLdAddrOp || lclHasSingleSsaStoreDef(varDsc)); + // Ignore the CSE flag in Global Assertion Prop for checked bound as those usually // unlock more opportunities for BCE. - if (optLocalAssertionProp || !vnStore->IsVNCheckedBound(optConservativeNormalVN(tree))) + if (!reuseAllows && (optLocalAssertionProp || !vnStore->IsVNCheckedBound(optConservativeNormalVN(tree)))) { return nullptr; } @@ -6684,12 +6751,15 @@ Compiler::fgWalkResult Compiler::optVNBasedFoldCurStmt(BasicBlock* block, case GT_LCL_VAR: case GT_LCL_FLD: - // Let's not conflict with CSE (to save the movw/movt). - if (lclNumIsCSE(tree->AsLclVarCommon()->GetLclNum())) + { + // Preserve fresh CSE temps. For reused locals, optIsProfitableToSubstitute checks the replacement cost. + LclVarDsc* const lclDsc = lvaGetDesc(tree->AsLclVarCommon()->GetLclNum()); + if (lclDsc->lvIsCSE && !lclDsc->lvIsCSEReuse) { return WALK_CONTINUE; } break; + } case GT_CALL: // The checks aren't for correctness, but to avoid unnecessary work. diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index 51165b3353d148..90ca6f77551d44 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -8121,8 +8121,7 @@ class Compiler // bool lclNumIsCSE(unsigned lclNum) const { - const LclVarDsc* varDsc = lvaGetDesc(lclNum); - return varDsc->lvIsCSE && !varDsc->lvIsCSEReuse; + return lvaGetDesc(lclNum)->lvIsCSE; } #ifdef DEBUG