From 6d66a5caf0ce9fd31c45715ad089689d43ca6fd1 Mon Sep 17 00:00:00 2001 From: Bruce Forstall Date: Mon, 22 Jan 2024 23:30:25 -0800 Subject: [PATCH 1/2] Fix handling of loop alignment targets Now that `BBJ_COND` block false target is not necessarily fall-through, the loop alignment code needs to consider the false target as what induces a loop via a false target back edge. Also, stop marking blocks after possible loop back edges for aligned loops as needing labels; they do not need to be so marked. --- src/coreclr/jit/codegencommon.cpp | 2 - src/coreclr/jit/codegenlinear.cpp | 58 +++-- src/coreclr/jit/compiler.cpp | 4 +- src/coreclr/jit/emit.cpp | 345 ++++++++++++++++-------------- 4 files changed, 207 insertions(+), 202 deletions(-) diff --git a/src/coreclr/jit/codegencommon.cpp b/src/coreclr/jit/codegencommon.cpp index 133403e2f9d2bd..a0d95f2773e61c 100644 --- a/src/coreclr/jit/codegencommon.cpp +++ b/src/coreclr/jit/codegencommon.cpp @@ -327,11 +327,9 @@ void CodeGen::genPrepForCompiler() // 1. the target of jumps (fall-through flow doesn't require a label), // 2. referenced labels such as for "switch" codegen, // 3. needed to denote the range of EH regions to the VM. -// 4. needed to denote the range of code for alignment processing. // // No labels will be in the IR before now, but future codegen might annotate additional blocks // with this flag, such as "switch" codegen, or codegen-created blocks from genCreateTempLabel(). -// Also, the alignment processing code marks BBJ_COND fall-through labels elsewhere. // // To report exception handling information to the VM, we need the size of the exception // handling regions. To compute that, we need to emit labels for the beginning block of diff --git a/src/coreclr/jit/codegenlinear.cpp b/src/coreclr/jit/codegenlinear.cpp index 67f4bb73c0eb18..6968df2c4e65e2 100644 --- a/src/coreclr/jit/codegenlinear.cpp +++ b/src/coreclr/jit/codegenlinear.cpp @@ -643,6 +643,25 @@ void CodeGen::genCodeForBBlist() } #endif // TARGET_AMD64 +#if FEATURE_LOOP_ALIGN + auto SetLoopAlignBackEdge = [=](BasicBlock* target) { + // This is the last place where we operate on blocks and after this, we operate + // on IG. Hence, if we know that the destination of "block" is the first block + // of a loop and that loop needs alignment (it has BBF_LOOP_ALIGN), then "block" + // might represent the lexical end of the loop. Propagate that information on the + // IG through "igLoopBackEdge". + // + // During emitter, this information will be used to calculate the loop size. + // Depending on the loop size, the decision of whether to align a loop or not will be taken. + // (Loop size is calculated by walking the instruction groups; see emitter::getLoopSize()). + + if (target->isLoopAlign()) + { + GetEmitter()->emitSetLoopBackEdge(target); + } + }; +#endif // FEATURE_LOOP_ALIGN + /* Do we need to generate a jump or return? */ switch (block->GetKind()) @@ -746,45 +765,16 @@ void CodeGen::genCodeForBBlist() } #if FEATURE_LOOP_ALIGN - // This is the last place where we operate on blocks and after this, we operate - // on IG. Hence, if we know that the destination of "block" is the first block - // of a loop and needs alignment (it has BBF_LOOP_ALIGN), then "block" represents - // end of the loop. Propagate that information on the IG through "igLoopBackEdge". - // - // During emitter, this information will be used to calculate the loop size. - // Depending on the loop size, decision of whether to align a loop or not will be taken. - // - // In the emitter, we need to calculate the loop size from `block->bbTarget` through - // `block` (inclusive). Thus, we need to ensure there is a label on the lexical fall-through - // block, even if one is not otherwise needed, to be able to calculate the size of this - // loop (loop size is calculated by walking the instruction groups; see emitter::getLoopSize()). - - if (block->GetTarget()->isLoopAlign()) - { - GetEmitter()->emitSetLoopBackEdge(block->GetTarget()); - - if (!block->IsLast()) - { - JITDUMP("Mark " FMT_BB " as label: alignment end-of-loop\n", block->Next()->bbNum); - block->Next()->SetFlags(BBF_HAS_LABEL); - } - } + SetLoopAlignBackEdge(block->GetTarget()); #endif // FEATURE_LOOP_ALIGN break; case BBJ_COND: #if FEATURE_LOOP_ALIGN - if (block->GetTrueTarget()->isLoopAlign()) - { - GetEmitter()->emitSetLoopBackEdge(block->GetTrueTarget()); - - if (!block->IsLast()) - { - JITDUMP("Mark " FMT_BB " as label: alignment end-of-loop\n", block->Next()->bbNum); - block->Next()->SetFlags(BBF_HAS_LABEL); - } - } + // Either true or false target of BBJ_COND can induce a loop. + SetLoopAlignBackEdge(block->GetTrueTarget()); + SetLoopAlignBackEdge(block->GetFalseTarget()); #endif // FEATURE_LOOP_ALIGN break; @@ -824,7 +814,7 @@ void CodeGen::genCodeForBBlist() GetEmitter()->emitConnectAlignInstrWithCurIG(); } } -#endif +#endif // FEATURE_LOOP_ALIGN #ifdef DEBUG if (compiler->verbose) diff --git a/src/coreclr/jit/compiler.cpp b/src/coreclr/jit/compiler.cpp index bd8cd590eea537..c677a903943963 100644 --- a/src/coreclr/jit/compiler.cpp +++ b/src/coreclr/jit/compiler.cpp @@ -5318,8 +5318,8 @@ bool Compiler::shouldAlignLoop(FlowGraphNaturalLoop* loop, BasicBlock* top) if (top->Prev()->isBBCallFinallyPairTail()) { - // If the previous block is the BBJ_ALWAYS of a - // BBJ_CALLFINALLY/BBJ_ALWAYS pair, then we can't add alignment + // If the previous block is the BBJ_CALLFINALLYRET of a + // BBJ_CALLFINALLY/BBJ_CALLFINALLYRET pair, then we can't add alignment // because we can't add instructions in that block. In the // FEATURE_EH_CALLFINALLY_THUNKS case, it would affect the // reported EH, as above. diff --git a/src/coreclr/jit/emit.cpp b/src/coreclr/jit/emit.cpp index b6adc24d275206..008fb1ddde0138 100644 --- a/src/coreclr/jit/emit.cpp +++ b/src/coreclr/jit/emit.cpp @@ -5620,14 +5620,14 @@ void emitter::emitCheckAlignFitInCurIG(unsigned nAlignInstr) } //----------------------------------------------------------------------------- +// emitLoopAlign: The next instruction will be a loop head. Insert an alignment instruction +// here so we can properly align the code. // -// emitLoopAlign: The next instruction will be a loop head entry point -// So insert an alignment instruction of "paddingBytes" to ensure that -// the code is properly aligned. // Arguments: // paddingBytes - Number of padding bytes to insert. // isFirstAlign - For multiple 'align' instructions case, if this is the first // 'align' instruction of that group. +// isPlacedBehindJmp - DEBUG only. 'true' if this align instruction is placed after an unconditional jump. // void emitter::emitLoopAlign(unsigned paddingBytes, bool isFirstAlign DEBUG_ARG(bool isPlacedBehindJmp)) { @@ -5693,16 +5693,15 @@ void emitter::emitLoopAlign(unsigned paddingBytes, bool isFirstAlign DEBUG_ARG(b } //----------------------------------------------------------------------------- -// -// emitLongLoopAlign: The next instruction will be a loop head entry point -// So insert alignment instruction(s) here to ensure that -// we can properly align the code. +// emitLongLoopAlign: The next instruction will be a loop head. Insert alignment instruction(s) +// here so we can properly align the code. // // This emits more than one `INS_align` instruction depending on the // alignmentBoundary parameter. // // Arguments: // alignmentBoundary - The boundary at which loop needs to be aligned. +// isPlacedBehindJmp - DEBUG only. 'true' if this align instruction is placed after an unconditional jump. // void emitter::emitLongLoopAlign(unsigned alignmentBoundary DEBUG_ARG(bool isPlacedBehindJmp)) { @@ -5811,24 +5810,27 @@ bool emitter::emitEndsWithAlignInstr() } //----------------------------------------------------------------------------- -// getLoopSize: Starting from loopHeaderIg, find the size of the smallest possible loop +// getLoopSize: Starting from igLoopHeader, find the size of the smallest possible loop // such that it doesn't exceed the maxLoopSize. // // Arguments: -// igLoopHeader - The header IG of a loop -// maxLoopSize - Maximum loop size. If the loop is bigger than this value, we will just -// return this value. -// isAlignAdjusted - Determine if adjustments are done to the align instructions or not. -// During generating code, it is 'false' (because we haven't adjusted the size yet). -// During outputting code, it is 'true'. -// containingIGNum - IG number of IG that contains the current align instruction we are processing. -// loopHeadPredIGNum - IG number of IG that preceds the IG that we are aligning with current align instruction. +// igLoopHeader - The header IG of a loop +// maxLoopSize - Maximum loop size. If the loop is bigger than this value, we will just +// return this value. +// isAlignAdjusted - DEBUG only. Determine if adjustments are done to the align instructions or not. +// During generating code, it is 'false' (because we haven't adjusted the size yet). +// During outputting code, it is 'true'. +// containingIGNum - DEBUG only. IG number of IG that contains the current align instruction we are processing. +// loopHeadPredIGNum - DEBUG only. IG number of IG that precedes the IG that we are aligning with current align +// instruction. // // Returns: size of a loop in bytes. // unsigned emitter::getLoopSize(insGroup* igLoopHeader, - unsigned maxLoopSize DEBUG_ARG(bool isAlignAdjusted) - DEBUG_ARG(UNATIVE_OFFSET containingIGNum) DEBUG_ARG(UNATIVE_OFFSET loopHeadPredIGNum)) + unsigned maxLoopSize // + DEBUG_ARG(bool isAlignAdjusted) // + DEBUG_ARG(UNATIVE_OFFSET containingIGNum) // + DEBUG_ARG(UNATIVE_OFFSET loopHeadPredIGNum)) { unsigned loopSize = 0; @@ -5841,44 +5843,45 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, if (igInLoop->endsWithAlignInstr() || igInLoop->hadAlignInstr()) { -// If IGF_HAS_ALIGN is present, igInLoop contains align instruction at the end, -// for next IG or some future IG. -// -// For both cases, remove the padding bytes from igInLoop's size so it is not included in loopSize. -// -// If the loop was formed because of forward jumps like the loop IG18 below, the backedge is not -// set for them and such loops are not aligned. For such cases, the loop size threshold will never -// be met and we would break as soon as loopSize > maxLoopSize. -// -// IG05: -// ... -// jmp IG18 -// ... -// IG18: -// ... -// jne IG05 -// -// If igInLoop is a legitimate loop, and igInLoop's end with another 'align' instruction for different IG -// representing a loop that needs alignment, then igInLoop should be the last IG of the current loop and -// should have backedge to current loop header. -// -// Below, IG05 is the last IG of loop IG04-IG05 and its backedge points to IG04. -// -// IG03: -// ... -// align -// IG04: -// ... -// ... -// IG05: -// ... -// jne IG04 -// align ; <--- -// IG06: -// ... -// jne IG06 -// -// + // If IGF_HAS_ALIGN is present, igInLoop contains align instruction at the end, + // for next IG or some future IG. + // + // For both cases, remove the padding bytes from igInLoop's size so it is not included in loopSize. + // + // If the loop was formed because of forward jumps like the loop IG18 below, the backedge is not + // set for them and such loops are not aligned. For such cases, the loop size threshold will never + // be met and we would break as soon as loopSize > maxLoopSize. + // + // IG05: + // ... + // jmp IG18 + // ... + // IG18: + // ... + // jne IG05 + // + // If igInLoop is a legitimate loop, and igInLoop's end with another 'align' instruction for different IG + // representing a loop that needs alignment, then igInLoop should be the last IG of the current loop and + // should have backedge to current loop header. + // + // Below, IG05 is the last IG of loop IG04-IG05 and its backedge points to IG04. + // + // IG03: + // ... + // align + // IG04: + // ... + // ... + // IG05: + // ... + // jne IG04 + // align ; <--- + // IG06: + // ... + // jne IG06 + // + // + CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if ((igInLoop->igLoopBackEdge != nullptr) && (igInLoop->igLoopBackEdge != igLoopHeader)) @@ -5889,8 +5892,8 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, written += sprintf_s(buffer + written, 100, "loopHeadPredIG: IG%02u\n", loopHeadPredIGNum); written += sprintf_s(buffer + written, 100, "loopHeadIG: IG%02u\n", igLoopHeader->igNum); written += sprintf_s(buffer + written, 100, "igInLoop: IG%02u\n", igInLoop->igNum); - written += - sprintf_s(buffer + written, 100, "igInLoop->backEdge: IG%02u\n", igInLoop->igLoopBackEdge->igNum); + written += sprintf_s(buffer + written, 100, "igInLoop->igLoopBackEdge: IG%02u\n", + igInLoop->igLoopBackEdge->igNum); #if EMIT_BACKWARDS_NAVIGATION if (igInLoop->endsWithAlignInstr()) @@ -5904,16 +5907,19 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, #endif // EMIT_BACKWARDS_NAVIGATION written += sprintf_s(buffer + written, 35, "Loop:\n"); - for (insGroup* igInLoop = igLoopHeader; igInLoop != nullptr; igInLoop = igInLoop->igNext) + insGroup* igIter; + for (igIter = igLoopHeader; (igIter != nullptr) && (igIter->igLoopBackEdge != igLoopHeader); + igIter = igIter->igNext) { - if (igInLoop->igLoopBackEdge == igLoopHeader) - { - break; - } - written += sprintf_s(buffer + written, 100, "\tIG%02u\n", igInLoop->igNum); + written += sprintf_s(buffer + written, 100, "\tIG%02u\n", igIter->igNum); + } + if (igIter == nullptr) + { + written += sprintf_s(buffer + written, 100, "Did not find IG with back edge to IG%02u\n", + igLoopHeader->igNum); } - printf("%s", buffer); - assert(false); + printf("\n\n%s", buffer); + assert(false && !"Mismatch in align instruction"); } if (isAlignAdjusted) @@ -5951,7 +5957,7 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, loopSize -= adjustedPadding; } else -#endif +#endif // DEBUG { JITDUMP(" but ends with align instruction, taking off %u bytes.", emitComp->opts.compJitAlignPaddingLimit); @@ -5964,14 +5970,14 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, #ifdef DEBUG if (igInLoop->igLoopBackEdge == igLoopHeader) { - JITDUMP(" -- Found the back edge."); + JITDUMP(" -- Found the back edge.\n"); } else { - JITDUMP(" -- loopSize exceeded the threshold of %u bytes.", maxLoopSize); + JITDUMP(" -- loopSize exceeded the threshold of %u bytes.\n", maxLoopSize); } - JITDUMP("\n"); -#endif +#endif // DEBUG + break; } JITDUMP("\n"); @@ -5986,122 +5992,132 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, // if currIG has back-edge to dstIG. // // Notes: -// Despite we align only inner most loop, we might see intersected loops because of control flow +// Although we align only inner-most loops, we might see intersected loops because of control flow // re-arrangement like adding a split edge in LSRA. // // If there is an intersection of current loop with last loop that is already marked as align, -// then *do not align* one of the loop that completely encloses the other one. Or if they both intersect, -// then *do not align* either of them because since the flow is complicated enough that aligning one of them -// will not improve the performance. +// then *do not align* one of the loops that completely encloses the other one. Or if they both intersect, +// then *do not align* either of them since the flow is complicated enough that aligning one of them +// will not improve performance. // void emitter::emitSetLoopBackEdge(BasicBlock* loopTopBlock) { - insGroup* dstIG = (insGroup*)loopTopBlock->bbEmitCookie; - bool alignCurrentLoop = true; - bool alignLastLoop = true; + insGroup* dstIG = (insGroup*)loopTopBlock->bbEmitCookie; + if (dstIG == nullptr) + { + // This is a forward branch. + JITDUMP("ALIGN: loop block " FMT_BB + " needing alignment has not been generated yet; not marking IG back edge.\n", + loopTopBlock->bbNum); + return; + } - // With (dstIG != nullptr), ensure that only back edges are tracked. - // If there is forward jump, dstIG is not yet generated. - // - // We don't rely on (block->GetTarget()->bbNum <= block->bbNum) because the basic - // block numbering is not guaranteed to be sequential. - if ((dstIG != nullptr) && (dstIG->igNum <= emitCurIG->igNum)) + if (dstIG->igNum > emitCurIG->igNum) { - unsigned currLoopStart = dstIG->igNum; - unsigned currLoopEnd = emitCurIG->igNum; + // Is this possible? + JITDUMP("ALIGN: found forward branch from IG%02u to IG%02u; not marking IG back edge.\n", emitCurIG->igNum, + dstIG->igNum); + return; + } - // Only mark back-edge if current loop starts after the last inner loop ended. - if (emitLastLoopEnd < currLoopStart) - { - emitCurIG->igLoopBackEdge = dstIG; + bool alignCurrentLoop = true; + bool alignLastLoop = true; - JITDUMP("** IG%02u jumps back to IG%02u forming a loop.\n", currLoopEnd, currLoopStart); + unsigned currLoopStart = dstIG->igNum; + unsigned currLoopEnd = emitCurIG->igNum; - emitLastLoopStart = currLoopStart; - emitLastLoopEnd = currLoopEnd; - } - else if (currLoopStart == emitLastLoopStart) - { - // Note: If current and last loop starts at same point, - // retain the alignment flag of the smaller loop. - // | - // .---->|<----. - // last | | | - // loop | | | current - // .---->| | loop - // | | - // |-----. - // - } - else if ((currLoopStart < emitLastLoopStart) && (emitLastLoopEnd < currLoopEnd)) - { - // if current loop completely encloses last loop, - // then current loop should not be aligned. - alignCurrentLoop = false; - } - else if ((emitLastLoopStart < currLoopStart) && (currLoopEnd < emitLastLoopEnd)) - { - // if last loop completely encloses current loop, - // then last loop should not be aligned. - alignLastLoop = false; - } - else - { - // The loops intersect and should not align either of the loops - alignLastLoop = false; - alignCurrentLoop = false; - } + // Only mark back-edge if current loop starts after the last inner loop ended. + if (emitLastLoopEnd < currLoopStart) + { + assert(emitCurIG->igLoopBackEdge == nullptr); + emitCurIG->igLoopBackEdge = dstIG; - if (!alignLastLoop || !alignCurrentLoop) - { - instrDescAlign* alignInstr = emitAlignList; - bool markedLastLoop = alignLastLoop; - bool markedCurrLoop = alignCurrentLoop; - while ((alignInstr != nullptr)) - { - insGroup* loopHeadIG = alignInstr->loopHeadIG(); + JITDUMP("** IG%02u jumps back to IG%02u forming a loop.\n", currLoopEnd, currLoopStart); - // Find the IG that has 'align' instruction to align the current loop - // and clear the IGF_HAS_ALIGN flag. - if (!alignCurrentLoop && (loopHeadIG == dstIG)) - { - assert(!markedCurrLoop); + emitLastLoopStart = currLoopStart; + emitLastLoopEnd = currLoopEnd; + } + else if (currLoopStart == emitLastLoopStart) + { + // Note: If current and last loop start at the same point, + // retain the alignment flag of the smaller loop. + // | + // .---->|<----. + // last | | | + // loop | | | current + // .---->| | loop + // | | + // |-----. + // + } + else if ((currLoopStart < emitLastLoopStart) && (emitLastLoopEnd < currLoopEnd)) + { + // if current loop completely encloses last loop, + // then current loop should not be aligned. + alignCurrentLoop = false; + } + else if ((emitLastLoopStart < currLoopStart) && (currLoopEnd < emitLastLoopEnd)) + { + // if last loop completely encloses current loop, + // then last loop should not be aligned. + alignLastLoop = false; + } + else + { + // The loops intersect and should not align either of the loops + alignLastLoop = false; + alignCurrentLoop = false; + } - // This IG should no longer contain alignment instruction - alignInstr->removeAlignFlags(); + if (!alignLastLoop || !alignCurrentLoop) + { + instrDescAlign* alignInstr = emitAlignList; + bool markedLastLoop = alignLastLoop; + bool markedCurrLoop = alignCurrentLoop; + while (alignInstr != nullptr) + { + insGroup* loopHeadIG = alignInstr->loopHeadIG(); - markedCurrLoop = true; - JITDUMP(";; Skip alignment for current loop IG%02u ~ IG%02u because it encloses an aligned loop " - "IG%02u ~ IG%02u.\n", - currLoopStart, currLoopEnd, emitLastLoopStart, emitLastLoopEnd); - } + // Find the IG that has 'align' instruction to align the current loop + // and clear the IGF_HAS_ALIGN flag. + if (!alignCurrentLoop && (loopHeadIG == dstIG)) + { + assert(!markedCurrLoop); - // Find the IG that has 'align' instruction to align the last loop - // and clear the IGF_HAS_ALIGN flag. - if (!alignLastLoop && (loopHeadIG != nullptr) && (loopHeadIG->igNum == emitLastLoopStart)) - { - assert(!markedLastLoop); - assert(alignInstr->idaIG->endsWithAlignInstr() || alignInstr->idaIG->hadAlignInstr()); + // This IG should no longer contain alignment instruction + alignInstr->removeAlignFlags(); - // This IG should no longer contain alignment instruction - alignInstr->removeAlignFlags(); + markedCurrLoop = true; + JITDUMP(";; Skip alignment for current loop IG%02u ~ IG%02u because it encloses an aligned loop " + "IG%02u ~ IG%02u.\n", + currLoopStart, currLoopEnd, emitLastLoopStart, emitLastLoopEnd); + } - markedLastLoop = true; - JITDUMP(";; Skip alignment for aligned loop IG%02u ~ IG%02u because it encloses the current loop " - "IG%02u ~ IG%02u.\n", - emitLastLoopStart, emitLastLoopEnd, currLoopStart, currLoopEnd); - } + // Find the IG that has 'align' instruction to align the last loop + // and clear the IGF_HAS_ALIGN flag. + if (!alignLastLoop && (loopHeadIG != nullptr) && (loopHeadIG->igNum == emitLastLoopStart)) + { + assert(!markedLastLoop); + assert(alignInstr->idaIG->endsWithAlignInstr() || alignInstr->idaIG->hadAlignInstr()); - if (markedLastLoop && markedCurrLoop) - { - break; - } + // This IG should no longer contain alignment instruction + alignInstr->removeAlignFlags(); + + markedLastLoop = true; + JITDUMP(";; Skip alignment for aligned loop IG%02u ~ IG%02u because it encloses the current loop " + "IG%02u ~ IG%02u.\n", + emitLastLoopStart, emitLastLoopEnd, currLoopStart, currLoopEnd); + } - alignInstr = emitAlignInNextIG(alignInstr); + if (markedLastLoop && markedCurrLoop) + { + break; } - assert(markedLastLoop && markedCurrLoop); + alignInstr = emitAlignInNextIG(alignInstr); } + + assert(markedLastLoop && markedCurrLoop); } } @@ -6448,6 +6464,7 @@ unsigned emitter::emitCalculatePaddingForLoopAlignment(insGroup* loopHeadIG, return paddingToAdd; } +//----------------------------------------------------------------------------- // emitAlignInNextIG: On xarch, for adaptive alignment, this will usually return the next instruction in // 'emitAlignList'. But for arm64 or non-adaptive alignment on xarch, where multiple // align instructions are emitted, this method will skip the 'align' instruction present From b4cb68b9b4c2381322d6dee7b68f8f213aba4e5b Mon Sep 17 00:00:00 2001 From: Bruce Forstall Date: Tue, 23 Jan 2024 12:02:05 -0800 Subject: [PATCH 2/2] Restore setting label on BasicBlock after setting `igLoopBackEdge` This minimizes the size of an aligned loop by `getLoopSize`. Also, add `superpmi.py asmdiffs --alignloops` argument to allow specifying that you want to run asmdiffs with loop alignment enabled. By default, asmdiffs is done with loop alignment disabled, to avoid too many extraneous diffs. --- src/coreclr/jit/block.h | 2 +- src/coreclr/jit/codegencommon.cpp | 1 - src/coreclr/jit/codegenlinear.cpp | 23 ++++++++++++++++++----- src/coreclr/jit/compiler.hpp | 2 +- src/coreclr/jit/emit.cpp | 23 +++++++++++++++++++---- src/coreclr/jit/emit.h | 2 +- src/coreclr/scripts/superpmi.py | 12 ++++++++++-- 7 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/coreclr/jit/block.h b/src/coreclr/jit/block.h index 0760baaab01659..539dda93281fc8 100644 --- a/src/coreclr/jit/block.h +++ b/src/coreclr/jit/block.h @@ -2224,7 +2224,7 @@ inline PredBlockList::iterator& PredBlockList::iterator::operator++() * emitter to convert a basic block to its corresponding emitter cookie. */ -void* emitCodeGetCookie(BasicBlock* block); +void* emitCodeGetCookie(const BasicBlock* block); // An enumerator of a block's all successors. In some cases (e.g. SsaBuilder::TopologicalSort) // using iterators is not exactly efficient, at least because they contain an unnecessary diff --git a/src/coreclr/jit/codegencommon.cpp b/src/coreclr/jit/codegencommon.cpp index a0d95f2773e61c..c7c60788599776 100644 --- a/src/coreclr/jit/codegencommon.cpp +++ b/src/coreclr/jit/codegencommon.cpp @@ -2586,7 +2586,6 @@ void CodeGen::genReportEH() } else { - assert(bbLabel->bbEmitCookie != nullptr); hndEnd = compiler->ehCodeOffset(bbLabel); } diff --git a/src/coreclr/jit/codegenlinear.cpp b/src/coreclr/jit/codegenlinear.cpp index 6968df2c4e65e2..08b35cc501cca7 100644 --- a/src/coreclr/jit/codegenlinear.cpp +++ b/src/coreclr/jit/codegenlinear.cpp @@ -644,7 +644,7 @@ void CodeGen::genCodeForBBlist() #endif // TARGET_AMD64 #if FEATURE_LOOP_ALIGN - auto SetLoopAlignBackEdge = [=](BasicBlock* target) { + auto SetLoopAlignBackEdge = [=](const BasicBlock* block, const BasicBlock* target) { // This is the last place where we operate on blocks and after this, we operate // on IG. Hence, if we know that the destination of "block" is the first block // of a loop and that loop needs alignment (it has BBF_LOOP_ALIGN), then "block" @@ -654,10 +654,23 @@ void CodeGen::genCodeForBBlist() // During emitter, this information will be used to calculate the loop size. // Depending on the loop size, the decision of whether to align a loop or not will be taken. // (Loop size is calculated by walking the instruction groups; see emitter::getLoopSize()). + // If `igLoopBackEdge` is set, then mark the next BasicBlock as a label. This will cause + // the emitter to create a new IG for the next block. Otherwise, if the next block + // did not have a label, additional instructions might be added to the current IG. This + // would make the "back edge" IG larger, possibly causing the size of the loop computed + // by `getLoopSize()` to be larger than actual, which could push the loop size over the + // threshold of loop size that can be aligned. if (target->isLoopAlign()) { - GetEmitter()->emitSetLoopBackEdge(target); + if (GetEmitter()->emitSetLoopBackEdge(target)) + { + if (!block->IsLast()) + { + JITDUMP("Mark " FMT_BB " as label: alignment end-of-loop\n", block->Next()->bbNum); + block->Next()->SetFlags(BBF_HAS_LABEL); + } + } } }; #endif // FEATURE_LOOP_ALIGN @@ -765,7 +778,7 @@ void CodeGen::genCodeForBBlist() } #if FEATURE_LOOP_ALIGN - SetLoopAlignBackEdge(block->GetTarget()); + SetLoopAlignBackEdge(block, block->GetTarget()); #endif // FEATURE_LOOP_ALIGN break; @@ -773,8 +786,8 @@ void CodeGen::genCodeForBBlist() #if FEATURE_LOOP_ALIGN // Either true or false target of BBJ_COND can induce a loop. - SetLoopAlignBackEdge(block->GetTrueTarget()); - SetLoopAlignBackEdge(block->GetFalseTarget()); + SetLoopAlignBackEdge(block, block->GetTrueTarget()); + SetLoopAlignBackEdge(block, block->GetFalseTarget()); #endif // FEATURE_LOOP_ALIGN break; diff --git a/src/coreclr/jit/compiler.hpp b/src/coreclr/jit/compiler.hpp index a4cc4bcd13c089..3694af6ae3f356 100644 --- a/src/coreclr/jit/compiler.hpp +++ b/src/coreclr/jit/compiler.hpp @@ -3488,7 +3488,7 @@ inline void Compiler::compUpdateLife(VARSET_VALARG_TP newLife) * the cookie associated with the given basic block. */ -inline void* emitCodeGetCookie(BasicBlock* block) +inline void* emitCodeGetCookie(const BasicBlock* block) { assert(block); return block->bbEmitCookie; diff --git a/src/coreclr/jit/emit.cpp b/src/coreclr/jit/emit.cpp index 008fb1ddde0138..bcbb819f582e4b 100644 --- a/src/coreclr/jit/emit.cpp +++ b/src/coreclr/jit/emit.cpp @@ -5991,6 +5991,12 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, // emitSetLoopBackEdge : Sets igLoopBackEdge field, if not already set and // if currIG has back-edge to dstIG. // +// Arguments: +// loopTopBlock - The target block of a branch instruction that is expected to be aligned. +// +// Returns: +// true if igLoopBackEdge is set, false otherwise. +// // Notes: // Although we align only inner-most loops, we might see intersected loops because of control flow // re-arrangement like adding a split edge in LSRA. @@ -6000,16 +6006,21 @@ unsigned emitter::getLoopSize(insGroup* igLoopHeader, // then *do not align* either of them since the flow is complicated enough that aligning one of them // will not improve performance. // -void emitter::emitSetLoopBackEdge(BasicBlock* loopTopBlock) +// This means that a call to this function might set `igLoopBackEdge`, but a subsequent call might remove +// the alignment instruction from the current IG (but not null out `igLoopBackEdge`). +// +bool emitter::emitSetLoopBackEdge(const BasicBlock* loopTopBlock) { - insGroup* dstIG = (insGroup*)loopTopBlock->bbEmitCookie; + assert(loopTopBlock->isLoopAlign()); + + insGroup* dstIG = (insGroup*)emitCodeGetCookie(loopTopBlock); if (dstIG == nullptr) { // This is a forward branch. JITDUMP("ALIGN: loop block " FMT_BB " needing alignment has not been generated yet; not marking IG back edge.\n", loopTopBlock->bbNum); - return; + return false; } if (dstIG->igNum > emitCurIG->igNum) @@ -6017,9 +6028,10 @@ void emitter::emitSetLoopBackEdge(BasicBlock* loopTopBlock) // Is this possible? JITDUMP("ALIGN: found forward branch from IG%02u to IG%02u; not marking IG back edge.\n", emitCurIG->igNum, dstIG->igNum); - return; + return false; } + bool backEdgeSet = false; bool alignCurrentLoop = true; bool alignLastLoop = true; @@ -6031,6 +6043,7 @@ void emitter::emitSetLoopBackEdge(BasicBlock* loopTopBlock) { assert(emitCurIG->igLoopBackEdge == nullptr); emitCurIG->igLoopBackEdge = dstIG; + backEdgeSet = true; JITDUMP("** IG%02u jumps back to IG%02u forming a loop.\n", currLoopEnd, currLoopStart); @@ -6119,6 +6132,8 @@ void emitter::emitSetLoopBackEdge(BasicBlock* loopTopBlock) assert(markedLastLoop && markedCurrLoop); } + + return backEdgeSet; } //----------------------------------------------------------------------------- diff --git a/src/coreclr/jit/emit.h b/src/coreclr/jit/emit.h index 5d629deaf95e19..15c312b194369e 100644 --- a/src/coreclr/jit/emit.h +++ b/src/coreclr/jit/emit.h @@ -2508,7 +2508,7 @@ class emitter DEBUG_ARG(UNATIVE_OFFSET loopHeadPredIGNum)); // Get the smallest loop size void emitLoopAlignment(DEBUG_ARG1(bool isPlacedBehindJmp)); bool emitEndsWithAlignInstr(); // Validate if newLabel is appropriate - void emitSetLoopBackEdge(BasicBlock* loopTopBlock); + bool emitSetLoopBackEdge(const BasicBlock* loopTopBlock); void emitLoopAlignAdjustments(); // Predict if loop alignment is needed and make appropriate adjustments unsigned emitCalculatePaddingForLoopAlignment(insGroup* ig, size_t offset DEBUG_ARG(bool isAlignAdjusted) diff --git a/src/coreclr/scripts/superpmi.py b/src/coreclr/scripts/superpmi.py index 23bd265620dfdb..baca765929ce4c 100644 --- a/src/coreclr/scripts/superpmi.py +++ b/src/coreclr/scripts/superpmi.py @@ -344,6 +344,7 @@ def add_core_root_arguments(parser, build_type_default, build_type_help): asm_diff_parser.add_argument("--diff_jit_dump", action="store_true", help="Generate JitDump output for diffs. Default: only generate asm, not JitDump.") asm_diff_parser.add_argument("--gcinfo", action="store_true", help="Include GC info in disassembly (sets DOTNET_JitGCDump; requires instructions to be prefixed by offsets).") asm_diff_parser.add_argument("--debuginfo", action="store_true", help="Include debug info after disassembly (sets DOTNET_JitDebugDump).") +asm_diff_parser.add_argument("--alignloops", action="store_true", help="Do diffs with loop alignment enabled (uses DOTNET_JitAlignLoops default; otherwise DOTNET_JitAlignLoops is set to zero (loop alignment disabled)).") asm_diff_parser.add_argument("-tag", help="Specify a word to add to the directory name where the asm diffs will be placed") asm_diff_parser.add_argument("-metrics", action="append", help="Metrics option to pass to jit-analyze. Can be specified multiple times, one for each metric.") asm_diff_parser.add_argument("--diff_with_release", action="store_true", help="Specify if this is asmdiff using release binaries.") @@ -1971,17 +1972,19 @@ def replay_with_asm_diffs(self): # These vars are force overridden in the SPMI runs for both the base and diff, always. replay_vars = { - "DOTNET_JitAlignLoops": "0", # disable loop alignment to filter noise "DOTNET_JitEnableNoWayAssert": "1", "DOTNET_JitNoForceFallback": "1", } + if not self.coreclr_args.alignloops: + replay_vars.update({ + "DOTNET_JitAlignLoops": "0" }) + # These vars are used in addition to the replay vars when creating disassembly for the interesting contexts asm_dotnet_vars = { "DOTNET_JitDisasm": "*", "DOTNET_JitUnwindDump": "*", "DOTNET_JitEHDump": "*", - "DOTNET_JitDiffableDasm": "1", # to be removed "DOTNET_JitDisasmDiffable": "1", "DOTNET_JitDisasmWithGC": "1" } @@ -4752,6 +4755,11 @@ def verify_base_diff_args(): lambda unused: True, "Unable to set debuginfo.") + coreclr_args.verify(args, + "alignloops", + lambda unused: True, + "Unable to set alignloops.") + coreclr_args.verify(args, "diff_jit_dump", lambda unused: True,