Coverage Report

Created: 2019-01-21 03:01

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/wasm/Driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Driver.cpp ---------------------------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "lld/Common/Driver.h"
10
#include "Config.h"
11
#include "InputChunks.h"
12
#include "InputGlobal.h"
13
#include "MarkLive.h"
14
#include "SymbolTable.h"
15
#include "Writer.h"
16
#include "lld/Common/Args.h"
17
#include "lld/Common/ErrorHandler.h"
18
#include "lld/Common/Memory.h"
19
#include "lld/Common/Strings.h"
20
#include "lld/Common/Threads.h"
21
#include "lld/Common/Version.h"
22
#include "llvm/ADT/Twine.h"
23
#include "llvm/Object/Wasm.h"
24
#include "llvm/Option/ArgList.h"
25
#include "llvm/Support/CommandLine.h"
26
#include "llvm/Support/Path.h"
27
#include "llvm/Support/Process.h"
28
#include "llvm/Support/TargetSelect.h"
29
30
#define DEBUG_TYPE "lld"
31
32
using namespace llvm;
33
using namespace llvm::object;
34
using namespace llvm::sys;
35
using namespace llvm::wasm;
36
37
using namespace lld;
38
using namespace lld::wasm;
39
40
Configuration *lld::wasm::Config;
41
42
namespace {
43
44
// Create enum with OPT_xxx values for each option in Options.td
45
enum {
46
  OPT_INVALID = 0,
47
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
48
#include "Options.inc"
49
#undef OPTION
50
};
51
52
// This function is called on startup. We need this for LTO since
53
// LTO calls LLVM functions to compile bitcode files to native code.
54
// Technically this can be delayed until we read bitcode files, but
55
// we don't bother to do lazily because the initialization is fast.
56
131
static void initLLVM() {
57
131
  InitializeAllTargets();
58
131
  InitializeAllTargetMCs();
59
131
  InitializeAllAsmPrinters();
60
131
  InitializeAllAsmParsers();
61
131
}
62
63
class LinkerDriver {
64
public:
65
  void link(ArrayRef<const char *> ArgsArr);
66
67
private:
68
  void createFiles(opt::InputArgList &Args);
69
  void addFile(StringRef Path);
70
  void addLibrary(StringRef Name);
71
72
  // True if we are in --whole-archive and --no-whole-archive.
73
  bool InWholeArchive = false;
74
75
  std::vector<InputFile *> Files;
76
};
77
} // anonymous namespace
78
79
bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
80
131
                     raw_ostream &Error) {
81
131
  errorHandler().LogName = args::getFilenameWithoutExe(Args[0]);
82
131
  errorHandler().ErrorOS = &Error;
83
131
  errorHandler().ColorDiagnostics = Error.has_colors();
84
131
  errorHandler().ErrorLimitExceededMsg =
85
131
      "too many errors emitted, stopping now (use "
86
131
      "-error-limit=0 to see all errors)";
87
131
88
131
  Config = make<Configuration>();
89
131
  Symtab = make<SymbolTable>();
90
131
91
131
  initLLVM();
92
131
  LinkerDriver().link(Args);
93
131
94
131
  // Exit immediately if we don't need to return to the caller.
95
131
  // This saves time because the overhead of calling destructors
96
131
  // for all globally-allocated objects is not negligible.
97
131
  if (CanExitEarly)
98
0
    exitLld(errorCount() ? 1 : 0);
99
131
100
131
  freeArena();
101
131
  return !errorCount();
102
131
}
103
104
// Create prefix string literals used in Options.td
105
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
106
#include "Options.inc"
107
#undef PREFIX
108
109
// Create table mapping all options defined in Options.td
110
static const opt::OptTable::Info OptInfo[] = {
111
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
112
  {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
113
   X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
114
#include "Options.inc"
115
#undef OPTION
116
};
117
118
namespace {
119
class WasmOptTable : public llvm::opt::OptTable {
120
public:
121
131
  WasmOptTable() : OptTable(OptInfo) {}
122
  opt::InputArgList parse(ArrayRef<const char *> Argv);
123
};
124
} // namespace
125
126
// Set color diagnostics according to -color-diagnostics={auto,always,never}
127
// or -no-color-diagnostics flags.
128
131
static void handleColorDiagnostics(opt::InputArgList &Args) {
129
131
  auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
130
131
                              OPT_no_color_diagnostics);
131
131
  if (!Arg)
132
131
    return;
133
0
  if (Arg->getOption().getID() == OPT_color_diagnostics) {
134
0
    errorHandler().ColorDiagnostics = true;
135
0
  } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
136
0
    errorHandler().ColorDiagnostics = false;
137
0
  } else {
138
0
    StringRef S = Arg->getValue();
139
0
    if (S == "always")
140
0
      errorHandler().ColorDiagnostics = true;
141
0
    else if (S == "never")
142
0
      errorHandler().ColorDiagnostics = false;
143
0
    else if (S != "auto")
144
0
      error("unknown option: --color-diagnostics=" + S);
145
0
  }
