[lld] [LLD] Add CLASS syntax to SECTIONS (PR #95323)

Daniel Thornburgh via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 13 15:13:33 PDT 2024


https://github.com/mysterymath updated https://github.com/llvm/llvm-project/pull/95323

>From 2008e1b67829e2ed1b47e59c65713ed0ab9e1fdd Mon Sep 17 00:00:00 2001
From: Daniel Thornburgh <dthorn at google.com>
Date: Mon, 13 May 2024 11:21:26 -0700
Subject: [PATCH 1/2] [LLD] Add CLASS syntax to SECTIONS

This allows the input section matching algorithm to be separated from
output section descriptions. This allows a group of sections to be
assigned to multiple output sections, providing an explicit version of
--enable-non-contiguous-regions's spilling that doesn't require altering
global linker script matching behavior with a flag. It also makes the
linker script language more expressive even if spilling is not intended,
since input section matching can be done in a different order than
sections are placed in an output section.

The implementation reuses the backend mechanism provided by
--enable-non-contiguous-regions, so it has roughly similar semantics and
limitations. In particular, sections cannot be spilled into or out of
INSERT, OVERWRITE_SECTIONS, or /DISCARD/. The former two aren't
intrinsic, so it may be possible to relax those restrictions later.
---
 lld/ELF/InputSection.cpp                     |   2 +
 lld/ELF/InputSection.h                       |   6 +-
 lld/ELF/LinkerScript.cpp                     | 239 ++++++++----
 lld/ELF/LinkerScript.h                       |  24 +-
 lld/ELF/MapFile.cpp                          |   2 +
 lld/ELF/OutputSections.h                     |  19 +
 lld/ELF/ScriptParser.cpp                     |  59 ++-
 lld/docs/ELF/linker_script.rst               |  53 ++-
 lld/docs/ReleaseNotes.rst                    |   7 +
 lld/test/ELF/linkerscript/section-class.test | 379 +++++++++++++++++++
 10 files changed, 693 insertions(+), 97 deletions(-)
 create mode 100644 lld/test/ELF/linkerscript/section-class.test

diff --git a/lld/ELF/InputSection.cpp b/lld/ELF/InputSection.cpp
index f4287bc94ee5e..5175d26687178 100644
--- a/lld/ELF/InputSection.cpp
+++ b/lld/ELF/InputSection.cpp
@@ -159,6 +159,8 @@ uint64_t SectionBase::getOffset(uint64_t offset) const {
     // For output sections we treat offset -1 as the end of the section.
     return offset == uint64_t(-1) ? os->size : offset;
   }
+  case Class:
+    llvm_unreachable("section classes do not have offsets");
   case Regular:
   case Synthetic:
   case Spill:
diff --git a/lld/ELF/InputSection.h b/lld/ELF/InputSection.h
index 58e5306fd6dcd..1c8550ba19baf 100644
--- a/lld/ELF/InputSection.h
+++ b/lld/ELF/InputSection.h
@@ -48,7 +48,7 @@ template <class ELFT> struct RelsOrRelas {
 // sections.
 class SectionBase {
 public:
-  enum Kind { Regular, Synthetic, Spill, EHFrame, Merge, Output };
+  enum Kind { Regular, Synthetic, Spill, EHFrame, Merge, Output, Class };
 
   Kind kind() const { return (Kind)sectionKind; }
 
@@ -132,7 +132,9 @@ class InputSectionBase : public SectionBase {
                    uint32_t addralign, ArrayRef<uint8_t> data, StringRef name,
                    Kind sectionKind);
 
-  static bool classof(const SectionBase *s) { return s->kind() != Output; }
+  static bool classof(const SectionBase *s) {
+    return s->kind() != Output && s->kind() != Class;
+  }
 
   // The file which contains this section. Its dynamic type is usually
   // ObjFile<ELFT>, but may be an InputFile of InternalKind (for a synthetic
diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index 68f5240ddc690..2666ab780975f 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -276,6 +276,8 @@ getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
                                                     assign->sym->value));
       continue;
     }
+    if (isa<SectionClassDesc>(cmd))
+      continue;
     for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
       if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
         if (assign->sym)
@@ -347,6 +349,8 @@ void LinkerScript::declareSymbols() {
       declareSymbol(assign);
       continue;
     }
+    if (isa<SectionClassDesc>(cmd))
+      continue;
 
     // If the output section directive has constraints,
     // we can't say for sure if it is going to be included or not.
