[lld] [lld][COFF] Emit coffgrp debug record (PR #205630)

via llvm-commits llvm-commits at lists.llvm.org
Wed Jun 24 13:00:28 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-lld

Author: eleviant

<details>
<summary>Changes</summary>

This is an undocumented debug metadata entry introduced in Visual Studio 2015. In Windows SDK header files (such as <winnt.h>), this entry maps to value 13, formally defined as IMAGE_DEBUG_TYPE_POGO.

The primary purpose of the coffgrp debug entry is to support Profile guided optimization (PGO) and post-compile code layout optimization.

The coffgrp payload records exactly how those original COFF sections and COMDATs were bundled together. This allows downstream tools—like performance profilers, crash-dump utilities, and internal PGO utilities to safely correlate telemetry with the optimized machine code blocks.

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


6 Files Affected:

- (modified) lld/COFF/Chunks.h (+32) 
- (modified) lld/COFF/Config.h (+2) 
- (modified) lld/COFF/Driver.cpp (+4) 
- (modified) lld/COFF/Options.td (+4) 
- (modified) lld/COFF/Writer.cpp (+73-2) 
- (added) lld/test/COFF/coffgrp.s (+52) 


``````````diff
diff --git a/lld/COFF/Chunks.h b/lld/COFF/Chunks.h
index fd2948fc31eb1..dc80cc300e572 100644
--- a/lld/COFF/Chunks.h
+++ b/lld/COFF/Chunks.h
@@ -996,6 +996,38 @@ class FakeSectionChunk {
   SectionChunk chunk;
 };
 
+class COFFDebugRecordChunk : public NonSectionChunk {
+public:
+  COFFDebugRecordChunk(COFFLinkerContext &c) : ctx(c) {}
+  size_t getSize() const override;
+  void writeTo(uint8_t *b) const override;
+  void computeRecords();
+
+private:
+  static constexpr const char *const pgoSectionNames[] = {
+      ".text$_00hot", ".text$_01", ".text$_02", ".text$unlikely", ".text$zzzz"};
+
+  struct COFFGrpRecord {
+    Chunk *first;
+    Chunk *last;
+    StringRef name;
+
+    uint32_t size() const { return sizeof(uint32_t) * 2 + nameSize(); }
+    uint32_t nameSize() const { return llvm::alignTo(name.size() + 1, 4); }
+    uint32_t getRecSize() const {
+      return last->getRVA() + last->getSize() - first->getRVA();
+    }
+    void dump(COFFLinkerContext &ctx) const {
+      Log(ctx) << "coffgrp rec " << name
+               << " RVA = " << llvm::format_hex(first->getRVA(), 4)
+               << " size = " << llvm::format_hex(getRecSize(), 4);
+    }
+  };
+
+  COFFLinkerContext &ctx;
+  std::vector<COFFGrpRecord> records;
+};
+
 } // namespace lld::coff
 
 namespace llvm {
diff --git a/lld/COFF/Config.h b/lld/COFF/Config.h
index f22d5800b62c4..7033d40b7367e 100644
--- a/lld/COFF/Config.h
+++ b/lld/COFF/Config.h
@@ -34,6 +34,7 @@ class StringChunk;
 class Symbol;
 class InputFile;
 class SectionChunk;
+class COFFDebugRecordChunk;
 
 // Short aliases.
 static const auto AMD64 = llvm::COFF::IMAGE_FILE_MACHINE_AMD64;
@@ -133,6 +134,7 @@ struct Configuration {
   bool forceMultiple = false;
   bool forceMultipleRes = false;
   bool forceUnresolved = false;
+  bool emitCoffDebugRecord = true;
   bool debug = false;
   bool includeDwarfChunks = false;
   bool debugGHashes = false;
diff --git a/lld/COFF/Driver.cpp b/lld/COFF/Driver.cpp
index 024cb2c95cd20..af5c23b00b728 100644
--- a/lld/COFF/Driver.cpp
+++ b/lld/COFF/Driver.cpp
@@ -1817,6 +1817,10 @@ void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
     }
   }
 
+  // Handle /coff-debug-record[:no]
+  config->emitCoffDebugRecord =
+      args.hasFlag(OPT_coff_debug_record, OPT_coff_debug_record_no, false);
+
   // Handle /demangle
   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true);
 