146
0
}
147
148
// Find a file by concatenating given paths.
149
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
150
  SmallString<128> S;
151
  path::append(S, Path1, Path2);
152
  if (fs::exists(S))
153
    return S.str().str();
154
  return None;
155
}
156
157
131
opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
158
131
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
159
131
160
131
  unsigned MissingIndex;
161
131
  unsigned MissingCount;
162
131
163
131
  // Expand response files (arguments in the form of @<filename>)
164
131
  cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Vec);
165
131
166
131
  opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
167
131
168
131
  handleColorDiagnostics(Args);
169
131
  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
170
0
    error("unknown argument: " + Arg->getSpelling());
171
131
  return Args;
172
131
}
173
174
// Currently we allow a ".imports" to live alongside a library. This can
175
// be used to specify a list of symbols which can be undefined at link
176
// time (imported from the environment.  For example libc.a include an
177
// import file that lists the syscall functions it relies on at runtime.
178
// In the long run this information would be better stored as a symbol
179
// attribute/flag in the object file itself.
180
// See: https://github.com/WebAssembly/tool-conventions/issues/35
181
5
static void readImportFile(StringRef Filename) {
182
5
  if (Optional<MemoryBufferRef> Buf = readFile(Filename))
183
5
    for (StringRef Sym : args::getLines(*Buf))
184
5
      Config->AllowUndefinedSymbols.insert(Sym);
185
5
}
186
187
// Returns slices of MB by parsing MB as an archive file.
188
// Each slice consists of a member file in the archive.
189
std::vector<MemoryBufferRef> static getArchiveMembers(MemoryBufferRef MB) {
190
  std::unique_ptr<Archive> File =
191
      CHECK(Archive::create(MB),
192
            MB.getBufferIdentifier() + ": failed to parse archive");
193
194
  std::vector<MemoryBufferRef> V;
195
  Error Err = Error::success();
196
  for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
197
    Archive::Child C =
198
        CHECK(COrErr, MB.getBufferIdentifier() +
199
                          ": could not get the child of the archive");
200
    MemoryBufferRef MBRef =
201
        CHECK(C.getMemoryBufferRef(),
202
              MB.getBufferIdentifier() +
203
                  ": could not get the buffer for a child of the archive");
204
    V.push_back(MBRef);
205
  }
206
  if (Err)
207
    fatal(MB.getBufferIdentifier() +
208
          ": Archive::children failed: " + toString(std::move(Err)));
209
210
  // Take ownership of memory buffers created for members of thin archives.
211
  for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
212
    make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
213
214
  return V;