@@ -490,99 +494,130 @@ static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,
 SmallVector<InputSectionBase *, 0>
 LinkerScript::computeInputSections(const InputSectionDescription *cmd,
                                    ArrayRef<InputSectionBase *> sections,
-                                   const OutputSection &outCmd) {
+                                   const SectionBase &outCmd) {
   SmallVector<InputSectionBase *, 0> ret;
-  SmallVector<size_t, 0> indexes;
-  DenseSet<size_t> seen;
   DenseSet<InputSectionBase *> spills;
-  auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
-    llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
-    for (size_t i = begin; i != end; ++i)
-      ret[i] = sections[indexes[i]];
-    sortInputSections(
-        MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
-        config->sortSection, SortSectionPolicy::None);
+
+  const auto flagsMatch = [cmd](InputSectionBase *sec) {
+    return (sec->flags & cmd->withFlags) == cmd->withFlags &&
+           (sec->flags & cmd->withoutFlags) == 0;
   };
 
   // Collects all sections that satisfy constraints of Cmd.
-  size_t sizeAfterPrevSort = 0;
-  for (const SectionPattern &pat : cmd->sectionPatterns) {
-    size_t sizeBeforeCurrPat = ret.size();
-
-    for (size_t i = 0, e = sections.size(); i != e; ++i) {
-      // Skip if the section is dead or has been matched by a previous pattern
-      // in this input section description.
-      InputSectionBase *sec = sections[i];
-      if (!sec->isLive() || seen.contains(i))
-        continue;
-
-      // For --emit-relocs we have to ignore entries like
-      //   .rela.dyn : { *(.rela.data) }
-      // which are common because they are in the default bfd script.
-      // We do not ignore SHT_REL[A] linker-synthesized sections here because
-      // want to support scripts that do custom layout for them.
-      if (isa<InputSection>(sec) &&
-          cast<InputSection>(sec)->getRelocatedSection())
-        continue;
-
-      // Check the name early to improve performance in the common case.
-      if (!pat.sectionPat.match(sec->name))
-        continue;
-
-      if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||
-          (sec->flags & cmd->withFlags) != cmd->withFlags ||
-          (sec->flags & cmd->withoutFlags) != 0)
-        continue;
-
-      if (sec->parent) {
-        // Skip if not allowing multiple matches.
-        if (!config->enableNonContiguousRegions)
+  if (cmd->className.empty()) {
+    DenseSet<size_t> seen;
+    size_t sizeAfterPrevSort = 0;
+    SmallVector<size_t, 0> indexes;
+    auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
+      llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
+      for (size_t i = begin; i != end; ++i)
+        ret[i] = sections[indexes[i]];
+      sortInputSections(
+          MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
+          config->sortSection, SortSectionPolicy::None);
+    };
+
+    for (const SectionPattern &pat : cmd->sectionPatterns) {
+      size_t sizeBeforeCurrPat = ret.size();
+
+      for (size_t i = 0, e = sections.size(); i != e; ++i) {
+        // Skip if the section is dead or has been matched by a previous pattern
+        // in this input section description.
+        InputSectionBase *sec = sections[i];
+        if (!sec->isLive() || seen.contains(i))
           continue;
 
-        // Disallow spilling into /DISCARD/; special handling would be needed
-        // for this in address assignment, and the semantics are nebulous.
-        if (outCmd.name == "/DISCARD/")
+        // For --emit-relocs we have to ignore entries like
+        //   .rela.dyn : { *(.rela.data) }
+        // which are common because they are in the default bfd script.
+        // We do not ignore SHT_REL[A] linker-synthesized sections here because
+        // want to support scripts that do custom layout for them.
+        if (isa<InputSection>(sec) &&
+            cast<InputSection>(sec)->getRelocatedSection())
           continue;
 
-        // Skip if the section's first match was /DISCARD/; such sections are
-        // always discarded.
-        if (sec->parent->name == "/DISCARD/")
+        // Check the name early to improve performance in the common case.
+        if (!pat.sectionPat.match(sec->name))
           continue;
 
-        // Skip if the section was already matched by a different input section
-        // description within this output section.
-        if (sec->parent == &outCmd)
+        if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||
+            !flagsMatch(sec))
           continue;
 
-        spills.insert(sec);
+        if (sec->parent) {
+          // Skip if not allowing multiple matches.
+          if (!config->enableNonContiguousRegions)
+            continue;
+
+          // Disallow spilling out of or into section classes; that's already a
+          // mechanism for spilling.
+          if (isa<SectionClass>(sec->parent) || isa<SectionClass>(outCmd))
+            continue;
+
+          // Disallow spilling into /DISCARD/; special handling would be needed
+          // for this in address assignment, and the semantics are nebulous.
+          if (outCmd.name == "/DISCARD/")
+            continue;
+
+          // Skip if the section was already matched by a different input
+          // section description within this output section or class.
+          if (sec->parent == &outCmd)
+            continue;
+
+          spills.insert(sec);
+        }
+
+        ret.push_back(sec);
+        indexes.push_back(i);
+        seen.insert(i);
       }
 
-      ret.push_back(sec);
-      indexes.push_back(i);
-      seen.insert(i);
+      if (pat.sortOuter == SortSectionPolicy::Default)
+        continue;
+
+      // Matched sections are ordered by radix sort with the keys being (SORT*,
+      // --sort-section, input order), where SORT* (if present) is most
+      // significant.
+      //
+      // Matched sections between the previous SORT* and this SORT* are sorted
+      // by (--sort-alignment, input order).
+      sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
+      // Matched sections by this SORT* pattern are sorted using all 3 keys.
+      // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
+      // just sort by sortOuter and sortInner.
+      sortInputSections(
+          MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
+          pat.sortOuter, pat.sortInner);
+      sizeAfterPrevSort = ret.size();
     }
 
-    if (pat.sortOuter == SortSectionPolicy::Default)
-      continue;
+    // Matched sections after the last SORT* are sorted by (--sort-alignment,
+    // input order).
+    sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
+  } else {
+    SectionClassDesc *scd = script->sectionClasses.lookup(cmd->className);
+    if (!scd) {
+      error("undefined section class '" + cmd->className + "'");
+      return ret;
+    }
+    if (!scd->sc.assigned) {
+      error("section class '" + cmd->className + "' used before assigned");
+      return ret;
+    }
 
-    // Matched sections are ordered by radix sort with the keys being (SORT*,
-    // --sort-section, input order), where SORT* (if present) is most
-    // significant.
-    //
-    // Matched sections between the previous SORT* and this SORT* are sorted by
-    // (--sort-alignment, input order).
-    sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
-    // Matched sections by this SORT* pattern are sorted using all 3 keys.
-    // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
-    // just sort by sortOuter and sortInner.
-    sortInputSections(
-        MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
-        pat.sortOuter, pat.sortInner);
-    sizeAfterPrevSort = ret.size();
+    for (InputSectionDescription *isd : scd->sc.commands) {
+      for (InputSectionBase *sec : isd->sectionBases) {
+        if (sec->parent == &outCmd || !flagsMatch(sec))
+          continue;
+        bool isSpill = sec->parent && isa<OutputSection>(sec->parent);
+        if (!sec->parent || (isSpill && outCmd.name == "/DISCARD/"))
+          error("section '" + sec->name + "' cannot spill from/to /DISCARD/");
+        if (isSpill)
+          spills.insert(sec);
+        ret.push_back(sec);
+      }
+    }
   }
-  // Matched sections after the last SORT* are sorted by (--sort-alignment,
-  // input order).
-  sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
 
   // The flag --enable-non-contiguous-regions may cause sections to match an
   // InputSectionDescription in more than one OutputSection. Matches after the
@@ -707,7 +742,7 @@ void LinkerScript::processSectionCommands() {
         !map.try_emplace(CachedHashStringRef(osec->name), osd).second)
       warn("OVERWRITE_SECTIONS specifies duplicate " + osec->name);
   }
