Index: ELF/InputSection.h =================================================================== --- ELF/InputSection.h +++ ELF/InputSection.h @@ -314,6 +314,11 @@ // to. The writer sets a value. uint64_t OutSecOff = 0; + // The order in which the section was added to its output section. This is + // used when ordering SHF_LINK_ORDER sections. It is not set for sections + // inserted late, such as thunk sections. + llvm::Optional OutSecPos; + static bool classof(const SectionBase *S); InputSectionBase *getRelocatedSection(); Index: ELF/OutputSections.h =================================================================== --- ELF/OutputSections.h +++ ELF/OutputSections.h @@ -113,6 +113,11 @@ void sort(std::function Order); void sortInitFini(); void sortCtorsDtors(); + +private: + // The number of input sections assigned to this section excluding + // late-inserted sections, such as thunk sections. + size_t InputSectionCount = 0; }; int getPriority(StringRef S); Index: ELF/OutputSections.cpp =================================================================== --- ELF/OutputSections.cpp +++ ELF/OutputSections.cpp @@ -87,6 +87,7 @@ Live = true; S->Parent = this; this->updateAlignment(S->Alignment); + S->OutSecPos = InputSectionCount++; // The actual offsets will be computed by assignAddresses. For now, use // crude approximation so that it is at least easy for other code to know the @@ -427,7 +428,9 @@ OutputSection *BOut = LB->getParent(); if (AOut != BOut) return AOut->SectionIndex < BOut->SectionIndex; - return LA->OutSecOff < LB->OutSecOff; + assert(LA->OutSecPos && LB->OutSecPos && + "Cannot compare late-inserted section positions."); + return LA->OutSecPos < LB->OutSecPos; } template