215
}
216
217
202
void LinkerDriver::addFile(StringRef Path) {
218
202
  Optional<MemoryBufferRef> Buffer = readFile(Path);
219
202
  if (!Buffer.hasValue())
220
1
    return;
221
201
  MemoryBufferRef MBRef = *Buffer;
222
201
223
201
  switch (identify_magic(MBRef.getBuffer())) {
224
201
  case file_magic::archive: {
225
18
    // Handle -whole-archive.
226
18
    if (InWholeArchive) {
227
3
      for (MemoryBufferRef &M : getArchiveMembers(MBRef))
228
3
        Files.push_back(createObjectFile(M));
229
3
      return;
230
3
    }
231
15
232
15
    SmallString<128> ImportFile = Path;
233
15
    path::replace_extension(ImportFile, ".imports");
234
15
    if (fs::exists(ImportFile))
235
4
      readImportFile(ImportFile.str());
236
15
237
15
    Files.push_back(make<ArchiveFile>(MBRef));
238
15
    return;
239
15
  }
240
183
  case file_magic::bitcode:
241
183
  case file_magic::wasm_object:
242
183
    Files.push_back(createObjectFile(MBRef));
243
183
    break;
244
183
  default:
245
0
    error("unknown file type: " + MBRef.getBufferIdentifier());
246
201
  }
247
201
}
248
249
// Add a given library by searching it from input search paths.
250
0
void LinkerDriver::addLibrary(StringRef Name) {
251
0
  for (StringRef Dir : Config->SearchPaths) {
252
0
    if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
253
0
      addFile(*S);
254
0
      return;
255
0
    }
256
0
  }
257
0
258
0
  error("unable to find library -l" + Name);
259
0
}
260
261
129
void LinkerDriver::createFiles(opt::InputArgList &Args) {
262
500
  for (auto *Arg : Args) {
263
500
    switch (Arg->getOption().getUnaliasedOption().getID()) {
264
500
    case OPT_l:
265
0
      addLibrary(Arg->getValue());
266
0
      break;
267
500
    case OPT_INPUT:
268
202
      addFile(Arg->getValue());
269
202
      break;
270
500
    case OPT_whole_archive:
271
5
      InWholeArchive = true;
272
5
      break;
273
500
    case OPT_no_whole_archive:
274
3
      InWholeArchive = false;
275
3
      break;
276
500
    }
277
500
  }
278
129
}
279
280
131
static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
281
131
  auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
282
131
  if (!Arg)
283
113
    return Default;
284
18
  if (Arg->getOption().getID() == OPT_no_entry)
285
9
    return "";
286
9
  return Arg->getValue();
