xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 9284931e)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The driver drives the entire linking process. It is responsible for
11 // parsing command line options and doing whatever it is instructed to do.
12 //
13 // One notable thing in the LLD's driver when compared to other linkers is
14 // that the LLD's driver is agnostic on the host operating system.
15 // Other linkers usually have implicit default values (such as a dynamic
16 // linker path or library paths) for each host OS.
17 //
18 // I don't think implicit default values are useful because they are
19 // usually explicitly specified by the compiler driver. They can even
20 // be harmful when you are doing cross-linking. Therefore, in LLD, we
21 // simply trust the compiler driver to pass all required options and
22 // don't try to make effort on our side.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "Driver.h"
27 #include "Config.h"
28 #include "Filesystem.h"
29 #include "ICF.h"
30 #include "InputFiles.h"
31 #include "InputSection.h"
32 #include "LinkerScript.h"
33 #include "OutputSections.h"
34 #include "ScriptParser.h"
35 #include "Strings.h"
36 #include "SymbolTable.h"
37 #include "Symbols.h"
38 #include "SyntheticSections.h"
39 #include "Target.h"
40 #include "Writer.h"
41 #include "lld/Common/Args.h"
42 #include "lld/Common/Driver.h"
43 #include "lld/Common/ErrorHandler.h"
44 #include "lld/Common/Memory.h"
45 #include "lld/Common/TargetOptionsCommandFlags.h"
46 #include "lld/Common/Threads.h"
47 #include "lld/Common/Version.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/ADT/StringSwitch.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Compression.h"
52 #include "llvm/Support/Path.h"
53 #include "llvm/Support/TarWriter.h"
54 #include "llvm/Support/TargetSelect.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <cstdlib>
57 #include <utility>
58 
59 using namespace llvm;
60 using namespace llvm::ELF;
61 using namespace llvm::object;
62 using namespace llvm::sys;
63 
64 using namespace lld;
65 using namespace lld::elf;
66 
67 Configuration *elf::Config;
68 LinkerDriver *elf::Driver;
69 
70 static void setConfigs(opt::InputArgList &Args);
71 
72 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
73                raw_ostream &Error) {
74   errorHandler().LogName = Args[0];
75   errorHandler().ErrorLimitExceededMsg =
76       "too many errors emitted, stopping now (use "
77       "-error-limit=0 to see all errors)";
78   errorHandler().ErrorOS = &Error;
79   errorHandler().ColorDiagnostics = Error.has_colors();
80   InputSections.clear();
81   OutputSections.clear();
82   Tar = nullptr;
83   BinaryFiles.clear();
84   BitcodeFiles.clear();
85   ObjectFiles.clear();
86   SharedFiles.clear();
87 
88   Config = make<Configuration>();
89   Driver = make<LinkerDriver>();
90   Script = make<LinkerScript>();
91   Symtab = make<SymbolTable>();
92   Config->ProgName = Args[0];
93 
94   Driver->main(Args, CanExitEarly);
95 
96   // Exit immediately if we don't need to return to the caller.
97   // This saves time because the overhead of calling destructors
98   // for all globally-allocated objects is not negligible.
99   if (Config->ExitEarly)
100     exitLld(errorCount() ? 1 : 0);
101 
102   freeArena();
103   return !errorCount();
104 }
105 
106 // Parses a linker -m option.
107 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
108   uint8_t OSABI = 0;
109   StringRef S = Emul;
110   if (S.endswith("_fbsd")) {
111     S = S.drop_back(5);
112     OSABI = ELFOSABI_FREEBSD;
113   }
114 
115   std::pair<ELFKind, uint16_t> Ret =
116       StringSwitch<std::pair<ELFKind, uint16_t>>(S)
117           .Cases("aarch64elf", "aarch64linux", {ELF64LEKind, EM_AARCH64})
118           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
119           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
120           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
121           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
122           .Case("elf32ppc", {ELF32BEKind, EM_PPC})
123           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
124           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
125           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
126           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
127           .Case("elf_i386", {ELF32LEKind, EM_386})
128           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
129           .Default({ELFNoneKind, EM_NONE});
130 
131   if (Ret.first == ELFNoneKind)
132     error("unknown emulation: " + Emul);
133   return std::make_tuple(Ret.first, Ret.second, OSABI);
134 }
135 
136 // Returns slices of MB by parsing MB as an archive file.
137 // Each slice consists of a member file in the archive.
138 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
139     MemoryBufferRef MB) {
140   std::unique_ptr<Archive> File =
141       CHECK(Archive::create(MB),
142             MB.getBufferIdentifier() + ": failed to parse archive");
143 
144   std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
145   Error Err = Error::success();
146   bool AddToTar = File->isThin() && Tar;
147   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
148     Archive::Child C =
149         CHECK(COrErr, MB.getBufferIdentifier() +
150                           ": could not get the child of the archive");
151     MemoryBufferRef MBRef =
152         CHECK(C.getMemoryBufferRef(),
153               MB.getBufferIdentifier() +
154                   ": could not get the buffer for a child of the archive");
155     if (AddToTar)
156       Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
157     V.push_back(std::make_pair(MBRef, C.getChildOffset()));
158   }
159   if (Err)
160     fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
161           toString(std::move(Err)));
162 
163   // Take ownership of memory buffers created for members of thin archives.
164   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
165     make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
166 
167   return V;
168 }
169 
170 // Opens a file and create a file object. Path has to be resolved already.
171 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
172   using namespace sys::fs;
173 
174   Optional<MemoryBufferRef> Buffer = readFile(Path);
175   if (!Buffer.hasValue())
176     return;
177   MemoryBufferRef MBRef = *Buffer;
178 
179   if (InBinary) {
180     Files.push_back(make<BinaryFile>(MBRef));
181     return;
182   }
183 
184   switch (identify_magic(MBRef.getBuffer())) {
185   case file_magic::unknown:
186     readLinkerScript(MBRef);
187     return;
188   case file_magic::archive: {
189     // Handle -whole-archive.
190     if (InWholeArchive) {
191       for (const auto &P : getArchiveMembers(MBRef))
192         Files.push_back(createObjectFile(P.first, Path, P.second));
193       return;
194     }
195 
196     std::unique_ptr<Archive> File =
197         CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
198 
199     // If an archive file has no symbol table, it is likely that a user
200     // is attempting LTO and using a default ar command that doesn't
201     // understand the LLVM bitcode file. It is a pretty common error, so
202     // we'll handle it as if it had a symbol table.
203     if (!File->isEmpty() && !File->hasSymbolTable()) {
204       for (const auto &P : getArchiveMembers(MBRef))
205         Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
206       return;
207     }
208 
209     // Handle the regular case.
210     Files.push_back(make<ArchiveFile>(std::move(File)));
211     return;
212   }
213   case file_magic::elf_shared_object:
214     if (Config->Relocatable) {
215       error("attempted static link of dynamic object " + Path);
216       return;
217     }
218 
219     // DSOs usually have DT_SONAME tags in their ELF headers, and the
220     // sonames are used to identify DSOs. But if they are missing,
221     // they are identified by filenames. We don't know whether the new
222     // file has a DT_SONAME or not because we haven't parsed it yet.
223     // Here, we set the default soname for the file because we might
224     // need it later.
225     //
226     // If a file was specified by -lfoo, the directory part is not
227     // significant, as a user did not specify it. This behavior is
228     // compatible with GNU.
229     Files.push_back(
230         createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
231     return;
232   case file_magic::bitcode:
233   case file_magic::elf_relocatable:
234     if (InLib)
235       Files.push_back(make<LazyObjFile>(MBRef, "", 0));
236     else
237       Files.push_back(createObjectFile(MBRef));
238     break;
239   default:
240     error(Path + ": unknown file type");
241   }
242 }
243 
244 // Add a given library by searching it from input search paths.
245 void LinkerDriver::addLibrary(StringRef Name) {
246   if (Optional<std::string> Path = searchLibrary(Name))
247     addFile(*Path, /*WithLOption=*/true);
248   else
249     error("unable to find library -l" + Name);
250 }
251 
252 // This function is called on startup. We need this for LTO since
253 // LTO calls LLVM functions to compile bitcode files to native code.
254 // Technically this can be delayed until we read bitcode files, but
255 // we don't bother to do lazily because the initialization is fast.
256 static void initLLVM() {
257   InitializeAllTargets();
258   InitializeAllTargetMCs();
259   InitializeAllAsmPrinters();
260   InitializeAllAsmParsers();
261 }
262 
263 // Some command line options or some combinations of them are not allowed.
264 // This function checks for such errors.
265 static void checkOptions(opt::InputArgList &Args) {
266   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
267   // table which is a relatively new feature.
268   if (Config->EMachine == EM_MIPS && Config->GnuHash)
269     error("the .gnu.hash section is not compatible with the MIPS target.");
270 
271   if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64)
272     error("--fix-cortex-a53-843419 is only supported on AArch64 targets.");
273 
274   if (Config->Pie && Config->Shared)
275     error("-shared and -pie may not be used together");
276 
277   if (!Config->Shared && !Config->FilterList.empty())
278     error("-F may not be used without -shared");
279 
280   if (!Config->Shared && !Config->AuxiliaryList.empty())
281     error("-f may not be used without -shared");
282 
283   if (!Config->Relocatable && !Config->DefineCommon)
284     error("-no-define-common not supported in non relocatable output");
285 
286   if (Config->Relocatable) {
287     if (Config->Shared)
288       error("-r and -shared may not be used together");
289     if (Config->GcSections)
290       error("-r and --gc-sections may not be used together");
291     if (Config->ICF)
292       error("-r and --icf may not be used together");
293     if (Config->Pie)
294       error("-r and -pie may not be used together");
295   }
296 }
297 
298 static const char *getReproduceOption(opt::InputArgList &Args) {
299   if (auto *Arg = Args.getLastArg(OPT_reproduce))
300     return Arg->getValue();
301   return getenv("LLD_REPRODUCE");
302 }
303 
304 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
305   for (auto *Arg : Args.filtered(OPT_z))
306     if (Key == Arg->getValue())
307       return true;
308   return false;
309 }
310 
311 void LinkerDriver::main(ArrayRef<const char *> ArgsArr, bool CanExitEarly) {
312   ELFOptTable Parser;
313   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
314 
315   // Interpret this flag early because error() depends on them.
316   errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
317 
318   // Handle -help
319   if (Args.hasArg(OPT_help)) {
320     printHelp();
321     return;
322   }
323 
324   // Handle -v or -version.
325   //
326   // A note about "compatible with GNU linkers" message: this is a hack for
327   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
328   // still the newest version in March 2017) or earlier to recognize LLD as
329   // a GNU compatible linker. As long as an output for the -v option
330   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
331   //
332   // This is somewhat ugly hack, but in reality, we had no choice other
333   // than doing this. Considering the very long release cycle of Libtool,
334   // it is not easy to improve it to recognize LLD as a GNU compatible
335   // linker in a timely manner. Even if we can make it, there are still a
336   // lot of "configure" scripts out there that are generated by old version
337   // of Libtool. We cannot convince every software developer to migrate to
338   // the latest version and re-generate scripts. So we have this hack.
339   if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
340     message(getLLDVersion() + " (compatible with GNU linkers)");
341 
342   // The behavior of -v or --version is a bit strange, but this is
343   // needed for compatibility with GNU linkers.
344   if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT))
345     return;
346   if (Args.hasArg(OPT_version))
347     return;
348 
349   Config->ExitEarly = CanExitEarly && !Args.hasArg(OPT_full_shutdown);
350   errorHandler().ExitEarly = Config->ExitEarly;
351 
352   if (const char *Path = getReproduceOption(Args)) {
353     // Note that --reproduce is a debug option so you can ignore it
354     // if you are trying to understand the whole picture of the code.
355     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
356         TarWriter::create(Path, path::stem(Path));
357     if (ErrOrWriter) {
358       Tar = ErrOrWriter->get();
359       Tar->append("response.txt", createResponseFile(Args));
360       Tar->append("version.txt", getLLDVersion() + "\n");
361       make<std::unique_ptr<TarWriter>>(std::move(*ErrOrWriter));
362     } else {
363       error(Twine("--reproduce: failed to open ") + Path + ": " +
364             toString(ErrOrWriter.takeError()));
365     }
366   }
367 
368   readConfigs(Args);
369   initLLVM();
370   createFiles(Args);
371   inferMachineType();
372   setConfigs(Args);
373   checkOptions(Args);
374   if (errorCount())
375     return;
376 
377   switch (Config->EKind) {
378   case ELF32LEKind:
379     link<ELF32LE>(Args);
380     return;
381   case ELF32BEKind:
382     link<ELF32BE>(Args);
383     return;
384   case ELF64LEKind:
385     link<ELF64LE>(Args);
386     return;
387   case ELF64BEKind:
388     link<ELF64BE>(Args);
389     return;
390   default:
391     llvm_unreachable("unknown Config->EKind");
392   }
393 }
394 
395 static std::string getRpath(opt::InputArgList &Args) {
396   std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
397   return llvm::join(V.begin(), V.end(), ":");
398 }
399 
400 // Determines what we should do if there are remaining unresolved
401 // symbols after the name resolution.
402 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
403   if (Args.hasArg(OPT_relocatable))
404     return UnresolvedPolicy::IgnoreAll;
405 
406   UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
407                                               OPT_warn_unresolved_symbols, true)
408                                      ? UnresolvedPolicy::ReportError
409                                      : UnresolvedPolicy::Warn;
410 
411   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
412   for (auto *Arg : llvm::reverse(Args)) {
413     switch (Arg->getOption().getID()) {
414     case OPT_unresolved_symbols: {
415       StringRef S = Arg->getValue();
416       if (S == "ignore-all" || S == "ignore-in-object-files")
417         return UnresolvedPolicy::Ignore;
418       if (S == "ignore-in-shared-libs" || S == "report-all")
419         return ErrorOrWarn;
420       error("unknown --unresolved-symbols value: " + S);
421       continue;
422     }
423     case OPT_no_undefined:
424       return ErrorOrWarn;
425     case OPT_z:
426       if (StringRef(Arg->getValue()) == "defs")
427         return ErrorOrWarn;
428       continue;
429     }
430   }
431 
432   // -shared implies -unresolved-symbols=ignore-all because missing
433   // symbols are likely to be resolved at runtime using other DSOs.
434   if (Config->Shared)
435     return UnresolvedPolicy::Ignore;
436   return ErrorOrWarn;
437 }
438 
439 static Target2Policy getTarget2(opt::InputArgList &Args) {
440   StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
441   if (S == "rel")
442     return Target2Policy::Rel;
443   if (S == "abs")
444     return Target2Policy::Abs;
445   if (S == "got-rel")
446     return Target2Policy::GotRel;
447   error("unknown --target2 option: " + S);
448   return Target2Policy::GotRel;
449 }
450 
451 static bool isOutputFormatBinary(opt::InputArgList &Args) {
452   if (auto *Arg = Args.getLastArg(OPT_oformat)) {
453     StringRef S = Arg->getValue();
454     if (S == "binary")
455       return true;
456     error("unknown --oformat value: " + S);
457   }
458   return false;
459 }
460 
461 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
462   if (Args.hasArg(OPT_relocatable))
463     return DiscardPolicy::None;
464 
465   auto *Arg =
466       Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
467   if (!Arg)
468     return DiscardPolicy::Default;
469   if (Arg->getOption().getID() == OPT_discard_all)
470     return DiscardPolicy::All;
471   if (Arg->getOption().getID() == OPT_discard_locals)
472     return DiscardPolicy::Locals;
473   return DiscardPolicy::None;
474 }
475 
476 static StringRef getDynamicLinker(opt::InputArgList &Args) {
477   auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
478   if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
479     return "";
480   return Arg->getValue();
481 }
482 
483 static StripPolicy getStrip(opt::InputArgList &Args) {
484   if (Args.hasArg(OPT_relocatable))
485     return StripPolicy::None;
486 
487   auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
488   if (!Arg)
489     return StripPolicy::None;
490   if (Arg->getOption().getID() == OPT_strip_all)
491     return StripPolicy::All;
492   return StripPolicy::Debug;
493 }
494 
495 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
496   uint64_t VA = 0;
497   if (S.startswith("0x"))
498     S = S.drop_front(2);
499   if (!to_integer(S, VA, 16))
500     error("invalid argument: " + toString(Arg));
501   return VA;
502 }
503 
504 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
505   StringMap<uint64_t> Ret;
506   for (auto *Arg : Args.filtered(OPT_section_start)) {
507     StringRef Name;
508     StringRef Addr;
509     std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
510     Ret[Name] = parseSectionAddress(Addr, *Arg);
511   }
512 
513   if (auto *Arg = Args.getLastArg(OPT_Ttext))
514     Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
515   if (auto *Arg = Args.getLastArg(OPT_Tdata))
516     Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
517   if (auto *Arg = Args.getLastArg(OPT_Tbss))
518     Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
519   return Ret;
520 }
521 
522 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
523   StringRef S = Args.getLastArgValue(OPT_sort_section);
524   if (S == "alignment")
525     return SortSectionPolicy::Alignment;
526   if (S == "name")
527     return SortSectionPolicy::Name;
528   if (!S.empty())
529     error("unknown --sort-section rule: " + S);
530   return SortSectionPolicy::Default;
531 }
532 
533 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
534   StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
535   if (S == "warn")
536     return OrphanHandlingPolicy::Warn;
537   if (S == "error")
538     return OrphanHandlingPolicy::Error;
539   if (S != "place")
540     error("unknown --orphan-handling mode: " + S);
541   return OrphanHandlingPolicy::Place;
542 }
543 
544 // Parse --build-id or --build-id=<style>. We handle "tree" as a
545 // synonym for "sha1" because all our hash functions including
546 // -build-id=sha1 are actually tree hashes for performance reasons.
547 static std::pair<BuildIdKind, std::vector<uint8_t>>
548 getBuildId(opt::InputArgList &Args) {
549   auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
550   if (!Arg)
551     return {BuildIdKind::None, {}};
552 
553   if (Arg->getOption().getID() == OPT_build_id)
554     return {BuildIdKind::Fast, {}};
555 
556   StringRef S = Arg->getValue();
557   if (S == "fast")
558     return {BuildIdKind::Fast, {}};
559   if (S == "md5")
560     return {BuildIdKind::Md5, {}};
561   if (S == "sha1" || S == "tree")
562     return {BuildIdKind::Sha1, {}};
563   if (S == "uuid")
564     return {BuildIdKind::Uuid, {}};
565   if (S.startswith("0x"))
566     return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
567 
568   if (S != "none")
569     error("unknown --build-id style: " + S);
570   return {BuildIdKind::None, {}};
571 }
572 
573 static bool getCompressDebugSections(opt::InputArgList &Args) {
574   StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
575   if (S == "none")
576     return false;
577   if (S != "zlib")
578     error("unknown --compress-debug-sections value: " + S);
579   if (!zlib::isAvailable())
580     error("--compress-debug-sections: zlib is not available");
581   return true;
582 }
583 
584 static int parseInt(StringRef S, opt::Arg *Arg) {
585   int V = 0;
586   if (!to_integer(S, V, 10))
587     error(Arg->getSpelling() + "=" + Arg->getValue() +
588           ": number expected, but got '" + S + "'");
589   return V;
590 }
591 
592 // Initializes Config members by the command line options.
593 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
594   errorHandler().Verbose = Args.hasArg(OPT_verbose);
595   errorHandler().FatalWarnings =
596       Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
597 
598   Config->AllowMultipleDefinition =
599       Args.hasFlag(OPT_allow_multiple_definition,
600                    OPT_no_allow_multiple_definition, false) ||
601       hasZOption(Args, "muldefs");
602   Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
603   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
604   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
605   Config->CheckSections =
606       Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
607   Config->Chroot = Args.getLastArgValue(OPT_chroot);
608   Config->CompressDebugSections = getCompressDebugSections(Args);
609   Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
610                                       !Args.hasArg(OPT_relocatable));
611   Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
612   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
613   Config->Discard = getDiscard(Args);
614   Config->DynamicLinker = getDynamicLinker(Args);
615   Config->EhFrameHdr =
616       Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
617   Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
618   Config->EnableNewDtags = !Args.hasArg(OPT_disable_new_dtags);
619   Config->Entry = Args.getLastArgValue(OPT_entry);
620   Config->ExportDynamic =
621       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
622   Config->FilterList = args::getStrings(Args, OPT_filter);
623   Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
624   Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
625   Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
626   Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
627   Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
628   Config->ICF = Args.hasFlag(OPT_icf_all, OPT_icf_none, false);
629   Config->IgnoreDataAddressEquality =
630       Args.hasArg(OPT_ignore_data_address_equality);
631   Config->IgnoreFunctionAddressEquality =
632       Args.hasArg(OPT_ignore_function_address_equality);
633   Config->Init = Args.getLastArgValue(OPT_init, "_init");
634   Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
635   Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
636   Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
637   Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
638   Config->MapFile = Args.getLastArgValue(OPT_Map);
639   Config->MergeArmExidx =
640       Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
641   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
642   Config->Nostdlib = Args.hasArg(OPT_nostdlib);
643   Config->OFormatBinary = isOutputFormatBinary(Args);
644   Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
645   Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
646   Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
647   Config->Optimize = args::getInteger(Args, OPT_O, 1);
648   Config->OrphanHandling = getOrphanHandling(Args);
649   Config->OutputFile = Args.getLastArgValue(OPT_o);
650   Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
651   Config->PrintIcfSections =
652       Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
653   Config->PrintGcSections =
654       Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
655   Config->Rpath = getRpath(Args);
656   Config->Relocatable = Args.hasArg(OPT_relocatable);
657   Config->SaveTemps = Args.hasArg(OPT_save_temps);
658   Config->SearchPaths = args::getStrings(Args, OPT_library_path);
659   Config->SectionStartMap = getSectionStartMap(Args);
660   Config->Shared = Args.hasArg(OPT_shared);
661   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
662   Config->SoName = Args.getLastArgValue(OPT_soname);
663   Config->SortSection = getSortSection(Args);
664   Config->Strip = getStrip(Args);
665   Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
666   Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
667   Config->Target2 = getTarget2(Args);
668   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
669   Config->ThinLTOCachePolicy = CHECK(
670       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
671       "--thinlto-cache-policy: invalid cache policy");
672   Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
673   ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
674   Config->Trace = Args.hasArg(OPT_trace);
675   Config->Undefined = args::getStrings(Args, OPT_undefined);
676   Config->UndefinedVersion =
677       Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
678   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
679   Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
680   Config->ZCombreloc = !hasZOption(Args, "nocombreloc");
681   Config->ZExecstack = hasZOption(Args, "execstack");
682   Config->ZNocopyreloc = hasZOption(Args, "nocopyreloc");
683   Config->ZNodelete = hasZOption(Args, "nodelete");
684   Config->ZNodlopen = hasZOption(Args, "nodlopen");
685   Config->ZNow = hasZOption(Args, "now");
686   Config->ZOrigin = hasZOption(Args, "origin");
687   Config->ZRelro = !hasZOption(Args, "norelro");
688   Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
689   Config->ZRodynamic = hasZOption(Args, "rodynamic");
690   Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
691   Config->ZText = !hasZOption(Args, "notext");
692   Config->ZWxneeded = hasZOption(Args, "wxneeded");
693 
694   // Parse LTO plugin-related options for compatibility with gold.
695   std::vector<const char *> LTOOptions({Config->ProgName.data()});
696   for (auto *Arg : Args.filtered(OPT_plugin_opt)) {
697     StringRef S = Arg->getValue();
698     if (S == "disable-verify")
699       Config->DisableVerify = true;
700     else if (S == "save-temps")
701       Config->SaveTemps = true;
702     else if (S.startswith("O"))
703       Config->LTOO = parseInt(S.substr(1), Arg);
704     else if (S.startswith("lto-partitions="))
705       Config->LTOPartitions = parseInt(S.substr(15), Arg);
706     else if (S.startswith("jobs="))
707       Config->ThinLTOJobs = parseInt(S.substr(5), Arg);
708     else if (S.startswith("mcpu="))
709       LTOOptions.push_back(Saver.save("-" + S).data());
710     else if (!S.startswith("/") && !S.startswith("-fresolution=") &&
711              !S.startswith("-pass-through=") && !S.startswith("thinlto"))
712       LTOOptions.push_back(S.data());
713   }
714   // Parse and evaluate -mllvm options.
715   for (auto *Arg : Args.filtered(OPT_mllvm))
716     LTOOptions.push_back(Arg->getValue());
717   cl::ParseCommandLineOptions(LTOOptions.size(), LTOOptions.data());
718 
719   if (Config->LTOO > 3)
720     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
721   if (Config->LTOPartitions == 0)
722     error("--lto-partitions: number of threads must be > 0");
723   if (Config->ThinLTOJobs == 0)
724     error("--thinlto-jobs: number of threads must be > 0");
725 
726   // Parse ELF{32,64}{LE,BE} and CPU type.
727   if (auto *Arg = Args.getLastArg(OPT_m)) {
728     StringRef S = Arg->getValue();
729     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
730         parseEmulation(S);
731     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
732     Config->Emulation = S;
733   }
734 
735   // Parse -hash-style={sysv,gnu,both}.
736   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
737     StringRef S = Arg->getValue();
738     if (S == "sysv")
739       Config->SysvHash = true;
740     else if (S == "gnu")
741       Config->GnuHash = true;
742     else if (S == "both")
743       Config->SysvHash = Config->GnuHash = true;
744     else
745       error("unknown -hash-style: " + S);
746   }
747 
748   if (Args.hasArg(OPT_print_map))
749     Config->MapFile = "-";
750 
751   // --omagic is an option to create old-fashioned executables in which
752   // .text segments are writable. Today, the option is still in use to
753   // create special-purpose programs such as boot loaders. It doesn't
754   // make sense to create PT_GNU_RELRO for such executables.
755   if (Config->Omagic)
756     Config->ZRelro = false;
757 
758   std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
759 
760   if (auto *Arg = Args.getLastArg(OPT_pack_dyn_relocs_eq)) {
761     StringRef S = Arg->getValue();
762     if (S == "android")
763       Config->AndroidPackDynRelocs = true;
764     else if (S != "none")
765       error("unknown -pack-dyn-relocs format: " + S);
766   }
767 
768   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
769     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
770       Config->SymbolOrderingFile = args::getLines(*Buffer);
771 
772   // If --retain-symbol-file is used, we'll keep only the symbols listed in
773   // the file and discard all others.
774   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
775     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
776     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
777       for (StringRef S : args::getLines(*Buffer))
778         Config->VersionScriptGlobals.push_back(
779             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
780   }
781 
782   bool HasExportDynamic =
783       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
784 
785   // Parses -dynamic-list and -export-dynamic-symbol. They make some
786   // symbols private. Note that -export-dynamic takes precedence over them
787   // as it says all symbols should be exported.
788   if (!HasExportDynamic) {
789     for (auto *Arg : Args.filtered(OPT_dynamic_list))
790       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
791         readDynamicList(*Buffer);
792 
793     for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol)) {
794       Config->DynamicList.push_back(
795           {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
796       Config->Undefined.push_back(Arg->getValue());
797     }
798   }
799 
800   for (auto *Arg : Args.filtered(OPT_version_script))
801     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
802       readVersionScript(*Buffer);
803 }
804 
805 // Some Config members do not directly correspond to any particular
806 // command line options, but computed based on other Config values.
807 // This function initialize such members. See Config.h for the details
808 // of these values.
809 static void setConfigs(opt::InputArgList &Args) {
810   ELFKind Kind = Config->EKind;
811   uint16_t Machine = Config->EMachine;
812 
813   // There is an ILP32 ABI for x86-64, although it's not very popular.
814   // It is called the x32 ABI.
815   bool IsX32 = (Kind == ELF32LEKind && Machine == EM_X86_64);
816 
817   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
818   Config->Is64 = (Kind == ELF64LEKind || Kind == ELF64BEKind);
819   Config->IsLE = (Kind == ELF32LEKind || Kind == ELF64LEKind);
820   Config->Endianness =
821       Config->IsLE ? support::endianness::little : support::endianness::big;
822   Config->IsMips64EL = (Kind == ELF64LEKind && Machine == EM_MIPS);
823   Config->IsRela =
824       (Config->Is64 || IsX32 || Machine == EM_PPC) && Machine != EM_MIPS;
825   Config->Pic = Config->Pie || Config->Shared;
826   Config->Wordsize = Config->Is64 ? 8 : 4;
827   Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
828                                       OPT_no_apply_dynamic_relocs, false) ||
829                          !Config->IsRela;
830 }
831 
832 // Returns a value of "-format" option.
833 static bool getBinaryOption(StringRef S) {
834   if (S == "binary")
835     return true;
836   if (S == "elf" || S == "default")
837     return false;
838   error("unknown -format value: " + S +
839         " (supported formats: elf, default, binary)");
840   return false;
841 }
842 
843 void LinkerDriver::createFiles(opt::InputArgList &Args) {
844   for (auto *Arg : Args) {
845     switch (Arg->getOption().getUnaliasedOption().getID()) {
846     case OPT_library:
847       addLibrary(Arg->getValue());
848       break;
849     case OPT_INPUT:
850       addFile(Arg->getValue(), /*WithLOption=*/false);
851       break;
852     case OPT_defsym: {
853       StringRef From;
854       StringRef To;
855       std::tie(From, To) = StringRef(Arg->getValue()).split('=');
856       readDefsym(From, MemoryBufferRef(To, "-defsym"));
857       break;
858     }
859     case OPT_script:
860       if (Optional<std::string> Path = searchLinkerScript(Arg->getValue())) {
861         if (Optional<MemoryBufferRef> MB = readFile(*Path))
862           readLinkerScript(*MB);
863         break;
864       }
865       error(Twine("cannot find linker script ") + Arg->getValue());
866       break;
867     case OPT_as_needed:
868       Config->AsNeeded = true;
869       break;
870     case OPT_format:
871       InBinary = getBinaryOption(Arg->getValue());
872       break;
873     case OPT_no_as_needed:
874       Config->AsNeeded = false;
875       break;
876     case OPT_Bstatic:
877       Config->Static = true;
878       break;
879     case OPT_Bdynamic:
880       Config->Static = false;
881       break;
882     case OPT_whole_archive:
883       InWholeArchive = true;
884       break;
885     case OPT_no_whole_archive:
886       InWholeArchive = false;
887       break;
888     case OPT_start_lib:
889       InLib = true;
890       break;
891     case OPT_end_lib:
892       InLib = false;
893       break;
894     }
895   }
896 
897   if (Files.empty() && errorCount() == 0)
898     error("no input files");
899 }
900 
901 // If -m <machine_type> was not given, infer it from object files.
902 void LinkerDriver::inferMachineType() {
903   if (Config->EKind != ELFNoneKind)
904     return;
905 
906   for (InputFile *F : Files) {
907     if (F->EKind == ELFNoneKind)
908       continue;
909     Config->EKind = F->EKind;
910     Config->EMachine = F->EMachine;
911     Config->OSABI = F->OSABI;
912     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
913     return;
914   }
915   error("target emulation unknown: -m or at least one .o file required");
916 }
917 
918 // Parse -z max-page-size=<value>. The default value is defined by
919 // each target.
920 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
921   uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
922                                        Target->DefaultMaxPageSize);
923   if (!isPowerOf2_64(Val))
924     error("max-page-size: value isn't a power of 2");
925   return Val;
926 }
927 
928 // Parses -image-base option.
929 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
930   // Because we are using "Config->MaxPageSize" here, this function has to be
931   // called after the variable is initialized.
932   auto *Arg = Args.getLastArg(OPT_image_base);
933   if (!Arg)
934     return None;
935 
936   StringRef S = Arg->getValue();
937   uint64_t V;
938   if (!to_integer(S, V)) {
939     error("-image-base: number expected, but got " + S);
940     return 0;
941   }
942   if ((V % Config->MaxPageSize) != 0)
943     warn("-image-base: address isn't multiple of page size: " + S);
944   return V;
945 }
946 
947 // Parses `--exclude-libs=lib,lib,...`.
948 // The library names may be delimited by commas or colons.
949 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
950   DenseSet<StringRef> Ret;
951   for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
952     StringRef S = Arg->getValue();
953     for (;;) {
954       size_t Pos = S.find_first_of(",:");
955       if (Pos == StringRef::npos)
956         break;
957       Ret.insert(S.substr(0, Pos));
958       S = S.substr(Pos + 1);
959     }
960     Ret.insert(S);
961   }
962   return Ret;
963 }
964 
965 static Optional<StringRef> getArchiveName(InputFile *File) {
966   if (isa<ArchiveFile>(File))
967     return File->getName();
968   if (!File->ArchiveName.empty())
969     return File->ArchiveName;
970   return None;
971 }
972 
973 // Handles the -exclude-libs option. If a static library file is specified
974 // by the -exclude-libs option, all public symbols from the archive become
975 // private unless otherwise specified by version scripts or something.
976 // A special library name "ALL" means all archive files.
977 //
978 // This is not a popular option, but some programs such as bionic libc use it.
979 template <class ELFT>
980 static void excludeLibs(opt::InputArgList &Args, ArrayRef<InputFile *> Files) {
981   DenseSet<StringRef> Libs = getExcludeLibs(Args);
982   bool All = Libs.count("ALL");
983 
984   for (InputFile *File : Files)
985     if (Optional<StringRef> Archive = getArchiveName(File))
986       if (All || Libs.count(path::filename(*Archive)))
987         for (Symbol *Sym : File->getSymbols())
988           if (!Sym->isLocal())
989             Sym->VersionId = VER_NDX_LOCAL;
990 }
991 
992 // Do actual linking. Note that when this function is called,
993 // all linker scripts have already been parsed.
994 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
995   Target = getTarget();
996 
997   Config->MaxPageSize = getMaxPageSize(Args);
998   Config->ImageBase = getImageBase(Args);
999 
1000   // If a -hash-style option was not given, set to a default value,
1001   // which varies depending on the target.
1002   if (!Args.hasArg(OPT_hash_style)) {
1003     if (Config->EMachine == EM_MIPS)
1004       Config->SysvHash = true;
1005     else
1006       Config->SysvHash = Config->GnuHash = true;
1007   }
1008 
1009   // Default output filename is "a.out" by the Unix tradition.
1010   if (Config->OutputFile.empty())
1011     Config->OutputFile = "a.out";
1012 
1013   // Fail early if the output file or map file is not writable. If a user has a
1014   // long link, e.g. due to a large LTO link, they do not wish to run it and
1015   // find that it failed because there was a mistake in their command-line.
1016   if (auto E = tryCreateFile(Config->OutputFile))
1017     error("cannot open output file " + Config->OutputFile + ": " + E.message());
1018   if (auto E = tryCreateFile(Config->MapFile))
1019     error("cannot open map file " + Config->MapFile + ": " + E.message());
1020   if (errorCount())
1021     return;
1022 
1023   // Use default entry point name if no name was given via the command
1024   // line nor linker scripts. For some reason, MIPS entry point name is
1025   // different from others.
1026   Config->WarnMissingEntry =
1027       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1028   if (Config->Entry.empty() && !Config->Relocatable)
1029     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1030 
1031   // Handle --trace-symbol.
1032   for (auto *Arg : Args.filtered(OPT_trace_symbol))
1033     Symtab->trace(Arg->getValue());
1034 
1035   // Add all files to the symbol table. This will add almost all
1036   // symbols that we need to the symbol table.
1037   for (InputFile *F : Files)
1038     Symtab->addFile<ELFT>(F);
1039 
1040   // Now that we have every file, we can decide if we will need a
1041   // dynamic symbol table.
1042   // We need one if we were asked to export dynamic symbols or if we are
1043   // producing a shared library.
1044   // We also need one if any shared libraries are used and for pie executables
1045   // (probably because the dynamic linker needs it).
1046   Config->HasDynSymTab =
1047       !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1048 
1049   // Some symbols (such as __ehdr_start) are defined lazily only when there
1050   // are undefined symbols for them, so we add these to trigger that logic.
1051   for (StringRef Sym : Script->ReferencedSymbols)
1052     Symtab->addUndefined<ELFT>(Sym);
1053 
1054   // Handle the `--undefined <sym>` options.
1055   for (StringRef S : Config->Undefined)
1056     Symtab->fetchIfLazy<ELFT>(S);
1057 
1058   // If an entry symbol is in a static archive, pull out that file now
1059   // to complete the symbol table. After this, no new names except a
1060   // few linker-synthesized ones will be added to the symbol table.
1061   Symtab->fetchIfLazy<ELFT>(Config->Entry);
1062 
1063   // Return if there were name resolution errors.
1064   if (errorCount())
1065     return;
1066 
1067   // Handle undefined symbols in DSOs.
1068   if (!Config->Shared)
1069     Symtab->scanShlibUndefined<ELFT>();
1070 
1071   // Handle the -exclude-libs option.
1072   if (Args.hasArg(OPT_exclude_libs))
1073     excludeLibs<ELFT>(Args, Files);
1074 
1075   // Create ElfHeader early. We need a dummy section in
1076   // addReservedSymbols to mark the created symbols as not absolute.
1077   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1078   Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1079 
1080   // We need to create some reserved symbols such as _end. Create them.
1081   if (!Config->Relocatable)
1082     addReservedSymbols();
1083 
1084   // We want to declare linker script's symbols early,
1085   // so that we can version them.
1086   Script->declareSymbols();
1087 
1088   // Apply version scripts.
1089   Symtab->scanVersionScript();
1090 
1091   // Create wrapped symbols for -wrap option.
1092   for (auto *Arg : Args.filtered(OPT_wrap))
1093     Symtab->addSymbolWrap<ELFT>(Arg->getValue());
1094 
1095   Symtab->addCombinedLTOObject<ELFT>();
1096   if (errorCount())
1097     return;
1098 
1099   // Apply symbol renames for -wrap.
1100   Symtab->applySymbolWrap();
1101 
1102   // Now that we have a complete list of input files.
1103   // Beyond this point, no new files are added.
1104   // Aggregate all input sections into one place.
1105   for (InputFile *F : ObjectFiles)
1106     for (InputSectionBase *S : F->getSections())
1107       if (S && S != &InputSection::Discarded)
1108         InputSections.push_back(S);
1109   for (BinaryFile *F : BinaryFiles)
1110     for (InputSectionBase *S : F->getSections())
1111       InputSections.push_back(cast<InputSection>(S));
1112 
1113   // We do not want to emit debug sections if --strip-all
1114   // or -strip-debug are given.
1115   if (Config->Strip != StripPolicy::None)
1116     llvm::erase_if(InputSections, [](InputSectionBase *S) {
1117       return S->Name.startswith(".debug") || S->Name.startswith(".zdebug");
1118     });
1119 
1120   Config->EFlags = Target->calcEFlags();
1121 
1122   if (Config->EMachine == EM_ARM) {
1123     // FIXME: These warnings can be removed when lld only uses these features
1124     // when the input objects have been compiled with an architecture that
1125     // supports them.
1126     if (Config->ARMHasBlx == false)
1127       warn("lld uses blx instruction, no object with architecture supporting "
1128            "feature detected.");
1129     if (Config->ARMJ1J2BranchEncoding == false)
1130       warn("lld uses extended branch encoding, no object with architecture "
1131            "supporting feature detected.");
1132     if (Config->ARMHasMovtMovw == false)
1133       warn("lld may use movt/movw, no object with architecture supporting "
1134            "feature detected.");
1135   }
1136 
1137   // This adds a .comment section containing a version string. We have to add it
1138   // before decompressAndMergeSections because the .comment section is a
1139   // mergeable section.
1140   if (!Config->Relocatable)
1141     InputSections.push_back(createCommentSection());
1142 
1143   // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1144   // and identical code folding.
1145   markLive<ELFT>();
1146   decompressSections();
1147   mergeSections();
1148   if (Config->ICF)
1149     doIcf<ELFT>();
1150 
1151   // Write the result to the file.
1152   writeResult<ELFT>();
1153 }
1154