diff --git a/lld/COFF/Options.td b/lld/COFF/Options.td
index bc1902d093a0f..774967e225c08 100644
--- a/lld/COFF/Options.td
+++ b/lld/COFF/Options.td
@@ -317,6 +317,10 @@ defm lto_pgo_warn_mismatch: B<
      "lto-pgo-warn-mismatch",
      "turn on warnings about profile cfg mismatch (default)>",
      "turn off warnings about profile cfg mismatch">;
+defm coff_debug_record: B<
+     "coff-debug-record",
+     "emit COFF group information in PE",
+     "do no emit COFF group information in PE">;
 def dash_dash_version : Flag<["--"], "version">,
   HelpText<"Display the version number and exit">;
 def threads
diff --git a/lld/COFF/Writer.cpp b/lld/COFF/Writer.cpp
index 955a9897ac2b0..fca331393cf06 100644
--- a/lld/COFF/Writer.cpp
+++ b/lld/COFF/Writer.cpp
@@ -82,7 +82,6 @@ static_assert((sizeof(dos_header) + sizeof(dosProgram)) % 8 == 0,
 static const int numberOfDataDirectory = 16;
 
 namespace {
-
 class DebugDirectoryChunk : public NonSectionChunk {
 public:
   DebugDirectoryChunk(const COFFLinkerContext &c,
@@ -302,6 +301,7 @@ class Writer {
 
   DebugDirectoryChunk *debugDirectory = nullptr;
   std::vector<std::pair<COFF::DebugType, Chunk *>> debugRecords;
+  COFFDebugRecordChunk *coffDebugRecord = nullptr;
   CVDebugRecordChunk *buildId = nullptr;
   ArrayRef<uint8_t> sectionTable;
 
@@ -1246,7 +1246,8 @@ void Writer::createMiscChunks() {
   if (config->buildIDHash != BuildIDHash::None || config->debug ||
       config->repro || config->cetCompat || config->cetCompatStrict ||
       config->cetCompatIpValidationRelaxed ||
-      config->cetCompatDynamicApisInProcOnly || config->hotpatchCompat) {
+      config->cetCompatDynamicApisInProcOnly || config->hotpatchCompat ||
+      config->emitCoffDebugRecord) {
     debugDirectory =
         make<DebugDirectoryChunk>(ctx, debugRecords, config->repro);
     debugDirectory->setAlignment(4);
@@ -1267,6 +1268,12 @@ void Writer::createMiscChunks() {
     });
   }
 
+  // Create COFF group table when ever debug directory table is created
+  if (config->emitCoffDebugRecord) {
+    coffDebugRecord = make<COFFDebugRecordChunk>(ctx);
+    debugRecords.push_back({COFF::IMAGE_DEBUG_TYPE_POGO, coffDebugRecord});
+  }
+
   uint16_t ex_characteristics_flags = 0;
   if (config->cetCompat)
     ex_characteristics_flags |= IMAGE_DLL_CHARACTERISTICS_EX_CET_COMPAT;
@@ -1758,6 +1765,9 @@ void Writer::assignAddresses() {
   // The first page is kept unmapped.
   uint64_t rva = alignTo(sizeOfHeaders, config->align);
 
+  if (coffDebugRecord)
+    coffDebugRecord->computeRecords();
+
   for (OutputSection *sec : ctx.outputSections) {
     llvm::TimeTraceScope timeScope("Section: ", sec->name);
     if (sec == relocSec) {
@@ -3113,3 +3123,64 @@ void Writer::printSummary() {
 
   Msg(ctx) << buffer;
 }
+
+size_t COFFDebugRecordChunk::getSize() const {
+  size_t size = sizeof(uint32_t);
+  llvm::for_each(records, [&](auto &r) { size += r.size(); });
+  return size;
+}
+
+void COFFDebugRecordChunk::computeRecords() {
+  records.clear();
+  auto addRange = [](const auto &range, Chunk *end, StringRef name) {
+    bool hasData = false;
+    Chunk *last = nullptr;
+    for (auto *c : range) {
+      if (c == end)
+        break;
+      hasData |= c->getSize();
+      last = c;
+    }
+    return hasData ? COFFGrpRecord{*range.begin(), last, name}
+                   : COFFGrpRecord{nullptr, nullptr, ""};
+  };
+
+  for (OutputSection *os : ctx.outputSections) {
+    for (auto *sec : os->contribSections) {
+      COFFGrpRecord rec = addRange(sec->chunks, nullptr, sec->name);
+      if (!rec.first)
+        continue;
+      records.push_back(rec);
+    }
+    Chunk *lastChunk = records.empty() ? nullptr : records.back().last;
+    COFFGrpRecord lastRec =
+        addRange(llvm::reverse(os->chunks), lastChunk, os->name);
+    if (lastRec.first) {
+      std::swap(lastRec.first, lastRec.last);
+      records.push_back(lastRec);
+    }
+  }
+}
+
+void COFFDebugRecordChunk::writeTo(uint8_t *b) const {
+  bool is_pgo = llvm::any_of(records, [](auto &r) {
+    return llvm::is_contained(pgoSectionNames, r.name);
+  });
+  // ASCII code of "PGO\0" or zero
+  uint8_t *start = b;
+  write32le(b, is_pgo ? 0x50474F00 : 0);
+  uint32_t sig = read32be(b);
+  Log(ctx) << "coffgrp signature: '" << reinterpret_cast<char *>(&sig) << "'";
+  b += sizeof(uint32_t);
+  for (auto &rec : records) {
+    rec.dump(ctx);
+    write32le(b, rec.first->getRVA());
+    b += sizeof(uint32_t);
+    write32le(b, rec.getRecSize());
+    b += sizeof(uint32_t);
+    memset(b, 0, rec.nameSize());
+    memcpy(b, rec.name.data(), rec.name.size());
+    b += rec.nameSize();
+  }
+  assert(static_cast<size_t>(b - start) == getSize());
+}
diff --git a/lld/test/COFF/coffgrp.s b/lld/test/COFF/coffgrp.s
new file mode 100644
index 0000000000000..a19cf7473a904
--- /dev/null
+++ b/lld/test/COFF/coffgrp.s
@@ -0,0 +1,52 @@
+# REQUIRES: x86
+
+# Make a DLL that exports exportfn1.
+# RUN: yaml2obj %p/Inputs/export.yaml -o %t.obj
+# RUN: lld-link /out:%t.dll /dll %t.obj /export:exportfn1 /implib:%t.lib
+
+# Make an obj that takes the address of that exported function.
+# RUN: llvm-mc -filetype=obj -triple=x86_64-windows-msvc %s -o %t2.obj
+# RUN: lld-link -entry:main -guard:cf %t2.obj %t.lib -nodefaultlib -out:%t.exe /verbose /coff-debug-record 2>&1 | FileCheck %s --check-prefix=NOPGO,REC
+# RUN: llvm-mc -filetype=obj -triple=x86_64-windows-msvc -defsym HOT=1 %s -o %t2h.obj
+# RUN: lld-link -entry:main -guard:cf %t2h.obj %t.lib -nodefaultlib -out:%t.exe /verbose /coff-debug-record 2>&1 | FileCheck %s --check-prefix=PGO,REC
+
+# NOPGO:      coffgrp signature: ''
+# NOPGO-NEXT: coffgrp rec .text$abcdef RVA = 0x1000 size = 0x08
+# PGO:        coffgrp signature: 'PGO'
+# PGO-NEXT:   coffgrp rec .text$_00hot RVA = 0x1000 size = 0x08
+# REC:        coffgrp rec .text RVA = 0x1010 size = 0x06
+# REC-NEXT:   coffgrp rec .rdata RVA = 0x2000 size = 0x114
+# REC-NEXT:   coffgrp rec .idata$2 RVA = 0x21d8 size = 0x28
+# REC-NEXT:   coffgrp rec .idata$4 RVA = 0x2200 size = 0x10
+# REC-NEXT:   coffgrp rec .idata$5 RVA = 0x2210 size = 0x10
+# REC-NEXT:   coffgrp rec .idata$6 RVA = 0x2220 size = 0x0c
+# REC-NEXT:   coffgrp rec .idata$7 RVA = 0x222c size = 0x12
+
+        .def     @feat.00;
+        .scl    3;
+        .type   0;
+        .endef
+        .globl  @feat.00
+ at feat.00 = 0x001
+
+.ifndef HOT
+	.section .text$abcdef,"xr"
+.else
+	.section .text$_00hot,"xr"
+.endif
+        .def     main; .scl    2; .type   32; .endef
+        .global main
+main:
+        leaq exportfn1(%rip), %rax
+        retq
+
+        .section .rdata,"dr"
+.globl _load_config_used
+_load_config_used:
+        .long 256
+        .fill 124, 1, 0
+        .quad __guard_fids_table
+        .quad __guard_fids_count
+        .long __guard_flags
+        .fill 128, 1, 0
+

``````````

</details>


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


More information about the llvm-commits mailing list