287
9
}
288
289
static const uint8_t UnreachableFn[] = {
290
    0x03 /* ULEB length */, 0x00 /* ULEB num locals */,
291
    0x00 /* opcode unreachable */, 0x0b /* opcode end */
292
};
293
294
// For weak undefined functions, there may be "call" instructions that reference
295
// the symbol. In this case, we need to synthesise a dummy/stub function that
296
// will abort at runtime, so that relocations can still provided an operand to
297
// the call instruction that passes Wasm validation.
298
101
static void handleWeakUndefines() {
299
827
  for (Symbol *Sym : Symtab->getSymbols()) {
300
827
    if (!Sym->isUndefined() || 
!Sym->isWeak()35
)
301
819
      continue;
302
8
    auto *FuncSym = dyn_cast<FunctionSymbol>(Sym);
303
8
    if (!FuncSym)
304
1
      continue;
305
7
306
7
    // It is possible for undefined functions not to have a signature (eg. if
307
7
    // added via "--undefined"), but weak undefined ones do have a signature.
308
7
    assert(FuncSym->Signature);
309
7
    const WasmSignature &Sig = *FuncSym->Signature;
310
7
311
7
    // Add a synthetic dummy for weak undefined functions.  These dummies will
312
7
    // be GC'd if not used as the target of any "call" instructions.
313
7
    std::string SymName = toString(*Sym);
314
7
    StringRef DebugName = Saver.save("undefined function " + SymName);
315
7
    auto *Func = make<SyntheticFunction>(Sig, Sym->getName(), DebugName);
316
7
    Func->setBody(UnreachableFn);
317
7
    // Ensure it compares equal to the null pointer, and so that table relocs
318
7
    // don't pull in the stub body (only call-operand relocs should do that).
319
7
    Func->setTableIndex(0);
320
7
    Symtab->SyntheticFunctions.emplace_back(Func);
321
7
    // Hide our dummy to prevent export.
322
7
    uint32_t Flags = WASM_SYMBOL_VISIBILITY_HIDDEN;
323
7
    replaceSymbol<DefinedFunction>(Sym, Sym->getName(), Flags, nullptr, Func);
324
7
  }
325
101
}
326
327
// Some Config members do not directly correspond to any particular
328
// command line options, but computed based on other Config values.
329
// This function initialize such members. See Config.h for the details
330
// of these values.
331
static void setConfigs(opt::InputArgList &Args) {
332
  Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
333
  Config->CompressRelocations = Args.hasArg(OPT_compress_relocations);
334
  Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
335
  Config->DisableVerify = Args.hasArg(OPT_disable_verify);
336
  Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
337
  Config->ExportAll = Args.hasArg(OPT_export_all);
338
  Config->ExportDynamic = Args.hasFlag(OPT_export_dynamic,
339
      OPT_no_export_dynamic, false);
340
  Config->ExportTable = Args.hasArg(OPT_export_table);
341
  errorHandler().FatalWarnings =
342
      Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
343
  Config->ImportMemory = Args.hasArg(OPT_import_memory);
344
  Config->SharedMemory = Args.hasArg(OPT_shared_memory);
345
  Config->ImportTable = Args.hasArg(OPT_import_table);
346
  Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
347
  Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
348
  Config->Optimize = args::getInteger(Args, OPT_O, 0);
349
  Config->OutputFile = Args.getLastArgValue(OPT_o);
350
  Config->Relocatable = Args.hasArg(OPT_relocatable);
351
  Config->GcSections =
352
      Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
353
  Config->MergeDataSegments =
354
      Args.hasFlag(OPT_merge_data_segments, OPT_no_merge_data_segments,
355
                   !Config->Relocatable);
356
  Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
357
  Config->PrintGcSections =
358
      Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
359
  Config->SaveTemps = Args.hasArg(OPT_save_temps);
360
  Config->SearchPaths = args::getStrings(Args, OPT_L);
361
  Config->Shared = Args.hasArg(OPT_shared);
362
  Config->StripAll = Args.hasArg(OPT_strip_all);
363
  Config->StripDebug = Args.hasArg(OPT_strip_debug);
364
  Config->StackFirst = Args.hasArg(OPT_stack_first);
365
  Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
366
  Config->ThinLTOCachePolicy = CHECK(
367
      parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
368
      "--thinlto-cache-policy: invalid cache policy");
369
  Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
370
  errorHandler().Verbose = Args.hasArg(OPT_verbose);
371
  ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
372
373
  Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
374
  Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
375
  Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
376
  Config->ZStackSize =
377
      args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
378
}
379
380
// Some command line options or some combinations of them are not allowed.
381
// This function checks for such errors.
382
131
static void checkOptions(opt::InputArgList &Args) {
383
131
  if (!Config->StripDebug && 
!Config->StripAll127
&&
Config->CompressRelocations125
)
384
1
    error("--compress-relocations is incompatible with output debug"
385
1
          " information. Please pass --strip-debug or --strip-all");
386
131
387
131
  if (Config->LTOO > 3)
388
0
    error("invalid optimization level for LTO: " + Twine(Config->LTOO));
389
131
  if (Config->LTOPartitions == 0)
390
0
    error("--lto-partitions: number of threads must be > 0");
391
131
  if (Config->ThinLTOJobs == 0)
392
0
    error("--thinlto-jobs: number of threads must be > 0");
393
131
394
131
  if (Config->Pie && 
Config->Shared0
)
395
0
    error("-shared and -pie may not be used together");
396
131
397
131
  if (Config->OutputFile.empty())
398
4
    error("no output file specified");
399
131
400
131
  if (Config->ImportTable && 
Config->ExportTable2
)
401
1
    error("--import-table and --export-table may not be used together");
402
131
403
131
  if (Config->Relocatable) {
404
18
    if (!Config->Entry.empty())
405
0
      error("entry point specified for relocatable output file");
406
18
    if (Config->GcSections)
407
1
      error("-r and --gc-sections may not be used together");
408
18
    if (Config->CompressRelocations)
409
0
      error("-r -and --compress-relocations may not be used together");
410
18
    if (Args.hasArg(OPT_undefined))
411
0
      error("-r -and --undefined may not be used together");
412
18
    if (Config->Pie)
413
0
      error("-r and -pie may not be used together");
414
18
  }
415
131
}
416
417
// Force Sym to be entered in the output. Used for -u or equivalent.
418
108
static Symbol *handleUndefined(StringRef Name) {
419
108
  Symbol *Sym = Symtab->find(Name);
420
108
  if (!Sym)
421
8
    return nullptr;
422
100
423
100
  // Since symbol S may not be used inside the program, LTO may
424
100
  // eliminate it. Mark the symbol as "used" to prevent it.
425
100
  Sym->IsUsedInRegularObj = true;
426
100
427
100
  if (auto *LazySym = dyn_cast<LazySymbol>(Sym))
428
3
    LazySym->fetch();
429
100
430
100
  return Sym;
431
100
}
432
433
static UndefinedGlobal *
434
3
createUndefinedGlobal(StringRef Name, llvm::wasm::WasmGlobalType *Type) {
435
3
  auto *Sym =
436
3
      cast<UndefinedGlobal>(Symtab->addUndefinedGlobal(Name, 0, nullptr, Type));
437
3
  Config->AllowUndefinedSymbols.insert(Sym->getName());
438
3
  Sym->IsUsedInRegularObj = true;
439
3
  return Sym;
440
3
}
441
442
// Create ABI-defined synthetic symbols
443
111
static void createSyntheticSymbols() {
444
111
  static WasmSignature NullSignature = {{}, {}};
445
111
  static llvm::wasm::WasmGlobalType GlobalTypeI32 = {WASM_TYPE_I32, false};
446
111
  static llvm::wasm::WasmGlobalType MutableGlobalTypeI32 = {WASM_TYPE_I32,
447
111
                                                            true};
448
111
449
111
  if (!Config->Relocatable)
450
111
    WasmSym::CallCtors = Symtab->addSyntheticFunction(
451
111
        "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
452
111
        make<SyntheticFunction>(NullSignature, "__wasm_call_ctors"));
453
111
454
111
  // The __stack_pointer is imported in the shared library case, and exported
455
111
  // in the non-shared (executable) case.
456
111
  if (Config->Shared) {
457
1
    WasmSym::StackPointer =
458
1
        createUndefinedGlobal("__stack_pointer", &MutableGlobalTypeI32);
459
110
  } else {
460
110
    llvm::wasm::WasmGlobal Global;
461
110
    Global.Type = {WASM_TYPE_I32, true};
462
110
    Global.InitExpr.Value.Int32 = 0;
463
110
    Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
464
110
    Global.SymbolName = "__stack_pointer";
465
110
    auto *StackPointer = make<InputGlobal>(Global, nullptr);
466
110
    StackPointer->Live = true;
467
110
    // For non-PIC code
468
110
    // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN when the mutable global
469
110
    // spec proposal is implemented in all major browsers.
470
110
    // See: https://github.com/WebAssembly/mutable-global
471
110
    WasmSym::StackPointer = Symtab->addSyntheticGlobal(
472
110
        "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
473
110
    WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base", 0);
474
110
    WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end", 0);
475
110
476
110
    // These two synthetic symbols exist purely for the embedder so we always
477
110
    // want to export them.
478
110
    WasmSym::HeapBase->ForceExport = true;
479
110
    WasmSym::DataEnd->ForceExport = true;
480
110
  }
481
111
482
111
  if (Config->Pic) {
483
1
    // For PIC code, we import two global variables (__memory_base and
484
1
    // __table_base) from the environment and use these as the offset at
485
1
    // which to load our static data and function table.
486
1
    // See:
487
1
    // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
488
1
    WasmSym::MemoryBase =
489
1
        createUndefinedGlobal("__memory_base", &GlobalTypeI32);
490
1
    WasmSym::TableBase = createUndefinedGlobal("__table_base", &GlobalTypeI32);
491
1
    WasmSym::MemoryBase->markLive();
492
1
    WasmSym::TableBase->markLive();
493
1
  }
494
111
495
111
  WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
496
111
      "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
497
111
}
498
499
131
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
500
131
  WasmOptTable Parser;
501
131
  opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
502
131
503
131
  // Handle --help
504
131
  if (Args.hasArg(OPT_help)) {
505
0
    Parser.PrintHelp(outs(),
506
0
                     (std::string(ArgsArr[0]) + " [options] file...").c_str(),
507
0
                     "LLVM Linker", false);
508
0
    return;
509
0
  }
510
131
511
131
  // Handle --version
512
131
  if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
513
0
    outs() << getLLDVersion() << "\n";
514
0
    return;
515
0
  }
