[lld] [lld][ELF] Introduce an option to keep data section prefix. (PR #148985)

Fangrui Song via llvm-commits llvm-commits at lists.llvm.org
Mon Aug 4 23:46:46 PDT 2025


================
@@ -103,13 +103,48 @@ StringRef LinkerScript::getOutputSectionName(const InputSectionBase *s) const {
     return ".text";
   }
 
-  for (StringRef v : {".data.rel.ro", ".data",       ".rodata",
-                      ".bss.rel.ro",  ".bss",        ".ldata",
-                      ".lrodata",     ".lbss",       ".gcc_except_table",
-                      ".init_array",  ".fini_array", ".tbss",
-                      ".tdata",       ".ARM.exidx",  ".ARM.extab",
-                      ".ctors",       ".dtors",      ".sbss",
-                      ".sdata",       ".srodata"})
+  // When zKeepDataSectionPrefix is true, keep .hot and .unlikely suffixes
+  // in data sections.
+  static constexpr StringRef dataSectionPrefixes[] = {
+      ".data.rel.ro", ".data", ".rodata", ".bss.rel.ro", ".bss",
+  };
+
+  for (auto [index, v] : llvm::enumerate(dataSectionPrefixes)) {
+    StringRef secName = s->name;
+    if (!secName.consume_front(v))
+      continue;
+    if (!secName.empty() && secName[0] != '.') {
+      continue;
+    }
+
+    // The section name starts with 'v', and the remaining string is either
+    // empty or starts with a '.' character. If keep-data-section-prefix is
+    // false, map s to output section with name 'v'.
+    if (!ctx.arg.zKeepDataSectionPrefix)
+      return v;
+    // Preserve .hot or .unlikely suffixes in data sections with
+    // keep-data-section-prefix=true.
+    if (isSectionPrefix(".hot", secName))
+      return s->name.substr(0, v.size() + 4);
+    if (isSectionPrefix(".unlikely", secName))
+      return s->name.substr(0, v.size() + 9);
+    if (index == 2) {
----------------
MaskRay wrote:

Thanks for the explanation! I think the current `index == 2` looks better.

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


More information about the llvm-commits mailing list