← Back to Pull requests

[DebugInfo] Preserve irlayers across inlining, remapping and hoisting #229615

Open
ayermolo opened this pull request with 1009 lines diff across 30 files
View on GitHub
ayermolo ayermolo commented on Oct 07, 2026 00:14 UTC
Author

Keep a DILocation's irlayers through the transformations that rebuild,
move or copy locations. The inliner, atom remapping and the
line-tables-only downgrade rebuilt locations without them, and hoisting
dropped them along with the source position.

Hoisting still drops the source position, because keeping it would
mislead single-stepping, but now keeps the layers on a line 0 location.
Layers are used by profilers, not debuggers, and moving an instruction
does not change what it was lowered from. LangRef and HowToUpdateDebugInfo
document this.

SimplifyCFG copies one branch's location onto another only if their
layers match too (new isSameSourceLocationAndIRLayers), so a branch
never takes another branch's layers.

Superseded by:
https://github.com/llvm/llvm-project/pull/242125
https://github.com/llvm/llvm-project/pull/242127
https://github.com/llvm/llvm-project/pull/242128
https://github.com/llvm/llvm-project/pull/242129

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

Diff: 1009 lines (+979 / -30) across 30 files Reviewer: enferex Review duration: 84954m
All Vouch review confidence checks passed
Residual risk 0.12 = Change Risk (0.84) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.84 · 1009 lines diff across 30 files
0.84
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.91 · 5 substantive comment(s)
0.91
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
85%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Mass File Touch mass_file_touch
0.080
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
19 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 07, 2026 00:14 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-debuginfo
@llvm/pr-subscribers-llvm-transforms

@llvm/pr-subscribers-llvm-ir

Author: Alexander Yermolovich (ayermolo)

<details>
<summary>Changes</summary>

Keep a DILocation's irlayers through the transformations that rebuild,
move or copy locations. The inliner, atom remapping and the
line-tables-only downgrade rebuilt locations without them, and hoisting
dropped them along with the source position.

Hoisting still drops the source position, because keeping it would
mislead single-stepping, but now keeps the layers on a line 0 location.
Layers are used by profilers, not debuggers, and moving an instruction
does not change what it was lowered from. LangRef and HowToUpdateDebugInfo
document this.

SimplifyCFG copies one branch's location onto another only if their
layers match too (new isSameSourceLocationAndIRLayers), so a branch
never takes another branch's layers.

Co-Authored-By: Claude Sonnet 4.6 (1M context) &lt;noreply@<!-- -->anthropic.com&gt;

---

Patch is 38.33 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/229615.diff