516
131
517
131
  // Parse and evaluate -mllvm options.
518
131
  std::vector<const char *> V;
519
131
  V.push_back("wasm-ld (LLVM option parsing)");
520
131
  for (auto *Arg : Args.filtered(OPT_mllvm))
521
2
    V.push_back(Arg->getValue());
522
131
  cl::ParseCommandLineOptions(V.size(), V.data());
523
131
524
131
  errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
525
131
526
131
  setConfigs(Args);
527
131
  checkOptions(Args);
528
131
529
131
  if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
530
1
    readImportFile(Arg->getValue());
531
131
532
131
  if (!Args.hasArg(OPT_INPUT)) {
533
2
    error("no input files");
534
2
    return;
535
2
  }
536
129
537
129
  Config->Pic = Config->Pie || Config->Shared;
538
129
539
129
  if (Config->Pic) {
540
1
    if (Config->ExportTable)
541
0
      error("-shared/-pie is incompatible with --export-table");
542
1
    Config->ImportTable = true;
543
1
  }
544
129
545
129
  if (Config->Shared) {
546
1
    Config->ExportDynamic = true;
547
1
    Config->AllowUndefined = true;
548
1
  }
549
129
550
129
  if (!Config->Relocatable)
551
111
    createSyntheticSymbols();
