xref: /llvm-project-15.0.7/lld/COFF/Driver.cpp (revision 6f4fb4e7)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Driver.h"
10 #include "Config.h"
11 #include "DebugTypes.h"
12 #include "ICF.h"
13 #include "InputFiles.h"
14 #include "MarkLive.h"
15 #include "MinGW.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "Writer.h"
19 #include "lld/Common/Args.h"
20 #include "lld/Common/Driver.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Filesystem.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Threads.h"
25 #include "lld/Common/Timer.h"
26 #include "lld/Common/Version.h"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/BinaryFormat/Magic.h"
30 #include "llvm/Object/ArchiveWriter.h"
31 #include "llvm/Object/COFFImportFile.h"
32 #include "llvm/Object/COFFModuleDefinition.h"
33 #include "llvm/Object/WindowsMachineFlag.h"
34 #include "llvm/Option/Arg.h"
35 #include "llvm/Option/ArgList.h"
36 #include "llvm/Option/Option.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/LEB128.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/TarWriter.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
45 #include <algorithm>
46 #include <future>
47 #include <memory>
48 
49 using namespace llvm;
50 using namespace llvm::object;
51 using namespace llvm::COFF;
52 using llvm::sys::Process;
53 
54 namespace lld {
55 namespace coff {
56 
57 static Timer inputFileTimer("Input File Reading", Timer::root());
58 
59 Configuration *config;
60 LinkerDriver *driver;
61 
62 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &diag) {
63   errorHandler().logName = args::getFilenameWithoutExe(args[0]);
64   errorHandler().errorOS = &diag;
65   errorHandler().colorDiagnostics = diag.has_colors();
66   errorHandler().errorLimitExceededMsg =
67       "too many errors emitted, stopping now"
68       " (use /errorlimit:0 to see all errors)";
69   errorHandler().exitEarly = canExitEarly;
70   config = make<Configuration>();
71 
72   symtab = make<SymbolTable>();
73 
74   driver = make<LinkerDriver>();
75   driver->link(args);
76 
77   // Call exit() if we can to avoid calling destructors.
78   if (canExitEarly)
79     exitLld(errorCount() ? 1 : 0);
80 
81   freeArena();
82   ObjFile::instances.clear();
83   ImportFile::instances.clear();
84   BitcodeFile::instances.clear();
85   memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
86   return !errorCount();
87 }
88 
89 // Parse options of the form "old;new".
90 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
91                                                         unsigned id) {
92   auto *arg = args.getLastArg(id);
93   if (!arg)
94     return {"", ""};
95 
96   StringRef s = arg->getValue();
97   std::pair<StringRef, StringRef> ret = s.split(';');
98   if (ret.second.empty())
99     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
100   return ret;
101 }
102 
103 // Drop directory components and replace extension with ".exe" or ".dll".
104 static std::string getOutputPath(StringRef path) {
105   auto p = path.find_last_of("\\/");
106   StringRef s = (p == StringRef::npos) ? path : path.substr(p + 1);
107   const char* e = config->dll ? ".dll" : ".exe";
108   return (s.substr(0, s.rfind('.')) + e).str();
109 }
110 
111 // Returns true if S matches /crtend.?\.o$/.
112 static bool isCrtend(StringRef s) {
113   if (!s.endswith(".o"))
114     return false;
115   s = s.drop_back(2);
116   if (s.endswith("crtend"))
117     return true;
118   return !s.empty() && s.drop_back().endswith("crtend");
119 }
120 
121 // ErrorOr is not default constructible, so it cannot be used as the type
122 // parameter of a future.
123 // FIXME: We could open the file in createFutureForFile and avoid needing to
124 // return an error here, but for the moment that would cost us a file descriptor
125 // (a limited resource on Windows) for the duration that the future is pending.
126 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
127 
128 // Create a std::future that opens and maps a file using the best strategy for
129 // the host platform.
130 static std::future<MBErrPair> createFutureForFile(std::string path) {
131 #if _WIN32
132   // On Windows, file I/O is relatively slow so it is best to do this
133   // asynchronously.
134   auto strategy = std::launch::async;
135 #else
136   auto strategy = std::launch::deferred;
137 #endif
138   return std::async(strategy, [=]() {
139     auto mbOrErr = MemoryBuffer::getFile(path,
140                                          /*FileSize*/ -1,
141                                          /*RequiresNullTerminator*/ false);
142     if (!mbOrErr)
143       return MBErrPair{nullptr, mbOrErr.getError()};
144     return MBErrPair{std::move(*mbOrErr), std::error_code()};
145   });
146 }
147 
148 // Symbol names are mangled by prepending "_" on x86.
149 static StringRef mangle(StringRef sym) {
150   assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
151   if (config->machine == I386)
152     return saver.save("_" + sym);
153   return sym;
154 }
155 
156 static bool findUnderscoreMangle(StringRef sym) {
157   Symbol *s = symtab->findMangle(mangle(sym));
158   return s && !isa<Undefined>(s);
159 }
160 
161 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
162   MemoryBufferRef mbref = *mb;
163   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
164 
165   if (driver->tar)
166     driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
167                         mbref.getBuffer());
168   return mbref;
169 }
170 
171 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
172                              bool wholeArchive) {
173   StringRef filename = mb->getBufferIdentifier();
174 
175   MemoryBufferRef mbref = takeBuffer(std::move(mb));
176   filePaths.push_back(filename);
177 
178   // File type is detected by contents, not by file extension.
179   switch (identify_magic(mbref.getBuffer())) {
180   case file_magic::windows_resource:
181     resources.push_back(mbref);
182     break;
183   case file_magic::archive:
184     if (wholeArchive) {
185       std::unique_ptr<Archive> file =
186           CHECK(Archive::create(mbref), filename + ": failed to parse archive");
187 
188       for (MemoryBufferRef m : getArchiveMembers(file.get()))
189         addArchiveBuffer(m, "<whole-archive>", filename, 0);
190       return;
191     }
192     symtab->addFile(make<ArchiveFile>(mbref));
193     break;
194   case file_magic::bitcode:
195     symtab->addFile(make<BitcodeFile>(mbref, "", 0));
196     break;
197   case file_magic::coff_object:
198   case file_magic::coff_import_library:
199     symtab->addFile(make<ObjFile>(mbref));
200     break;
201   case file_magic::pdb:
202     loadTypeServerSource(mbref);
203     break;
204   case file_magic::coff_cl_gl_object:
205     error(filename + ": is not a native COFF file. Recompile without /GL");
206     break;
207   case file_magic::pecoff_executable:
208     if (filename.endswith_lower(".dll")) {
209       error(filename + ": bad file type. Did you specify a DLL instead of an "
210                        "import library?");
211       break;
212     }
213     LLVM_FALLTHROUGH;
214   default:
215     error(mbref.getBufferIdentifier() + ": unknown file type");
216     break;
217   }
218 }
219 
220 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive) {
221   auto future =
222       std::make_shared<std::future<MBErrPair>>(createFutureForFile(path));
223   std::string pathStr = path;
224   enqueueTask([=]() {
225     auto mbOrErr = future->get();
226     if (mbOrErr.second) {
227       std::string msg =
228           "could not open '" + pathStr + "': " + mbOrErr.second.message();
229       // Check if the filename is a typo for an option flag. OptTable thinks
230       // that all args that are not known options and that start with / are
231       // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
232       // the option `/nodefaultlib` than a reference to a file in the root
233       // directory.
234       std::string nearest;
235       if (COFFOptTable().findNearest(pathStr, nearest) > 1)
236         error(msg);
237       else
238         error(msg + "; did you mean '" + nearest + "'");
239     } else
240       driver->addBuffer(std::move(mbOrErr.first), wholeArchive);
241   });
242 }
243 
244 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
245                                     StringRef parentName,
246                                     uint64_t offsetInArchive) {
247   file_magic magic = identify_magic(mb.getBuffer());
248   if (magic == file_magic::coff_import_library) {
249     InputFile *imp = make<ImportFile>(mb);
250     imp->parentName = parentName;
251     symtab->addFile(imp);
252     return;
253   }
254 
255   InputFile *obj;
256   if (magic == file_magic::coff_object) {
257     obj = make<ObjFile>(mb);
258   } else if (magic == file_magic::bitcode) {
259     obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
260   } else {
261     error("unknown file type: " + mb.getBufferIdentifier());
262     return;
263   }
264 
265   obj->parentName = parentName;
266   symtab->addFile(obj);
267   log("Loaded " + toString(obj) + " for " + symName);
268 }
269 
270 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
271                                         StringRef symName,
272                                         StringRef parentName) {
273 
274   auto reportBufferError = [=](Error &&e,
275                               StringRef childName) {
276     fatal("could not get the buffer for the member defining symbol " +
277           symName + ": " + parentName + "(" + childName + "): " +
278           toString(std::move(e)));
279   };
280 
281   if (!c.getParent()->isThin()) {
282     uint64_t offsetInArchive = c.getChildOffset();
283     Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
284     if (!mbOrErr)
285       reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
286     MemoryBufferRef mb = mbOrErr.get();
287     enqueueTask([=]() {
288       driver->addArchiveBuffer(mb, symName, parentName, offsetInArchive);
289     });
290     return;
291   }
292 
293   std::string childName = CHECK(
294       c.getFullName(),
295       "could not get the filename for the member defining symbol " +
296       symName);
297   auto future = std::make_shared<std::future<MBErrPair>>(
298       createFutureForFile(childName));
299   enqueueTask([=]() {
300     auto mbOrErr = future->get();
301     if (mbOrErr.second)
302       reportBufferError(errorCodeToError(mbOrErr.second), childName);
303     driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), symName,
304                              parentName, /* OffsetInArchive */ 0);
305   });
306 }
307 
308 static bool isDecorated(StringRef sym) {
309   return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
310          (!config->mingw && sym.contains('@'));
311 }
312 
313 // Parses .drectve section contents and returns a list of files
314 // specified by /defaultlib.
315 void LinkerDriver::parseDirectives(InputFile *file) {
316   StringRef s = file->getDirectives();
317   if (s.empty())
318     return;
319 
320   log("Directives: " + toString(file) + ": " + s);
321 
322   ArgParser parser;
323   // .drectve is always tokenized using Windows shell rules.
324   // /EXPORT: option can appear too many times, processing in fastpath.
325   opt::InputArgList args;
326   std::vector<StringRef> exports;
327   std::tie(args, exports) = parser.parseDirectives(s);
328 
329   for (StringRef e : exports) {
330     // If a common header file contains dllexported function
331     // declarations, many object files may end up with having the
332     // same /EXPORT options. In order to save cost of parsing them,
333     // we dedup them first.
334     if (!directivesExports.insert(e).second)
335       continue;
336 
337     Export exp = parseExport(e);
338     if (config->machine == I386 && config->mingw) {
339       if (!isDecorated(exp.name))
340         exp.name = saver.save("_" + exp.name);
341       if (!exp.extName.empty() && !isDecorated(exp.extName))
342         exp.extName = saver.save("_" + exp.extName);
343     }
344     exp.directives = true;
345     config->exports.push_back(exp);
346   }
347 
348   for (auto *arg : args) {
349     switch (arg->getOption().getID()) {
350     case OPT_aligncomm:
351       parseAligncomm(arg->getValue());
352       break;
353     case OPT_alternatename:
354       parseAlternateName(arg->getValue());
355       break;
356     case OPT_defaultlib:
357       if (Optional<StringRef> path = findLib(arg->getValue()))
358         enqueuePath(*path, false);
359       break;
360     case OPT_entry:
361       config->entry = addUndefined(mangle(arg->getValue()));
362       break;
363     case OPT_failifmismatch:
364       checkFailIfMismatch(arg->getValue(), file);
365       break;
366     case OPT_incl:
367       addUndefined(arg->getValue());
368       break;
369     case OPT_merge:
370       parseMerge(arg->getValue());
371       break;
372     case OPT_nodefaultlib:
373       config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
374       break;
375     case OPT_section:
376       parseSection(arg->getValue());
377       break;
378     case OPT_subsystem:
379       parseSubsystem(arg->getValue(), &config->subsystem,
380                      &config->majorOSVersion, &config->minorOSVersion);
381       break;
382     // Only add flags here that link.exe accepts in
383     // `#pragma comment(linker, "/flag")`-generated sections.
384     case OPT_editandcontinue:
385     case OPT_guardsym:
386     case OPT_throwingnew:
387       break;
388     default:
389       error(arg->getSpelling() + " is not allowed in .drectve");
390     }
391   }
392 }
393 
394 // Find file from search paths. You can omit ".obj", this function takes
395 // care of that. Note that the returned path is not guaranteed to exist.
396 StringRef LinkerDriver::doFindFile(StringRef filename) {
397   bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
398   if (hasPathSep)
399     return filename;
400   bool hasExt = filename.contains('.');
401   for (StringRef dir : searchPaths) {
402     SmallString<128> path = dir;
403     sys::path::append(path, filename);
404     if (sys::fs::exists(path.str()))
405       return saver.save(path.str());
406     if (!hasExt) {
407       path.append(".obj");
408       if (sys::fs::exists(path.str()))
409         return saver.save(path.str());
410     }
411   }
412   return filename;
413 }
414 
415 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
416   sys::fs::UniqueID ret;
417   if (sys::fs::getUniqueID(path, ret))
418     return None;
419   return ret;
420 }
421 
422 // Resolves a file path. This never returns the same path
423 // (in that case, it returns None).
424 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
425   StringRef path = doFindFile(filename);
426 
427   if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
428     bool seen = !visitedFiles.insert(*id).second;
429     if (seen)
430       return None;
431   }
432 
433   if (path.endswith_lower(".lib"))
434     visitedLibs.insert(sys::path::filename(path));
435   return path;
436 }
437 
438 // MinGW specific. If an embedded directive specified to link to
439 // foo.lib, but it isn't found, try libfoo.a instead.
440 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
441   if (filename.contains('/') || filename.contains('\\'))
442     return filename;
443 
444   SmallString<128> s = filename;
445   sys::path::replace_extension(s, ".a");
446   StringRef libName = saver.save("lib" + s.str());
447   return doFindFile(libName);
448 }
449 
450 // Find library file from search path.
451 StringRef LinkerDriver::doFindLib(StringRef filename) {
452   // Add ".lib" to Filename if that has no file extension.
453   bool hasExt = filename.contains('.');
454   if (!hasExt)
455     filename = saver.save(filename + ".lib");
456   StringRef ret = doFindFile(filename);
457   // For MinGW, if the find above didn't turn up anything, try
458   // looking for a MinGW formatted library name.
459   if (config->mingw && ret == filename)
460     return doFindLibMinGW(filename);
461   return ret;
462 }
463 
464 // Resolves a library path. /nodefaultlib options are taken into
465 // consideration. This never returns the same path (in that case,
466 // it returns None).
467 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
468   if (config->noDefaultLibAll)
469     return None;
470   if (!visitedLibs.insert(filename.lower()).second)
471     return None;
472 
473   StringRef path = doFindLib(filename);
474   if (config->noDefaultLibs.count(path.lower()))
475     return None;
476 
477   if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
478     if (!visitedFiles.insert(*id).second)
479       return None;
480   return path;
481 }
482 
483 // Parses LIB environment which contains a list of search paths.
484 void LinkerDriver::addLibSearchPaths() {
485   Optional<std::string> envOpt = Process::GetEnv("LIB");
486   if (!envOpt.hasValue())
487     return;
488   StringRef env = saver.save(*envOpt);
489   while (!env.empty()) {
490     StringRef path;
491     std::tie(path, env) = env.split(';');
492     searchPaths.push_back(path);
493   }
494 }
495 
496 Symbol *LinkerDriver::addUndefined(StringRef name) {
497   Symbol *b = symtab->addUndefined(name);
498   if (!b->isGCRoot) {
499     b->isGCRoot = true;
500     config->gcroot.push_back(b);
501   }
502   return b;
503 }
504 
505 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
506   // If the plain symbol name has already been resolved, do nothing.
507   Undefined *unmangled = dyn_cast<Undefined>(s);
508   if (!unmangled)
509     return "";
510 
511   // Otherwise, see if a similar, mangled symbol exists in the symbol table.
512   Symbol *mangled = symtab->findMangle(unmangled->getName());
513   if (!mangled)
514     return "";
515 
516   // If we find a similar mangled symbol, make this an alias to it and return
517   // its name.
518   log(unmangled->getName() + " aliased to " + mangled->getName());
519   unmangled->weakAlias = symtab->addUndefined(mangled->getName());
520   return mangled->getName();
521 }
522 
523 // Windows specific -- find default entry point name.
524 //
525 // There are four different entry point functions for Windows executables,
526 // each of which corresponds to a user-defined "main" function. This function
527 // infers an entry point from a user-defined "main" function.
528 StringRef LinkerDriver::findDefaultEntry() {
529   assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
530          "must handle /subsystem before calling this");
531 
532   if (config->mingw)
533     return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
534                       ? "WinMainCRTStartup"
535                       : "mainCRTStartup");
536 
537   if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
538     if (findUnderscoreMangle("wWinMain")) {
539       if (!findUnderscoreMangle("WinMain"))
540         return mangle("wWinMainCRTStartup");
541       warn("found both wWinMain and WinMain; using latter");
542     }
543     return mangle("WinMainCRTStartup");
544   }
545   if (findUnderscoreMangle("wmain")) {
546     if (!findUnderscoreMangle("main"))
547       return mangle("wmainCRTStartup");
548     warn("found both wmain and main; using latter");
549   }
550   return mangle("mainCRTStartup");
551 }
552 
553 WindowsSubsystem LinkerDriver::inferSubsystem() {
554   if (config->dll)
555     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
556   if (config->mingw)
557     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
558   // Note that link.exe infers the subsystem from the presence of these
559   // functions even if /entry: or /nodefaultlib are passed which causes them
560   // to not be called.
561   bool haveMain = findUnderscoreMangle("main");
562   bool haveWMain = findUnderscoreMangle("wmain");
563   bool haveWinMain = findUnderscoreMangle("WinMain");
564   bool haveWWinMain = findUnderscoreMangle("wWinMain");
565   if (haveMain || haveWMain) {
566     if (haveWinMain || haveWWinMain) {
567       warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
568            (haveWinMain ? "WinMain" : "wWinMain") +
569            "; defaulting to /subsystem:console");
570     }
571     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
572   }
573   if (haveWinMain || haveWWinMain)
574     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
575   return IMAGE_SUBSYSTEM_UNKNOWN;
576 }
577 
578 static uint64_t getDefaultImageBase() {
579   if (config->is64())
580     return config->dll ? 0x180000000 : 0x140000000;
581   return config->dll ? 0x10000000 : 0x400000;
582 }
583 
584 static std::string createResponseFile(const opt::InputArgList &args,
585                                       ArrayRef<StringRef> filePaths,
586                                       ArrayRef<StringRef> searchPaths) {
587   SmallString<0> data;
588   raw_svector_ostream os(data);
589 
590   for (auto *arg : args) {
591     switch (arg->getOption().getID()) {
592     case OPT_linkrepro:
593     case OPT_INPUT:
594     case OPT_defaultlib:
595     case OPT_libpath:
596     case OPT_manifest:
597     case OPT_manifest_colon:
598     case OPT_manifestdependency:
599     case OPT_manifestfile:
600     case OPT_manifestinput:
601     case OPT_manifestuac:
602       break;
603     case OPT_implib:
604     case OPT_pdb:
605     case OPT_out:
606       os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
607       break;
608     default:
609       os << toString(*arg) << "\n";
610     }
611   }
612 
613   for (StringRef path : searchPaths) {
614     std::string relPath = relativeToRoot(path);
615     os << "/libpath:" << quote(relPath) << "\n";
616   }
617 
618   for (StringRef path : filePaths)
619     os << quote(relativeToRoot(path)) << "\n";
620 
621   return data.str();
622 }
623 
624 enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
625 
626 static DebugKind parseDebugKind(const opt::InputArgList &args) {
627   auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
628   if (!a)
629     return DebugKind::None;
630   if (a->getNumValues() == 0)
631     return DebugKind::Full;
632 
633   DebugKind debug = StringSwitch<DebugKind>(a->getValue())
634                      .CaseLower("none", DebugKind::None)
635                      .CaseLower("full", DebugKind::Full)
636                      .CaseLower("fastlink", DebugKind::FastLink)
637                      // LLD extensions
638                      .CaseLower("ghash", DebugKind::GHash)
639                      .CaseLower("dwarf", DebugKind::Dwarf)
640                      .CaseLower("symtab", DebugKind::Symtab)
641                      .Default(DebugKind::Unknown);
642 
643   if (debug == DebugKind::FastLink) {
644     warn("/debug:fastlink unsupported; using /debug:full");
645     return DebugKind::Full;
646   }
647   if (debug == DebugKind::Unknown) {
648     error("/debug: unknown option: " + Twine(a->getValue()));
649     return DebugKind::None;
650   }
651   return debug;
652 }
653 
654 static unsigned parseDebugTypes(const opt::InputArgList &args) {
655   unsigned debugTypes = static_cast<unsigned>(DebugType::None);
656 
657   if (auto *a = args.getLastArg(OPT_debugtype)) {
658     SmallVector<StringRef, 3> types;
659     StringRef(a->getValue())
660         .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
661 
662     for (StringRef type : types) {
663       unsigned v = StringSwitch<unsigned>(type.lower())
664                        .Case("cv", static_cast<unsigned>(DebugType::CV))
665                        .Case("pdata", static_cast<unsigned>(DebugType::PData))
666                        .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
667                        .Default(0);
668       if (v == 0) {
669         warn("/debugtype: unknown option '" + type + "'");
670         continue;
671       }
672       debugTypes |= v;
673     }
674     return debugTypes;
675   }
676 
677   // Default debug types
678   debugTypes = static_cast<unsigned>(DebugType::CV);
679   if (args.hasArg(OPT_driver))
680     debugTypes |= static_cast<unsigned>(DebugType::PData);
681   if (args.hasArg(OPT_profile))
682     debugTypes |= static_cast<unsigned>(DebugType::Fixup);
683 
684   return debugTypes;
685 }
686 
687 static std::string getMapFile(const opt::InputArgList &args) {
688   auto *arg = args.getLastArg(OPT_lldmap, OPT_lldmap_file);
689   if (!arg)
690     return "";
691   if (arg->getOption().getID() == OPT_lldmap_file)
692     return arg->getValue();
693 
694   assert(arg->getOption().getID() == OPT_lldmap);
695   StringRef outFile = config->outputFile;
696   return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
697 }
698 
699 static std::string getImplibPath() {
700   if (!config->implib.empty())
701     return config->implib;
702   SmallString<128> out = StringRef(config->outputFile);
703   sys::path::replace_extension(out, ".lib");
704   return out.str();
705 }
706 
707 //
708 // The import name is caculated as the following:
709 //
710 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
711 //   -----+----------------+---------------------+------------------
712 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
713 //    LIB | {value}        | {value}.dll         | {output name}.dll
714 //
715 static std::string getImportName(bool asLib) {
716   SmallString<128> out;
717 
718   if (config->importName.empty()) {
719     out.assign(sys::path::filename(config->outputFile));
720     if (asLib)
721       sys::path::replace_extension(out, ".dll");
722   } else {
723     out.assign(config->importName);
724     if (!sys::path::has_extension(out))
725       sys::path::replace_extension(out,
726                                    (config->dll || asLib) ? ".dll" : ".exe");
727   }
728 
729   return out.str();
730 }
731 
732 static void createImportLibrary(bool asLib) {
733   std::vector<COFFShortExport> exports;
734   for (Export &e1 : config->exports) {
735     COFFShortExport e2;
736     e2.Name = e1.name;
737     e2.SymbolName = e1.symbolName;
738     e2.ExtName = e1.extName;
739     e2.Ordinal = e1.ordinal;
740     e2.Noname = e1.noname;
741     e2.Data = e1.data;
742     e2.Private = e1.isPrivate;
743     e2.Constant = e1.constant;
744     exports.push_back(e2);
745   }
746 
747   auto handleError = [](Error &&e) {
748     handleAllErrors(std::move(e),
749                     [](ErrorInfoBase &eib) { error(eib.message()); });
750   };
751   std::string libName = getImportName(asLib);
752   std::string path = getImplibPath();
753 
754   if (!config->incremental) {
755     handleError(writeImportLibrary(libName, path, exports, config->machine,
756                                    config->mingw));
757     return;
758   }
759 
760   // If the import library already exists, replace it only if the contents
761   // have changed.
762   ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
763       path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
764   if (!oldBuf) {
765     handleError(writeImportLibrary(libName, path, exports, config->machine,
766                                    config->mingw));
767     return;
768   }
769 
770   SmallString<128> tmpName;
771   if (std::error_code ec =
772           sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
773     fatal("cannot create temporary file for import library " + path + ": " +
774           ec.message());
775 
776   if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
777                                    config->mingw)) {
778     handleError(std::move(e));
779     return;
780   }
781 
782   std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
783       tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
784   if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
785     oldBuf->reset();
786     handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
787   } else {
788     sys::fs::remove(tmpName);
789   }
790 }
791 
792 static void parseModuleDefs(StringRef path) {
793   std::unique_ptr<MemoryBuffer> mb = CHECK(
794       MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
795   COFFModuleDefinition m = check(parseCOFFModuleDefinition(
796       mb->getMemBufferRef(), config->machine, config->mingw));
797 
798   if (config->outputFile.empty())
799     config->outputFile = saver.save(m.OutputFile);
800   config->importName = saver.save(m.ImportName);
801   if (m.ImageBase)
802     config->imageBase = m.ImageBase;
803   if (m.StackReserve)
804     config->stackReserve = m.StackReserve;
805   if (m.StackCommit)
806     config->stackCommit = m.StackCommit;
807   if (m.HeapReserve)
808     config->heapReserve = m.HeapReserve;
809   if (m.HeapCommit)
810     config->heapCommit = m.HeapCommit;
811   if (m.MajorImageVersion)
812     config->majorImageVersion = m.MajorImageVersion;
813   if (m.MinorImageVersion)
814     config->minorImageVersion = m.MinorImageVersion;
815   if (m.MajorOSVersion)
816     config->majorOSVersion = m.MajorOSVersion;
817   if (m.MinorOSVersion)
818     config->minorOSVersion = m.MinorOSVersion;
819 
820   for (COFFShortExport e1 : m.Exports) {
821     Export e2;
822     // In simple cases, only Name is set. Renamed exports are parsed
823     // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
824     // it shouldn't be a normal exported function but a forward to another
825     // DLL instead. This is supported by both MS and GNU linkers.
826     if (e1.ExtName != e1.Name && StringRef(e1.Name).contains('.')) {
827       e2.name = saver.save(e1.ExtName);
828       e2.forwardTo = saver.save(e1.Name);
829       config->exports.push_back(e2);
830       continue;
831     }
832     e2.name = saver.save(e1.Name);
833     e2.extName = saver.save(e1.ExtName);
834     e2.ordinal = e1.Ordinal;
835     e2.noname = e1.Noname;
836     e2.data = e1.Data;
837     e2.isPrivate = e1.Private;
838     e2.constant = e1.Constant;
839     config->exports.push_back(e2);
840   }
841 }
842 
843 void LinkerDriver::enqueueTask(std::function<void()> task) {
844   taskQueue.push_back(std::move(task));
845 }
846 
847 bool LinkerDriver::run() {
848   ScopedTimer t(inputFileTimer);
849 
850   bool didWork = !taskQueue.empty();
851   while (!taskQueue.empty()) {
852     taskQueue.front()();
853     taskQueue.pop_front();
854   }
855   return didWork;
856 }
857 
858 // Parse an /order file. If an option is given, the linker places
859 // COMDAT sections in the same order as their names appear in the
860 // given file.
861 static void parseOrderFile(StringRef arg) {
862   // For some reason, the MSVC linker requires a filename to be
863   // preceded by "@".
864   if (!arg.startswith("@")) {
865     error("malformed /order option: '@' missing");
866     return;
867   }
868 
869   // Get a list of all comdat sections for error checking.
870   DenseSet<StringRef> set;
871   for (Chunk *c : symtab->getChunks())
872     if (auto *sec = dyn_cast<SectionChunk>(c))
873       if (sec->sym)
874         set.insert(sec->sym->getName());
875 
876   // Open a file.
877   StringRef path = arg.substr(1);
878   std::unique_ptr<MemoryBuffer> mb = CHECK(
879       MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
880 
881   // Parse a file. An order file contains one symbol per line.
882   // All symbols that were not present in a given order file are
883   // considered to have the lowest priority 0 and are placed at
884   // end of an output section.
885   for (std::string s : args::getLines(mb->getMemBufferRef())) {
886     if (config->machine == I386 && !isDecorated(s))
887       s = "_" + s;
888 
889     if (set.count(s) == 0) {
890       if (config->warnMissingOrderSymbol)
891         warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
892     }
893     else
894       config->order[s] = INT_MIN + config->order.size();
895   }
896 }
897 
898 static void markAddrsig(Symbol *s) {
899   if (auto *d = dyn_cast_or_null<Defined>(s))
900     if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
901       c->keepUnique = true;
902 }
903 
904 static void findKeepUniqueSections() {
905   // Exported symbols could be address-significant in other executables or DSOs,
906   // so we conservatively mark them as address-significant.
907   for (Export &r : config->exports)
908     markAddrsig(r.sym);
909 
910   // Visit the address-significance table in each object file and mark each
911   // referenced symbol as address-significant.
912   for (ObjFile *obj : ObjFile::instances) {
913     ArrayRef<Symbol *> syms = obj->getSymbols();
914     if (obj->addrsigSec) {
915       ArrayRef<uint8_t> contents;
916       cantFail(
917           obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
918       const uint8_t *cur = contents.begin();
919       while (cur != contents.end()) {
920         unsigned size;
921         const char *err;
922         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
923         if (err)
924           fatal(toString(obj) + ": could not decode addrsig section: " + err);
925         if (symIndex >= syms.size())
926           fatal(toString(obj) + ": invalid symbol index in addrsig section");
927         markAddrsig(syms[symIndex]);
928         cur += size;
929       }
930     } else {
931       // If an object file does not have an address-significance table,
932       // conservatively mark all of its symbols as address-significant.
933       for (Symbol *s : syms)
934         markAddrsig(s);
935     }
936   }
937 }
938 
939 // link.exe replaces each %foo% in AltPath with the contents of environment
940 // variable foo, and adds the two magic env vars _PDB (expands to the basename
941 // of pdb's output path) and _EXT (expands to the extension of the output
942 // binary).
943 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
944 // vars.
945 static void parsePDBAltPath(StringRef altPath) {
946   SmallString<128> buf;
947   StringRef pdbBasename =
948       sys::path::filename(config->pdbPath, sys::path::Style::windows);
949   StringRef binaryExtension =
950       sys::path::extension(config->outputFile, sys::path::Style::windows);
951   if (!binaryExtension.empty())
952     binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
953 
954   // Invariant:
955   //   +--------- Cursor ('a...' might be the empty string).
956   //   |   +----- FirstMark
957   //   |   |   +- SecondMark
958   //   v   v   v
959   //   a...%...%...
960   size_t cursor = 0;
961   while (cursor < altPath.size()) {
962     size_t firstMark, secondMark;
963     if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
964         (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
965       // Didn't find another full fragment, treat rest of string as literal.
966       buf.append(altPath.substr(cursor));
967       break;
968     }
969 
970     // Found a full fragment. Append text in front of first %, and interpret
971     // text between first and second % as variable name.
972     buf.append(altPath.substr(cursor, firstMark - cursor));
973     StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
974     if (var.equals_lower("%_pdb%"))
975       buf.append(pdbBasename);
976     else if (var.equals_lower("%_ext%"))
977       buf.append(binaryExtension);
978     else {
979       warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
980            var + " as literal");
981       buf.append(var);
982     }
983 
984     cursor = secondMark + 1;
985   }
986 
987   config->pdbAltPath = buf;
988 }
989 
990 /// Check that at most one resource obj file was used.
991 /// Call after ObjFile::Instances is complete.
992 static void diagnoseMultipleResourceObjFiles() {
993   // The .rsrc$01 section in a resource obj file contains a tree description
994   // of resources.  Merging multiple resource obj files would require merging
995   // the trees instead of using usual linker section merging semantics.
996   // Since link.exe disallows linking more than one resource obj file with
997   // LNK4078, mirror that.  The normal use of resource files is to give the
998   // linker many .res files, which are then converted to a single resource obj
999   // file internally, so this is not a big restriction in practice.
1000   ObjFile *resourceObjFile = nullptr;
1001   for (ObjFile *f : ObjFile::instances) {
1002     if (!f->isResourceObjFile)
1003       continue;
1004 
1005     if (!resourceObjFile) {
1006       resourceObjFile = f;
1007       continue;
1008     }
1009 
1010     error(toString(f) +
1011           ": more than one resource obj file not allowed, already got " +
1012           toString(resourceObjFile));
1013   }
1014 }
1015 
1016 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1017 // automatically exported by default. This behavior can be forced by the
1018 // -export-all-symbols option, so that it happens even when exports are
1019 // explicitly specified. The automatic behavior can be disabled using the
1020 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1021 // than MinGW in the case that nothing is explicitly exported.
1022 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1023   if (!config->dll)
1024     return;
1025 
1026   if (!args.hasArg(OPT_export_all_symbols)) {
1027     if (!config->exports.empty())
1028       return;
1029     if (args.hasArg(OPT_exclude_all_symbols))
1030       return;
1031   }
1032 
1033   AutoExporter exporter;
1034 
1035   for (auto *arg : args.filtered(OPT_wholearchive_file))
1036     if (Optional<StringRef> path = doFindFile(arg->getValue()))
1037       exporter.addWholeArchive(*path);
1038 
1039   symtab->forEachSymbol([&](Symbol *s) {
1040     auto *def = dyn_cast<Defined>(s);
1041     if (!exporter.shouldExport(def))
1042       return;
1043 
1044     Export e;
1045     e.name = def->getName();
1046     e.sym = def;
1047     if (Chunk *c = def->getChunk())
1048       if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1049         e.data = true;
1050     config->exports.push_back(e);
1051   });
1052 }
1053 
1054 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
1055   // Needed for LTO.
1056   InitializeAllTargetInfos();
1057   InitializeAllTargets();
1058   InitializeAllTargetMCs();
1059   InitializeAllAsmParsers();
1060   InitializeAllAsmPrinters();
1061 
1062   // If the first command line argument is "/lib", link.exe acts like lib.exe.
1063   // We call our own implementation of lib.exe that understands bitcode files.
1064   if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) {
1065     if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1066       fatal("lib failed");
1067     return;
1068   }
1069 
1070   // Parse command line options.
1071   ArgParser parser;
1072   opt::InputArgList args = parser.parseLINK(argsArr);
1073 
1074   // Parse and evaluate -mllvm options.
1075   std::vector<const char *> v;
1076   v.push_back("lld-link (LLVM option parsing)");
1077   for (auto *arg : args.filtered(OPT_mllvm))
1078     v.push_back(arg->getValue());
1079   cl::ParseCommandLineOptions(v.size(), v.data());
1080 
1081   // Handle /errorlimit early, because error() depends on it.
1082   if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1083     int n = 20;
1084     StringRef s = arg->getValue();
1085     if (s.getAsInteger(10, n))
1086       error(arg->getSpelling() + " number expected, but got " + s);
1087     errorHandler().errorLimit = n;
1088   }
1089 
1090   // Handle /help
1091   if (args.hasArg(OPT_help)) {
1092     printHelp(argsArr[0]);
1093     return;
1094   }
1095 
1096   lld::threadsEnabled = args.hasFlag(OPT_threads, OPT_threads_no, true);
1097 
1098   if (args.hasArg(OPT_show_timing))
1099     config->showTiming = true;
1100 
1101   config->showSummary = args.hasArg(OPT_summary);
1102 
1103   ScopedTimer t(Timer::root());
1104   // Handle --version, which is an lld extension. This option is a bit odd
1105   // because it doesn't start with "/", but we deliberately chose "--" to
1106   // avoid conflict with /version and for compatibility with clang-cl.
1107   if (args.hasArg(OPT_dash_dash_version)) {
1108     outs() << getLLDVersion() << "\n";
1109     return;
1110   }
1111 
1112   // Handle /lldmingw early, since it can potentially affect how other
1113   // options are handled.
1114   config->mingw = args.hasArg(OPT_lldmingw);
1115 
1116   if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1117     SmallString<64> path = StringRef(arg->getValue());
1118     sys::path::append(path, "repro.tar");
1119 
1120     Expected<std::unique_ptr<TarWriter>> errOrWriter =
1121         TarWriter::create(path, "repro");
1122 
1123     if (errOrWriter) {
1124       tar = std::move(*errOrWriter);
1125     } else {
1126       error("/linkrepro: failed to open " + path + ": " +
1127             toString(errOrWriter.takeError()));
1128     }
1129   }
1130 
1131   if (!args.hasArg(OPT_INPUT)) {
1132     if (args.hasArg(OPT_deffile))
1133       config->noEntry = true;
1134     else
1135       fatal("no input files");
1136   }
1137 
1138   // Construct search path list.
1139   searchPaths.push_back("");
1140   for (auto *arg : args.filtered(OPT_libpath))
1141     searchPaths.push_back(arg->getValue());
1142   addLibSearchPaths();
1143 
1144   // Handle /ignore
1145   for (auto *arg : args.filtered(OPT_ignore)) {
1146     SmallVector<StringRef, 8> vec;
1147     StringRef(arg->getValue()).split(vec, ',');
1148     for (StringRef s : vec) {
1149       if (s == "4037")
1150         config->warnMissingOrderSymbol = false;
1151       else if (s == "4099")
1152         config->warnDebugInfoUnusable = false;
1153       else if (s == "4217")
1154         config->warnLocallyDefinedImported = false;
1155       // Other warning numbers are ignored.
1156     }
1157   }
1158 
1159   // Handle /out
1160   if (auto *arg = args.getLastArg(OPT_out))
1161     config->outputFile = arg->getValue();
1162 
1163   // Handle /verbose
1164   if (args.hasArg(OPT_verbose))
1165     config->verbose = true;
1166   errorHandler().verbose = config->verbose;
1167 
1168   // Handle /force or /force:unresolved
1169   if (args.hasArg(OPT_force, OPT_force_unresolved))
1170     config->forceUnresolved = true;
1171 
1172   // Handle /force or /force:multiple
1173   if (args.hasArg(OPT_force, OPT_force_multiple))
1174     config->forceMultiple = true;
1175 
1176   // Handle /force or /force:multipleres
1177   if (args.hasArg(OPT_force, OPT_force_multipleres))
1178     config->forceMultipleRes = true;
1179 
1180   // Handle /debug
1181   DebugKind debug = parseDebugKind(args);
1182   if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1183       debug == DebugKind::GHash) {
1184     config->debug = true;
1185     config->incremental = true;
1186   }
1187 
1188   // Handle /demangle
1189   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1190 
1191   // Handle /debugtype
1192   config->debugTypes = parseDebugTypes(args);
1193 
1194   // Handle /pdb
1195   bool shouldCreatePDB =
1196       (debug == DebugKind::Full || debug == DebugKind::GHash);
1197   if (shouldCreatePDB) {
1198     if (auto *arg = args.getLastArg(OPT_pdb))
1199       config->pdbPath = arg->getValue();
1200     if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1201       config->pdbAltPath = arg->getValue();
1202     if (args.hasArg(OPT_natvis))
1203       config->natvisFiles = args.getAllArgValues(OPT_natvis);
1204 
1205     if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1206       config->pdbSourcePath = arg->getValue();
1207   }
1208 
1209   // Handle /noentry
1210   if (args.hasArg(OPT_noentry)) {
1211     if (args.hasArg(OPT_dll))
1212       config->noEntry = true;
1213     else
1214       error("/noentry must be specified with /dll");
1215   }
1216 
1217   // Handle /dll
1218   if (args.hasArg(OPT_dll)) {
1219     config->dll = true;
1220     config->manifestID = 2;
1221   }
1222 
1223   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1224   // because we need to explicitly check whether that option or its inverse was
1225   // present in the argument list in order to handle /fixed.
1226   auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1227   if (dynamicBaseArg &&
1228       dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1229     config->dynamicBase = false;
1230 
1231   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1232   // default setting for any other project type.", but link.exe defaults to
1233   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1234   bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1235   if (fixed) {
1236     if (dynamicBaseArg &&
1237         dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1238       error("/fixed must not be specified with /dynamicbase");
1239     } else {
1240       config->relocatable = false;
1241       config->dynamicBase = false;
1242     }
1243   }
1244 
1245   // Handle /appcontainer
1246   config->appContainer =
1247       args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1248 
1249   // Handle /machine
1250   if (auto *arg = args.getLastArg(OPT_machine)) {
1251     config->machine = getMachineType(arg->getValue());
1252     if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1253       fatal(Twine("unknown /machine argument: ") + arg->getValue());
1254   }
1255 
1256   // Handle /nodefaultlib:<filename>
1257   for (auto *arg : args.filtered(OPT_nodefaultlib))
1258     config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1259 
1260   // Handle /nodefaultlib
1261   if (args.hasArg(OPT_nodefaultlib_all))
1262     config->noDefaultLibAll = true;
1263 
1264   // Handle /base
1265   if (auto *arg = args.getLastArg(OPT_base))
1266     parseNumbers(arg->getValue(), &config->imageBase);
1267 
1268   // Handle /filealign
1269   if (auto *arg = args.getLastArg(OPT_filealign)) {
1270     parseNumbers(arg->getValue(), &config->fileAlign);
1271     if (!isPowerOf2_64(config->fileAlign))
1272       error("/filealign: not a power of two: " + Twine(config->fileAlign));
1273   }
1274 
1275   // Handle /stack
1276   if (auto *arg = args.getLastArg(OPT_stack))
1277     parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1278 
1279   // Handle /guard:cf
1280   if (auto *arg = args.getLastArg(OPT_guard))
1281     parseGuard(arg->getValue());
1282 
1283   // Handle /heap
1284   if (auto *arg = args.getLastArg(OPT_heap))
1285     parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1286 
1287   // Handle /version
1288   if (auto *arg = args.getLastArg(OPT_version))
1289     parseVersion(arg->getValue(), &config->majorImageVersion,
1290                  &config->minorImageVersion);
1291 
1292   // Handle /subsystem
1293   if (auto *arg = args.getLastArg(OPT_subsystem))
1294     parseSubsystem(arg->getValue(), &config->subsystem, &config->majorOSVersion,
1295                    &config->minorOSVersion);
1296 
1297   // Handle /timestamp
1298   if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1299     if (arg->getOption().getID() == OPT_repro) {
1300       config->timestamp = 0;
1301       config->repro = true;
1302     } else {
1303       config->repro = false;
1304       StringRef value(arg->getValue());
1305       if (value.getAsInteger(0, config->timestamp))
1306         fatal(Twine("invalid timestamp: ") + value +
1307               ".  Expected 32-bit integer");
1308     }
1309   } else {
1310     config->repro = false;
1311     config->timestamp = time(nullptr);
1312   }
1313 
1314   // Handle /alternatename
1315   for (auto *arg : args.filtered(OPT_alternatename))
1316     parseAlternateName(arg->getValue());
1317 
1318   // Handle /include
1319   for (auto *arg : args.filtered(OPT_incl))
1320     addUndefined(arg->getValue());
1321 
1322   // Handle /implib
1323   if (auto *arg = args.getLastArg(OPT_implib))
1324     config->implib = arg->getValue();
1325 
1326   // Handle /opt.
1327   bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1328   unsigned icfLevel =
1329       args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1330   unsigned tailMerge = 1;
1331   for (auto *arg : args.filtered(OPT_opt)) {
1332     std::string str = StringRef(arg->getValue()).lower();
1333     SmallVector<StringRef, 1> vec;
1334     StringRef(str).split(vec, ',');
1335     for (StringRef s : vec) {
1336       if (s == "ref") {
1337         doGC = true;
1338       } else if (s == "noref") {
1339         doGC = false;
1340       } else if (s == "icf" || s.startswith("icf=")) {
1341         icfLevel = 2;
1342       } else if (s == "noicf") {
1343         icfLevel = 0;
1344       } else if (s == "lldtailmerge") {
1345         tailMerge = 2;
1346       } else if (s == "nolldtailmerge") {
1347         tailMerge = 0;
1348       } else if (s.startswith("lldlto=")) {
1349         StringRef optLevel = s.substr(7);
1350         if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1351           error("/opt:lldlto: invalid optimization level: " + optLevel);
1352       } else if (s.startswith("lldltojobs=")) {
1353         StringRef jobs = s.substr(11);
1354         if (jobs.getAsInteger(10, config->thinLTOJobs) ||
1355             config->thinLTOJobs == 0)
1356           error("/opt:lldltojobs: invalid job count: " + jobs);
1357       } else if (s.startswith("lldltopartitions=")) {
1358         StringRef n = s.substr(17);
1359         if (n.getAsInteger(10, config->ltoPartitions) ||
1360             config->ltoPartitions == 0)
1361           error("/opt:lldltopartitions: invalid partition count: " + n);
1362       } else if (s != "lbr" && s != "nolbr")
1363         error("/opt: unknown option: " + s);
1364     }
1365   }
1366 
1367   // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1368   // explicitly.
1369   // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1370   // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1371   // comdat readonly data.
1372   if (icfLevel == 1 && !doGC)
1373     icfLevel = 0;
1374   config->doGC = doGC;
1375   config->doICF = icfLevel > 0;
1376   config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2;
1377 
1378   // Handle /lldsavetemps
1379   if (args.hasArg(OPT_lldsavetemps))
1380     config->saveTemps = true;
1381 
1382   // Handle /kill-at
1383   if (args.hasArg(OPT_kill_at))
1384     config->killAt = true;
1385 
1386   // Handle /lldltocache
1387   if (auto *arg = args.getLastArg(OPT_lldltocache))
1388     config->ltoCache = arg->getValue();
1389 
1390   // Handle /lldsavecachepolicy
1391   if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1392     config->ltoCachePolicy = CHECK(
1393         parseCachePruningPolicy(arg->getValue()),
1394         Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1395 
1396   // Handle /failifmismatch
1397   for (auto *arg : args.filtered(OPT_failifmismatch))
1398     checkFailIfMismatch(arg->getValue(), nullptr);
1399 
1400   // Handle /merge
1401   for (auto *arg : args.filtered(OPT_merge))
1402     parseMerge(arg->getValue());
1403 
1404   // Add default section merging rules after user rules. User rules take
1405   // precedence, but we will emit a warning if there is a conflict.
1406   parseMerge(".idata=.rdata");
1407   parseMerge(".didat=.rdata");
1408   parseMerge(".edata=.rdata");
1409   parseMerge(".xdata=.rdata");
1410   parseMerge(".bss=.data");
1411 
1412   if (config->mingw) {
1413     parseMerge(".ctors=.rdata");
1414     parseMerge(".dtors=.rdata");
1415     parseMerge(".CRT=.rdata");
1416   }
1417 
1418   // Handle /section
1419   for (auto *arg : args.filtered(OPT_section))
1420     parseSection(arg->getValue());
1421 
1422   // Handle /aligncomm
1423   for (auto *arg : args.filtered(OPT_aligncomm))
1424     parseAligncomm(arg->getValue());
1425 
1426   // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1427   // also passed.
1428   if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
1429     config->manifestDependency = arg->getValue();
1430     config->manifest = Configuration::SideBySide;
1431   }
1432 
1433   // Handle /manifest and /manifest:
1434   if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1435     if (arg->getOption().getID() == OPT_manifest)
1436       config->manifest = Configuration::SideBySide;
1437     else
1438       parseManifest(arg->getValue());
1439   }
1440 
1441   // Handle /manifestuac
1442   if (auto *arg = args.getLastArg(OPT_manifestuac))
1443     parseManifestUAC(arg->getValue());
1444 
1445   // Handle /manifestfile
1446   if (auto *arg = args.getLastArg(OPT_manifestfile))
1447     config->manifestFile = arg->getValue();
1448 
1449   // Handle /manifestinput
1450   for (auto *arg : args.filtered(OPT_manifestinput))
1451     config->manifestInput.push_back(arg->getValue());
1452 
1453   if (!config->manifestInput.empty() &&
1454       config->manifest != Configuration::Embed) {
1455     fatal("/manifestinput: requires /manifest:embed");
1456   }
1457 
1458   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1459   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1460                              args.hasArg(OPT_thinlto_index_only_arg);
1461   config->thinLTOIndexOnlyArg =
1462       args.getLastArgValue(OPT_thinlto_index_only_arg);
1463   config->thinLTOPrefixReplace =
1464       getOldNewOptions(args, OPT_thinlto_prefix_replace);
1465   config->thinLTOObjectSuffixReplace =
1466       getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1467   // Handle miscellaneous boolean flags.
1468   config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1469   config->allowIsolation =
1470       args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1471   config->incremental =
1472       args.hasFlag(OPT_incremental, OPT_incremental_no,
1473                    !config->doGC && !config->doICF && !args.hasArg(OPT_order) &&
1474                        !args.hasArg(OPT_profile));
1475   config->integrityCheck =
1476       args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1477   config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1478   for (auto *arg : args.filtered(OPT_swaprun))
1479     parseSwaprun(arg->getValue());
1480   config->terminalServerAware =
1481       !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1482   config->debugDwarf = debug == DebugKind::Dwarf;
1483   config->debugGHashes = debug == DebugKind::GHash;
1484   config->debugSymtab = debug == DebugKind::Symtab;
1485 
1486   config->mapFile = getMapFile(args);
1487 
1488   if (config->incremental && args.hasArg(OPT_profile)) {
1489     warn("ignoring '/incremental' due to '/profile' specification");
1490     config->incremental = false;
1491   }
1492 
1493   if (config->incremental && args.hasArg(OPT_order)) {
1494     warn("ignoring '/incremental' due to '/order' specification");
1495     config->incremental = false;
1496   }
1497 
1498   if (config->incremental && config->doGC) {
1499     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1500          "disable");
1501     config->incremental = false;
1502   }
1503 
1504   if (config->incremental && config->doICF) {
1505     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1506          "disable");
1507     config->incremental = false;
1508   }
1509 
1510   if (errorCount())
1511     return;
1512 
1513   std::set<sys::fs::UniqueID> wholeArchives;
1514   for (auto *arg : args.filtered(OPT_wholearchive_file))
1515     if (Optional<StringRef> path = doFindFile(arg->getValue()))
1516       if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1517         wholeArchives.insert(*id);
1518 
1519   // A predicate returning true if a given path is an argument for
1520   // /wholearchive:, or /wholearchive is enabled globally.
1521   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1522   // needs to be handled as "/wholearchive:foo.obj foo.obj".
1523   auto isWholeArchive = [&](StringRef path) -> bool {
1524     if (args.hasArg(OPT_wholearchive_flag))
1525       return true;
1526     if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1527       return wholeArchives.count(*id);
1528     return false;
1529   };
1530 
1531   // Create a list of input files. Files can be given as arguments
1532   // for /defaultlib option.
1533   for (auto *arg : args.filtered(OPT_INPUT, OPT_wholearchive_file))
1534     if (Optional<StringRef> path = findFile(arg->getValue()))
1535       enqueuePath(*path, isWholeArchive(*path));
1536 
1537   for (auto *arg : args.filtered(OPT_defaultlib))
1538     if (Optional<StringRef> path = findLib(arg->getValue()))
1539       enqueuePath(*path, false);
1540 
1541   // Windows specific -- Create a resource file containing a manifest file.
1542   if (config->manifest == Configuration::Embed)
1543     addBuffer(createManifestRes(), false);
1544 
1545   // Read all input files given via the command line.
1546   run();
1547 
1548   if (errorCount())
1549     return;
1550 
1551   // We should have inferred a machine type by now from the input files, but if
1552   // not we assume x64.
1553   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1554     warn("/machine is not specified. x64 is assumed");
1555     config->machine = AMD64;
1556   }
1557   config->wordsize = config->is64() ? 8 : 4;
1558 
1559   // Handle /functionpadmin
1560   for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1561     parseFunctionPadMin(arg, config->machine);
1562 
1563   // Input files can be Windows resource files (.res files). We use
1564   // WindowsResource to convert resource files to a regular COFF file,
1565   // then link the resulting file normally.
1566   if (!resources.empty())
1567     symtab->addFile(make<ObjFile>(convertResToCOFF(resources)));
1568 
1569   if (tar)
1570     tar->append("response.txt",
1571                 createResponseFile(args, filePaths,
1572                                    ArrayRef<StringRef>(searchPaths).slice(1)));
1573 
1574   // Handle /largeaddressaware
1575   config->largeAddressAware = args.hasFlag(
1576       OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1577 
1578   // Handle /highentropyva
1579   config->highEntropyVA =
1580       config->is64() &&
1581       args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1582 
1583   if (!config->dynamicBase &&
1584       (config->machine == ARMNT || config->machine == ARM64))
1585     error("/dynamicbase:no is not compatible with " +
1586           machineToStr(config->machine));
1587 
1588   // Handle /export
1589   for (auto *arg : args.filtered(OPT_export)) {
1590     Export e = parseExport(arg->getValue());
1591     if (config->machine == I386) {
1592       if (!isDecorated(e.name))
1593         e.name = saver.save("_" + e.name);
1594       if (!e.extName.empty() && !isDecorated(e.extName))
1595         e.extName = saver.save("_" + e.extName);
1596     }
1597     config->exports.push_back(e);
1598   }
1599 
1600   // Handle /def
1601   if (auto *arg = args.getLastArg(OPT_deffile)) {
1602     // parseModuleDefs mutates Config object.
1603     parseModuleDefs(arg->getValue());
1604   }
1605 
1606   // Handle generation of import library from a def file.
1607   if (!args.hasArg(OPT_INPUT)) {
1608     fixupExports();
1609     createImportLibrary(/*AsLib=*/true);
1610     return;
1611   }
1612 
1613   // Windows specific -- if no /subsystem is given, we need to infer
1614   // that from entry point name.  Must happen before /entry handling,
1615   // and after the early return when just writing an import library.
1616   if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1617     config->subsystem = inferSubsystem();
1618     if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1619       fatal("subsystem must be defined");
1620   }
1621 
1622   // Handle /entry and /dll
1623   if (auto *arg = args.getLastArg(OPT_entry)) {
1624     config->entry = addUndefined(mangle(arg->getValue()));
1625   } else if (!config->entry && !config->noEntry) {
1626     if (args.hasArg(OPT_dll)) {
1627       StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
1628                                               : "_DllMainCRTStartup";
1629       config->entry = addUndefined(s);
1630     } else {
1631       // Windows specific -- If entry point name is not given, we need to
1632       // infer that from user-defined entry name.
1633       StringRef s = findDefaultEntry();
1634       if (s.empty())
1635         fatal("entry point must be defined");
1636       config->entry = addUndefined(s);
1637       log("Entry name inferred: " + s);
1638     }
1639   }
1640 
1641   // Handle /delayload
1642   for (auto *arg : args.filtered(OPT_delayload)) {
1643     config->delayLoads.insert(StringRef(arg->getValue()).lower());
1644     if (config->machine == I386) {
1645       config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
1646     } else {
1647       config->delayLoadHelper = addUndefined("__delayLoadHelper2");
1648     }
1649   }
1650 
1651   // Set default image name if neither /out or /def set it.
1652   if (config->outputFile.empty()) {
1653     config->outputFile =
1654         getOutputPath((*args.filtered(OPT_INPUT).begin())->getValue());
1655   }
1656 
1657   // Fail early if an output file is not writable.
1658   if (auto e = tryCreateFile(config->outputFile)) {
1659     error("cannot open output file " + config->outputFile + ": " + e.message());
1660     return;
1661   }
1662 
1663   if (shouldCreatePDB) {
1664     // Put the PDB next to the image if no /pdb flag was passed.
1665     if (config->pdbPath.empty()) {
1666       config->pdbPath = config->outputFile;
1667       sys::path::replace_extension(config->pdbPath, ".pdb");
1668     }
1669 
1670     // The embedded PDB path should be the absolute path to the PDB if no
1671     // /pdbaltpath flag was passed.
1672     if (config->pdbAltPath.empty()) {
1673       config->pdbAltPath = config->pdbPath;
1674 
1675       // It's important to make the path absolute and remove dots.  This path
1676       // will eventually be written into the PE header, and certain Microsoft
1677       // tools won't work correctly if these assumptions are not held.
1678       sys::fs::make_absolute(config->pdbAltPath);
1679       sys::path::remove_dots(config->pdbAltPath);
1680     } else {
1681       // Don't do this earlier, so that Config->OutputFile is ready.
1682       parsePDBAltPath(config->pdbAltPath);
1683     }
1684   }
1685 
1686   // Set default image base if /base is not given.
1687   if (config->imageBase == uint64_t(-1))
1688     config->imageBase = getDefaultImageBase();
1689 
1690   symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1691   if (config->machine == I386) {
1692     symtab->addAbsolute("___safe_se_handler_table", 0);
1693     symtab->addAbsolute("___safe_se_handler_count", 0);
1694   }
1695 
1696   symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1697   symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1698   symtab->addAbsolute(mangle("__guard_flags"), 0);
1699   symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1700   symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1701   symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1702   symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1703   // Needed for MSVC 2017 15.5 CRT.
1704   symtab->addAbsolute(mangle("__enclave_config"), 0);
1705 
1706   if (config->mingw) {
1707     symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1708     symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1709     symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1710     symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1711   }
1712 
1713   // This code may add new undefined symbols to the link, which may enqueue more
1714   // symbol resolution tasks, so we need to continue executing tasks until we
1715   // converge.
1716   do {
1717     // Windows specific -- if entry point is not found,
1718     // search for its mangled names.
1719     if (config->entry)
1720       mangleMaybe(config->entry);
1721 
1722     // Windows specific -- Make sure we resolve all dllexported symbols.
1723     for (Export &e : config->exports) {
1724       if (!e.forwardTo.empty())
1725         continue;
1726       e.sym = addUndefined(e.name);
1727       if (!e.directives)
1728         e.symbolName = mangleMaybe(e.sym);
1729     }
1730 
1731     // Add weak aliases. Weak aliases is a mechanism to give remaining
1732     // undefined symbols final chance to be resolved successfully.
1733     for (auto pair : config->alternateNames) {
1734       StringRef from = pair.first;
1735       StringRef to = pair.second;
1736       Symbol *sym = symtab->find(from);
1737       if (!sym)
1738         continue;
1739       if (auto *u = dyn_cast<Undefined>(sym))
1740         if (!u->weakAlias)
1741           u->weakAlias = symtab->addUndefined(to);
1742     }
1743 
1744     // Windows specific -- if __load_config_used can be resolved, resolve it.
1745     if (symtab->findUnderscore("_load_config_used"))
1746       addUndefined(mangle("_load_config_used"));
1747   } while (run());
1748 
1749   if (errorCount())
1750     return;
1751 
1752   // Do LTO by compiling bitcode input files to a set of native COFF files then
1753   // link those files (unless -thinlto-index-only was given, in which case we
1754   // resolve symbols and write indices, but don't generate native code or link).
1755   symtab->addCombinedLTOObjects();
1756 
1757   // If -thinlto-index-only is given, we should create only "index
1758   // files" and not object files. Index file creation is already done
1759   // in addCombinedLTOObject, so we are done if that's the case.
1760   if (config->thinLTOIndexOnly)
1761     return;
1762 
1763   // If we generated native object files from bitcode files, this resolves
1764   // references to the symbols we use from them.
1765   run();
1766 
1767   if (args.hasArg(OPT_include_optional)) {
1768     // Handle /includeoptional
1769     for (auto *arg : args.filtered(OPT_include_optional))
1770       if (dyn_cast_or_null<Lazy>(symtab->find(arg->getValue())))
1771         addUndefined(arg->getValue());
1772     while (run());
1773   }
1774 
1775   if (config->mingw) {
1776     // Load any further object files that might be needed for doing automatic
1777     // imports.
1778     //
1779     // For cases with no automatically imported symbols, this iterates once
1780     // over the symbol table and doesn't do anything.
1781     //
1782     // For the normal case with a few automatically imported symbols, this
1783     // should only need to be run once, since each new object file imported
1784     // is an import library and wouldn't add any new undefined references,
1785     // but there's nothing stopping the __imp_ symbols from coming from a
1786     // normal object file as well (although that won't be used for the
1787     // actual autoimport later on). If this pass adds new undefined references,
1788     // we won't iterate further to resolve them.
1789     symtab->loadMinGWAutomaticImports();
1790     run();
1791   }
1792 
1793   // Make sure we have resolved all symbols.
1794   symtab->reportRemainingUndefines();
1795   if (errorCount())
1796     return;
1797 
1798   // Handle /safeseh.
1799   if (args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1800     for (ObjFile *file : ObjFile::instances)
1801       if (!file->hasSafeSEH())
1802         error("/safeseh: " + file->getName() + " is not compatible with SEH");
1803     if (errorCount())
1804       return;
1805   }
1806 
1807   if (config->mingw) {
1808     // In MinGW, all symbols are automatically exported if no symbols
1809     // are chosen to be exported.
1810     maybeExportMinGWSymbols(args);
1811 
1812     // Make sure the crtend.o object is the last object file. This object
1813     // file can contain terminating section chunks that need to be placed
1814     // last. GNU ld processes files and static libraries explicitly in the
1815     // order provided on the command line, while lld will pull in needed
1816     // files from static libraries only after the last object file on the
1817     // command line.
1818     for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
1819          i != e; i++) {
1820       ObjFile *file = *i;
1821       if (isCrtend(file->getName())) {
1822         ObjFile::instances.erase(i);
1823         ObjFile::instances.push_back(file);
1824         break;
1825       }
1826     }
1827   }
1828 
1829   // Windows specific -- when we are creating a .dll file, we also
1830   // need to create a .lib file.
1831   if (!config->exports.empty() || config->dll) {
1832     fixupExports();
1833     createImportLibrary(/*AsLib=*/false);
1834     assignExportOrdinals();
1835   }
1836 
1837   // Handle /output-def (MinGW specific).
1838   if (auto *arg = args.getLastArg(OPT_output_def))
1839     writeDefFile(arg->getValue());
1840 
1841   // Set extra alignment for .comm symbols
1842   for (auto pair : config->alignComm) {
1843     StringRef name = pair.first;
1844     uint32_t alignment = pair.second;
1845 
1846     Symbol *sym = symtab->find(name);
1847     if (!sym) {
1848       warn("/aligncomm symbol " + name + " not found");
1849       continue;
1850     }
1851 
1852     // If the symbol isn't common, it must have been replaced with a regular
1853     // symbol, which will carry its own alignment.
1854     auto *dc = dyn_cast<DefinedCommon>(sym);
1855     if (!dc)
1856       continue;
1857 
1858     CommonChunk *c = dc->getChunk();
1859     c->setAlignment(std::max(c->getAlignment(), alignment));
1860   }
1861 
1862   // Windows specific -- Create a side-by-side manifest file.
1863   if (config->manifest == Configuration::SideBySide)
1864     createSideBySideManifest();
1865 
1866   // Handle /order. We want to do this at this moment because we
1867   // need a complete list of comdat sections to warn on nonexistent
1868   // functions.
1869   if (auto *arg = args.getLastArg(OPT_order))
1870     parseOrderFile(arg->getValue());
1871 
1872   // Identify unreferenced COMDAT sections.
1873   if (config->doGC)
1874     markLive(symtab->getChunks());
1875 
1876   // Needs to happen after the last call to addFile().
1877   diagnoseMultipleResourceObjFiles();
1878 
1879   // Identify identical COMDAT sections to merge them.
1880   if (config->doICF) {
1881     findKeepUniqueSections();
1882     doICF(symtab->getChunks());
1883   }
1884 
1885   // Write the result.
1886   writeResult();
1887 
1888   // Stop early so we can print the results.
1889   Timer::root().stop();
1890   if (config->showTiming)
1891     Timer::root().print();
1892 }
1893 
1894 } // namespace coff
1895 } // namespace lld
1896