20 Files Affected:

  • (modified) llvm/docs/HowToUpdateDebugInfo.md (+8)

  • (modified) llvm/docs/LangRef.md (+5-1)

  • (modified) llvm/include/llvm/IR/DebugInfoMetadata.h (+8)

  • (modified) llvm/include/llvm/IR/DebugLoc.h (+13-2)

  • (modified) llvm/include/llvm/IR/Instruction.h (+5-1)

  • (modified) llvm/lib/IR/DebugInfo.cpp (+34-5)

  • (modified) llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp (+1-1)

  • (modified) llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp (+1-1)

  • (modified) llvm/lib/Transforms/Utils/InlineFunction.cpp (+7-2)

  • (modified) llvm/lib/Transforms/Utils/SimplifyCFG.cpp (+3-3)

  • (modified) llvm/lib/Transforms/Utils/ValueMapper.cpp (+4-3)

  • (added) llvm/test/Transforms/Inline/intermediate-loc-inline.ll (+43)

  • (added) llvm/test/Transforms/LICM/irlayers-hoist.ll (+43)

  • (added) llvm/test/Transforms/SimpleLoopUnswitch/irlayers-hoist.ll (+57)

  • (added) llvm/test/Transforms/SimplifyCFG/irlayers-atom-transfer.ll (+57)

  • (added) llvm/test/Transforms/SimplifyCFG/irlayers-hoist.ll (+110)

  • (added) llvm/test/Transforms/SpeculativeExecution/irlayers-hoist.ll (+37)

  • (added) llvm/test/Transforms/Util/strip-nonlinetable-debuginfo-irlayers.ll (+56)

  • (modified) llvm/unittests/IR/DebugInfoTest.cpp (+39)

  • (modified) llvm/unittests/IR/InstructionsTest.cpp (+97)
  • ``````

    diff --git a/llvm/docs/HowToUpdateDebugInfo.md b/llvm/docs/HowToUpdateDebugInfo.md
    index e1d528978bf63f..84be9e64cd76d0 100644
    --- a/llvm/docs/HowToUpdateDebugInfo.md
    +++ b/llvm/docs/HowToUpdateDebugInfo.md
    @@ -143,6 +143,14 @@ The purpose of this rule is to prevent erratic or misleading single-stepping
     behavior in situations in which an instruction has no clear, unambiguous
     relationship to a source location.
     
    +That purpose does not apply to a location's intermediate-IR layers (the
    +`irlayers:` field of a `DILocation`). Profilers use them to attribute machine
    +code to the intermediate IRs it was lowered through; they play no part in
    +single-stepping, and moving an instruction does not change what it was lowered
    +from. So when the instruction is hoisted into a predecessor block, use
    +`Instruction::updateLocationAfterHoist()` instead of `dropLocation()`: it drops
    +the source location the same way but keeps the layers.
    +
     To handle an instruction without a location, the DWARF generator
     defaults to allowing the last-set location after a label to cascade forward, or
     to setting a line 0 location with viable scope information if no previous
    diff --git a/llvm/docs/LangRef.md b/llvm/docs/LangRef.md
    index b653097152672d..ccf0cc04bf84a3 100644
    --- a/llvm/docs/LangRef.md
    +++ b/llvm/docs/LangRef.md
    @@ -7236,7 +7236,11 @@ addition to its primary source position. It is independent of `inlinedAt:`; a
     location may have either, both, or neither. A location with no intermediate
     position omits the field entirely. The field belongs to the location that
     carries it: locations in an `inlinedAt:` chain may each have their own, and LLVM
    -defines no relationship between them.
    +defines no relationship between them, with one exception. Hoisting an
    +instruction drops its source position but not its intermediate ones: if any
    +location in its `inlinedAt:` chain has layers, the instruction gets a line 0
    +location in the enclosing function's scope, with no `inlinedAt:`, that keeps the
    +layers of the innermost such location, starting with its own.
     
     
    text
    !0 = !DILocation(line: 2900, column: 42, scope: !1, irlayers: !3)
    diff --git a/llvm/include/llvm/IR/DebugInfoMetadata.h b/llvm/include/llvm/IR/DebugInfoMetadata.h
    index d53f8869827184..da2c264a06410c 100644
    --- a/llvm/include/llvm/IR/DebugInfoMetadata.h
    +++ b/llvm/include/llvm/IR/DebugInfoMetadata.h
    @@ -3090,6 +3090,14 @@ class DILocation : public MDNode {
    DILayerLocList getIRLayers() const {
    return cast_if_present<DILayerLocList>(getRawIRLayers());
    }
    + /// The layer list of the innermost location in this inlined-at chain that
    + /// has one, starting with this location; null if none does.
    + DILayerLocList
    getInnermostIRLayers() const {
    + for (const DILocation L = this; L; L = L->getInlinedAt())
    + if (DILayerLocList
    Layers = L->getIRLayers())
    + return Layers;
    + return nullptr;
    + }
    unsigned getNumLayers() const {
    DILayerLocList L = getIRLayers();
    return L ? L->getNumLayers() : 0;
    diff --git a/llvm/include/llvm/IR/DebugLoc.h b/llvm/include/llvm/IR/DebugLoc.h
    index 0d59fe06b68f53..8b74ce15b0626a 100644
    --- a/llvm/include/llvm/IR/DebugLoc.h
    +++ b/llvm/include/llvm/IR/DebugLoc.h
    @@ -245,8 +245,11 @@ class DebugLoc {
    appendInlinedAt(const DebugLoc &DL, DILocation
    InlinedAt, LLVMContext &Ctx,
    DenseMap<const MDNode , MDNode > &Cache);

  • /// Return true if the source locations match, ignoring isImplicitCode and

  • /// source atom info.

  • + /// Return true if the source locations match, ignoring isImplicitCode,
    + /// source atom info and intermediate-IR layers. Layers are deliberately not
    + /// part of this comparison: two locations at the same source position are the
    + /// same source position regardless of which intermediate IR they came from.
    + /// Callers that must also match layers use isSameSourceLocationAndIRLayers.
    bool isSameSourceLocation(const DebugLoc &Other) const {
    if (get() == Other.get())
    return true;
    @@ -255,6 +258,14 @@ class DebugLoc {
    getInlinedAt() == Other.getInlinedAt();
    }

    + /// As isSameSourceLocation, and additionally requires the intermediate-IR
    + /// layers to match. For callers that replace a location wholesale, or that
    + /// emit something derived from the layers.
    + bool isSameSourceLocationAndIRLayers(const DebugLoc &Other) const {
    + return isSameSourceLocation(Other) &&
    + getRawIRLayers() == Other.getRawIRLayers();
    + }
    +
    LLVM_ABI unsigned getLine() const;
    LLVM_ABI unsigned getCol() const;
    LLVM_ABI MDNode getScope() const;
    diff --git a/llvm/include/llvm/IR/Instruction.h b/llvm/include/llvm/IR/Instruction.h
    index 0ad9e4ff47b66d..8c12d93197137f 100644
    --- a/llvm/include/llvm/IR/Instruction.h
    +++ b/llvm/include/llvm/IR/Instruction.h
    @@ -747,7 +747,11 @@ class Instruction : public User,
    LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB);

    /// Updates the debug location given that the instruction has been hoisted
  • /// from a block to a predecessor of that block.

  • + /// from a block to a predecessor of that block. The source location is
    + /// dropped as by \ref dropLocation(), but intermediate-IR layers survive the
    + /// move: if the instruction has any (see
    + /// DILocation::getInnermostIRLayers()), it gets a line 0 location in the
    + /// function's scope that carries them.
    /// Note: it is undefined behavior to call this on an instruction not
    /// currently inserted into a function.
    LLVM_ABI void updateLocationAfterHoist();
    diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
    index 8a119a98784a6b..7b4bd93fa23d3b 100644
    --- a/llvm/lib/IR/DebugInfo.cpp
    +++ b/llvm/lib/IR/DebugInfo.cpp
    @@ -856,11 +856,16 @@ class DebugTypeInfoRemoval {
    DILocation
    getReplacementMDLocation(DILocation MLD) {
    auto
    Scope = map(MLD->getScope());
    auto InlinedAt = map(MLD->getInlinedAt());
    + // Intermediate-IR layers are line-table data (a line/column in a DIFile),
    + // so they survive the downgrade to line-tables-only.
    + Metadata
    IRLayers = map(MLD->getRawIRLayers());
    if (MLD->isDistinct())
  • return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),

  • MLD->getColumn(), Scope, InlinedAt);

  • + return DILocation::getDistinct(
    + MLD->getContext(), MLD->getLine(), MLD->getColumn(), Scope, InlinedAt,
    + /ImplicitCode=/false, /AtomGroup=/0, /AtomRank=/0, IRLayers);
    return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
  • Scope, InlinedAt);

  • + Scope, InlinedAt, /ImplicitCode=/false,
    + /AtomGroup=/0, /AtomRank=/0, IRLayers);
    }

    /// Create a new generic MDNode, to replace the one given
    @@ -892,6 +897,12 @@ class DebugTypeInfoRemoval {
    return getReplacementCU(CU);
    if (isa<DIFile>(N))
    return N;
    + // Intermediate-IR layer nodes hold only a kind string and a DIFile, so
    + // none of their content is part of the type hierarchy being stripped. The
    + // generic fallback below would rebuild them as plain MDTuples, which
    + // DILocation::getIRLayers() cannot cast.
    + if (isa<DILayerLoc>(N) || isa<DILayerLocList>(N))
    + return N;
    if (auto MDLB = dyn_cast<DILexicalBlockBase>(N))
    // Remap to our referenced scope (recursively).
    return mapNode(MDLB->getScope());
    @@ -995,8 +1006,12 @@ bool llvm::stripNonLineTableDebugInfo(Module &M) {
    MDNode
    InlinedAt = DL.getInlinedAt();
    Scope = remap(Scope);
    InlinedAt = remap(InlinedAt);
    + // Layers need no remapping (Mapper maps them to themselves), but they
    + // do need carrying over -- they are line-table data.
    return DILocation::get(M.getContext(), DL.getLine(), DL.getCol(),
  • Scope, InlinedAt);

  • + Scope, InlinedAt, /ImplicitCode=/false,
    + /AtomGroup=/0, /AtomRank=/0,
    + DL.getRawIRLayers());
    };

    if (I.getDebugLoc() != DebugLoc())
    @@ -1077,7 +1092,21 @@ void Instruction::mergeDIAssignID(
    setMetadata(LLVMContext::MD_DIAssignID, MergeID);
    }

    -void Instruction::updateLocationAfterHoist() { dropLocation(); }
    +void Instruction::updateLocationAfterHoist() {
    + const DebugLoc &DL = getDebugLoc();
    + DILayerLocList IRLayers = DL ? DL->getInnermostIRLayers() : nullptr;
    + DISubprogram
    SP = getFunction()->getSubprogram();
    + if (!IRLayers || !SP) {
    + dropLocation();
    + return;
    + }
    + // The function's scope, as dropLocation() uses for calls, so a hoisted
    + // instruction does not appear inside an inlined scope before that code is
    + // reached.
    + setDebugLoc(DILocation::get(getContext(), 0, 0, SP, /InlinedAt=/nullptr,
    + /ImplicitCode=/false, /AtomGroup=/0,
    + /AtomRank=/0, IRLayers));
    +}

    void Instruction::dropLocation() {
    const DebugLoc &DL = getDebugLoc();
    diff --git a/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp b/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
    index 310ef7c4f3548d..6ec0b85bf43843 100644
    --- a/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
    +++ b/llvm/lib/Transforms/Scalar/SimpleLoopUnswitch.cpp
    @@ -2177,7 +2177,7 @@ static void unswitchNontrivialInvariants(
    // Splice the terminator from the original loop and rewrite its
    // successors.
    TI.moveBefore(SplitBB, SplitBB->end());
  • TI.dropLocation();

  • + TI.updateLocationAfterHoist();

    // First wire up the moved terminator to the preheaders.
    if (BI) {
    diff --git a/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp b/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp
    index 0a2a3f8a495bf7..31b9ecae23362e 100644
    --- a/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp
    +++ b/llvm/lib/Transforms/Scalar/SpeculativeExecution.cpp
    @@ -319,7 +319,7 @@ bool SpeculativeExecutionPass::considerHoistingFromTo(
    ++I;
    if (!NotHoisted.count(&
    Current)) {
    Current->moveBefore(ToBlock.getTerminator()->getIterator());
  • Current->dropLocation();

  • + Current->updateLocationAfterHoist();
    }
    }
    return true;
    diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
    index a8eae7dcd5ec0f..1af9b835d51d85 100644
    --- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
    +++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
    @@ -1948,7 +1948,8 @@ static DebugLoc inlineDebugLoc(
    : InlinedAt;
    DILocation Result = DILocation::getDistinct(
    Ctx, OrigDL.getLine(), OrigDL.getCol(), OrigDL.getScope(), IA,
  • OrigDL.isImplicitCode(), OrigDL->getAtomGroup(), OrigDL->getAtomRank());

  • + OrigDL.isImplicitCode(), OrigDL->getAtomGroup(), OrigDL->getAtomRank(),
    + OrigDL.getRawIRLayers());
    InlineLocs[OrigDL.get()] = Result;
    return DebugLoc(Result);
    }
    @@ -1985,9 +1986,13 @@ static void fixupLineNumbers(Function
    Fn, Function::iterator FI,

    // Create a unique call site, not to be confused with any other call from the
    // same location.
    + // Preserve the call site's irlayers so the (outermost) inlined-at
    + // frame keeps its intermediate-IR snapshot instead of being stripped.
    InlinedAtNode = DILocation::getDistinct(
    Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(),
  • InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt());

  • + InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt(),
    + /ImplicitCode=/false, /AtomGroup=/0, /AtomRank=/0,
    + InlinedAtNode->getRawIRLayers());

    // Cache the inlined-at nodes as they're built so they are reused, without
    // this every instruction's inlined-at chain would become distinct from each
    diff --git a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
    index e3db3b230c2388..6d1d65d9c1d969 100644
    --- a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
    +++ b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
    @@ -1188,7 +1188,7 @@ static void cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(
    // branch, drop it. When we fold the bonus instructions we want to make
    // sure we reset their debug locations in order to avoid stepping on
    // dead code caused by folding dead branches.
  • NewBonusInst->dropLocation();

  • + NewBonusInst->updateLocationAfterHoist();
    } else if (const DebugLoc &DL = NewBonusInst->getDebugLoc()) {
    mapAtomInstance(DL, VMap);
    }
    @@ -1241,7 +1241,7 @@ static void cloneInstructionsIntoPredecessorBlockAndUpdateSSAUses(
    if (auto &PredDL = PTI->getDebugLoc()) {
    auto &DL = BB->getTerminator()->getDebugLoc();
    if (!PredDL->getAtomGroup() && DL && DL->getAtomGroup() &&
  • PredDL.isSameSourceLocation(DL)) {

  • + PredDL.isSameSourceLocationAndIRLayers(DL)) {
    PTI->setDebugLoc(DL);
    RemapSourceAtom(PTI, VMap);
    }
    @@ -3431,7 +3431,7 @@ bool SimplifyCFGOpt::speculativelyExecuteBB(CondBrInst BI,
    // hoisting above.
    for (auto &I : make_early_inc_range(
    ThenBB)) {
    if (!SpeculatedStoreValue || &I != SpeculatedStore) {
  • I.dropLocation();

  • + I.updateLocationAfterHoist();
    I.dropUBImplyingAttrsAndMetadata();
    } else {
    assert(PreviousStoreAccess && "Missing previous store access");
    diff --git a/llvm/lib/Transforms/Utils/ValueMapper.cpp b/llvm/lib/Transforms/Utils/ValueMapper.cpp
    index 22230c352bf01c..ee506afe06f123 100644
    --- a/llvm/lib/Transforms/Utils/ValueMapper.cpp
    +++ b/llvm/lib/Transforms/Utils/ValueMapper.cpp
    @@ -1332,8 +1332,9 @@ void llvm::RemapSourceAtom(Instruction I, ValueToValueMapTy &VM) {
    AtomGroup = R->second;

    // Remap the atom group and copy all other fields.
  • DILocation New = DILocation::get(

  • I->getContext(), DL.getLine(), DL.getCol(), DL.getScope(),

  • DL.getInlinedAt(), DL.isImplicitCode(), AtomGroup, DL->getAtomRank());

  • + DILocation New =
    + DILocation::get(I->getContext(), DL.getLine(), DL.getCol(), DL.getScope(),
    + DL.getInlinedAt(), DL.isImplicitCode(), AtomGroup,
    + DL->getAtomRank(), DL.getRawIRLayers());
    I->setDebugLoc(New);
    }
    diff --git a/llvm/test/Transforms/Inline/intermediate-loc-inline.ll b/llvm/test/Transforms/Inline/intermediate-loc-inline.ll
    new file mode 100644
    index 00000000000000..817410015cb87f
    --- /dev/null
    +++ b/llvm/test/Transforms/Inline/intermediate-loc-inline.ll
    @@ -0,0 +1,43 @@
    +; RUN: opt %s -passes='always-inline' -S | FileCheck %s
    +
    +;; The store's location has no layers of its own; they are on the location it
    +;; is inlined at. Inlining @outer into @caller appends the call site to the
    +;; chain, and the location in @outer must keep its layers.
    +
    +define void @outer(ptr %p) alwaysinline !dbg !6 {
    + store ptr null, ptr %p, align 8, !dbg !9
    + ret void, !dbg !8
    +}
    +
    +define void @caller(ptr %p) !dbg !12 {
    + call void @outer(ptr %p), !dbg !15
    + ret void, !dbg !16
    +}
    +
    +; CHECK-LABEL: define void @caller
    +; CHECK: store ptr null, ptr %p,{{.
    }} !dbg ![[INST:[0-9]+]]
    +; CHECK-DAG: ![[INST]] = distinct !DILocation(line: 6, column: 1, scope: ![[HELPER:[0-9]+]], inlinedAt: ![[OUTER:[0-9]+]])
    +; CHECK-DAG: ![[OUTER]] = distinct !DILocation(line: 11, column: 1, scope: ![[OUTER_SP:[0-9]+]], inlinedAt: ![[CS:[0-9]+]], irlayers: ![[LIST:[0-9]+]])
    +; CHECK-DAG: ![[CS]] = distinct !DILocation(line: 15, column: 1, scope: ![[CALLER:[0-9]+]])
    +; CHECK-DAG: ![[LIST]] = !DILayerLocList(![[LAYER:[0-9]+]])
    +; CHECK-DAG: ![[LAYER]] = !DILayerLoc(line: 100, column: 1, file: {{![0-9]+}}, kind: "IntermediateIR")
    +
    +!llvm.dbg.cu = !{!0}
    +!llvm.module.flags = !{!3}
    +
    +!0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug)
    +!1 = !DIFile(filename: "test.c", directory: "/")
    +!3 = !{i32 2, !"Debug Info Version", i32 3}
    +!4 = !DISubroutineType(types: !5)
    +!5 = !{null}
    +!6 = distinct !DISubprogram(name: "outer", scope: !1, file: !1, line: 10, type: !4, spFlags: DISPFlagDefinition, unit: !0)
    +!7 = distinct !DISubprogram(name: "helper", scope: !1, file: !1, line: 5, type: !4, spFlags: DISPFlagDefinition, unit: !0)
    +!8 = !DILocation(line: 10, column: 1, scope: !6)
    +!9 = !DILocation(line: 6, column: 1, scope: !7, inlinedAt: !10)
    +!10 = !DILocation(line: 11, column: 1, scope: !6, irlayers: !17)
    +!12 = distinct !DISubprogram(name: "caller", scope: !1, file: !1, line: 20, type: !4, spFlags: DISPFlagDefinition, unit: !0)
    +!15 = !DILocation(line: 15, column: 1, scope: !12)
    +!16 = !DILocation(line: 16, column: 1, scope: !12)
    +!17 = !DILayerLocList(!19)
    +!18 = !DIFile(filename: "intermediate.ir", directory: "/")
    +!19 = !DILayerLoc(line: 100, column: 1, file: !18, kind: "IntermediateIR")
    diff --git a/llvm/test/Transforms/LICM/irlayers-hoist.ll b/llvm/test/Transforms/LICM/irlayers-hoist.ll
    new file mode 100644
    index 00000000000000..fcd3d7e3414a0a
    --- /dev/null
    +++ b/llvm/test/Transforms/LICM/irlayers-hoist.ll
    @@ -0,0 +1,43 @@
    +; RUN: opt -S -passes=licm < %s | FileCheck %s
    +
    +;; An instruction hoisted to the preheader gets a line 0 location in the
    +;; function's scope that keeps its layers.
    +
    +define void @f(i32 %x, i32 %n, ptr %p) !dbg !4 {
    +; CHECK-LABEL: define void @f(
    +; CHECK-SAME: !dbg ![[SP:[0-9]+]]
    +; CHECK: entry:
    +; CHECK-NEXT: %inv = mul i32 %x, %x, !dbg ![[INV:[0-9]+]]
    +; CHECK-NEXT: br label %loop
    +entry:
    + br label %loop
    +
    +loop:
    + %i = phi i32 [ 0, %entry ], [ %i.next, %loop ]
    + %inv = mul i32 %x, %x, !dbg !8
    + %gep = getelementptr i32, ptr %p, i32 %i
    + store i32 %inv, ptr %gep
    + %i.next = add i32 %i, 1
    + %done = icmp eq i32 %i.next, %n
    + br i1 %done, label %exit, label %loop
    +
    +exit:
    + ret void
    +}
    +
    +; CHECK: ![[INV]] = !DILocation(line: 0, scope: ![[SP]], irlayers: ![[LIST:[0-9]+]])
    +; CHECK-NEXT: ![[LIST]] = !DILayerLocList(![[LAYER:[0-9]+]])
    +; CHECK-NEXT: ![[LAYER]] = !DILayerLoc(line: 100,
    +
    +!llvm.dbg.cu = !{!0}
    +!llvm.module.flags = !{!3}
    +
    +!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug)
    +!1 = !DIFile(filename: "test.c", directory: "/tmp")
    +!2 = !DISubroutineType(types: !{})
    +!3 = !{i32 2, !"Debug Info Version", i32 3}
    +!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !2, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0)
    +!5 = !DIFile(filename: "intermediate.ir", directory: "/tmp")
    +!6 = !DILayerLoc(line: 100, column: 1, file: !5, kind: "IntermediateIR")
    +!7 = !DILayerLocList(!6)
    +!8 = !DILocation(line: 5, column: 9, scope: !4, irlayers: !7)
    diff --git a/llvm/test/Transforms/SimpleLoopUnswitch/irlayers-hoist.ll b/llvm/test/Transforms/SimpleLoopUnswitch/irlayers-hoist.ll
    new file mode 100644
    index 00000000000000..8ed2546ffb72f9
    --- /dev/null
    +++ b/llvm/test/Transforms/SimpleLoopUnswitch/irlayers-hoist.ll
    @@ -0,0 +1,57 @@
    +; RUN: opt -passes='simple-loop-unswitch<nontrivial>' -S < %s | FileCheck %s
    +
    +;; The unswitched branch, hoisted out of the loop, gets a line 0 location in the
    +;; function's scope that keeps its layers.
    +
    +declare void @a()
    +declare void @b()
    +
    +define void @f(i32 %n, i1 %c) !dbg !4 {
    +; CHECK-LABEL: define void @f(
    +; CHECK-SAME: !dbg ![[SP:[0-9]+]]
    +; CHECK: entry:
    +; CHECK-NEXT: %c.fr = freeze i1 %c{{$}}
    +; CHECK-NEXT: br i1 %c.fr, label %{{.}}, label %{{.}}, !dbg ![[HOISTED:[0-9]+]]
    +entry:
    + br label %loop
    +
    +loop:
    + %i = phi i32 [ 0, %entry ], [ %inc, %latch ]
    + %cmp = icmp slt i32 %i, %n
    + br i1 %cmp, label %body, label %exit
    +
    +body:
    + br i1 %c, label %then, label %else, !dbg !8
    +
    +then:
    + call void @a()
    + br label %latch
    +
    +else:
    + call void @b()
    + br label %latch
    +
    +latch:
    + %inc = add nuw nsw i32 %i, 1
    + br label %loop
    +
    +exit:
    + ret void
    +}
    +
    +; CHECK: ![[HOISTED]] = !DILocation(line: 0, scope: ![[SP]], irlayers: ![[LIST:[0-9]+]])
    +; CHECK-NEXT: ![[LIST]] = !DILayerLocList(![[LAYER:[0-9]+]])
    +; CHECK-NEXT: ![[LAYER]] = !DILayerLoc(line: 100,
    +
    +!llvm.dbg.cu = !{!0}
    +!llvm.module.flags = !{!3}
    +
    +!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug)
    +!1 = !DIFile(filename: "test.c", directory: "/tmp")
    +!2 = !DISubroutineType(types: !{})
    +!3 = !{i32 2, !"Debug Info Version", i32 3}
    +!4 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type:...
    [truncated]

    `````````

    </details>

    enferex enferex commented on code on Oct 08, 2026 16:20 UTC
    Code Review
    llvm/include/llvm/IR/DebugLoc.h:1
    @@ -255,6 +258,14 @@ class DebugLoc {
                getInlinedAt() == Other.getInlinedAt();
       }
     
    +  /// As isSameSourceLocation, and additionally requires the intermediate-IR

    I'm not entirely sure I understand the grammar here: "As isSameSourceLocation," are you trying to say that this function behaves in a similar manner as isSameSourceLocation?

    enferex enferex commented on code on Oct 08, 2026 16:22 UTC
    Code Review
    llvm/include/llvm/IR/DebugInfoMetadata.h:1
    @@ -3090,6 +3090,14 @@ class DILocation : public MDNode {
       DILayerLocList *getIRLayers() const {
         return cast_if_present<DILayerLocList>(getRawIRLayers());
       }
    +  /// The layer list of the innermost location in this inlined-at chain that

    This is probably just a misunderstanding on my behalf, but is the shallowest DILayerLocList the innermost? In other words, the first layer list found is returned, by "innermost", I was expecting the deepest/last layer list.

    enferex enferex commented on code on Oct 08, 2026 16:53 UTC
    Code Review
    llvm/docs/HowToUpdateDebugInfo.md:1
    @@ -143,6 +143,14 @@ The purpose of this rule is to prevent erratic or misleading single-stepping
     behavior in situations in which an instruction has no clear, unambiguous
     relationship to a source location.
     
    +That purpose does not apply to a location's intermediate-IR layers (the
    +`irlayers:` field of a `DILocation`). Profilers use them to attribute machine
    +code to the intermediate IRs it was lowered through; they play no part in
    +single-stepping, and moving an instruction does not change what it was lowered
    +from. So when the instruction is hoisted into a predecessor block, use
    +`Instruction::updateLocationAfterHoist()` instead of `dropLocation()`: it drops

    Given the original updateLocationAfterHoist was a wrapper around dropLocation I'm wondering, if there are other calls to dropLocation, not in the hoisting context, that might benefit from preserving the layers? If so, would it make sense to add a bool param to dropLocation that would inform the function to preserve the layers?

    ayermolo ayermolo commented on code on Oct 10, 2026 00:11 UTC
    Code Review
    llvm/docs/HowToUpdateDebugInfo.md:1
    @@ -143,6 +143,14 @@ The purpose of this rule is to prevent erratic or misleading single-stepping
     behavior in situations in which an instruction has no clear, unambiguous
     relationship to a source location.
     
    +That purpose does not apply to a location's intermediate-IR layers (the
    +`irlayers:` field of a `DILocation`). Profilers use them to attribute machine
    +code to the intermediate IRs it was lowered through; they play no part in
    +single-stepping, and moving an instruction does not change what it was lowered
    +from. So when the instruction is hoisted into a predecessor block, use
    +`Instruction::updateLocationAfterHoist()` instead of `dropLocation()`: it drops

    Good call missed some, and updated API name.
    As for bool, I think a new API conveys better the intent then "overloading" dropLocation with bool.

    ayermolo ayermolo commented on code on Oct 10, 2026 00:12 UTC
    Code Review
    llvm/include/llvm/IR/DebugInfoMetadata.h:1
    @@ -3090,6 +3090,14 @@ class DILocation : public MDNode {
       DILayerLocList *getIRLayers() const {
         return cast_if_present<DILayerLocList>(getRawIRLayers());
       }
    +  /// The layer list of the innermost location in this inlined-at chain that

    Updated verbage.
    Every time I think about it, I have to draw a diagram. lol

    ayermolo ayermolo commented on code on Oct 10, 2026 00:12 UTC
    Code Review
    llvm/include/llvm/IR/DebugLoc.h:1
    @@ -255,6 +258,14 @@ class DebugLoc {
                getInlinedAt() == Other.getInlinedAt();
       }
     
    +  /// As isSameSourceLocation, and additionally requires the intermediate-IR

    better?

    enferex enferex approved these changes on Oct 12, 2026 10:46 UTC
    Approved Reviewer

    LGTM, but would be good to get another approval.

    ayermolo ayermolo commented on Oct 16, 2026 22:18 UTC
    Author

    @echristo updated based on internal feedback.
    I left GVN alone (just added comment), as it's for sample PGO, and I think following the same logic is fine for irlayers.

    github-actions[bot] github-actions[bot] commented on Oct 17, 2026 03:08 UTC
    Bot

    <!--PREMERGE ADVISOR COMMENT: Linux-->

    :penguin: Linux x64 Test Results

    181428 tests passed
    4277 tests skipped

    :white_check_mark: The build succeeded and all tests passed.

    github-actions[bot] github-actions[bot] commented on Oct 17, 2026 03:08 UTC
    Bot

    <!--PREMERGE ADVISOR COMMENT: Windows-->

    :window: Windows x64 Test Results

    146993 tests passed
    2296 tests skipped

    :white_check_mark: The build succeeded and all tests passed.

    ayermolo ayermolo commented on Oct 21, 2026 17:13 UTC
    Author

    @jmorse can you take a look? This is 2/3 PR that is primarily in general llvm.
    The last one is in NVPTX BE.

    jmorse jmorse commented on code on Oct 29, 2026 21:22 UTC
    Code Review
    llvm/lib/Transforms/Scalar/GVNHoist.cpp:1
    @@ -1113,8 +1113,14 @@ std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) {
           DFSNumber[Repl] = DFSNumber[Last]++;
         }
     
    -    // Drop debug location as per debug info update guide.
    -    Repl->dropLocation();
    +    // Drop the source position as per the debug info update guide, keeping
    +    // only the intermediate-IR layers all the hoisted instructions share (or,
    +    // with -pick-merged-source-locations, the picked location's layers).
    +    SmallVector<DebugLoc> Locs;
    +    for (Instruction *I : InstructionsToHoist)
    +      Locs.push_back(I->getDebugLoc());
    +    Repl->setDebugLoc(DebugLoc::getMergedLocations(Locs));

    Please move the addition of getMergedLocations to a separate PR with a separate test please -- it's too complicated to review multiple dimensions of change all at once.

    jmorse jmorse commented on Oct 29, 2026 21:54 UTC
    Reviewer

    This broadly seems good, I think the move to preserve /some/ source information when we would otherwise completely drop it is relevant to @ZequanWu 's interests,

    The diffstat for this change is +800 lines, largely tests, and IMO it looks like it easily decomposes into individual passes being tested. To ease reviewing, could you please instead open a PR per pass changed, or perhaps decompose into small groupings of changes in several PRs if there are groups of the same "kind" of change. That's going to reduce the amount of thinking required in review, and ease the job of downstream mergers and bisection in the future. (I don't think there's anything controversial in the behaviour being added).

    I don't like the new name for updateLocationAfterHoist, because it's creating two subtly different kinds of "locations" and requiring developers to think about it while writing their code. This kind of ambiguity (IMHO) will lead to future accidental misuse -- that's why the existing function call is named after an action, it avoids compiler engineers having to think about what's right or wrong for source locations, only that some maintenance happens when that action happens. The re-purposing of updateLocationAfterHoist seems like a good plan, it's just the name that bugs me.

    ayermolo ayermolo commented on Nov 03, 2026 01:32 UTC
    Author

    @jmorse Refactored with help of skynet into multiple commits (and a bit more cleanup).
    Let me know if that is good granularity and I'll split into actual PRs to continue review.

    Regarding the name. I changed the name to be slightly more explicit, but not sure what would be a better name that follows an action.
    Fundamentally it's used in two contexts.
    Updating after hoist:
    https://github.com/llvm/llvm-project/pull/229615/changes/5eaf89fc42b59638d7ca759ea4be3f6f621a2872
    and more generally when we want to drop source location, but preserve irlayers:
    https://github.com/llvm/llvm-project/pull/229615/changes/d3676e1409493b36a7bf3675455767ffcfbbf7d6

    Unless we add an API wrapper just for first, maybe it's better to keep it generic and name it after what it does?

    ayermolo ayermolo commented on Nov 10, 2026 20:37 UTC
    Author

    @slinder1 would this be in your wheel barrel to look at? :)

    SLTozer SLTozer commented on Nov 13, 2026 10:30 UTC
    Contributor

    Apologies for not having looking at this yet, had my head in other work.

    I have one main comment, around the decision to keep/drop layers. The justification for keeping layers when otherwise dropping source locations is that (1) single-stepping wants to drop hoisted locations while profiling doesn't, and (2) IRLayers are used by profilers, not debuggers. I can accept (1) at face value; although I don't fully understand the rationale, since I would expect this to mislead profilers about branches taken, there have been results that support preserving "misleading" debug locations (for the pick-merged-locations case). I'd question (2) though - there is already one existing use case for IRLayers that isn't profiling related, and it's not too hard to imaging non-profiling uses for the feature. I wouldn't demand the code to be rewritten to support a hypothetical future use case, but in this case I think it could simplify the patch: if the "don't drop locations while hoisting" behaviour is beneficial for profiling, it makes more sense to me that we would have some flag to always preserve locations while hoisting, including for normal DILocation info, and that we would use this flag when generating debug info for profiling purposes; and otherwise, we'd drop both the source location and the layer locations. The flag could be split into a separate review, which would be trivial to understand, and the size and breadth of changes in this patch would be reduced, if I'm not misunderstanding anything at least.

    Also, regarding the "finding the innermost IR layers" change - this adds a bit of cost to all builds, since builds without IRLayers still need to search the full inlining chain, although the impact probably fairly small. There's no way AFAICT to know at this point whether any IRLayers exist, so it's most likely unavoidable. It does make me wonder whether there'd be any value to keeping some information (scope/inlinedAt) around for all dropped instructions, but that's beyond the scope of this patch.

    Reviewers
    Assignees
    ayermolo ayermolo
    Labels
    risk: low confidence: 85.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 83.5% (HIGH) · Higher = larger blast radius
    83.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.6% · Lower = rushed or shallow review
    85.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 12% · Safe to merge
    12%