#include "ICF.h"
#include "COFFLinkerContext.h"
#include "Chunks.h"
#include "Symbols.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Timer.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/xxhash.h"
#include <algorithm>
#include <atomic>
#include <vector>
using namespace llvm;
namespace lld::coff {
class ICF {
public:
ICF(COFFLinkerContext &c) : ctx(c){};
void run();
private:
void segregate(size_t begin, size_t end, bool constant);
bool assocEquals(const SectionChunk *a, const SectionChunk *b);
bool equalsConstant(const SectionChunk *a, const SectionChunk *b);
bool equalsVariable(const SectionChunk *a, const SectionChunk *b);
bool isEligible(SectionChunk *c);
size_t findBoundary(size_t begin, size_t end);
void forEachClassRange(size_t begin, size_t end,
std::function<void(size_t, size_t)> fn);
void forEachClass(std::function<void(size_t, size_t)> fn);
std::vector<SectionChunk *> chunks;
int cnt = 0;
std::atomic<bool> repeat = {false};
COFFLinkerContext &ctx;
};
bool ICF::isEligible(SectionChunk *c) {
bool writable = c->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
if (!c->isCOMDAT() || !c->live || writable)
return false;
if ((ctx.config.doICF == ICFLevel::All) &&
c->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
return true;
StringRef outSecName = c->getSectionName().split('$').first;
if (outSecName == ".pdata" || outSecName == ".xdata")
return true;
const char *itaniumVtablePrefix =
ctx.config.machine == I386 ? "__ZTV" : "_ZTV";
if (c->sym && (c->sym->getName().starts_with("??_7") ||
c->sym->getName().starts_with(itaniumVtablePrefix)))
return true;
return !c->keepUnique;
}
void ICF::segregate(size_t begin, size_t end, bool constant) {
while (begin < end) {
auto bound = std::stable_partition(
chunks.begin() + begin + 1, chunks.begin() + end, [&](SectionChunk *s) {
if (constant)
return equalsConstant(chunks[begin], s);
return equalsVariable(chunks[begin], s);
});
size_t mid = bound - chunks.begin();
for (size_t i = begin; i < mid; ++i)
chunks[i]->eqClass[(cnt + 1) % 2] = mid;
if (mid != end)
repeat = true;
begin = mid;
}
}
bool ICF::assocEquals(const SectionChunk *a, const SectionChunk *b) {
auto considerForICF = [](const SectionChunk &assoc) {
StringRef Name = assoc.getSectionName();
return !(Name.starts_with(".debug") || Name == ".gfids$y" ||
Name == ".giats$y" || Name == ".gljmp$y");
};
auto ra = make_filter_range(a->children(), considerForICF);
auto rb = make_filter_range(b->children(), considerForICF);
return std::equal(ra.begin(), ra.end(), rb.begin(), rb.end(),
[&](const SectionChunk &ia, const SectionChunk &ib) {
return ia.eqClass[cnt % 2] == ib.eqClass[cnt % 2];
});
}
bool ICF::equalsConstant(const SectionChunk *a, const SectionChunk *b) {
if (a->relocsSize != b->relocsSize)
return false;
auto eq = [&](const coff_relocation &r1, const coff_relocation &r2) {
if (r1.Type != r2.Type ||
r1.VirtualAddress != r2.VirtualAddress) {
return false;
}
Symbol *b1 = a->file->getSymbol(r1.SymbolTableIndex);
Symbol *b2 = b->file->getSymbol(r2.SymbolTableIndex);
if (b1 == b2)
return true;
if (auto *d1 = dyn_cast<DefinedRegular>(b1))
if (auto *d2 = dyn_cast<DefinedRegular>(b2))
return d1->getValue() == d2->getValue() &&
d1->getChunk()->eqClass[cnt % 2] == d2->getChunk()->eqClass[cnt % 2];
return false;
};
if (!std::equal(a->getRelocs().begin(), a->getRelocs().end(),
b->getRelocs().begin(), eq))
return false;
return a->getOutputCharacteristics() == b->getOutputCharacteristics() &&
a->getSectionName() == b->getSectionName() &&
a->header->SizeOfRawData == b->header->SizeOfRawData &&
a->checksum == b->checksum && a->getContents() == b->getContents() &&
a->getMachine() == b->getMachine() && assocEquals(a, b);
}
bool ICF::equalsVariable(const SectionChunk *a, const SectionChunk *b) {
auto eqSym = [&](Symbol *b1, Symbol *b2) {
if (b1 == b2)
return true;
if (auto *d1 = dyn_cast<DefinedRegular>(b1))
if (auto *d2 = dyn_cast<DefinedRegular>(b2))
return d1->getChunk()->eqClass[cnt % 2] == d2->getChunk()->eqClass[cnt % 2];
return false;
};
auto eq = [&](const coff_relocation &r1, const coff_relocation &r2) {
Symbol *b1 = a->file->getSymbol(r1.SymbolTableIndex);
Symbol *b2 = b->file->getSymbol(r2.SymbolTableIndex);
return eqSym(b1, b2);
};
Symbol *e1 = a->getEntryThunk();
Symbol *e2 = b->getEntryThunk();
if ((e1 || e2) && (!e1 || !e2 || !eqSym(e1, e2)))
return false;
return std::equal(a->getRelocs().begin(), a->getRelocs().end(),
b->getRelocs().begin(), eq) &&
assocEquals(a, b);
}
size_t ICF::findBoundary(size_t begin, size_t end) {
for (size_t i = begin + 1; i < end; ++i)
if (chunks[begin]->eqClass[cnt % 2] != chunks[i]->eqClass[cnt % 2])
return i;
return end;
}
void ICF::forEachClassRange(size_t begin, size_t end,
std::function<void(size_t, size_t)> fn) {
while (begin < end) {
size_t mid = findBoundary(begin, end);
fn(begin, mid);
begin = mid;
}
}
void ICF::forEachClass(std::function<void(size_t, size_t)> fn) {
if (chunks.size() < 1024) {
forEachClassRange(0, chunks.size(), fn);
++cnt;
return;
}
const size_t numShards = 256;
size_t step = chunks.size() / numShards;
size_t boundaries[numShards + 1];
boundaries[0] = 0;
boundaries[numShards] = chunks.size();
parallelFor(1, numShards, [&](size_t i) {
boundaries[i] = findBoundary((i - 1) * step, chunks.size());
});
parallelFor(1, numShards + 1, [&](size_t i) {
if (boundaries[i - 1] < boundaries[i]) {
forEachClassRange(boundaries[i - 1], boundaries[i], fn);
}
});
++cnt;
}
void ICF::run() {
llvm::TimeTraceScope timeScope("ICF");
ScopedTimer t(ctx.icfTimer);
uint32_t nextId = 1;
for (Chunk *c : ctx.symtab.getChunks()) {
if (auto *sc = dyn_cast<SectionChunk>(c)) {
if (isEligible(sc))
chunks.push_back(sc);
else
sc->eqClass[0] = nextId++;
}
}
for (MergeChunk *mc : ctx.mergeChunkInstances)
if (mc)
for (SectionChunk *sc : mc->sections)
sc->eqClass[0] = nextId++;
parallelForEach(chunks, [&](SectionChunk *sc) {
sc->eqClass[0] = xxh3_64bits(sc->getContents());
});
for (unsigned cnt = 0; cnt != 2; ++cnt) {
parallelForEach(chunks, [&](SectionChunk *sc) {
uint32_t hash = sc->eqClass[cnt % 2];
for (Symbol *b : sc->symbols())
if (auto *sym = dyn_cast_or_null<DefinedRegular>(b))
hash += sym->getChunk()->eqClass[cnt % 2];
sc->eqClass[(cnt + 1) % 2] = hash | (1U << 31);
});
}
llvm::stable_sort(chunks, [](const SectionChunk *a, const SectionChunk *b) {
return a->eqClass[0] < b->eqClass[0];
});
forEachClass([&](size_t begin, size_t end) { segregate(begin, end, true); });
do {
repeat = false;
forEachClass(
[&](size_t begin, size_t end) { segregate(begin, end, false); });
} while (repeat);
log("ICF needed " + Twine(cnt) + " iterations");
forEachClass([&](size_t begin, size_t end) {
if (end - begin == 1)
return;
log("Selected " + chunks[begin]->getDebugName());
for (size_t i = begin + 1; i < end; ++i) {
log(" Removed " + chunks[i]->getDebugName());
chunks[begin]->replace(chunks[i]);
}
});
}
void doICF(COFFLinkerContext &ctx) { ICF(ctx).run(); }
}