Skip to content

Commit 8aef04f

Browse files
committed
[lld][WebAssembly] Implement --why-extract flag from the ELF backend
See https://reviews.llvm.org/D109572 for the original ELF version. Differential Revision: https://reviews.llvm.org/D145431
1 parent 71b3806 commit 8aef04f

File tree

5 files changed

+143
-8
lines changed

5 files changed

+143
-8
lines changed

lld/test/wasm/why-extract.s

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# RUN: rm -rf %t && split-file %s %t
2+
# RUN: llvm-mc -filetype=obj -triple=wasm32-unknown-unknown %t/main.s -o %t/main.o
3+
# RUN: llvm-mc -filetype=obj -triple=wasm32-unknown-unknown %t/a.s -o %t/a.o
4+
# RUN: llvm-mc -filetype=obj -triple=wasm32-unknown-unknown %t/a_b.s -o %t/a_b.o
5+
# RUN: llvm-mc -filetype=obj -triple=wasm32-unknown-unknown %t/b.s -o %t/b.o
6+
# RUN: llvm-ar rc %t/a.a %t/a.o
7+
# RUN: llvm-ar rc %t/a_b.a %t/a_b.o
8+
# RUN: llvm-ar rc %t/b.a %t/b.o
9+
# RUN: cd %t
10+
11+
## Nothing is extracted from an archive. The file is created with just a header.
12+
# RUN: wasm-ld main.o a.o b.a -o /dev/null --why-extract=why1.txt
13+
# RUN: FileCheck %s --input-file=why1.txt --check-prefix=CHECK1 --match-full-lines --strict-whitespace
14+
15+
# CHECK1:reference extracted symbol
16+
# CHECK1-NOT:{{.}}
17+
18+
## Some archive members are extracted.
19+
# RUN: wasm-ld main.o a_b.a b.a -o /dev/null --why-extract=why2.txt
20+
# RUN: FileCheck %s --input-file=why2.txt --check-prefix=CHECK2 --match-full-lines --strict-whitespace
21+
22+
# CHECK2:reference extracted symbol
23+
# CHECK2-NEXT:main.o a_b.a(a_b.o) a
24+
# CHECK2-NEXT:a_b.a(a_b.o) b.a(b.o) b()
25+
26+
## An undefined symbol error does not suppress the output.
27+
# RUN: not wasm-ld main.o a_b.a -o /dev/null --why-extract=why3.txt
28+
# RUN: FileCheck %s --input-file=why3.txt --check-prefix=CHECK3 --match-full-lines --strict-whitespace
29+
30+
## Check that backward references are supported.
31+
## - means stdout.
32+
# RUN: wasm-ld b.a a_b.a main.o -o /dev/null --why-extract=- | FileCheck %s --check-prefix=CHECK4
33+
34+
# CHECK3:reference extracted symbol
35+
# CHECK3-NEXT:main.o a_b.a(a_b.o) a
36+
37+
# CHECK4:reference extracted symbol
38+
# CHECK4-NEXT:a_b.a(a_b.o) b.a(b.o) b()
39+
# CHECK4-NEXT:main.o a_b.a(a_b.o) a
40+
41+
# RUN: wasm-ld main.o a_b.a b.a -o /dev/null --no-demangle --why-extract=- | FileCheck %s --check-prefix=MANGLED
42+
43+
# MANGLED: a_b.a(a_b.o) b.a(b.o) _Z1bv
44+
45+
# RUN: wasm-ld main.o a.a b.a -o /dev/null -u _Z1bv --why-extract=- | FileCheck %s --check-prefix=UNDEFINED
46+
47+
## We insert -u symbol before processing other files, so its name is <internal>.
48+
## This is not ideal.
49+
# UNDEFINED: <internal> b.a(b.o) b()
50+
51+
# RUN: wasm-ld main.o a.a b.a -o /dev/null -e _Z1bv --why-extract=- | FileCheck %s --check-prefix=ENTRY
52+
53+
# ENTRY: --entry b.a(b.o) b()
54+
55+
# SCRIPT: <internal> b.a(b.o) b()
56+
57+
# RUN: not wasm-ld -shared main.o -o /dev/null --why-extract=/ 2>&1 | FileCheck %s --check-prefix=ERR
58+
59+
# ERR: error: cannot open --why-extract= file /: {{.*}}
60+
61+
#--- main.s
62+
.globl _start
63+
.functype a () -> ()
64+
_start:
65+
.functype _start () -> ()
66+
call a
67+
end_function
68+
69+
#--- a.s
70+
.globl a
71+
a:
72+
.functype a () -> ()
73+
end_function
74+
75+
#--- a_b.s
76+
.functype _Z1bv () -> ()
77+
.globl a
78+
a:
79+
.functype a () -> ()
80+
call _Z1bv
81+
end_function
82+
83+
#--- b.s
84+
.globl _Z1bv
85+
_Z1bv:
86+
.functype _Z1bv () -> ()
87+
end_function

