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