xref: /llvm-project-15.0.7/lld/ELF/Driver.cpp (revision 3dee12e4)
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 // The driver drives the entire linking process. It is responsible for
10 // parsing command line options and doing whatever it is instructed to do.
11 //
12 // One notable thing in the LLD's driver when compared to other linkers is
13 // that the LLD's driver is agnostic on the host operating system.
14 // Other linkers usually have implicit default values (such as a dynamic
15 // linker path or library paths) for each host OS.
16 //
17 // I don't think implicit default values are useful because they are
18 // usually explicitly specified by the compiler driver. They can even
19 // be harmful when you are doing cross-linking. Therefore, in LLD, we
20 // simply trust the compiler driver to pass all required options and
21 // don't try to make effort on our side.
22 //
23 //===----------------------------------------------------------------------===//
24 
25 #include "Driver.h"
26 #include "Config.h"
27 #include "ICF.h"
28 #include "InputFiles.h"
29 #include "InputSection.h"
30 #include "LinkerScript.h"
31 #include "MarkLive.h"
32 #include "OutputSections.h"
33 #include "ScriptParser.h"
34 #include "SymbolTable.h"
35 #include "Symbols.h"
36 #include "SyntheticSections.h"
37 #include "Target.h"
38 #include "Writer.h"
39 #include "lld/Common/Args.h"
40 #include "lld/Common/Driver.h"
41 #include "lld/Common/ErrorHandler.h"
42 #include "lld/Common/Filesystem.h"
43 #include "lld/Common/Memory.h"
44 #include "lld/Common/Strings.h"
45 #include "lld/Common/TargetOptionsCommandFlags.h"
46 #include "lld/Common/Threads.h"
47 #include "lld/Common/Version.h"
48 #include "llvm/ADT/SetVector.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSwitch.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compression.h"
53 #include "llvm/Support/LEB128.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/TarWriter.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <cstdlib>
59 #include <utility>
60 
61 using namespace llvm;
62 using namespace llvm::ELF;
63 using namespace llvm::object;
64 using namespace llvm::sys;
65 using namespace llvm::support;
66 
67 using namespace lld;
68 using namespace lld::elf;
69 
70 Configuration *elf::Config;
71 LinkerDriver *elf::Driver;
72 
73 static void setConfigs(opt::InputArgList &Args);
74 
75 bool elf::link(ArrayRef<const char *> Args, bool CanExitEarly,
76                raw_ostream &Error) {
77   errorHandler().LogName = args::getFilenameWithoutExe(Args[0]);
78   errorHandler().ErrorLimitExceededMsg =
79       "too many errors emitted, stopping now (use "
80       "-error-limit=0 to see all errors)";
81   errorHandler().ErrorOS = &Error;
82   errorHandler().ExitEarly = CanExitEarly;
83   errorHandler().ColorDiagnostics = Error.has_colors();
84 
85   InputSections.clear();
86   OutputSections.clear();
87   BinaryFiles.clear();
88   BitcodeFiles.clear();
89   ObjectFiles.clear();
90   SharedFiles.clear();
91 
92   Config = make<Configuration>();
93   Driver = make<LinkerDriver>();
94   Script = make<LinkerScript>();
95   Symtab = make<SymbolTable>();
96 
97   Tar = nullptr;
98   memset(&In, 0, sizeof(In));
99 
100   SharedFile::VernauxNum = 0;
101 
102   Config->ProgName = Args[0];
103 
104   Driver->main(Args);
105 
106   // Exit immediately if we don't need to return to the caller.
107   // This saves time because the overhead of calling destructors
108   // for all globally-allocated objects is not negligible.
109   if (CanExitEarly)
110     exitLld(errorCount() ? 1 : 0);
111 
112   freeArena();
113   return !errorCount();
114 }
115 
116 // Parses a linker -m option.
117 static std::tuple<ELFKind, uint16_t, uint8_t> parseEmulation(StringRef Emul) {
118   uint8_t OSABI = 0;
119   StringRef S = Emul;
120   if (S.endswith("_fbsd")) {
121     S = S.drop_back(5);
122     OSABI = ELFOSABI_FREEBSD;
123   }
124 
125   std::pair<ELFKind, uint16_t> Ret =
126       StringSwitch<std::pair<ELFKind, uint16_t>>(S)
127           .Cases("aarch64elf", "aarch64linux", "aarch64_elf64_le_vec",
128                  {ELF64LEKind, EM_AARCH64})
129           .Cases("armelf", "armelf_linux_eabi", {ELF32LEKind, EM_ARM})
130           .Case("elf32_x86_64", {ELF32LEKind, EM_X86_64})
131           .Cases("elf32btsmip", "elf32btsmipn32", {ELF32BEKind, EM_MIPS})
132           .Cases("elf32ltsmip", "elf32ltsmipn32", {ELF32LEKind, EM_MIPS})
133           .Case("elf32lriscv", {ELF32LEKind, EM_RISCV})
134           .Cases("elf32ppc", "elf32ppclinux", {ELF32BEKind, EM_PPC})
135           .Case("elf64btsmip", {ELF64BEKind, EM_MIPS})
136           .Case("elf64ltsmip", {ELF64LEKind, EM_MIPS})
137           .Case("elf64lriscv", {ELF64LEKind, EM_RISCV})
138           .Case("elf64ppc", {ELF64BEKind, EM_PPC64})
139           .Case("elf64lppc", {ELF64LEKind, EM_PPC64})
140           .Cases("elf_amd64", "elf_x86_64", {ELF64LEKind, EM_X86_64})
141           .Case("elf_i386", {ELF32LEKind, EM_386})
142           .Case("elf_iamcu", {ELF32LEKind, EM_IAMCU})
143           .Default({ELFNoneKind, EM_NONE});
144 
145   if (Ret.first == ELFNoneKind)
146     error("unknown emulation: " + Emul);
147   return std::make_tuple(Ret.first, Ret.second, OSABI);
148 }
149 
150 // Returns slices of MB by parsing MB as an archive file.
151 // Each slice consists of a member file in the archive.
152 std::vector<std::pair<MemoryBufferRef, uint64_t>> static getArchiveMembers(
153     MemoryBufferRef MB) {
154   std::unique_ptr<Archive> File =
155       CHECK(Archive::create(MB),
156             MB.getBufferIdentifier() + ": failed to parse archive");
157 
158   std::vector<std::pair<MemoryBufferRef, uint64_t>> V;
159   Error Err = Error::success();
160   bool AddToTar = File->isThin() && Tar;
161   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
162     Archive::Child C =
163         CHECK(COrErr, MB.getBufferIdentifier() +
164                           ": could not get the child of the archive");
165     MemoryBufferRef MBRef =
166         CHECK(C.getMemoryBufferRef(),
167               MB.getBufferIdentifier() +
168                   ": could not get the buffer for a child of the archive");
169     if (AddToTar)
170       Tar->append(relativeToRoot(check(C.getFullName())), MBRef.getBuffer());
171     V.push_back(std::make_pair(MBRef, C.getChildOffset()));
172   }
173   if (Err)
174     fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
175           toString(std::move(Err)));
176 
177   // Take ownership of memory buffers created for members of thin archives.
178   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
179     make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
180 
181   return V;
182 }
183 
184 // Opens a file and create a file object. Path has to be resolved already.
185 void LinkerDriver::addFile(StringRef Path, bool WithLOption) {
186   using namespace sys::fs;
187 
188   Optional<MemoryBufferRef> Buffer = readFile(Path);
189   if (!Buffer.hasValue())
190     return;
191   MemoryBufferRef MBRef = *Buffer;
192 
193   if (Config->FormatBinary) {
194     Files.push_back(make<BinaryFile>(MBRef));
195     return;
196   }
197 
198   switch (identify_magic(MBRef.getBuffer())) {
199   case file_magic::unknown:
200     readLinkerScript(MBRef);
201     return;
202   case file_magic::archive: {
203     // Handle -whole-archive.
204     if (InWholeArchive) {
205       for (const auto &P : getArchiveMembers(MBRef))
206         Files.push_back(createObjectFile(P.first, Path, P.second));
207       return;
208     }
209 
210     std::unique_ptr<Archive> File =
211         CHECK(Archive::create(MBRef), Path + ": failed to parse archive");
212 
213     // If an archive file has no symbol table, it is likely that a user
214     // is attempting LTO and using a default ar command that doesn't
215     // understand the LLVM bitcode file. It is a pretty common error, so
216     // we'll handle it as if it had a symbol table.
217     if (!File->isEmpty() && !File->hasSymbolTable()) {
218       // Check if all members are bitcode files. If not, ignore, which is the
219       // default action without the LTO hack described above.
220       for (const std::pair<MemoryBufferRef, uint64_t> &P :
221            getArchiveMembers(MBRef))
222         if (identify_magic(P.first.getBuffer()) != file_magic::bitcode)
223           return;
224 
225       for (const std::pair<MemoryBufferRef, uint64_t> &P :
226            getArchiveMembers(MBRef))
227         Files.push_back(make<LazyObjFile>(P.first, Path, P.second));
228       return;
229     }
230 
231     // Handle the regular case.
232     Files.push_back(make<ArchiveFile>(std::move(File)));
233     return;
234   }
235   case file_magic::elf_shared_object:
236     if (Config->Static || Config->Relocatable) {
237       error("attempted static link of dynamic object " + Path);
238       return;
239     }
240 
241     // DSOs usually have DT_SONAME tags in their ELF headers, and the
242     // sonames are used to identify DSOs. But if they are missing,
243     // they are identified by filenames. We don't know whether the new
244     // file has a DT_SONAME or not because we haven't parsed it yet.
245     // Here, we set the default soname for the file because we might
246     // need it later.
247     //
248     // If a file was specified by -lfoo, the directory part is not
249     // significant, as a user did not specify it. This behavior is
250     // compatible with GNU.
251     Files.push_back(
252         createSharedFile(MBRef, WithLOption ? path::filename(Path) : Path));
253     return;
254   case file_magic::bitcode:
255   case file_magic::elf_relocatable:
256     if (InLib)
257       Files.push_back(make<LazyObjFile>(MBRef, "", 0));
258     else
259       Files.push_back(createObjectFile(MBRef));
260     break;
261   default:
262     error(Path + ": unknown file type");
263   }
264 }
265 
266 // Add a given library by searching it from input search paths.
267 void LinkerDriver::addLibrary(StringRef Name) {
268   if (Optional<std::string> Path = searchLibrary(Name))
269     addFile(*Path, /*WithLOption=*/true);
270   else
271     error("unable to find library -l" + Name);
272 }
273 
274 // This function is called on startup. We need this for LTO since
275 // LTO calls LLVM functions to compile bitcode files to native code.
276 // Technically this can be delayed until we read bitcode files, but
277 // we don't bother to do lazily because the initialization is fast.
278 static void initLLVM() {
279   InitializeAllTargets();
280   InitializeAllTargetMCs();
281   InitializeAllAsmPrinters();
282   InitializeAllAsmParsers();
283 }
284 
285 // Some command line options or some combinations of them are not allowed.
286 // This function checks for such errors.
287 static void checkOptions() {
288   // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
289   // table which is a relatively new feature.
290   if (Config->EMachine == EM_MIPS && Config->GnuHash)
291     error("the .gnu.hash section is not compatible with the MIPS target");
292 
293   if (Config->FixCortexA53Errata843419 && Config->EMachine != EM_AARCH64)
294     error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
295 
296   if (Config->TocOptimize && Config->EMachine != EM_PPC64)
297     error("--toc-optimize is only supported on the PowerPC64 target");
298 
299   if (Config->Pie && Config->Shared)
300     error("-shared and -pie may not be used together");
301 
302   if (!Config->Shared && !Config->FilterList.empty())
303     error("-F may not be used without -shared");
304 
305   if (!Config->Shared && !Config->AuxiliaryList.empty())
306     error("-f may not be used without -shared");
307 
308   if (!Config->Relocatable && !Config->DefineCommon)
309     error("-no-define-common not supported in non relocatable output");
310 
311   if (Config->Relocatable) {
312     if (Config->Shared)
313       error("-r and -shared may not be used together");
314     if (Config->GcSections)
315       error("-r and --gc-sections may not be used together");
316     if (Config->GdbIndex)
317       error("-r and --gdb-index may not be used together");
318     if (Config->ICF != ICFLevel::None)
319       error("-r and --icf may not be used together");
320     if (Config->Pie)
321       error("-r and -pie may not be used together");
322   }
323 
324   if (Config->ExecuteOnly) {
325     if (Config->EMachine != EM_AARCH64)
326       error("-execute-only is only supported on AArch64 targets");
327 
328     if (Config->SingleRoRx && !Script->HasSectionsCommand)
329       error("-execute-only and -no-rosegment cannot be used together");
330   }
331 }
332 
333 static const char *getReproduceOption(opt::InputArgList &Args) {
334   if (auto *Arg = Args.getLastArg(OPT_reproduce))
335     return Arg->getValue();
336   return getenv("LLD_REPRODUCE");
337 }
338 
339 static bool hasZOption(opt::InputArgList &Args, StringRef Key) {
340   for (auto *Arg : Args.filtered(OPT_z))
341     if (Key == Arg->getValue())
342       return true;
343   return false;
344 }
345 
346 static bool getZFlag(opt::InputArgList &Args, StringRef K1, StringRef K2,
347                      bool Default) {
348   for (auto *Arg : Args.filtered_reverse(OPT_z)) {
349     if (K1 == Arg->getValue())
350       return true;
351     if (K2 == Arg->getValue())
352       return false;
353   }
354   return Default;
355 }
356 
357 static bool isKnownZFlag(StringRef S) {
358   return S == "combreloc" || S == "copyreloc" || S == "defs" ||
359          S == "execstack" || S == "global" || S == "hazardplt" ||
360          S == "initfirst" || S == "interpose" ||
361          S == "keep-text-section-prefix" || S == "lazy" || S == "muldefs" ||
362          S == "nocombreloc" || S == "nocopyreloc" || S == "nodefaultlib" ||
363          S == "nodelete" || S == "nodlopen" || S == "noexecstack" ||
364          S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" ||
365          S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" ||
366          S == "rodynamic" || S == "text" || S == "wxneeded" ||
367          S.startswith("max-page-size=") || S.startswith("stack-size=");
368 }
369 
370 // Report an error for an unknown -z option.
371 static void checkZOptions(opt::InputArgList &Args) {
372   for (auto *Arg : Args.filtered(OPT_z))
373     if (!isKnownZFlag(Arg->getValue()))
374       error("unknown -z value: " + StringRef(Arg->getValue()));
375 }
376 
377 void LinkerDriver::main(ArrayRef<const char *> ArgsArr) {
378   ELFOptTable Parser;
379   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
380 
381   // Interpret this flag early because error() depends on them.
382   errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
383   checkZOptions(Args);
384 
385   // Handle -help
386   if (Args.hasArg(OPT_help)) {
387     printHelp();
388     return;
389   }
390 
391   // Handle -v or -version.
392   //
393   // A note about "compatible with GNU linkers" message: this is a hack for
394   // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
395   // still the newest version in March 2017) or earlier to recognize LLD as
396   // a GNU compatible linker. As long as an output for the -v option
397   // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
398   //
399   // This is somewhat ugly hack, but in reality, we had no choice other
400   // than doing this. Considering the very long release cycle of Libtool,
401   // it is not easy to improve it to recognize LLD as a GNU compatible
402   // linker in a timely manner. Even if we can make it, there are still a
403   // lot of "configure" scripts out there that are generated by old version
404   // of Libtool. We cannot convince every software developer to migrate to
405   // the latest version and re-generate scripts. So we have this hack.
406   if (Args.hasArg(OPT_v) || Args.hasArg(OPT_version))
407     message(getLLDVersion() + " (compatible with GNU linkers)");
408 
409   if (const char *Path = getReproduceOption(Args)) {
410     // Note that --reproduce is a debug option so you can ignore it
411     // if you are trying to understand the whole picture of the code.
412     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
413         TarWriter::create(Path, path::stem(Path));
414     if (ErrOrWriter) {
415       Tar = std::move(*ErrOrWriter);
416       Tar->append("response.txt", createResponseFile(Args));
417       Tar->append("version.txt", getLLDVersion() + "\n");
418     } else {
419       error("--reproduce: " + toString(ErrOrWriter.takeError()));
420     }
421   }
422 
423   readConfigs(Args);
424 
425   // The behavior of -v or --version is a bit strange, but this is
426   // needed for compatibility with GNU linkers.
427   if (Args.hasArg(OPT_v) && !Args.hasArg(OPT_INPUT))
428     return;
429   if (Args.hasArg(OPT_version))
430     return;
431 
432   initLLVM();
433   createFiles(Args);
434   if (errorCount())
435     return;
436 
437   inferMachineType();
438   setConfigs(Args);
439   checkOptions();
440   if (errorCount())
441     return;
442 
443   switch (Config->EKind) {
444   case ELF32LEKind:
445     link<ELF32LE>(Args);
446     return;
447   case ELF32BEKind:
448     link<ELF32BE>(Args);
449     return;
450   case ELF64LEKind:
451     link<ELF64LE>(Args);
452     return;
453   case ELF64BEKind:
454     link<ELF64BE>(Args);
455     return;
456   default:
457     llvm_unreachable("unknown Config->EKind");
458   }
459 }
460 
461 static std::string getRpath(opt::InputArgList &Args) {
462   std::vector<StringRef> V = args::getStrings(Args, OPT_rpath);
463   return llvm::join(V.begin(), V.end(), ":");
464 }
465 
466 // Determines what we should do if there are remaining unresolved
467 // symbols after the name resolution.
468 static UnresolvedPolicy getUnresolvedSymbolPolicy(opt::InputArgList &Args) {
469   UnresolvedPolicy ErrorOrWarn = Args.hasFlag(OPT_error_unresolved_symbols,
470                                               OPT_warn_unresolved_symbols, true)
471                                      ? UnresolvedPolicy::ReportError
472                                      : UnresolvedPolicy::Warn;
473 
474   // Process the last of -unresolved-symbols, -no-undefined or -z defs.
475   for (auto *Arg : llvm::reverse(Args)) {
476     switch (Arg->getOption().getID()) {
477     case OPT_unresolved_symbols: {
478       StringRef S = Arg->getValue();
479       if (S == "ignore-all" || S == "ignore-in-object-files")
480         return UnresolvedPolicy::Ignore;
481       if (S == "ignore-in-shared-libs" || S == "report-all")
482         return ErrorOrWarn;
483       error("unknown --unresolved-symbols value: " + S);
484       continue;
485     }
486     case OPT_no_undefined:
487       return ErrorOrWarn;
488     case OPT_z:
489       if (StringRef(Arg->getValue()) == "defs")
490         return ErrorOrWarn;
491       continue;
492     }
493   }
494 
495   // -shared implies -unresolved-symbols=ignore-all because missing
496   // symbols are likely to be resolved at runtime using other DSOs.
497   if (Config->Shared)
498     return UnresolvedPolicy::Ignore;
499   return ErrorOrWarn;
500 }
501 
502 static Target2Policy getTarget2(opt::InputArgList &Args) {
503   StringRef S = Args.getLastArgValue(OPT_target2, "got-rel");
504   if (S == "rel")
505     return Target2Policy::Rel;
506   if (S == "abs")
507     return Target2Policy::Abs;
508   if (S == "got-rel")
509     return Target2Policy::GotRel;
510   error("unknown --target2 option: " + S);
511   return Target2Policy::GotRel;
512 }
513 
514 static bool isOutputFormatBinary(opt::InputArgList &Args) {
515   StringRef S = Args.getLastArgValue(OPT_oformat, "elf");
516   if (S == "binary")
517     return true;
518   if (!S.startswith("elf"))
519     error("unknown --oformat value: " + S);
520   return false;
521 }
522 
523 static DiscardPolicy getDiscard(opt::InputArgList &Args) {
524   if (Args.hasArg(OPT_relocatable))
525     return DiscardPolicy::None;
526 
527   auto *Arg =
528       Args.getLastArg(OPT_discard_all, OPT_discard_locals, OPT_discard_none);
529   if (!Arg)
530     return DiscardPolicy::Default;
531   if (Arg->getOption().getID() == OPT_discard_all)
532     return DiscardPolicy::All;
533   if (Arg->getOption().getID() == OPT_discard_locals)
534     return DiscardPolicy::Locals;
535   return DiscardPolicy::None;
536 }
537 
538 static StringRef getDynamicLinker(opt::InputArgList &Args) {
539   auto *Arg = Args.getLastArg(OPT_dynamic_linker, OPT_no_dynamic_linker);
540   if (!Arg || Arg->getOption().getID() == OPT_no_dynamic_linker)
541     return "";
542   return Arg->getValue();
543 }
544 
545 static ICFLevel getICF(opt::InputArgList &Args) {
546   auto *Arg = Args.getLastArg(OPT_icf_none, OPT_icf_safe, OPT_icf_all);
547   if (!Arg || Arg->getOption().getID() == OPT_icf_none)
548     return ICFLevel::None;
549   if (Arg->getOption().getID() == OPT_icf_safe)
550     return ICFLevel::Safe;
551   return ICFLevel::All;
552 }
553 
554 static StripPolicy getStrip(opt::InputArgList &Args) {
555   if (Args.hasArg(OPT_relocatable))
556     return StripPolicy::None;
557 
558   auto *Arg = Args.getLastArg(OPT_strip_all, OPT_strip_debug);
559   if (!Arg)
560     return StripPolicy::None;
561   if (Arg->getOption().getID() == OPT_strip_all)
562     return StripPolicy::All;
563   return StripPolicy::Debug;
564 }
565 
566 static uint64_t parseSectionAddress(StringRef S, const opt::Arg &Arg) {
567   uint64_t VA = 0;
568   if (S.startswith("0x"))
569     S = S.drop_front(2);
570   if (!to_integer(S, VA, 16))
571     error("invalid argument: " + toString(Arg));
572   return VA;
573 }
574 
575 static StringMap<uint64_t> getSectionStartMap(opt::InputArgList &Args) {
576   StringMap<uint64_t> Ret;
577   for (auto *Arg : Args.filtered(OPT_section_start)) {
578     StringRef Name;
579     StringRef Addr;
580     std::tie(Name, Addr) = StringRef(Arg->getValue()).split('=');
581     Ret[Name] = parseSectionAddress(Addr, *Arg);
582   }
583 
584   if (auto *Arg = Args.getLastArg(OPT_Ttext))
585     Ret[".text"] = parseSectionAddress(Arg->getValue(), *Arg);
586   if (auto *Arg = Args.getLastArg(OPT_Tdata))
587     Ret[".data"] = parseSectionAddress(Arg->getValue(), *Arg);
588   if (auto *Arg = Args.getLastArg(OPT_Tbss))
589     Ret[".bss"] = parseSectionAddress(Arg->getValue(), *Arg);
590   return Ret;
591 }
592 
593 static SortSectionPolicy getSortSection(opt::InputArgList &Args) {
594   StringRef S = Args.getLastArgValue(OPT_sort_section);
595   if (S == "alignment")
596     return SortSectionPolicy::Alignment;
597   if (S == "name")
598     return SortSectionPolicy::Name;
599   if (!S.empty())
600     error("unknown --sort-section rule: " + S);
601   return SortSectionPolicy::Default;
602 }
603 
604 static OrphanHandlingPolicy getOrphanHandling(opt::InputArgList &Args) {
605   StringRef S = Args.getLastArgValue(OPT_orphan_handling, "place");
606   if (S == "warn")
607     return OrphanHandlingPolicy::Warn;
608   if (S == "error")
609     return OrphanHandlingPolicy::Error;
610   if (S != "place")
611     error("unknown --orphan-handling mode: " + S);
612   return OrphanHandlingPolicy::Place;
613 }
614 
615 // Parse --build-id or --build-id=<style>. We handle "tree" as a
616 // synonym for "sha1" because all our hash functions including
617 // -build-id=sha1 are actually tree hashes for performance reasons.
618 static std::pair<BuildIdKind, std::vector<uint8_t>>
619 getBuildId(opt::InputArgList &Args) {
620   auto *Arg = Args.getLastArg(OPT_build_id, OPT_build_id_eq);
621   if (!Arg)
622     return {BuildIdKind::None, {}};
623 
624   if (Arg->getOption().getID() == OPT_build_id)
625     return {BuildIdKind::Fast, {}};
626 
627   StringRef S = Arg->getValue();
628   if (S == "fast")
629     return {BuildIdKind::Fast, {}};
630   if (S == "md5")
631     return {BuildIdKind::Md5, {}};
632   if (S == "sha1" || S == "tree")
633     return {BuildIdKind::Sha1, {}};
634   if (S == "uuid")
635     return {BuildIdKind::Uuid, {}};
636   if (S.startswith("0x"))
637     return {BuildIdKind::Hexstring, parseHex(S.substr(2))};
638 
639   if (S != "none")
640     error("unknown --build-id style: " + S);
641   return {BuildIdKind::None, {}};
642 }
643 
644 static std::pair<bool, bool> getPackDynRelocs(opt::InputArgList &Args) {
645   StringRef S = Args.getLastArgValue(OPT_pack_dyn_relocs, "none");
646   if (S == "android")
647     return {true, false};
648   if (S == "relr")
649     return {false, true};
650   if (S == "android+relr")
651     return {true, true};
652 
653   if (S != "none")
654     error("unknown -pack-dyn-relocs format: " + S);
655   return {false, false};
656 }
657 
658 static void readCallGraph(MemoryBufferRef MB) {
659   // Build a map from symbol name to section
660   DenseMap<StringRef, Symbol *> Map;
661   for (InputFile *File : ObjectFiles)
662     for (Symbol *Sym : File->getSymbols())
663       Map[Sym->getName()] = Sym;
664 
665   auto FindSection = [&](StringRef Name) -> InputSectionBase * {
666     Symbol *Sym = Map.lookup(Name);
667     if (!Sym) {
668       if (Config->WarnSymbolOrdering)
669         warn(MB.getBufferIdentifier() + ": no such symbol: " + Name);
670       return nullptr;
671     }
672     maybeWarnUnorderableSymbol(Sym);
673 
674     if (Defined *DR = dyn_cast_or_null<Defined>(Sym))
675       return dyn_cast_or_null<InputSectionBase>(DR->Section);
676     return nullptr;
677   };
678 
679   for (StringRef Line : args::getLines(MB)) {
680     SmallVector<StringRef, 3> Fields;
681     Line.split(Fields, ' ');
682     uint64_t Count;
683 
684     if (Fields.size() != 3 || !to_integer(Fields[2], Count)) {
685       error(MB.getBufferIdentifier() + ": parse error");
686       return;
687     }
688 
689     if (InputSectionBase *From = FindSection(Fields[0]))
690       if (InputSectionBase *To = FindSection(Fields[1]))
691         Config->CallGraphProfile[std::make_pair(From, To)] += Count;
692   }
693 }
694 
695 template <class ELFT> static void readCallGraphsFromObjectFiles() {
696   for (auto File : ObjectFiles) {
697     auto *Obj = cast<ObjFile<ELFT>>(File);
698 
699     for (const Elf_CGProfile_Impl<ELFT> &CGPE : Obj->CGProfile) {
700       auto *FromSym = dyn_cast<Defined>(&Obj->getSymbol(CGPE.cgp_from));
701       auto *ToSym = dyn_cast<Defined>(&Obj->getSymbol(CGPE.cgp_to));
702       if (!FromSym || !ToSym)
703         continue;
704 
705       auto *From = dyn_cast_or_null<InputSectionBase>(FromSym->Section);
706       auto *To = dyn_cast_or_null<InputSectionBase>(ToSym->Section);
707       if (From && To)
708         Config->CallGraphProfile[{From, To}] += CGPE.cgp_weight;
709     }
710   }
711 }
712 
713 static bool getCompressDebugSections(opt::InputArgList &Args) {
714   StringRef S = Args.getLastArgValue(OPT_compress_debug_sections, "none");
715   if (S == "none")
716     return false;
717   if (S != "zlib")
718     error("unknown --compress-debug-sections value: " + S);
719   if (!zlib::isAvailable())
720     error("--compress-debug-sections: zlib is not available");
721   return true;
722 }
723 
724 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &Args,
725                                                         unsigned Id) {
726   auto *Arg = Args.getLastArg(Id);
727   if (!Arg)
728     return {"", ""};
729 
730   StringRef S = Arg->getValue();
731   std::pair<StringRef, StringRef> Ret = S.split(';');
732   if (Ret.second.empty())
733     error(Arg->getSpelling() + " expects 'old;new' format, but got " + S);
734   return Ret;
735 }
736 
737 // Parse the symbol ordering file and warn for any duplicate entries.
738 static std::vector<StringRef> getSymbolOrderingFile(MemoryBufferRef MB) {
739   SetVector<StringRef> Names;
740   for (StringRef S : args::getLines(MB))
741     if (!Names.insert(S) && Config->WarnSymbolOrdering)
742       warn(MB.getBufferIdentifier() + ": duplicate ordered symbol: " + S);
743 
744   return Names.takeVector();
745 }
746 
747 static void parseClangOption(StringRef Opt, const Twine &Msg) {
748   std::string Err;
749   raw_string_ostream OS(Err);
750 
751   const char *Argv[] = {Config->ProgName.data(), Opt.data()};
752   if (cl::ParseCommandLineOptions(2, Argv, "", &OS))
753     return;
754   OS.flush();
755   error(Msg + ": " + StringRef(Err).trim());
756 }
757 
758 // Initializes Config members by the command line options.
759 void LinkerDriver::readConfigs(opt::InputArgList &Args) {
760   errorHandler().Verbose = Args.hasArg(OPT_verbose);
761   errorHandler().FatalWarnings =
762       Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
763   ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
764 
765   Config->AllowMultipleDefinition =
766       Args.hasFlag(OPT_allow_multiple_definition,
767                    OPT_no_allow_multiple_definition, false) ||
768       hasZOption(Args, "muldefs");
769   Config->AllowShlibUndefined =
770       Args.hasFlag(OPT_allow_shlib_undefined, OPT_no_allow_shlib_undefined,
771                    Args.hasArg(OPT_shared));
772   Config->AuxiliaryList = args::getStrings(Args, OPT_auxiliary);
773   Config->Bsymbolic = Args.hasArg(OPT_Bsymbolic);
774   Config->BsymbolicFunctions = Args.hasArg(OPT_Bsymbolic_functions);
775   Config->CheckSections =
776       Args.hasFlag(OPT_check_sections, OPT_no_check_sections, true);
777   Config->Chroot = Args.getLastArgValue(OPT_chroot);
778   Config->CompressDebugSections = getCompressDebugSections(Args);
779   Config->Cref = Args.hasFlag(OPT_cref, OPT_no_cref, false);
780   Config->DefineCommon = Args.hasFlag(OPT_define_common, OPT_no_define_common,
781                                       !Args.hasArg(OPT_relocatable));
782   Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
783   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
784   Config->Discard = getDiscard(Args);
785   Config->DwoDir = Args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
786   Config->DynamicLinker = getDynamicLinker(Args);
787   Config->EhFrameHdr =
788       Args.hasFlag(OPT_eh_frame_hdr, OPT_no_eh_frame_hdr, false);
789   Config->EmitLLVM = Args.hasArg(OPT_plugin_opt_emit_llvm, false);
790   Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
791   Config->CallGraphProfileSort = Args.hasFlag(
792       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
793   Config->EnableNewDtags =
794       Args.hasFlag(OPT_enable_new_dtags, OPT_disable_new_dtags, true);
795   Config->Entry = Args.getLastArgValue(OPT_entry);
796   Config->ExecuteOnly =
797       Args.hasFlag(OPT_execute_only, OPT_no_execute_only, false);
798   Config->ExportDynamic =
799       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
800   Config->FilterList = args::getStrings(Args, OPT_filter);
801   Config->Fini = Args.getLastArgValue(OPT_fini, "_fini");
802   Config->FixCortexA53Errata843419 = Args.hasArg(OPT_fix_cortex_a53_843419);
803   Config->GcSections = Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
804   Config->GnuUnique = Args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
805   Config->GdbIndex = Args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
806   Config->ICF = getICF(Args);
807   Config->IgnoreDataAddressEquality =
808       Args.hasArg(OPT_ignore_data_address_equality);
809   Config->IgnoreFunctionAddressEquality =
810       Args.hasArg(OPT_ignore_function_address_equality);
811   Config->Init = Args.getLastArgValue(OPT_init, "_init");
812   Config->LTOAAPipeline = Args.getLastArgValue(OPT_lto_aa_pipeline);
813   Config->LTOCSProfileGenerate = Args.hasArg(OPT_lto_cs_profile_generate);
814   Config->LTOCSProfileFile = Args.getLastArgValue(OPT_lto_cs_profile_file);
815   Config->LTODebugPassManager = Args.hasArg(OPT_lto_debug_pass_manager);
816   Config->LTONewPassManager = Args.hasArg(OPT_lto_new_pass_manager);
817   Config->LTONewPmPasses = Args.getLastArgValue(OPT_lto_newpm_passes);
818   Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
819   Config->LTOObjPath = Args.getLastArgValue(OPT_plugin_opt_obj_path_eq);
820   Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
821   Config->LTOSampleProfile = Args.getLastArgValue(OPT_lto_sample_profile);
822   Config->MapFile = Args.getLastArgValue(OPT_Map);
823   Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0);
824   Config->MergeArmExidx =
825       Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
826   Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
827   Config->Nostdlib = Args.hasArg(OPT_nostdlib);
828   Config->OFormatBinary = isOutputFormatBinary(Args);
829   Config->Omagic = Args.hasFlag(OPT_omagic, OPT_no_omagic, false);
830   Config->OptRemarksFilename = Args.getLastArgValue(OPT_opt_remarks_filename);
831   Config->OptRemarksPasses = Args.getLastArgValue(OPT_opt_remarks_passes);
832   Config->OptRemarksWithHotness = Args.hasArg(OPT_opt_remarks_with_hotness);
833   Config->Optimize = args::getInteger(Args, OPT_O, 1);
834   Config->OrphanHandling = getOrphanHandling(Args);
835   Config->OutputFile = Args.getLastArgValue(OPT_o);
836   Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
837   Config->PrintIcfSections =
838       Args.hasFlag(OPT_print_icf_sections, OPT_no_print_icf_sections, false);
839   Config->PrintGcSections =
840       Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
841   Config->PrintSymbolOrder =
842       Args.getLastArgValue(OPT_print_symbol_order);
843   Config->Rpath = getRpath(Args);
844   Config->Relocatable = Args.hasArg(OPT_relocatable);
845   Config->SaveTemps = Args.hasArg(OPT_save_temps);
846   Config->SearchPaths = args::getStrings(Args, OPT_library_path);
847   Config->SectionStartMap = getSectionStartMap(Args);
848   Config->Shared = Args.hasArg(OPT_shared);
849   Config->SingleRoRx = Args.hasArg(OPT_no_rosegment);
850   Config->SoName = Args.getLastArgValue(OPT_soname);
851   Config->SortSection = getSortSection(Args);
852   Config->SplitStackAdjustSize = args::getInteger(Args, OPT_split_stack_adjust_size, 16384);
853   Config->Strip = getStrip(Args);
854   Config->Sysroot = Args.getLastArgValue(OPT_sysroot);
855   Config->Target1Rel = Args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
856   Config->Target2 = getTarget2(Args);
857   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
858   Config->ThinLTOCachePolicy = CHECK(
859       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
860       "--thinlto-cache-policy: invalid cache policy");
861   Config->ThinLTOEmitImportsFiles =
862       Args.hasArg(OPT_plugin_opt_thinlto_emit_imports_files);
863   Config->ThinLTOIndexOnly = Args.hasArg(OPT_plugin_opt_thinlto_index_only) ||
864                              Args.hasArg(OPT_plugin_opt_thinlto_index_only_eq);
865   Config->ThinLTOIndexOnlyArg =
866       Args.getLastArgValue(OPT_plugin_opt_thinlto_index_only_eq);
867   Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
868   Config->ThinLTOObjectSuffixReplace =
869       getOldNewOptions(Args, OPT_plugin_opt_thinlto_object_suffix_replace_eq);
870   Config->ThinLTOPrefixReplace =
871       getOldNewOptions(Args, OPT_plugin_opt_thinlto_prefix_replace_eq);
872   Config->Trace = Args.hasArg(OPT_trace);
873   Config->Undefined = args::getStrings(Args, OPT_undefined);
874   Config->UndefinedVersion =
875       Args.hasFlag(OPT_undefined_version, OPT_no_undefined_version, true);
876   Config->UseAndroidRelrTags = Args.hasFlag(
877       OPT_use_android_relr_tags, OPT_no_use_android_relr_tags, false);
878   Config->UnresolvedSymbols = getUnresolvedSymbolPolicy(Args);
879   Config->WarnBackrefs =
880       Args.hasFlag(OPT_warn_backrefs, OPT_no_warn_backrefs, false);
881   Config->WarnCommon = Args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
882   Config->WarnIfuncTextrel =
883       Args.hasFlag(OPT_warn_ifunc_textrel, OPT_no_warn_ifunc_textrel, false);
884   Config->WarnSymbolOrdering =
885       Args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
886   Config->ZCombreloc = getZFlag(Args, "combreloc", "nocombreloc", true);
887   Config->ZCopyreloc = getZFlag(Args, "copyreloc", "nocopyreloc", true);
888   Config->ZExecstack = getZFlag(Args, "execstack", "noexecstack", false);
889   Config->ZGlobal = hasZOption(Args, "global");
890   Config->ZHazardplt = hasZOption(Args, "hazardplt");
891   Config->ZInitfirst = hasZOption(Args, "initfirst");
892   Config->ZInterpose = hasZOption(Args, "interpose");
893   Config->ZKeepTextSectionPrefix = getZFlag(
894       Args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
895   Config->ZNodefaultlib = hasZOption(Args, "nodefaultlib");
896   Config->ZNodelete = hasZOption(Args, "nodelete");
897   Config->ZNodlopen = hasZOption(Args, "nodlopen");
898   Config->ZNow = getZFlag(Args, "now", "lazy", false);
899   Config->ZOrigin = hasZOption(Args, "origin");
900   Config->ZRelro = getZFlag(Args, "relro", "norelro", true);
901   Config->ZRetpolineplt = hasZOption(Args, "retpolineplt");
902   Config->ZRodynamic = hasZOption(Args, "rodynamic");
903   Config->ZStackSize = args::getZOptionValue(Args, OPT_z, "stack-size", 0);
904   Config->ZText = getZFlag(Args, "text", "notext", true);
905   Config->ZWxneeded = hasZOption(Args, "wxneeded");
906 
907   // Parse LTO options.
908   if (auto *Arg = Args.getLastArg(OPT_plugin_opt_mcpu_eq))
909     parseClangOption(Saver.save("-mcpu=" + StringRef(Arg->getValue())),
910                      Arg->getSpelling());
911 
912   for (auto *Arg : Args.filtered(OPT_plugin_opt))
913     parseClangOption(Arg->getValue(), Arg->getSpelling());
914 
915   // Parse -mllvm options.
916   for (auto *Arg : Args.filtered(OPT_mllvm))
917     parseClangOption(Arg->getValue(), Arg->getSpelling());
918 
919   if (Config->LTOO > 3)
920     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
921   if (Config->LTOPartitions == 0)
922     error("--lto-partitions: number of threads must be > 0");
923   if (Config->ThinLTOJobs == 0)
924     error("--thinlto-jobs: number of threads must be > 0");
925 
926   if (Config->SplitStackAdjustSize < 0)
927     error("--split-stack-adjust-size: size must be >= 0");
928 
929   // Parse ELF{32,64}{LE,BE} and CPU type.
930   if (auto *Arg = Args.getLastArg(OPT_m)) {
931     StringRef S = Arg->getValue();
932     std::tie(Config->EKind, Config->EMachine, Config->OSABI) =
933         parseEmulation(S);
934     Config->MipsN32Abi = (S == "elf32btsmipn32" || S == "elf32ltsmipn32");
935     Config->Emulation = S;
936   }
937 
938   // Parse -hash-style={sysv,gnu,both}.
939   if (auto *Arg = Args.getLastArg(OPT_hash_style)) {
940     StringRef S = Arg->getValue();
941     if (S == "sysv")
942       Config->SysvHash = true;
943     else if (S == "gnu")
944       Config->GnuHash = true;
945     else if (S == "both")
946       Config->SysvHash = Config->GnuHash = true;
947     else
948       error("unknown -hash-style: " + S);
949   }
950 
951   if (Args.hasArg(OPT_print_map))
952     Config->MapFile = "-";
953 
954   // --omagic is an option to create old-fashioned executables in which
955   // .text segments are writable. Today, the option is still in use to
956   // create special-purpose programs such as boot loaders. It doesn't
957   // make sense to create PT_GNU_RELRO for such executables.
958   if (Config->Omagic)
959     Config->ZRelro = false;
960 
961   std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
962 
963   std::tie(Config->AndroidPackDynRelocs, Config->RelrPackDynRelocs) =
964       getPackDynRelocs(Args);
965 
966   if (auto *Arg = Args.getLastArg(OPT_symbol_ordering_file))
967     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
968       Config->SymbolOrderingFile = getSymbolOrderingFile(*Buffer);
969 
970   // If --retain-symbol-file is used, we'll keep only the symbols listed in
971   // the file and discard all others.
972   if (auto *Arg = Args.getLastArg(OPT_retain_symbols_file)) {
973     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
974     if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
975       for (StringRef S : args::getLines(*Buffer))
976         Config->VersionScriptGlobals.push_back(
977             {S, /*IsExternCpp*/ false, /*HasWildcard*/ false});
978   }
979 
980   bool HasExportDynamic =
981       Args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, false);
982 
983   // Parses -dynamic-list and -export-dynamic-symbol. They make some
984   // symbols private. Note that -export-dynamic takes precedence over them
985   // as it says all symbols should be exported.
986   if (!HasExportDynamic) {
987     for (auto *Arg : Args.filtered(OPT_dynamic_list))
988       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
989         readDynamicList(*Buffer);
990 
991     for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
992       Config->DynamicList.push_back(
993           {Arg->getValue(), /*IsExternCpp*/ false, /*HasWildcard*/ false});
994   }
995 
996   // If --export-dynamic-symbol=foo is given and symbol foo is defined in
997   // an object file in an archive file, that object file should be pulled
998   // out and linked. (It doesn't have to behave like that from technical
999   // point of view, but this is needed for compatibility with GNU.)
1000   for (auto *Arg : Args.filtered(OPT_export_dynamic_symbol))
1001     Config->Undefined.push_back(Arg->getValue());
1002 
1003   for (auto *Arg : Args.filtered(OPT_version_script))
1004     if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1005       if (Optional<MemoryBufferRef> Buffer = readFile(*Path))
1006         readVersionScript(*Buffer);
1007     } else {
1008       error(Twine("cannot find version script ") + Arg->getValue());
1009     }
1010 }
1011 
1012 // Some Config members do not directly correspond to any particular
1013 // command line options, but computed based on other Config values.
1014 // This function initialize such members. See Config.h for the details
1015 // of these values.
1016 static void setConfigs(opt::InputArgList &Args) {
1017   ELFKind K = Config->EKind;
1018   uint16_t M = Config->EMachine;
1019 
1020   Config->CopyRelocs = (Config->Relocatable || Config->EmitRelocs);
1021   Config->Is64 = (K == ELF64LEKind || K == ELF64BEKind);
1022   Config->IsLE = (K == ELF32LEKind || K == ELF64LEKind);
1023   Config->Endianness = Config->IsLE ? endianness::little : endianness::big;
1024   Config->IsMips64EL = (K == ELF64LEKind && M == EM_MIPS);
1025   Config->Pic = Config->Pie || Config->Shared;
1026   Config->PicThunk = Args.hasArg(OPT_pic_veneer, Config->Pic);
1027   Config->Wordsize = Config->Is64 ? 8 : 4;
1028 
1029   // ELF defines two different ways to store relocation addends as shown below:
1030   //
1031   //  Rel:  Addends are stored to the location where relocations are applied.
1032   //  Rela: Addends are stored as part of relocation entry.
1033   //
1034   // In other words, Rela makes it easy to read addends at the price of extra
1035   // 4 or 8 byte for each relocation entry. We don't know why ELF defined two
1036   // different mechanisms in the first place, but this is how the spec is
1037   // defined.
1038   //
1039   // You cannot choose which one, Rel or Rela, you want to use. Instead each
1040   // ABI defines which one you need to use. The following expression expresses
1041   // that.
1042   Config->IsRela = M == EM_AARCH64 || M == EM_AMDGPU || M == EM_HEXAGON ||
1043                    M == EM_PPC || M == EM_PPC64 || M == EM_RISCV ||
1044                    M == EM_X86_64;
1045 
1046   // If the output uses REL relocations we must store the dynamic relocation
1047   // addends to the output sections. We also store addends for RELA relocations
1048   // if --apply-dynamic-relocs is used.
1049   // We default to not writing the addends when using RELA relocations since
1050   // any standard conforming tool can find it in r_addend.
1051   Config->WriteAddends = Args.hasFlag(OPT_apply_dynamic_relocs,
1052                                       OPT_no_apply_dynamic_relocs, false) ||
1053                          !Config->IsRela;
1054 
1055   Config->TocOptimize =
1056       Args.hasFlag(OPT_toc_optimize, OPT_no_toc_optimize, M == EM_PPC64);
1057 }
1058 
1059 // Returns a value of "-format" option.
1060 static bool isFormatBinary(StringRef S) {
1061   if (S == "binary")
1062     return true;
1063   if (S == "elf" || S == "default")
1064     return false;
1065   error("unknown -format value: " + S +
1066         " (supported formats: elf, default, binary)");
1067   return false;
1068 }
1069 
1070 void LinkerDriver::createFiles(opt::InputArgList &Args) {
1071   // For --{push,pop}-state.
1072   std::vector<std::tuple<bool, bool, bool>> Stack;
1073 
1074   // Iterate over argv to process input files and positional arguments.
1075   for (auto *Arg : Args) {
1076     switch (Arg->getOption().getUnaliasedOption().getID()) {
1077     case OPT_library:
1078       addLibrary(Arg->getValue());
1079       break;
1080     case OPT_INPUT:
1081       addFile(Arg->getValue(), /*WithLOption=*/false);
1082       break;
1083     case OPT_defsym: {
1084       StringRef From;
1085       StringRef To;
1086       std::tie(From, To) = StringRef(Arg->getValue()).split('=');
1087       if (From.empty() || To.empty())
1088         error("-defsym: syntax error: " + StringRef(Arg->getValue()));
1089       else
1090         readDefsym(From, MemoryBufferRef(To, "-defsym"));
1091       break;
1092     }
1093     case OPT_script:
1094       if (Optional<std::string> Path = searchScript(Arg->getValue())) {
1095         if (Optional<MemoryBufferRef> MB = readFile(*Path))
1096           readLinkerScript(*MB);
1097         break;
1098       }
1099       error(Twine("cannot find linker script ") + Arg->getValue());
1100       break;
1101     case OPT_as_needed:
1102       Config->AsNeeded = true;
1103       break;
1104     case OPT_format:
1105       Config->FormatBinary = isFormatBinary(Arg->getValue());
1106       break;
1107     case OPT_no_as_needed:
1108       Config->AsNeeded = false;
1109       break;
1110     case OPT_Bstatic:
1111       Config->Static = true;
1112       break;
1113     case OPT_Bdynamic:
1114       Config->Static = false;
1115       break;
1116     case OPT_whole_archive:
1117       InWholeArchive = true;
1118       break;
1119     case OPT_no_whole_archive:
1120       InWholeArchive = false;
1121       break;
1122     case OPT_just_symbols:
1123       if (Optional<MemoryBufferRef> MB = readFile(Arg->getValue())) {
1124         Files.push_back(createObjectFile(*MB));
1125         Files.back()->JustSymbols = true;
1126       }
1127       break;
1128     case OPT_start_group:
1129       if (InputFile::IsInGroup)
1130         error("nested --start-group");
1131       InputFile::IsInGroup = true;
1132       break;
1133     case OPT_end_group:
1134       if (!InputFile::IsInGroup)
1135         error("stray --end-group");
1136       InputFile::IsInGroup = false;
1137       ++InputFile::NextGroupId;
1138       break;
1139     case OPT_start_lib:
1140       if (InLib)
1141         error("nested --start-lib");
1142       if (InputFile::IsInGroup)
1143         error("may not nest --start-lib in --start-group");
1144       InLib = true;
1145       InputFile::IsInGroup = true;
1146       break;
1147     case OPT_end_lib:
1148       if (!InLib)
1149         error("stray --end-lib");
1150       InLib = false;
1151       InputFile::IsInGroup = false;
1152       ++InputFile::NextGroupId;
1153       break;
1154     case OPT_push_state:
1155       Stack.emplace_back(Config->AsNeeded, Config->Static, InWholeArchive);
1156       break;
1157     case OPT_pop_state:
1158       if (Stack.empty()) {
1159         error("unbalanced --push-state/--pop-state");
1160         break;
1161       }
1162       std::tie(Config->AsNeeded, Config->Static, InWholeArchive) = Stack.back();
1163       Stack.pop_back();
1164       break;
1165     }
1166   }
1167 
1168   if (Files.empty() && errorCount() == 0)
1169     error("no input files");
1170 }
1171 
1172 // If -m <machine_type> was not given, infer it from object files.
1173 void LinkerDriver::inferMachineType() {
1174   if (Config->EKind != ELFNoneKind)
1175     return;
1176 
1177   for (InputFile *F : Files) {
1178     if (F->EKind == ELFNoneKind)
1179       continue;
1180     Config->EKind = F->EKind;
1181     Config->EMachine = F->EMachine;
1182     Config->OSABI = F->OSABI;
1183     Config->MipsN32Abi = Config->EMachine == EM_MIPS && isMipsN32Abi(F);
1184     return;
1185   }
1186   error("target emulation unknown: -m or at least one .o file required");
1187 }
1188 
1189 // Parse -z max-page-size=<value>. The default value is defined by
1190 // each target.
1191 static uint64_t getMaxPageSize(opt::InputArgList &Args) {
1192   uint64_t Val = args::getZOptionValue(Args, OPT_z, "max-page-size",
1193                                        Target->DefaultMaxPageSize);
1194   if (!isPowerOf2_64(Val))
1195     error("max-page-size: value isn't a power of 2");
1196   return Val;
1197 }
1198 
1199 // Parses -image-base option.
1200 static Optional<uint64_t> getImageBase(opt::InputArgList &Args) {
1201   // Because we are using "Config->MaxPageSize" here, this function has to be
1202   // called after the variable is initialized.
1203   auto *Arg = Args.getLastArg(OPT_image_base);
1204   if (!Arg)
1205     return None;
1206 
1207   StringRef S = Arg->getValue();
1208   uint64_t V;
1209   if (!to_integer(S, V)) {
1210     error("-image-base: number expected, but got " + S);
1211     return 0;
1212   }
1213   if ((V % Config->MaxPageSize) != 0)
1214     warn("-image-base: address isn't multiple of page size: " + S);
1215   return V;
1216 }
1217 
1218 // Parses `--exclude-libs=lib,lib,...`.
1219 // The library names may be delimited by commas or colons.
1220 static DenseSet<StringRef> getExcludeLibs(opt::InputArgList &Args) {
1221   DenseSet<StringRef> Ret;
1222   for (auto *Arg : Args.filtered(OPT_exclude_libs)) {
1223     StringRef S = Arg->getValue();
1224     for (;;) {
1225       size_t Pos = S.find_first_of(",:");
1226       if (Pos == StringRef::npos)
1227         break;
1228       Ret.insert(S.substr(0, Pos));
1229       S = S.substr(Pos + 1);
1230     }
1231     Ret.insert(S);
1232   }
1233   return Ret;
1234 }
1235 
1236 // Handles the -exclude-libs option. If a static library file is specified
1237 // by the -exclude-libs option, all public symbols from the archive become
1238 // private unless otherwise specified by version scripts or something.
1239 // A special library name "ALL" means all archive files.
1240 //
1241 // This is not a popular option, but some programs such as bionic libc use it.
1242 static void excludeLibs(opt::InputArgList &Args) {
1243   DenseSet<StringRef> Libs = getExcludeLibs(Args);
1244   bool All = Libs.count("ALL");
1245 
1246   auto Visit = [&](InputFile *File) {
1247     if (!File->ArchiveName.empty())
1248       if (All || Libs.count(path::filename(File->ArchiveName)))
1249         for (Symbol *Sym : File->getSymbols())
1250           if (!Sym->isLocal() && Sym->File == File)
1251             Sym->VersionId = VER_NDX_LOCAL;
1252   };
1253 
1254   for (InputFile *File : ObjectFiles)
1255     Visit(File);
1256 
1257   for (BitcodeFile *File : BitcodeFiles)
1258     Visit(File);
1259 }
1260 
1261 // Force Sym to be entered in the output. Used for -u or equivalent.
1262 template <class ELFT> static void handleUndefined(StringRef Name) {
1263   Symbol *Sym = Symtab->find(Name);
1264   if (!Sym)
1265     return;
1266 
1267   // Since symbol S may not be used inside the program, LTO may
1268   // eliminate it. Mark the symbol as "used" to prevent it.
1269   Sym->IsUsedInRegularObj = true;
1270 
1271   if (Sym->isLazy())
1272     Symtab->fetchLazy<ELFT>(Sym);
1273 }
1274 
1275 template <class ELFT> static void handleLibcall(StringRef Name) {
1276   Symbol *Sym = Symtab->find(Name);
1277   if (!Sym || !Sym->isLazy())
1278     return;
1279 
1280   MemoryBufferRef MB;
1281   if (auto *LO = dyn_cast<LazyObject>(Sym))
1282     MB = LO->File->MB;
1283   else
1284     MB = cast<LazyArchive>(Sym)->getMemberBuffer();
1285 
1286   if (isBitcode(MB))
1287     Symtab->fetchLazy<ELFT>(Sym);
1288 }
1289 
1290 // If all references to a DSO happen to be weak, the DSO is not added
1291 // to DT_NEEDED. If that happens, we need to eliminate shared symbols
1292 // created from the DSO. Otherwise, they become dangling references
1293 // that point to a non-existent DSO.
1294 static void demoteSharedSymbols() {
1295   for (Symbol *Sym : Symtab->getSymbols()) {
1296     if (auto *S = dyn_cast<SharedSymbol>(Sym)) {
1297       if (!S->getFile().IsNeeded) {
1298         bool Used = S->Used;
1299         replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_WEAK, S->StOther,
1300                                  S->Type);
1301         S->Used = Used;
1302       }
1303     }
1304   }
1305 }
1306 
1307 // The section referred to by S is considered address-significant. Set the
1308 // KeepUnique flag on the section if appropriate.
1309 static void markAddrsig(Symbol *S) {
1310   if (auto *D = dyn_cast_or_null<Defined>(S))
1311     if (D->Section)
1312       // We don't need to keep text sections unique under --icf=all even if they
1313       // are address-significant.
1314       if (Config->ICF == ICFLevel::Safe || !(D->Section->Flags & SHF_EXECINSTR))
1315         D->Section->KeepUnique = true;
1316 }
1317 
1318 // Record sections that define symbols mentioned in --keep-unique <symbol>
1319 // and symbols referred to by address-significance tables. These sections are
1320 // ineligible for ICF.
1321 template <class ELFT>
1322 static void findKeepUniqueSections(opt::InputArgList &Args) {
1323   for (auto *Arg : Args.filtered(OPT_keep_unique)) {
1324     StringRef Name = Arg->getValue();
1325     auto *D = dyn_cast_or_null<Defined>(Symtab->find(Name));
1326     if (!D || !D->Section) {
1327       warn("could not find symbol " + Name + " to keep unique");
1328       continue;
1329     }
1330     D->Section->KeepUnique = true;
1331   }
1332 
1333   // --icf=all --ignore-data-address-equality means that we can ignore
1334   // the dynsym and address-significance tables entirely.
1335   if (Config->ICF == ICFLevel::All && Config->IgnoreDataAddressEquality)
1336     return;
1337 
1338   // Symbols in the dynsym could be address-significant in other executables
1339   // or DSOs, so we conservatively mark them as address-significant.
1340   for (Symbol *S : Symtab->getSymbols())
1341     if (S->includeInDynsym())
1342       markAddrsig(S);
1343 
1344   // Visit the address-significance table in each object file and mark each
1345   // referenced symbol as address-significant.
1346   for (InputFile *F : ObjectFiles) {
1347     auto *Obj = cast<ObjFile<ELFT>>(F);
1348     ArrayRef<Symbol *> Syms = Obj->getSymbols();
1349     if (Obj->AddrsigSec) {
1350       ArrayRef<uint8_t> Contents =
1351           check(Obj->getObj().getSectionContents(Obj->AddrsigSec));
1352       const uint8_t *Cur = Contents.begin();
1353       while (Cur != Contents.end()) {
1354         unsigned Size;
1355         const char *Err;
1356         uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
1357         if (Err)
1358           fatal(toString(F) + ": could not decode addrsig section: " + Err);
1359         markAddrsig(Syms[SymIndex]);
1360         Cur += Size;
1361       }
1362     } else {
1363       // If an object file does not have an address-significance table,
1364       // conservatively mark all of its symbols as address-significant.
1365       for (Symbol *S : Syms)
1366         markAddrsig(S);
1367     }
1368   }
1369 }
1370 
1371 template <class ELFT> static Symbol *addUndefined(StringRef Name) {
1372   return Symtab->addUndefined<ELFT>(Name, STB_GLOBAL, STV_DEFAULT, 0, false,
1373                                     nullptr);
1374 }
1375 
1376 // The --wrap option is a feature to rename symbols so that you can write
1377 // wrappers for existing functions. If you pass `-wrap=foo`, all
1378 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
1379 // expected to write `wrap_foo` function as a wrapper). The original
1380 // symbol becomes accessible as `real_foo`, so you can call that from your
1381 // wrapper.
1382 //
1383 // This data structure is instantiated for each -wrap option.
1384 struct WrappedSymbol {
1385   Symbol *Sym;
1386   Symbol *Real;
1387   Symbol *Wrap;
1388 };
1389 
1390 // Handles -wrap option.
1391 //
1392 // This function instantiates wrapper symbols. At this point, they seem
1393 // like they are not being used at all, so we explicitly set some flags so
1394 // that LTO won't eliminate them.
1395 template <class ELFT>
1396 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &Args) {
1397   std::vector<WrappedSymbol> V;
1398   DenseSet<StringRef> Seen;
1399 
1400   for (auto *Arg : Args.filtered(OPT_wrap)) {
1401     StringRef Name = Arg->getValue();
1402     if (!Seen.insert(Name).second)
1403       continue;
1404 
1405     Symbol *Sym = Symtab->find(Name);
1406     if (!Sym)
1407       continue;
1408 
1409     Symbol *Real = addUndefined<ELFT>(Saver.save("__real_" + Name));
1410     Symbol *Wrap = addUndefined<ELFT>(Saver.save("__wrap_" + Name));
1411     V.push_back({Sym, Real, Wrap});
1412 
1413     // We want to tell LTO not to inline symbols to be overwritten
1414     // because LTO doesn't know the final symbol contents after renaming.
1415     Real->CanInline = false;
1416     Sym->CanInline = false;
1417 
1418     // Tell LTO not to eliminate these symbols.
1419     Sym->IsUsedInRegularObj = true;
1420     Wrap->IsUsedInRegularObj = true;
1421   }
1422   return V;
1423 }
1424 
1425 // Do renaming for -wrap by updating pointers to symbols.
1426 //
1427 // When this function is executed, only InputFiles and symbol table
1428 // contain pointers to symbol objects. We visit them to replace pointers,
1429 // so that wrapped symbols are swapped as instructed by the command line.
1430 static void wrapSymbols(ArrayRef<WrappedSymbol> Wrapped) {
1431   DenseMap<Symbol *, Symbol *> Map;
1432   for (const WrappedSymbol &W : Wrapped) {
1433     Map[W.Sym] = W.Wrap;
1434     Map[W.Real] = W.Sym;
1435   }
1436 
1437   // Update pointers in input files.
1438   parallelForEach(ObjectFiles, [&](InputFile *File) {
1439     std::vector<Symbol *> &Syms = File->getMutableSymbols();
1440     for (size_t I = 0, E = Syms.size(); I != E; ++I)
1441       if (Symbol *S = Map.lookup(Syms[I]))
1442         Syms[I] = S;
1443   });
1444 
1445   // Update pointers in the symbol table.
1446   for (const WrappedSymbol &W : Wrapped)
1447     Symtab->wrap(W.Sym, W.Real, W.Wrap);
1448 }
1449 
1450 static const char *LibcallRoutineNames[] = {
1451 #define HANDLE_LIBCALL(code, name) name,
1452 #include "llvm/IR/RuntimeLibcalls.def"
1453 #undef HANDLE_LIBCALL
1454 };
1455 
1456 // Do actual linking. Note that when this function is called,
1457 // all linker scripts have already been parsed.
1458 template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
1459   // If a -hash-style option was not given, set to a default value,
1460   // which varies depending on the target.
1461   if (!Args.hasArg(OPT_hash_style)) {
1462     if (Config->EMachine == EM_MIPS)
1463       Config->SysvHash = true;
1464     else
1465       Config->SysvHash = Config->GnuHash = true;
1466   }
1467 
1468   // Default output filename is "a.out" by the Unix tradition.
1469   if (Config->OutputFile.empty())
1470     Config->OutputFile = "a.out";
1471 
1472   // Fail early if the output file or map file is not writable. If a user has a
1473   // long link, e.g. due to a large LTO link, they do not wish to run it and
1474   // find that it failed because there was a mistake in their command-line.
1475   if (auto E = tryCreateFile(Config->OutputFile))
1476     error("cannot open output file " + Config->OutputFile + ": " + E.message());
1477   if (auto E = tryCreateFile(Config->MapFile))
1478     error("cannot open map file " + Config->MapFile + ": " + E.message());
1479   if (errorCount())
1480     return;
1481 
1482   // Use default entry point name if no name was given via the command
1483   // line nor linker scripts. For some reason, MIPS entry point name is
1484   // different from others.
1485   Config->WarnMissingEntry =
1486       (!Config->Entry.empty() || (!Config->Shared && !Config->Relocatable));
1487   if (Config->Entry.empty() && !Config->Relocatable)
1488     Config->Entry = (Config->EMachine == EM_MIPS) ? "__start" : "_start";
1489 
1490   // Handle --trace-symbol.
1491   for (auto *Arg : Args.filtered(OPT_trace_symbol))
1492     Symtab->trace(Arg->getValue());
1493 
1494   // Add all files to the symbol table. This will add almost all
1495   // symbols that we need to the symbol table.
1496   for (InputFile *F : Files)
1497     Symtab->addFile<ELFT>(F);
1498 
1499   // Now that we have every file, we can decide if we will need a
1500   // dynamic symbol table.
1501   // We need one if we were asked to export dynamic symbols or if we are
1502   // producing a shared library.
1503   // We also need one if any shared libraries are used and for pie executables
1504   // (probably because the dynamic linker needs it).
1505   Config->HasDynSymTab =
1506       !SharedFiles.empty() || Config->Pic || Config->ExportDynamic;
1507 
1508   // Some symbols (such as __ehdr_start) are defined lazily only when there
1509   // are undefined symbols for them, so we add these to trigger that logic.
1510   for (StringRef Name : Script->ReferencedSymbols)
1511     addUndefined<ELFT>(Name);
1512 
1513   // Handle the `--undefined <sym>` options.
1514   for (StringRef S : Config->Undefined)
1515     handleUndefined<ELFT>(S);
1516 
1517   // If an entry symbol is in a static archive, pull out that file now.
1518   handleUndefined<ELFT>(Config->Entry);
1519 
1520   // If any of our inputs are bitcode files, the LTO code generator may create
1521   // references to certain library functions that might not be explicit in the
1522   // bitcode file's symbol table. If any of those library functions are defined
1523   // in a bitcode file in an archive member, we need to arrange to use LTO to
1524   // compile those archive members by adding them to the link beforehand.
1525   //
1526   // However, adding all libcall symbols to the link can have undesired
1527   // consequences. For example, the libgcc implementation of
1528   // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
1529   // that aborts the program if the Linux kernel does not support 64-bit
1530   // atomics, which would prevent the program from running even if it does not
1531   // use 64-bit atomics.
1532   //
1533   // Therefore, we only add libcall symbols to the link before LTO if we have
1534   // to, i.e. if the symbol's definition is in bitcode. Any other required
1535   // libcall symbols will be added to the link after LTO when we add the LTO
1536   // object file to the link.
1537   if (!BitcodeFiles.empty())
1538     for (const char *S : LibcallRoutineNames)
1539       handleLibcall<ELFT>(S);
1540 
1541   // Return if there were name resolution errors.
1542   if (errorCount())
1543     return;
1544 
1545   // Now when we read all script files, we want to finalize order of linker
1546   // script commands, which can be not yet final because of INSERT commands.
1547   Script->processInsertCommands();
1548 
1549   // We want to declare linker script's symbols early,
1550   // so that we can version them.
1551   // They also might be exported if referenced by DSOs.
1552   Script->declareSymbols();
1553 
1554   // Handle the -exclude-libs option.
1555   if (Args.hasArg(OPT_exclude_libs))
1556     excludeLibs(Args);
1557 
1558   // Create ElfHeader early. We need a dummy section in
1559   // addReservedSymbols to mark the created symbols as not absolute.
1560   Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
1561   Out::ElfHeader->Size = sizeof(typename ELFT::Ehdr);
1562 
1563   // Create wrapped symbols for -wrap option.
1564   std::vector<WrappedSymbol> Wrapped = addWrappedSymbols<ELFT>(Args);
1565 
1566   // We need to create some reserved symbols such as _end. Create them.
1567   if (!Config->Relocatable)
1568     addReservedSymbols();
1569 
1570   // Apply version scripts.
1571   //
1572   // For a relocatable output, version scripts don't make sense, and
1573   // parsing a symbol version string (e.g. dropping "@ver1" from a symbol
1574   // name "foo@ver1") rather do harm, so we don't call this if -r is given.
1575   if (!Config->Relocatable)
1576     Symtab->scanVersionScript();
1577 
1578   // Do link-time optimization if given files are LLVM bitcode files.
1579   // This compiles bitcode files into real object files.
1580   //
1581   // With this the symbol table should be complete. After this, no new names
1582   // except a few linker-synthesized ones will be added to the symbol table.
1583   Symtab->addCombinedLTOObject<ELFT>();
1584   if (errorCount())
1585     return;
1586 
1587   // If -thinlto-index-only is given, we should create only "index
1588   // files" and not object files. Index file creation is already done
1589   // in addCombinedLTOObject, so we are done if that's the case.
1590   if (Config->ThinLTOIndexOnly)
1591     return;
1592 
1593   // Likewise, --plugin-opt=emit-llvm is an option to make LTO create
1594   // an output file in bitcode and exit, so that you can just get a
1595   // combined bitcode file.
1596   if (Config->EmitLLVM)
1597     return;
1598 
1599   // Apply symbol renames for -wrap.
1600   if (!Wrapped.empty())
1601     wrapSymbols(Wrapped);
1602 
1603   // Now that we have a complete list of input files.
1604   // Beyond this point, no new files are added.
1605   // Aggregate all input sections into one place.
1606   for (InputFile *F : ObjectFiles)
1607     for (InputSectionBase *S : F->getSections())
1608       if (S && S != &InputSection::Discarded)
1609         InputSections.push_back(S);
1610   for (BinaryFile *F : BinaryFiles)
1611     for (InputSectionBase *S : F->getSections())
1612       InputSections.push_back(cast<InputSection>(S));
1613 
1614   // We do not want to emit debug sections if --strip-all
1615   // or -strip-debug are given.
1616   if (Config->Strip != StripPolicy::None)
1617     llvm::erase_if(InputSections, [](InputSectionBase *S) { return S->Debug; });
1618 
1619   // The Target instance handles target-specific stuff, such as applying
1620   // relocations or writing a PLT section. It also contains target-dependent
1621   // values such as a default image base address.
1622   Target = getTarget();
1623 
1624   Config->EFlags = Target->calcEFlags();
1625   Config->MaxPageSize = getMaxPageSize(Args);
1626   Config->ImageBase = getImageBase(Args);
1627 
1628   if (Config->EMachine == EM_ARM) {
1629     // FIXME: These warnings can be removed when lld only uses these features
1630     // when the input objects have been compiled with an architecture that
1631     // supports them.
1632     if (Config->ARMHasBlx == false)
1633       warn("lld uses blx instruction, no object with architecture supporting "
1634            "feature detected");
1635   }
1636 
1637   // This adds a .comment section containing a version string. We have to add it
1638   // before mergeSections because the .comment section is a mergeable section.
1639   if (!Config->Relocatable)
1640     InputSections.push_back(createCommentSection());
1641 
1642   // Do size optimizations: garbage collection, merging of SHF_MERGE sections
1643   // and identical code folding.
1644   splitSections<ELFT>();
1645   markLive<ELFT>();
1646   demoteSharedSymbols();
1647   mergeSections();
1648   if (Config->ICF != ICFLevel::None) {
1649     findKeepUniqueSections<ELFT>(Args);
1650     doIcf<ELFT>();
1651   }
1652 
1653   // Read the callgraph now that we know what was gced or icfed
1654   if (Config->CallGraphProfileSort) {
1655     if (auto *Arg = Args.getLastArg(OPT_call_graph_ordering_file))
1656       if (Optional<MemoryBufferRef> Buffer = readFile(Arg->getValue()))
1657         readCallGraph(*Buffer);
1658     readCallGraphsFromObjectFiles<ELFT>();
1659   }
1660 
1661   // Write the result to the file.
1662   writeResult<ELFT>();
1663 }
1664