lld/wasm/Config.h

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ enum Level : int;
2323
namespace lld {
2424
namespace wasm {
2525

26+
class InputFile;
27+
class Symbol;
28+
2629
// For --unresolved-symbols.
2730
enum class UnresolvedPolicy { ReportError, Warn, Ignore, ImportDynamic };
2831

@@ -81,6 +84,7 @@ struct Configuration {
8184
llvm::StringRef mapFile;
8285
llvm::StringRef outputFile;
8386
llvm::StringRef thinLTOCacheDir;
87+
llvm::StringRef whyExtract;
8488

8589
llvm::StringSet<> allowUndefinedSymbols;
8690
llvm::StringSet<> exportedSymbols;
@@ -92,7 +96,8 @@ struct Configuration {
9296
llvm::SmallVector<uint8_t, 0> buildIdVector;
9397

9498
// The following config options do not directly correspond to any
95-
// particular command line options.
99+
// particular command line options, and should probably be moved to seperate
100+
// Ctx struct as in ELF/Config.h
96101

97102
// True if we are creating position-independent code.
98103
bool isPic;
@@ -110,6 +115,11 @@ struct Configuration {
110115
// Will be set to true if bss data segments should be emitted. In most cases
111116
// this is not necessary.
112117
bool emitBssSegments = false;
118+
119+
// A tuple of (reference, extractedFile, sym). Used by --why-extract=.
120+
llvm::SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>,
121+
0>
122+
whyExtractRecords;
113123
};
114124

115125
// The only instance of Configuration struct.

lld/wasm/Driver.cpp

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,7 @@ static void readConfigs(opt::InputArgList &args) {
485485
parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
486486
"--thinlto-cache-policy: invalid cache policy");
487487
config->unresolvedSymbols = getUnresolvedSymbolPolicy(args);
488+
config->whyExtract = args.getLastArgValue(OPT_why_extract);
488489
errorHandler().verbose = args.hasArg(OPT_verbose);
489490
LLVM_DEBUG(errorHandler().verbose = true);
490491

@@ -666,7 +667,7 @@ static const char *getReproduceOption(opt::InputArgList &args) {
666667
}
667668

668669
// Force Sym to be entered in the output. Used for -u or equivalent.
669-
static Symbol *handleUndefined(StringRef name) {
670+
static Symbol *handleUndefined(StringRef name, const char *option) {
670671
Symbol *sym = symtab->find(name);
671672
if (!sym)
672673
return nullptr;
@@ -675,8 +676,11 @@ static Symbol *handleUndefined(StringRef name) {
675676
// eliminate it. Mark the symbol as "used" to prevent it.
676677
sym->isUsedInRegularObj = true;
677678

678-
if (auto *lazySym = dyn_cast<LazySymbol>(sym))
679+
if (auto *lazySym = dyn_cast<LazySymbol>(sym)) {
679680
lazySym->fetch();
681+
if (!config->whyExtract.empty())
682+
config->whyExtractRecords.emplace_back(option, sym->getFile(), *sym);
683+
}
680684

681685
return sym;
682686
}
@@ -688,8 +692,31 @@ static void handleLibcall(StringRef name) {
688692

689693
if (auto *lazySym = dyn_cast<LazySymbol>(sym)) {
690694
MemoryBufferRef mb = lazySym->getMemberBuffer();
691-
if (isBitcode(mb))
695+
if (isBitcode(mb)) {
696+
if (!config->whyExtract.empty())
697+
config->whyExtractRecords.emplace_back("<libcall>", sym->getFile(),
698+
*sym);
692699
lazySym->fetch();
700+
}
701+
}
702+
}
703+
704+
static void writeWhyExtract() {
705+
if (config->whyExtract.empty())
706+
return;
707+
708+
std::error_code ec;
709+
raw_fd_ostream os(config->whyExtract, ec, sys::fs::OF_None);
710+
if (ec) {
711+
error("cannot open --why-extract= file " + config->whyExtract + ": " +
712+
ec.message());
713+
return;
714+
}
715+
716+
os << "reference\textracted\tsymbol\n";
717+
for (auto &entry : config->whyExtractRecords) {
718+
os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
719+
<< toString(std::get<2>(entry)) << '\n';
693720
}
694721
}
695722

@@ -1070,16 +1097,16 @@ void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
10701097

10711098
// Handle the `--undefined <sym>` options.
10721099
for (auto *arg : args.filtered(OPT_undefined))
1073-
handleUndefined(arg->getValue());
1100+
handleUndefined(arg->getValue(), "<internal>");
10741101

10751102
// Handle the `--export <sym>` options
10761103
// This works like --undefined but also exports the symbol if its found
10771104
for (auto &iter : config->exportedSymbols)
1078-
handleUndefined(iter.first());
1105+
handleUndefined(iter.first(), "--export");
10791106

10801107
Symbol *entrySym = nullptr;
10811108
if (!config->relocatable && !config->entry.empty()) {
1082-
entrySym = handleUndefined(config->entry);
1109+
entrySym = handleUndefined(config->entry, "--entry");
10831110
if (entrySym && entrySym->isDefined())
10841111
entrySym->forceExport = true;
10851112
else
@@ -1096,7 +1123,8 @@ void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
10961123
!WasmSym::callCtors->isUsedInRegularObj &&
10971124
WasmSym::callCtors->getName() != config->entry &&
10981125
!config->exportedSymbols.count(WasmSym::callCtors->getName())) {
1099-
if (Symbol *callDtors = handleUndefined("__wasm_call_dtors")) {
1126+
if (Symbol *callDtors =
1127+
handleUndefined("__wasm_call_dtors", "<internal>")) {
11001128
if (auto *callDtorsFunc = dyn_cast<DefinedFunction>(callDtors)) {
11011129
if (callDtorsFunc->signature &&
11021130
(!callDtorsFunc->signature->Params.empty() ||
@@ -1131,6 +1159,8 @@ void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
11311159
if (errorCount())
11321160
return;
11331161

1162+
writeWhyExtract();
1163+
11341164
// Do link-time optimization if given files are LLVM bitcode files.
11351165
// This compiles bitcode files into real object files.
11361166
symtab->compileBitcodeFiles();

lld/wasm/Options.td

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,8 @@ defm whole_archive: B<"whole-archive",
226226
"Force load of all members in a static library",
227227
"Do not force load of all members in a static library (default)">;
228228

229+
def why_extract: JJ<"why-extract=">, HelpText<"Print to a file about why archive members are extracted">;
230+
229231
defm check_features: BB<"check-features",
230232
"Check feature compatibility of linked objects (default)",
231233
"Ignore feature compatibility of linked objects">;

lld/wasm/SymbolTable.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,9 @@ Symbol *SymbolTable::addUndefinedFunction(StringRef name,
524524
lazy->signature = sig;
525525
} else {
526526
lazy->fetch();
527+
if (!config->whyExtract.empty())
528+
config->whyExtractRecords.emplace_back(toString(file), s->getFile(),
529+
*s);
527530
}
528531
} else {
529532
auto existingFunction = dyn_cast<FunctionSymbol>(s);
@@ -758,7 +761,10 @@ void SymbolTable::addLazy(ArchiveFile *file, const Archive::Symbol *sym) {
758761
}
759762

760763
LLVM_DEBUG(dbgs() << "replacing existing undefined\n");
764+
const InputFile *oldFile = s->getFile();
761765
file->addMember(sym);
766+
if (!config->whyExtract.empty())
767+
config->whyExtractRecords.emplace_back(toString(oldFile), s->getFile(), *s);
762768
}
763769

764770
bool SymbolTable::addComdat(StringRef name) {

0 commit comments

Comments
 (0)