[llvm] [llvm-profgen] Add executable range-end analysis (PR #224993)

via llvm-commits llvm-commits at lists.llvm.org
Sun Sep 20 22:20:45 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-pgo

Author: Sergey Shcherbinin (SergeyShch01)

<details>
<summary>Changes</summary>

This is the first part of splitting the Arm SPE branch-profile support originally proposed in
https://github.com/llvm/llvm-project/pull/209769. Later parts will add the SPE reader and user-facing integration.

Add lazy executable-range endpoint discovery that stops at transfers, traps, AArch64 SVC, code gaps, and function boundaries.

This is not NFC: disassemble() now sorts CodeAddressVec because section-header order need not match address order. The same invariant is required by getIndexForAddr and getCallAddrFromFrameAddr, and by InstructionPointer traversals used for
LBR/BRBE body-sample symbolization, hybrid-stack virtual unwinding, prologue/epilogue inference, and inline-context size tracking.  Sorting prevents dropped or misattributed body samples.

Add an AArch64 regression test with reversed executable section-header order.

Assited by GPT-5

---
Full diff: https://github.com/llvm/llvm-project/pull/224993.diff


3 Files Affected:

- (added) llvm/test/tools/llvm-profgen/AArch64/code-address-order.test (+225) 
- (modified) llvm/tools/llvm-profgen/ProfiledBinary.cpp (+105) 
- (modified) llvm/tools/llvm-profgen/ProfiledBinary.h (+24) 


``````````diff
diff --git a/llvm/test/tools/llvm-profgen/AArch64/code-address-order.test b/llvm/test/tools/llvm-profgen/AArch64/code-address-order.test
new file mode 100644
index 00000000000000..b960ab423707ec
--- /dev/null
+++ b/llvm/test/tools/llvm-profgen/AArch64/code-address-order.test
@@ -0,0 +1,225 @@
+# REQUIRES: aarch64-registered-target
+
+# RUN: split-file %s %t
+# RUN: yaml2obj %t/binary.yaml -o %t/code-address-order.exe
+# RUN: llvm-profgen --binary=%t/code-address-order.exe \
+# RUN:   --perfscript=%t/perfscript --format=text --output=%t/profile
+# RUN: FileCheck %s --check-prefix=LOW --input-file=%t/profile
+# RUN: FileCheck %s --check-prefix=HIGH --input-file=%t/profile
+
+## The executable sections are listed in decreasing virtual-address order.
+## Verify that symbolization traverses both functions in address order, which
+## requires ProfiledBinary::disassemble() to sort CodeAddressVec.
+# LOW-LABEL: low:
+# LOW-NEXT:   0: 1
+# LOW-NEXT:   1: 1
+# LOW-NEXT:   2: 1
+# LOW-NEXT:   3: 1
+# LOW-NEXT:   4: 2 low:2
+# HIGH-LABEL: high:
+# HIGH-NEXT:   0: 1
+# HIGH-NEXT:   1: 1
+# HIGH-NEXT:   2: 1
+# HIGH-NEXT:   3: 1
+# HIGH-NEXT:   4: 2 high:2
+
+#--- binary.yaml
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS64
+  Data:    ELFDATA2LSB
+  Type:    ET_DYN
+  Machine: EM_AARCH64
+  Entry:   0x1000
+Sections:
+  - Name:         .text.low
+    Type:         SHT_PROGBITS
+    Flags:        [ SHF_ALLOC, SHF_EXECINSTR ]
+    Address:      0x1000
+    Offset:       0x1000
+    AddressAlign: 0x4
+    ## nop; nop; nop; nop; b 0x1000
+    Content:      1F2003D51F2003D51F2003D51F2003D5FCFFFF17
+  - Name:         .text.high
+    Type:         SHT_PROGBITS
+    Flags:        [ SHF_ALLOC, SHF_EXECINSTR ]
+    Address:      0x2000
+    Offset:       0x2000
+    AddressAlign: 0x4
+    ## nop; nop; nop; nop; b 0x2000
+    Content:      1F2003D51F2003D51F2003D51F2003D5FCFFFF17
+  ## Keep file layout valid while presenting executable sections to consumers
+  ## in decreasing virtual-address order.
+  - Type: SectionHeaderTable
+    Sections:
+      - Name: .text.high
+      - Name: .text.low
+      - Name: .debug_line
+      - Name: .debug_abbrev
+      - Name: .debug_info
+      - Name: .symtab
+      - Name: .strtab
+      - Name: .shstrtab
+ProgramHeaders:
+  - Type:     PT_LOAD
+    Flags:    [ PF_X, PF_R ]
+    Offset:   0
+    VAddr:    0
+    FileSize: 0x2014
+    MemSize:  0x3000
+    Align:    0x10000
+Symbols:
+  - Name:    high
+    Type:    STT_FUNC
+    Section: .text.high
+    Binding: STB_GLOBAL
+    Value:   0x2000
+    Size:    0x14
+  - Name:    low
+    Type:    STT_FUNC
+    Section: .text.low
+    Binding: STB_GLOBAL
+    Value:   0x1000
+    Size:    0x14
+DWARF:
+  debug_abbrev:
+    - ID: 0
+      Table:
+        - Code:     1
+          Tag:      DW_TAG_compile_unit
+          Children: DW_CHILDREN_yes
+          Attributes:
+            - Attribute: DW_AT_name
+              Form:      DW_FORM_string
+            - Attribute: DW_AT_stmt_list
+              Form:      DW_FORM_sec_offset
+            - Attribute: DW_AT_low_pc
+              Form:      DW_FORM_addr
+            - Attribute: DW_AT_high_pc
+              Form:      DW_FORM_data8
+        - Code:     2
+          Tag:      DW_TAG_subprogram
+          Children: DW_CHILDREN_no
+          Attributes:
+            - Attribute: DW_AT_name
+              Form:      DW_FORM_string
+            - Attribute: DW_AT_low_pc
+              Form:      DW_FORM_addr
+            - Attribute: DW_AT_high_pc
+              Form:      DW_FORM_data8
+            - Attribute: DW_AT_decl_file
+              Form:      DW_FORM_data1
+            - Attribute: DW_AT_decl_line
+              Form:      DW_FORM_data1
+  debug_info:
+    - Version:       4
+      AbbrevTableID: 0
+      AddrSize:      8
+      Entries:
+        - AbbrCode: 1
+          Values:
+            - CStr: unordered.c
+            - Value: 0
+            ## DW_FORM_data8 makes high_pc an offset from low_pc. The resulting
+            ## half-open range [0x1000, 0x2014) covers both text sections.
+            - Value: 0x1000
+            - Value: 0x1014
+        - AbbrCode: 2
+          Values:
+            - CStr:  low
+            - Value: 0x1000
+            - Value: 0x14
+            - Value: 1
+            - Value: 10
+        - AbbrCode: 2
+          Values:
+            - CStr:  high
+            - Value: 0x2000
+            - Value: 0x14
+            - Value: 1
+            - Value: 20
+        - AbbrCode: 0
+  debug_line:
+    - Version:               4
+      MinInstLength:         1
+      MaxOpsPerInst:         1
+      DefaultIsStmt:         1
+      LineBase:              251
+      LineRange:             14
+      OpcodeBase:            13
+      StandardOpcodeLengths: [ 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ]
+      Files:
+        - Name:    unordered.c
+          DirIdx:  0
+          ModTime: 0
+          Length:  0
+      Opcodes:
+        - Opcode:    DW_LNS_extended_op
+          ExtLen:    9
+          SubOpcode: DW_LNE_set_address
+          Data:      0x1000
+        - Opcode:    DW_LNS_advance_line
+          SData:     9
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_extended_op
+          ExtLen:    1
+          SubOpcode: DW_LNE_end_sequence
+        - Opcode:    DW_LNS_extended_op
+          ExtLen:    9
+          SubOpcode: DW_LNE_set_address
+          Data:      0x2000
+        - Opcode:    DW_LNS_advance_line
+          SData:     19
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_advance_line
+          SData:     1
+        - Opcode:    DW_LNS_copy
+        - Opcode:    DW_LNS_advance_pc
+          Data:      4
+        - Opcode:    DW_LNS_extended_op
+          ExtLen:    1
+          SubOpcode: DW_LNE_end_sequence
+
+#--- perfscript
+PERF_RECORD_MMAP2 1/1: [0x700000000000(0x3000) @ 0 00:00 0 0]: r-xp /tmp/code-address-order.exe
+700000001010 0x700000001010/0x700000001000/P/-/-/0 0x700000001010/0x700000001000/P/-/-/0
+700000002010 0x700000002010/0x700000002000/P/-/-/0 0x700000002010/0x700000002000/P/-/-/0
diff --git a/llvm/tools/llvm-profgen/ProfiledBinary.cpp b/llvm/tools/llvm-profgen/ProfiledBinary.cpp
index a8a60a0b40dc51..9690c0bc651aae 100644
--- a/llvm/tools/llvm-profgen/ProfiledBinary.cpp
+++ b/llvm/tools/llvm-profgen/ProfiledBinary.cpp
@@ -26,6 +26,7 @@
 #include "llvm/Support/Format.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/TargetParser/Triple.h"
+#include <algorithm>
 #include <optional>
 
 #define DEBUG_TYPE "load-binary"
@@ -669,6 +670,14 @@ bool ProfiledBinary::dissassembleSymbol(std::size_t SI, ArrayRef<uint8_t> Bytes,
         if (MCDesc.isUnconditionalBranch())
           UncondBranchAddrSet.insert(Address);
         BranchAddressSet.insert(Address);
+      } else if (MCDesc.isBarrier() || MCDesc.isTrap() ||
+                 (TheTriple.isAArch64() &&
+                  MII->getName(Inst.getOpcode()) == "SVC")) {
+        // Transfers of control are handled above. Barriers and traps that reach
+        // here stop execution without naming a successor. SVC can return, but a
+        // branch sample does not prove execution past it. Recording the address
+        // prevents range inference from entering code that may not execute.
+        RangeStopAddressSet.insert(Address);
       }
 
       if (MCDesc.isIndirectBranch()) {
@@ -863,6 +872,13 @@ void ProfiledBinary::disassemble(const ObjectFile *Obj) {
     }
   }
 
+  // Binary search and sequential traversal through CodeAddressVec require
+  // increasing addresses. Instructions are collected in section-header order,
+  // which an object file need not keep sorted, so establish the invariant once
+  // after decoding every text section.
+  if (!llvm::is_sorted(CodeAddressVec))
+    llvm::sort(CodeAddressVec);
+
   if (!AddrsWithInvalidInstruction.empty()) {
     if (ShowDetailedWarning) {
       for (auto &Addr : AddrsWithInvalidInstruction) {
@@ -1306,6 +1322,95 @@ void ProfiledBinary::inferMissingFrames(
   MissingContextInferrer->inferMissingFrames(Context, NewContext);
 }
 
+void ProfiledBinary::buildRangeEnds() {
+  assert(llvm::is_sorted(CodeAddressVec) &&
+         "code addresses must be sorted after disassembly");
+
+  // Walk instructions and function ranges backwards at the same time, so that
+  // classifying every instruction costs one merge step instead of a search.
+  auto FuncIt = StartAddrToFuncRangeMap.rbegin();
+  const FuncRange *NextRange = nullptr;
+  for (size_t I = CodeAddressVec.size(); I != 0; --I) {
+    uint64_t Current = CodeAddressVec[I - 1];
+
+    // Advance to the last function range that starts at or before Current, then
+    // keep it only if Current is inside that range.
+    while (FuncIt != StartAddrToFuncRangeMap.rend() && Current < FuncIt->first)
+      ++FuncIt;
+    const FuncRange *CurrentRange = nullptr;
+    if (FuncIt != StartAddrToFuncRangeMap.rend() &&
+        Current < FuncIt->second.EndAddress)
+      CurrentRange = &FuncIt->second;
+
+    // An instruction outside every function range is never a valid range end,
+    // because a range must not extend into code whose function is unknown, and
+    // findRangeEnd rejects such an address before the search.
+    if (CurrentRange) {
+      // The following instruction continues the range only when it is adjacent
+      // and belongs to the same function. NextRange is null for the highest
+      // address and for a following instruction no function range covers.
+      bool FollowsAdjacently =
+          I < CodeAddressVec.size() &&
+          CodeAddressVec[I] - Current == getInstSize(Current);
+
+      // Comparing the owning function rather than the range keeps a function
+      // described by several adjacent ranges, as function splitting produces,
+      // in one inferred range. Ranges are owned by name, so two same-named
+      // functions laid out back to back are separated only by IsFuncEntry,
+      // which a symbol on the second one sets.
+      bool EndsRange = !NextRange || !FollowsAdjacently ||
+                       NextRange->Func != CurrentRange->Func ||
+                       (NextRange != CurrentRange && NextRange->IsFuncEntry);
+      if (EndsRange || addressIsTransfer(Current) ||
+          RangeStopAddressSet.count(Current))
+        RangeEnds.push_back(Current);
+    }
+    NextRange = CurrentRange;
+  }
+
+  // The traversal is backwards, so restore increasing order for binary search.
+  std::reverse(RangeEnds.begin(), RangeEnds.end());
+  RangeEndsBuilt = true;
+}
+
+uint64_t ProfiledBinary::findRangeEnd(uint64_t Address, bool *Uncovered) {
+  // Assigned on every path, so that a caller never reads a value left over
+  // from an earlier query.
+  if (Uncovered)
+    *Uncovered = false;
+
+  if (!addressIsCode(Address))
+    return 0;
+
+  // Function ranges come from debug info, and from the symbol table only where
+  // the binary carries pseudo probes. Where none covers Address, the executed
+  // range cannot be proven, so fail closed and keep that instruction alone.
+  if (!findFuncRange(Address)) {
+    if (Uncovered)
+      *Uncovered = true;
+    return Address;
+  }
+
+  // Every instruction before a range end has that end as its own, so indexing
+  // the ends alone keeps the index proportional to their number.
+  if (!RangeEndsBuilt)
+    buildRangeEnds();
+
+  // The greatest covered address always ends a range, and every covered address
+  // is at or below it, so the search finds an end.
+  auto End = llvm::lower_bound(RangeEnds, Address);
+  assert(End != RangeEnds.end() &&
+         "a covered instruction must have a range end at or above it");
+  // Should it not, fail closed as an uncovered address does rather than read
+  // past the index or hide the reduction from the caller.
+  if (End == RangeEnds.end()) {
+    if (Uncovered)
+      *Uncovered = true;
+    return Address;
+  }
+  return *End;
+}
+
 InstructionPointer::InstructionPointer(const ProfiledBinary *Binary,
                                        uint64_t Address, bool RoundToNext)
     : Binary(Binary), Address(Address) {
diff --git a/llvm/tools/llvm-profgen/ProfiledBinary.h b/llvm/tools/llvm-profgen/ProfiledBinary.h
index e4af7c0fdf7f4d..bb5ad9d3a0ae35 100644
--- a/llvm/tools/llvm-profgen/ProfiledBinary.h
+++ b/llvm/tools/llvm-profgen/ProfiledBinary.h
@@ -283,6 +283,13 @@ class ProfiledBinary {
   // An array of Addresses of all instructions sorted in increasing order. The
   // sorting is needed to fast advance to the next forward/backward instruction.
   std::vector<uint64_t> CodeAddressVec;
+  // Addresses that end an inferred executable range: transfer instructions,
+  // traps, SVC, and the last instructions before a code gap or a function
+  // boundary. Sorted in increasing order and filled on the first findRangeEnd
+  // query, so an input that needs no range inference never pays for it.
+  std::vector<uint64_t> RangeEnds;
+  // Whether RangeEnds has been built, which its emptiness does not indicate.
+  bool RangeEndsBuilt = false;
   // A set of call instruction addresses. Used by virtual unwinding.
   DenseSet<uint64_t> CallAddressSet;
   // A set of return instruction addresses. Used by virtual unwinding.
@@ -295,6 +302,10 @@ class ProfiledBinary {
   DenseSet<uint64_t> IndirectBranchAddressSet;
   // A set of branch target addresses (destinations of branches/calls).
   DenseSet<uint64_t> BranchTargetAddressSet;
+  // A set of the addresses of non-transfer instructions that stop range
+  // inference: traps and the AArch64 SVC system call. buildRangeEnds ends an
+  // inferred range there.
+  DenseSet<uint64_t> RangeStopAddressSet;
 
   // Estimate and track function prolog and epilog ranges.
   PrologEpilogTracker ProEpilogTracker;
@@ -421,6 +432,9 @@ class ProfiledBinary {
   bool dissassembleSymbol(std::size_t SI, ArrayRef<uint8_t> Bytes,
                           SectionSymbolsTy &Symbols,
                           const object::SectionRef &Section);
+  /// Collect the addresses that end an inferred executable range into
+  /// RangeEnds. Called on the first findRangeEnd query.
+  void buildRangeEnds();
   /// Symbolize a given instruction pointer and return a full call context.
   SampleContextFrameVector symbolize(const InstructionPointer &IP,
                                      bool UseCanonicalFnName = false,
@@ -510,6 +524,16 @@ class ProfiledBinary {
            CallAddressSet.count(Address);
   }
 
+  // Return the end of the executable range that starts at Address: the nearest
+  // instruction at or after it that is a transfer, trap, or SVC, without
+  // crossing a code gap or a function boundary, or the last instruction before
+  // either boundary. Return zero when Address is not an instruction, and
+  // Address itself when no function range covers it, which keeps an inferred
+  // range out of code that may belong to another function. Set *Uncovered, when
+  // given, to whether the range had to be reduced to Address; it is assigned on
+  // every path.
+  uint64_t findRangeEnd(uint64_t Address, bool *Uncovered = nullptr);
+
   bool rangeCrossUncondBranch(uint64_t Start, uint64_t End) {
     if (Start >= End)
       return false;

``````````

</details>


https://github.com/llvm/llvm-project/pull/224993


More information about the llvm-commits mailing list