552
129
553
129
  createFiles(Args);
554
129
  if (errorCount())
555
5
    return;
556
124
557
124
  // Add all files to the symbol table. This will add almost all
558
124
  // symbols that we need to the symbol table.
559
124
  for (InputFile *F : Files)
560
196
    Symtab->addFile(F);
561
124
  if (errorCount())
562
6
    return;
563
118
564
118
  // Handle the `--undefined <sym>` options.
565
118
  for (auto *Arg : Args.filtered(OPT_undefined))
566
6
    handleUndefined(Arg->getValue());
567
118
568
118
  // Handle the `--export <sym>` options
569
118
  // This works like --undefined but also exports the symbol if its found
570
118
  for (auto *Arg : Args.filtered(OPT_export)) {
571
10
    Symbol *Sym = handleUndefined(Arg->getValue());
572
10
    if (Sym && 
Sym->isDefined()7
)
573
7
      Sym->ForceExport = true;
574
3
    else if (!Config->AllowUndefined)
575
2
      error(Twine("symbol exported via --export not found: ") +
576
2
            Arg->getValue());
577
10
  }
578
118
579
118
  Symbol *EntrySym = nullptr;
580
118
  if (!Config->Relocatable) {
581
101
    // Add synthetic dummies for weak undefined functions.
582
101
    handleWeakUndefines();
583
101
584
101
    if (!Config->Shared && 
!Config->Entry.empty()100
) {
585
92
      EntrySym = handleUndefined(Config->Entry);
586
92
      if (EntrySym && 
EntrySym->isDefined()89
)
587
89
        EntrySym->ForceExport = true;
588
3
      else
589
3
        error("entry symbol not defined (pass --no-entry to supress): " +
590
3
              Config->Entry);
591
92
    }
592
101
593
101
    // Make sure we have resolved all symbols.
594
101
    if (!Config->AllowUndefined)
595
89
      Symtab->reportRemainingUndefines();
596
101
  }
597
118
598
118
  if (errorCount())
599
10
    return;
600
108
601
108
  // Do link-time optimization if given files are LLVM bitcode files.
602
108
  // This compiles bitcode files into real object files.
603
108
  Symtab->addCombinedLTOObject();
604
108
  if (errorCount())
605
2
    return;
606
106
607
106
  if (EntrySym)
608
80
    EntrySym->setHidden(false);
609
106
610
106
  if (errorCount())
611
0
    return;
612
106
613
106
  // Do size optimizations: garbage collection
614
106
  markLive();
615
106
616
106
  // Write the result to the file.
617
106
  writeResult();
618
106
}