-  for (SectionCommand *&base : sectionCommands)
+  for (SectionCommand *&base : sectionCommands) {
     if (auto *osd = dyn_cast<OutputDesc>(base)) {
       OutputSection *osec = &osd->osec;
       if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {
@@ -717,7 +752,44 @@ void LinkerScript::processSectionCommands() {
       } else if (process(osec)) {
         osec->sectionIndex = i++;
       }
+    } else if (auto *sc = dyn_cast<SectionClassDesc>(base)) {
+      for (InputSectionDescription *isd : sc->sc.commands) {
+        isd->sectionBases =
+            computeInputSections(isd, ctx.inputSections, sc->sc);
+        for (InputSectionBase *s : isd->sectionBases)
+          s->parent = &sc->sc;
+      }
+      sc->sc.assigned = true;
     }
+  }
+
+  // Check that input sections cannot spill into or out of INSERT,
+  // since the semantics are nebulous. This is also true for OVERWRITE_SECTIONS,
+  // but no check is needed, since the order of processing ensures they cannot
+  // legally reference classes.
+  if (!potentialSpillLists.empty()) {
+    DenseSet<StringRef> insertNames;
+    for (InsertCommand &ic : insertCommands)
+      insertNames.insert(ic.names.begin(), ic.names.end());
+    for (SectionCommand *&base : sectionCommands) {
+      auto *osd = dyn_cast<OutputDesc>(base);
+      if (!osd)
+        continue;
+      OutputSection *os = &osd->osec;
+      if (!insertNames.contains(os->name))
+        continue;
+      for (SectionCommand *sc : os->commands) {
+        auto *isd = dyn_cast<InputSectionDescription>(sc);
+        if (!isd)
+          continue;
+        for (InputSectionBase *isec : isd->sectionBases)
+          if (isa<PotentialSpillSection>(isec) ||
+              potentialSpillLists.contains(isec))
+            error("section '" + isec->name +
+                  "' cannot spill from/to INSERT section '" + os->name + "'");
+      }
+    }
+  }
 
   // If an OVERWRITE_SECTIONS specified output section is not in
   // sectionCommands, append it to the end. The section will be inserted by
@@ -725,6 +797,15 @@ void LinkerScript::processSectionCommands() {
   for (OutputDesc *osd : overwriteSections)
     if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)
       sectionCommands.push_back(osd);
+
+  // Input sections cannot have a section class parent past this point; they
+  // must have been assigned to an output section.
+  for (const auto &[_, sc] : sectionClasses)
+    for (InputSectionDescription *isd : sc->sc.commands)
+      for (InputSectionBase *sec : isd->sectionBases)
+        if (sec->parent && isa<SectionClass>(sec->parent))
+          error("section '" + sec->name + "' assigned to class '" +
+                sec->parent->name + "' but to no output section");
 }
 
 void LinkerScript::processSymbolAssignments() {
@@ -745,8 +826,8 @@ void LinkerScript::processSymbolAssignments() {
   for (SectionCommand *cmd : sectionCommands) {
     if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
       addSymbol(assign);
-    else
-      for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
+    else if (auto *od = dyn_cast<OutputDesc>(cmd))
+      for (SectionCommand *subCmd : od->osec.commands)
         if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
           addSymbol(assign);
   }
@@ -1421,6 +1502,8 @@ LinkerScript::assignAddresses() {
       assign->size = dot - assign->addr;
       continue;
     }
+    if (isa<SectionClassDesc>(cmd))
+      continue;
     if (assignOffsets(&cast<OutputDesc>(cmd)->osec) && !changedOsec)
       changedOsec = &cast<OutputDesc>(cmd)->osec;
   }
@@ -1441,7 +1524,7 @@ static bool hasRegionOverflowed(MemoryRegion *mr) {
 // Under-estimates may cause unnecessary spills, but over-estimates can always
 // be corrected on the next pass.
 bool LinkerScript::spillSections() {
-  if (!config->enableNonContiguousRegions)
+  if (potentialSpillLists.empty())
     return false;
 
   bool spilled = false;
diff --git a/lld/ELF/LinkerScript.h b/lld/ELF/LinkerScript.h
index 36feab36e26ba..a6bbc1019774a 100644
--- a/lld/ELF/LinkerScript.h
+++ b/lld/ELF/LinkerScript.h
@@ -35,6 +35,8 @@ class OutputSection;
 class SectionBase;
 class ThunkSection;
 struct OutputDesc;
+struct SectionClass;
+struct SectionClassDesc;
 
 // This represents an r-value in the linker script.
 struct ExprValue {
@@ -78,7 +80,8 @@ enum SectionsCommandKind {
   AssignmentKind, // . = expr or <sym> = expr
   OutputSectionKind,
   InputSectionKind,
-  ByteKind    // BYTE(expr), SHORT(expr), LONG(expr) or QUAD(expr)
+  ByteKind, // BYTE(expr), SHORT(expr), LONG(expr) or QUAD(expr)
+  ClassKind,
 };
 
 struct SectionCommand {
@@ -198,9 +201,12 @@ class InputSectionDescription : public SectionCommand {
 
 public:
   InputSectionDescription(StringRef filePattern, uint64_t withFlags = 0,
-                          uint64_t withoutFlags = 0)
+                          uint64_t withoutFlags = 0, StringRef className = {})
       : SectionCommand(InputSectionKind), filePat(filePattern),
-        withFlags(withFlags), withoutFlags(withoutFlags) {}
+        withFlags(withFlags), withoutFlags(withoutFlags), className(className) {
+    assert((filePattern.empty() || className.empty()) &&
+           "file pattern and class name are mutually exclusive");
+  }
 
   static bool classof(const SectionCommand *c) {
     return c->kind == InputSectionKind;
@@ -228,6 +234,10 @@ class InputSectionDescription : public SectionCommand {
   // SectionPatterns can be filtered with the INPUT_SECTION_FLAGS command.
   uint64_t withFlags;
   uint64_t withoutFlags;
+
+  // If present, input section matching uses class membership instead of file
+  // and section patterns (mutually exclusive).
+  StringRef className;
 };
 
 // Represents BYTE(), SHORT(), LONG(), or QUAD().
@@ -288,8 +298,7 @@ class LinkerScript final {
 
   SmallVector<InputSectionBase *, 0>
   computeInputSections(const InputSectionDescription *,
-                       ArrayRef<InputSectionBase *>,
-                       const OutputSection &outCmd);
+                       ArrayRef<InputSectionBase *>, const SectionBase &outCmd);
 
   SmallVector<InputSectionBase *, 0> createInputSectionList(OutputSection &cmd);
 
@@ -413,6 +422,11 @@ class LinkerScript final {
     PotentialSpillSection *tail;
   };
   llvm::DenseMap<InputSectionBase *, PotentialSpillList> potentialSpillLists;
+
+  // Named lists of input sections that can be collectively referenced in output
+  // section descriptions. Multiple references allow for sections to spill from
+  // one output section to another.
+  llvm::StringMap<SectionClassDesc *> sectionClasses;
 };
 
 struct ScriptWrapper {
diff --git a/lld/ELF/MapFile.cpp b/lld/ELF/MapFile.cpp
index c4f3fdde30f36..1bad529b40329 100644
--- a/lld/ELF/MapFile.cpp
+++ b/lld/ELF/MapFile.cpp
@@ -167,6 +167,8 @@ static void writeMapFile(raw_fd_ostream &os) {
       os << assign->commandString << '\n';
       continue;
     }
+    if (isa<SectionClassDesc>(cmd))
+      continue;
 
     osec = &cast<OutputDesc>(cmd)->osec;
     writeHeader(os, osec->addr, osec->getLMA(), osec->size, osec->addralign);
diff --git a/lld/ELF/OutputSections.h b/lld/ELF/OutputSections.h
index 78fede48a23f2..c5f03cb8d846a 100644
--- a/lld/ELF/OutputSections.h
+++ b/lld/ELF/OutputSections.h
@@ -137,6 +137,25 @@ struct OutputDesc final : SectionCommand {
   }
 };
 
+// A list of input sections that can be referenced in output descriptions.
+// Multiple references allow sections to spill from one output section to the
+// next.
+struct SectionClass final : public SectionBase {
+  SmallVector<InputSectionDescription *, 0> commands;
+  bool assigned = false;
+
+  SectionClass(StringRef name) : SectionBase(Class, name, 0, 0, 0, 0, 0, 0) {}
+  static bool classof(const SectionBase *s) { return s->kind() == Class; }
+};
+
+struct SectionClassDesc : SectionCommand {
+  SectionClass sc;
+
+  SectionClassDesc(StringRef name) : SectionCommand(ClassKind), sc(name) {}
+
+  static bool classof(const SectionCommand *c) { return c->kind == ClassKind; }
+};
+
 int getPriority(StringRef s);
 
 InputSection *getFirstInputSection(const OutputSection *os);
diff --git a/lld/ELF/ScriptParser.cpp b/lld/ELF/ScriptParser.cpp
index f90ce6fa74075..422bb63b8c03a 100644
--- a/lld/ELF/ScriptParser.cpp
+++ b/lld/ELF/ScriptParser.cpp
@@ -96,6 +96,8 @@ class ScriptParser final : ScriptLexer {
   OutputDesc *readOverlaySectionDescription();
   OutputDesc *readOutputSectionDescription(StringRef outSec);
   SmallVector<SectionCommand *, 0> readOverlay();
+  SectionClassDesc *readSectionClassDescription();
+  StringRef readSectionClassName();
   SmallVector<StringRef, 0> readOutputSectionPhdrs();
   std::pair<uint64_t, uint64_t> readInputSectionFlags();
   InputSectionDescription *readInputSectionDescription(StringRef tok);
@@ -585,6 +587,35 @@ SmallVector<SectionCommand *, 0> ScriptParser::readOverlay() {
   return v;
 }
 
+SectionClassDesc *ScriptParser::readSectionClassDescription() {
+  std::string loc = getCurrentLocation();
+  StringRef name = readSectionClassName();
+  SectionClassDesc *desc = make<SectionClassDesc>(name);
+  if (!script->sectionClasses.insert({name, desc}).second)
+    setError("section class '" + name + "' already defined");
+  expect("{");
+  while (!errorCount() && !consume("}")) {
+    StringRef tok = next();
+    if (tok == "(" || tok == ")")
+      setError("expected filename pattern");
+    else if (peek() == "(") {
+      InputSectionDescription *isd = readInputSectionDescription(tok);
+      if (!isd->className.empty())
+        setError("section class '" + name + "' references class '" +
+                 isd->className + "'");
+      desc->sc.commands.push_back(isd);
+    }
+  }
+  return desc;
+}
+
+StringRef ScriptParser::readSectionClassName() {
+  expect("(");
+  StringRef name = next();
+  expect(")");
+  return name;
+}
+
 void ScriptParser::readOverwriteSections() {
   expect("{");
   while (!errorCount() && !consume("}"))
@@ -600,7 +631,12 @@ void ScriptParser::readSections() {
       for (SectionCommand *cmd : readOverlay())
         v.push_back(cmd);
       continue;
-    } else if (tok == "INCLUDE") {
+    }
+    if (tok == "CLASS") {
+      v.push_back(readSectionClassDescription());
+      continue;
+    }
+    if (tok == "INCLUDE") {
       readInclude();
       continue;
     }
@@ -803,8 +839,14 @@ ScriptParser::readInputSectionDescription(StringRef tok) {
     expect("(");
     if (consume("INPUT_SECTION_FLAGS"))
       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
-    InputSectionDescription *cmd =
-        readInputSectionRules(next(), withFlags, withoutFlags);
+
+    tok = next();
+    InputSectionDescription *cmd;
+    if (tok == "CLASS")
+      cmd = make<InputSectionDescription>(StringRef{}, withFlags, withoutFlags,
+                                          readSectionClassName());
+    else
+      cmd = readInputSectionRules(tok, withFlags, withoutFlags);
     expect(")");
     script->keptSections.push_back(cmd);
     return cmd;
@@ -813,6 +855,9 @@ ScriptParser::readInputSectionDescription(StringRef tok) {
     std::tie(withFlags, withoutFlags) = readInputSectionFlags();
     tok = next();
   }
+  if (tok == "CLASS")
+    return make<InputSectionDescription>(StringRef{}, withFlags, withoutFlags,
+                                         readSectionClassName());
   return readInputSectionRules(tok, withFlags, withoutFlags);
 }
 
@@ -927,8 +972,12 @@ OutputDesc *ScriptParser::readOverlaySectionDescription() {
     uint64_t withoutFlags = 0;
     if (consume("INPUT_SECTION_FLAGS"))
       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
-    osd->osec.commands.push_back(
-        readInputSectionRules(next(), withFlags, withoutFlags));
+    if (peek() == "CLASS")
+      osd->osec.commands.push_back(make<InputSectionDescription>(
+          StringRef{}, withFlags, withoutFlags, next()));
+    else
+      osd->osec.commands.push_back(
+          readInputSectionRules(next(), withFlags, withoutFlags));
   }
   osd->osec.phdrs = readOutputSectionPhdrs();
   return osd;
diff --git a/lld/docs/ELF/linker_script.rst b/lld/docs/ELF/linker_script.rst
index 7a35534be096c..c13bc0dac1fbe 100644
--- a/lld/docs/ELF/linker_script.rst
+++ b/lld/docs/ELF/linker_script.rst
@@ -198,13 +198,52 @@ the current location to a max-page-size boundary, ensuring that the next
 LLD will insert ``.relro_padding`` immediately before the symbol assignment
 using ``DATA_SEGMENT_RELRO_END``.
 
+Section Classes
+~~~~~~~~~~~~~~~
+
+``SECTIONS`` commands can define classes of input sections:
+
+::
+
+  SECTIONS {
+    CLASS(class_name) {
+      input-section-description
+      input-section-description
+      ...
+    }
+  }
+
+Input section descriptions can refer to a class using ``CLASS(class_name)``
+instead of the usual filename and section name patterns. For example:
+
+::
+
+  SECTIONS {
+    CLASS(c) { *(.rodata.earlier) }
+    .rodata { *(.rodata) CLASS(c) (*.rodata.later) }
+  }
+
+Input sections that are assigned to a class cannot be matched by later
+wildcards, just as if they had been assigned to an earlier output section. If a
+class is referenced in multiple output sections, when a memory region would
+overflow, the linker spills input sections from a reference to later references
+rather than failing the link.
+
+Classes cannot reference other classes; an input section is assigned to at most
+one class.
+
+Sections cannot be specified to possibly spill into or out of
+``INSERT [AFTER|BEFORE]``, ``OVERWRITE_SECTIONS``, or ``/DISCARD/``.
+
 Non-contiguous regions
 ~~~~~~~~~~~~~~~~~~~~~~
 
-The flag ``--enable-non-contiguous-regions`` allows input sections to spill to
-later matches rather than causing the link to fail by overflowing a memory
-region. Unlike GNU ld, ``/DISCARD/`` only matches previously-unmatched sections
-(i.e., the flag does not affect it). Also, if a section fails to fit at any of
-its matches, the link fails instead of discarding the section. Accordingly, the
-GNU flag ``--enable-non-contiguous-regions-warnings`` is not implemented, as it
-exists to warn about such occurrences.
+The flag ``--enable-non-contiguous-regions`` provides a version of the above
+spilling functionality that is more compatible with GNU LD. It allows input
+sections to spill to later wildcard matches. (This globally changes the
+behavior of wildcards.) Unlike GNU ld, ``/DISCARD/`` only matches
+previously-unmatched sections (i.e., the flag does not affect it). Also, if a
+section fails to fit at any of its matches, the link fails instead of
+discarding the section. Accordingly, the GNU flag
+``--enable-non-contiguous-regions-warnings`` is not implemented, as it exists
+to warn about such occurrences.
diff --git a/lld/docs/ReleaseNotes.rst b/lld/docs/ReleaseNotes.rst
index 12ea6de0fc15c..685ad89a458d5 100644
--- a/lld/docs/ReleaseNotes.rst
+++ b/lld/docs/ReleaseNotes.rst
@@ -38,6 +38,13 @@ ELF Improvements
 * ``--debug-names`` is added to create a merged ``.debug_names`` index
   from input ``.debug_names`` sections. Type units are not handled yet.
   (`#86508 <https://github.com/llvm/llvm-project/pull/86508>`_)
+* Section ``CLASS`` syntax allows binding input section to named classes. This
+  allows the linker to automatically pack the input sections into memory
+  regions by automatically spilling to later class references if a region would
+  overflow. This reduces the toil of manually packing regions (typical for
+  embedded). It also makes full LTO feasible in such cases, since IR merging
+  currently prevents the linker script from referring to input files. (TODO: PR
+  Reference)
 * ``--enable-non-contiguous-regions`` option allows automatically packing input
   sections into memory regions by automatically spilling to later matches if a
   region would overflow. This reduces the toil of manually packing regions
diff --git a/lld/test/ELF/linkerscript/section-class.test b/lld/test/ELF/linkerscript/section-class.test
new file mode 100644
index 0000000000000..6a50cd0602784
--- /dev/null
+++ b/lld/test/ELF/linkerscript/section-class.test
@@ -0,0 +1,379 @@
+# REQUIRES: x86
+
+# RUN: rm -rf %t && split-file %s %t && cd %t
+
+# RUN: llvm-mc -n -filetype=obj -triple=x86_64 matching.s -o matching.o
+
+## CLASS definitions match sections in linker script order. The sections may be
+## placed in a different order. Classes may derive from one another, and class
+## references may be restricted by INPUT_SECTION_FLAGS.
+
+# RUN: ld.lld -T matching.ld matching.o -o matching
+# RUN: llvm-readobj -x .rodata matching | FileCheck %s --check-prefix=MATCHING
+
+# MATCHING: 02030104
+
+
+## An error is reported when a section class has more than one description.
+
+# RUN: not ld.lld -T already-defined.ld matching.o 2>&1 | \
+# RUN:   FileCheck %s --check-prefix=ALREADY-DEFINED --implicit-check-not=error:
+
+# ALREADY-DEFINED: error: already-defined.ld:3: section class 'a' already defined
+
+
+## An error is reported when a filename pattern is missing in a section class
+## description.
+
+# RUN: not ld.lld -T missing-filename-pattern.ld matching.o 2>&1 | \
+# RUN:   FileCheck %s --check-prefix=MISSING-FILENAME-PATTERN --implicit-check-not=error:
+
+# MISSING-FILENAME-PATTERN: error: missing-filename-pattern.ld:2: expected filename pattern
+
+
+## An error is reported when the content of section classes is demanded before
+## input sections have been assigned to them.
+
+# RUN: not ld.lld -T used-before-assigned.ld matching.o 2>&1 | \
+# RUN:   FileCheck %s --check-prefix=USED-BEFORE-ASSIGNED
+
+# USED-BEFORE-ASSIGNED: error: section class 'a' used before assigned
+
+
+## An error is reported when an input section is bound to a section class but
+## is not referenced by at least one output section.
+
+# RUN: not ld.lld -T unreferenced.ld matching.o 2>&1 | \
+# RUN:   FileCheck %s --check-prefix=UNREFERENCED
+
+# UNREFERENCED: error: section '.rodata.a' assigned to class 'a' but to no output section
+
+
+## An error is reported when one section class references another.
+
+# RUN: not ld.lld -T class-references-class.ld matching.o 2>&1 | \
+# RUN:   FileCheck %s --check-prefix=CLASS-REFERENCES-CLASS --implicit-check-not=error:
+
+# CLASS-REFERENCES-CLASS: error: class-references-class.ld:3: section class 'b' references class 'a'
+
+
+# RUN: llvm-mc -n -filetype=obj -triple=x86_64 spill.s -o spill.o
+
+
+## An input section in a class spills to a later class ref when the region of
+## its first ref would overflow. The spill uses the alignment of the later ref.
+
+# RUN: ld.lld -T spill.ld spill.o -o spill
+# RUN: llvm-readelf -S spill | FileCheck %s --check-prefix=SPILL
+
+# SPILL:      Name          Type     Address          Off    Size
+# SPILL:      .first_chance PROGBITS 0000000000000000 001000 000001
+# SPILL-NEXT: .last_chance  PROGBITS 0000000000000008 001008 000002
+
+
+## A spill off the end still fails the link.
+
+# RUN: not ld.lld -T spill-fail.ld spill.o 2>&1 |\
+# RUN:   FileCheck %s --check-prefix=SPILL-FAIL --implicit-check-not=error:
+
+# SPILL-FAIL: error: section '.last_chance' will not fit in region 'b': overflowed by 2 bytes
+
+
+## The above spill still occurs when the LMA would overflow, even though the
+## VMA would fit.
+
+# RUN: ld.lld -T spill-lma.ld spill.o -o spill-lma
+# RUN: llvm-readelf -S spill-lma | FileCheck %s --check-prefix=SPILL-LMA
+
+# SPILL-LMA:      Name          Type     Address          Off    Size
+# SPILL-LMA:      .first_chance PROGBITS 0000000000000000 001000 000001
+# SPILL-LMA-NEXT: .last_chance  PROGBITS 0000000000000003 001003 000002
+
+
+## A spill occurs to an additional class ref after the first.
+
+# RUN: ld.lld -T spill-later.ld spill.o -o spill-later
+# RUN: llvm-readelf -S spill-later | FileCheck %s --check-prefix=SPILL-LATER
+
+# SPILL-LATER:      Name            Type     Address          Off    Size
+# SPILL-LATER:      .first_chance   PROGBITS 0000000000000000 001000 000001
+# SPILL-LATER-NEXT: .second_chance  PROGBITS 0000000000000002 001001 000000
+# SPILL-LATER-NEXT: .last_chance    PROGBITS 0000000000000003 001003 000002
+
+
+## A later overflow causes an earlier section to spill.
+
+# RUN: ld.lld -T spill-earlier.ld spill.o -o spill-earlier
+# RUN: llvm-readelf -S spill-earlier | FileCheck %s --check-prefix=SPILL-EARLIER
+
+# SPILL-EARLIER:      Name          Type     Address          Off    Size
+# SPILL-EARLIER:      .first_chance PROGBITS 0000000000000000 001000 000002
+# SPILL-EARLIER-NEXT: .last_chance  PROGBITS 0000000000000002 001002 000001
+
+
+## SHF_MERGEd sections are spilled according to the class refs of the first
+## merged input section (the one giving the resulting section its name).
+
+# RUN: llvm-mc -n -filetype=obj -triple=x86_64 merge.s -o merge.o
+# RUN: ld.lld -T spill-merge.ld merge.o -o spill-merge
+# RUN: llvm-readelf -S spill-merge | FileCheck %s --check-prefix=SPILL-MERGE
+
+# SPILL-MERGE:      Name          Type     Address          Off    Size
+# SPILL-MERGE:      .first  PROGBITS 0000000000000000 000190 000000
+# SPILL-MERGE-NEXT: .second PROGBITS 0000000000000001 001001 000002
+# SPILL-MERGE-NEXT: .third  PROGBITS 0000000000000003 001003 000000
+
+
+## SHF_LINK_ORDER is reordered when spilling changes relative section order.
+
+# RUN: llvm-mc -n -filetype=obj -triple=x86_64 link-order.s -o link-order.o
+# RUN: ld.lld -T link-order.ld link-order.o -o link-order
+# RUN: llvm-readobj -x .order link-order | FileCheck %s --check-prefix=LINK-ORDER
+
+# LINK-ORDER: 020301
+
+
+## An error is reported when a section might spill from INSERT.
+
+# RUN: not ld.lld -T from-insert.ld spill.o 2>&1 |\
+# RUN:   FileCheck %s --check-prefix=FROM-INSERT
+
+# FROM-INSERT: error: section '.two_byte_section' cannot spill from/to INSERT section '.b'
+
+
+## An error is reported when a section might spill to INSERT.
+
+# RUN: not ld.lld -T to-insert.ld spill.o 2>&1 |\
+# RUN:   FileCheck %s --check-prefix=TO-INSERT
+
+# TO-INSERT: error: section '.two_byte_section' cannot spill from/to INSERT section '.b'
+
+
+## An error is reported when a section might spill from /DISCARD/.
+
+# RUN: not ld.lld -T from-discard.ld spill.o 2>&1 |\
+# RUN:   FileCheck %s --check-prefix=FROM-DISCARD
+
+# FROM-DISCARD: error: section '.two_byte_section' cannot spill from/to /DISCARD/
+
+
+## An error is reported when a section might spill to /DISCARD/.
+
+# RUN: not ld.lld -T to-discard.ld spill.o 2>&1 |\
+# RUN:   FileCheck %s --check-prefix=TO-DISCARD
+
+# TO-DISCARD: error: section '.two_byte_section' cannot spill from/to /DISCARD/
+
+#--- matching.s
+.section .rodata.a,"a", at progbits
+.byte 1
+
+.section .rodata.b,"a", at progbits
+.byte 2
+
+.section .rodata.c,"ax", at progbits
+.byte 3
+
+.section .rodata.d,"a", at progbits
+.byte 4
+
+#--- matching.ld
+MEMORY {
+ m : ORIGIN = 0, LENGTH = 4
+}
+
+SECTIONS {
+  CLASS(a) { *(.rodata.a) }
+  CLASS(cd) { *(.rodata.c) *(.rodata.d) }
+  .rodata : {
+    *(.rodata.*)
+    INPUT_SECTION_FLAGS(SHF_EXECINSTR) CLASS(cd)
+    CLASS(a)
+    CLASS(cd)
+  } >m
+}
+
+#--- already-defined.ld
+SECTIONS {
+  CLASS(a) { *(.rodata.a) }
+  CLASS(a) { *(.rodata.b) }
+}
+
+#--- missing-filename-pattern.ld
+SECTIONS {
+  CLASS(a) { (.rodata.a) }
+}
+
+#--- used-before-assigned.ld
+SECTIONS {
+  .rodata : { CLASS(a) }
+  CLASS(a) { *(.rodata.a) }
+}
+
+#--- unreferenced.ld
+SECTIONS {
+  CLASS(a) { *(.rodata.*) }
+}
+
+#--- class-references-class.ld
+SECTIONS {
+  CLASS(a) { *(.rodata.a) }
+  CLASS(b) { CLASS(a) }
+}
+
+#--- spill.s
+.section .one_byte_section,"a", at progbits
+.fill 1
+
+.section .two_byte_section,"a", at progbits
+.fill 2
+
+#--- spill.ld
+MEMORY {
+  a : ORIGIN = 0, LENGTH = 2
+  b : ORIGIN = 2, LENGTH = 16
+}
+
+SECTIONS {
+  CLASS(c) { *(.two_byte_section) }
+  .first_chance : SUBALIGN(1) { *(.one_byte_section) CLASS(c) } >a
+  .last_chance : SUBALIGN(8) { CLASS (c) } >b
+}
+
+#--- spill-fail.ld
+MEMORY {
+  a : ORIGIN = 0, LENGTH = 1
+  b : ORIGIN = 2, LENGTH = 0
+}
+
+SECTIONS {
+  CLASS(c) { *(.two_byte_section) }
+  .first_chance : { *(.one_byte_section) CLASS(c) } >a
+  .last_chance : { CLASS(c) } >b
+}
+
+#--- spill-lma.ld
+MEMORY {
+  vma_a : ORIGIN = 0, LENGTH = 3
+  vma_b : ORIGIN = 3, LENGTH = 3
+  lma_a : ORIGIN = 6, LENGTH = 2
+  lma_b : ORIGIN = 8, LENGTH = 2
+}
+
+SECTIONS {
+  CLASS(c) { *(.two_byte_section) }
+  .first_chance : { *(.one_byte_section) CLASS(c) } >vma_a AT>lma_a
+  .last_chance : { CLASS(c) } >vma_b AT>lma_b
+}
+
+#--- spill-later.ld
+MEMORY {
+  a : ORIGIN = 0, LENGTH = 2
+  b : ORIGIN = 2, LENGTH = 1
+  c : ORIGIN = 3, LENGTH = 2
+}
+
+SECTIONS {
+  CLASS(c) { *(.two_byte_section) }
+  .first_chance : { *(.one_byte_section) CLASS(c) } >a
+  .second_chance : { CLASS(c) } >b
+  .last_chance : { CLASS(c) } >c
+}
+
+#--- spill-earlier.ld
+MEMORY {
+  a : ORIGIN = 0, LENGTH = 2
+  b : ORIGIN = 2, LENGTH = 1
+}
+
+SECTIONS {
+  CLASS(c) { *(.one_byte_section) }
+  .first_chance : { CLASS(c) *(.two_byte_section) } >a
+  .last_chance : { CLASS(c) } >b
+}
+
+#--- merge.s
+.section .a,"aM", at progbits,1
+.byte 0x12, 0x34
+
+.section .b,"aM", at progbits,1
+.byte 0x12
+
+#--- spill-merge.ld
+MEMORY {
+  a : ORIGIN = 0, LENGTH = 1
+  b : ORIGIN = 1, LENGTH = 2
+  c : ORIGIN = 3, LENGTH = 2
+}
+
+SECTIONS {
+  CLASS(a) { *(.a) }
+  CLASS(b) { *(.b) }
+  .first : { CLASS(a) CLASS(b) } >a
+  .second : { CLASS(a) } >b
+  .third : { CLASS(b) } >c
+}
+
+#--- link-order.s
+.section .a,"a", at progbits
+.fill 1
+
+.section .b,"a", at progbits
+.fill 1
+
+.section .c,"a", at progbits
+.fill 1
+
+.section .link_order.a,"ao", at progbits,.a
+.byte 1
+
+.section .link_order.b,"ao", at progbits,.b
+.byte 2
+
+.section .link_order.c,"ao", at progbits,.c
+.byte 3
+
+#--- link-order.ld
+MEMORY {
+  order : ORIGIN = 0, LENGTH = 3
+  potential_a : ORIGIN = 3, LENGTH = 0
+  bc : ORIGIN = 3, LENGTH = 2
+  actual_a : ORIGIN = 5, LENGTH = 1
+}
+
+SECTIONS {
+  CLASS(a) { *(.a) }
+  .order :  { *(.link_order.*) } > order
+  .potential_a : { CLASS(a) } >potential_a
+  .bc : { *(.b) *(.c) } >bc
+  .actual_a : { CLASS(a) } >actual_a
+}
+
+#--- from-insert.ld
+SECTIONS {
+  CLASS(class) { *(.two_byte_section) }
+  .a : { *(.one_byte_section) }
+}
+SECTIONS { .b : { CLASS(class) } } INSERT AFTER .a;
+SECTIONS { .c : { CLASS(class) } }
+
+#--- to-insert.ld
+SECTIONS {
+  CLASS(class) { *(.two_byte_section) }
+  .a : { CLASS(class) *(.one_byte_section) }
+}
+SECTIONS { .b : { CLASS(class) } } INSERT AFTER .a;
+
+#--- from-discard.ld
+SECTIONS {
+  CLASS(class) { *(.two_byte_section) }
+  /DISCARD/ : { CLASS(class) }
+  .c : { CLASS(class) }
+}
+
+#--- to-discard.ld
+SECTIONS {
+  CLASS(class) { *(.two_byte_section) }
+  .a : { CLASS(class) }
+  /DISCARD/ : { CLASS(class) }
+}

>From 7715fc99d8b04d257d6de06d56f9548e6b2b8fab Mon Sep 17 00:00:00 2001
From: Daniel Thornburgh <dthorn at google.com>
Date: Thu, 13 Jun 2024 14:04:11 -0700
Subject: [PATCH 2/2] Address review comments

- Used consistent terminology for error when section classes are
  referenced before their definition.
- " for error when sections assigned to a class are never referenced
- Add test for class references in OVERLAY; fix parser.
---
 lld/ELF/LinkerScript.cpp                     |  5 ++--
 lld/ELF/ScriptParser.cpp                     |  7 ++---
 lld/test/ELF/linkerscript/section-class.test | 28 +++++++++-----------
 3 files changed, 20 insertions(+), 20 deletions(-)

diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index 2666ab780975f..39b428b0ea759 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -601,7 +601,8 @@ LinkerScript::computeInputSections(const InputSectionDescription *cmd,
       return ret;
     }
     if (!scd->sc.assigned) {
-      error("section class '" + cmd->className + "' used before assigned");
+      error("section class '" + cmd->className + "' referenced by '" +
+            outCmd.name + "' before class definition");
       return ret;
     }
 
@@ -805,7 +806,7 @@ void LinkerScript::processSectionCommands() {
       for (InputSectionBase *sec : isd->sectionBases)
         if (sec->parent && isa<SectionClass>(sec->parent))
           error("section '" + sec->name + "' assigned to class '" +
-                sec->parent->name + "' but to no output section");
+                sec->parent->name + "' but unreferenced by any output section");
 }
 
 void LinkerScript::processSymbolAssignments() {
diff --git a/lld/ELF/ScriptParser.cpp b/lld/ELF/ScriptParser.cpp
index 422bb63b8c03a..5b3dab1f20756 100644
--- a/lld/ELF/ScriptParser.cpp
+++ b/lld/ELF/ScriptParser.cpp
@@ -972,12 +972,13 @@ OutputDesc *ScriptParser::readOverlaySectionDescription() {
     uint64_t withoutFlags = 0;
     if (consume("INPUT_SECTION_FLAGS"))
       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
-    if (peek() == "CLASS")
+    StringRef tok = next();
+    if (tok == "CLASS")
       osd->osec.commands.push_back(make<InputSectionDescription>(
-          StringRef{}, withFlags, withoutFlags, next()));
+          StringRef{}, withFlags, withoutFlags, readSectionClassName()));
     else
       osd->osec.commands.push_back(
-          readInputSectionRules(next(), withFlags, withoutFlags));
+          readInputSectionRules(tok, withFlags, withoutFlags));
   }
   osd->osec.phdrs = readOutputSectionPhdrs();
   return osd;
diff --git a/lld/test/ELF/linkerscript/section-class.test b/lld/test/ELF/linkerscript/section-class.test
index 6a50cd0602784..5a3b07a0e485b 100644
--- a/lld/test/ELF/linkerscript/section-class.test
+++ b/lld/test/ELF/linkerscript/section-class.test
@@ -9,9 +9,12 @@
 ## references may be restricted by INPUT_SECTION_FLAGS.
 
 # RUN: ld.lld -T matching.ld matching.o -o matching
-# RUN: llvm-readobj -x .rodata matching | FileCheck %s --check-prefix=MATCHING
+# RUN: llvm-readobj -x .rodata -x .rodata.d matching | FileCheck %s --check-prefix=MATCHING
 
-# MATCHING: 02030104
+# MATCHING:      .rodata
+# MATCHING-NEXT: 020301
+# MATCHING:      .rodata.d
+# MATCHING-NEXT: 04
 
 
 ## An error is reported when a section class has more than one description.
@@ -32,13 +35,12 @@
 
 
 ## An error is reported when the content of section classes is demanded before
-## input sections have been assigned to them.
+## its definition is processed.
 
-# RUN: not ld.lld -T used-before-assigned.ld matching.o 2>&1 | \
-# RUN:   FileCheck %s --check-prefix=USED-BEFORE-ASSIGNED
-
-# USED-BEFORE-ASSIGNED: error: section class 'a' used before assigned
+# RUN: not ld.lld -T referenced-before-defined.ld matching.o 2>&1 | \
+# RUN:   FileCheck %s --check-prefix=REFERENCED-BEFORE-DEFINED
 
+# REFERENCED-BEFORE-DEFINED: error: section class 'a' referenced by '.rodata' before class definition
 
 ## An error is reported when an input section is bound to a section class but
 ## is not referenced by at least one output section.
@@ -46,7 +48,7 @@
 # RUN: not ld.lld -T unreferenced.ld matching.o 2>&1 | \
 # RUN:   FileCheck %s --check-prefix=UNREFERENCED
 
-# UNREFERENCED: error: section '.rodata.a' assigned to class 'a' but to no output section
+# UNREFERENCED: error: section '.rodata.a' assigned to class 'a' but unreferenced by any output section
 
 
 ## An error is reported when one section class references another.
@@ -178,10 +180,6 @@
 .byte 4
 
 #--- matching.ld
-MEMORY {
- m : ORIGIN = 0, LENGTH = 4
-}
-
 SECTIONS {
   CLASS(a) { *(.rodata.a) }
   CLASS(cd) { *(.rodata.c) *(.rodata.d) }
@@ -189,8 +187,8 @@ SECTIONS {
     *(.rodata.*)
     INPUT_SECTION_FLAGS(SHF_EXECINSTR) CLASS(cd)
     CLASS(a)
-    CLASS(cd)
-  } >m
+  }
+  OVERLAY : { .rodata.d { INPUT_SECTION_FLAGS(!SHF_EXECINSTR) CLASS(cd) } }
 }
 
 #--- already-defined.ld
@@ -204,7 +202,7 @@ SECTIONS {
   CLASS(a) { (.rodata.a) }
 }
 
-#--- used-before-assigned.ld
+#--- referenced-before-defined.ld
 SECTIONS {
   .rodata : { CLASS(a) }
   CLASS(a) { *(.rodata.a) }



More information about the llvm-commits mailing list