xref: /freebsd/contrib/llvm-project/lld/COFF/Driver.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 "COFFLinkerContext.h"
11 #include "Config.h"
12 #include "DebugTypes.h"
13 #include "ICF.h"
14 #include "InputFiles.h"
15 #include "MarkLive.h"
16 #include "MinGW.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "Writer.h"
20 #include "lld/Common/Args.h"
21 #include "lld/Common/CommonLinkerContext.h"
22 #include "lld/Common/Driver.h"
23 #include "lld/Common/Filesystem.h"
24 #include "lld/Common/Timer.h"
25 #include "lld/Common/Version.h"
26 #include "llvm/ADT/IntrusiveRefCntPtr.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/BinaryFormat/Magic.h"
29 #include "llvm/Config/llvm-config.h"
30 #include "llvm/LTO/LTO.h"
31 #include "llvm/Object/ArchiveWriter.h"
32 #include "llvm/Object/COFFImportFile.h"
33 #include "llvm/Object/COFFModuleDefinition.h"
34 #include "llvm/Object/WindowsMachineFlag.h"
35 #include "llvm/Option/Arg.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/Option.h"
38 #include "llvm/Support/BinaryStreamReader.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Parallel.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Process.h"
46 #include "llvm/Support/TarWriter.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/VirtualFileSystem.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/TargetParser/Triple.h"
51 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
52 #include <algorithm>
53 #include <future>
54 #include <memory>
55 #include <optional>
56 #include <tuple>
57 
58 using namespace llvm;
59 using namespace llvm::object;
60 using namespace llvm::COFF;
61 using namespace llvm::sys;
62 
63 namespace lld::coff {
64 
65 bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
66           llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
67   // This driver-specific context will be freed later by unsafeLldMain().
68   auto *ctx = new COFFLinkerContext;
69 
70   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
71   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
72   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now"
73                                  " (use /errorlimit:0 to see all errors)";
74 
75   ctx->driver.linkerMain(args);
76 
77   return errorCount() == 0;
78 }
79 
80 // Parse options of the form "old;new".
81 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
82                                                         unsigned id) {
83   auto *arg = args.getLastArg(id);
84   if (!arg)
85     return {"", ""};
86 
87   StringRef s = arg->getValue();
88   std::pair<StringRef, StringRef> ret = s.split(';');
89   if (ret.second.empty())
90     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
91   return ret;
92 }
93 
94 // Parse options of the form "old;new[;extra]".
95 static std::tuple<StringRef, StringRef, StringRef>
96 getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
97   auto [oldDir, second] = getOldNewOptions(args, id);
98   auto [newDir, extraDir] = second.split(';');
99   return {oldDir, newDir, extraDir};
100 }
101 
102 // Drop directory components and replace extension with
103 // ".exe", ".dll" or ".sys".
104 static std::string getOutputPath(StringRef path, bool isDll, bool isDriver) {
105   StringRef ext = ".exe";
106   if (isDll)
107     ext = ".dll";
108   else if (isDriver)
109     ext = ".sys";
110 
111   return (sys::path::stem(path) + ext).str();
112 }
113 
114 // Returns true if S matches /crtend.?\.o$/.
115 static bool isCrtend(StringRef s) {
116   if (!s.ends_with(".o"))
117     return false;
118   s = s.drop_back(2);
119   if (s.ends_with("crtend"))
120     return true;
121   return !s.empty() && s.drop_back().ends_with("crtend");
122 }
123 
124 // ErrorOr is not default constructible, so it cannot be used as the type
125 // parameter of a future.
126 // FIXME: We could open the file in createFutureForFile and avoid needing to
127 // return an error here, but for the moment that would cost us a file descriptor
128 // (a limited resource on Windows) for the duration that the future is pending.
129 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
130 
131 // Create a std::future that opens and maps a file using the best strategy for
132 // the host platform.
133 static std::future<MBErrPair> createFutureForFile(std::string path) {
134 #if _WIN64
135   // On Windows, file I/O is relatively slow so it is best to do this
136   // asynchronously.  But 32-bit has issues with potentially launching tons
137   // of threads
138   auto strategy = std::launch::async;
139 #else
140   auto strategy = std::launch::deferred;
141 #endif
142   return std::async(strategy, [=]() {
143     auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
144                                          /*RequiresNullTerminator=*/false);
145     if (!mbOrErr)
146       return MBErrPair{nullptr, mbOrErr.getError()};
147     return MBErrPair{std::move(*mbOrErr), std::error_code()};
148   });
149 }
150 
151 // Symbol names are mangled by prepending "_" on x86.
152 StringRef LinkerDriver::mangle(StringRef sym) {
153   assert(ctx.config.machine != IMAGE_FILE_MACHINE_UNKNOWN);
154   if (ctx.config.machine == I386)
155     return saver().save("_" + sym);
156   return sym;
157 }
158 
159 llvm::Triple::ArchType LinkerDriver::getArch() {
160   switch (ctx.config.machine) {
161   case I386:
162     return llvm::Triple::ArchType::x86;
163   case AMD64:
164     return llvm::Triple::ArchType::x86_64;
165   case ARMNT:
166     return llvm::Triple::ArchType::arm;
167   case ARM64:
168     return llvm::Triple::ArchType::aarch64;
169   default:
170     return llvm::Triple::ArchType::UnknownArch;
171   }
172 }
173 
174 bool LinkerDriver::findUnderscoreMangle(StringRef sym) {
175   Symbol *s = ctx.symtab.findMangle(mangle(sym));
176   return s && !isa<Undefined>(s);
177 }
178 
179 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
180   MemoryBufferRef mbref = *mb;
181   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
182 
183   if (ctx.driver.tar)
184     ctx.driver.tar->append(relativeToRoot(mbref.getBufferIdentifier()),
185                            mbref.getBuffer());
186   return mbref;
187 }
188 
189 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
190                              bool wholeArchive, bool lazy) {
191   StringRef filename = mb->getBufferIdentifier();
192 
193   MemoryBufferRef mbref = takeBuffer(std::move(mb));
194   filePaths.push_back(filename);
195 
196   // File type is detected by contents, not by file extension.
197   switch (identify_magic(mbref.getBuffer())) {
198   case file_magic::windows_resource:
199     resources.push_back(mbref);
200     break;
201   case file_magic::archive:
202     if (wholeArchive) {
203       std::unique_ptr<Archive> file =
204           CHECK(Archive::create(mbref), filename + ": failed to parse archive");
205       Archive *archive = file.get();
206       make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
207 
208       int memberIndex = 0;
209       for (MemoryBufferRef m : getArchiveMembers(archive))
210         addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
211       return;
212     }
213     ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref));
214     break;
215   case file_magic::bitcode:
216     ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy));
217     break;
218   case file_magic::coff_object:
219   case file_magic::coff_import_library:
220     ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy));
221     break;
222   case file_magic::pdb:
223     ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref));
224     break;
225   case file_magic::coff_cl_gl_object:
226     error(filename + ": is not a native COFF file. Recompile without /GL");
227     break;
228   case file_magic::pecoff_executable:
229     if (ctx.config.mingw) {
230       ctx.symtab.addFile(make<DLLFile>(ctx, mbref));
231       break;
232     }
233     if (filename.ends_with_insensitive(".dll")) {
234       error(filename + ": bad file type. Did you specify a DLL instead of an "
235                        "import library?");
236       break;
237     }
238     [[fallthrough]];
239   default:
240     error(mbref.getBufferIdentifier() + ": unknown file type");
241     break;
242   }
243 }
244 
245 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
246   auto future = std::make_shared<std::future<MBErrPair>>(
247       createFutureForFile(std::string(path)));
248   std::string pathStr = std::string(path);
249   enqueueTask([=]() {
250     auto [mb, ec] = future->get();
251     if (ec) {
252       // Retry reading the file (synchronously) now that we may have added
253       // winsysroot search paths from SymbolTable::addFile().
254       // Retrying synchronously is important for keeping the order of inputs
255       // consistent.
256       // This makes it so that if the user passes something in the winsysroot
257       // before something we can find with an architecture, we won't find the
258       // winsysroot file.
259       if (std::optional<StringRef> retryPath = findFileIfNew(pathStr)) {
260         auto retryMb = MemoryBuffer::getFile(*retryPath, /*IsText=*/false,
261                                              /*RequiresNullTerminator=*/false);
262         ec = retryMb.getError();
263         if (!ec)
264           mb = std::move(*retryMb);
265       } else {
266         // We've already handled this file.
267         return;
268       }
269     }
270     if (ec) {
271       std::string msg = "could not open '" + pathStr + "': " + ec.message();
272       // Check if the filename is a typo for an option flag. OptTable thinks
273       // that all args that are not known options and that start with / are
274       // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
275       // the option `/nodefaultlib` than a reference to a file in the root
276       // directory.
277       std::string nearest;
278       if (ctx.optTable.findNearest(pathStr, nearest) > 1)
279         error(msg);
280       else
281         error(msg + "; did you mean '" + nearest + "'");
282     } else
283       ctx.driver.addBuffer(std::move(mb), wholeArchive, lazy);
284   });
285 }
286 
287 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
288                                     StringRef parentName,
289                                     uint64_t offsetInArchive) {
290   file_magic magic = identify_magic(mb.getBuffer());
291   if (magic == file_magic::coff_import_library) {
292     InputFile *imp = make<ImportFile>(ctx, mb);
293     imp->parentName = parentName;
294     ctx.symtab.addFile(imp);
295     return;
296   }
297 
298   InputFile *obj;
299   if (magic == file_magic::coff_object) {
300     obj = make<ObjFile>(ctx, mb);
301   } else if (magic == file_magic::bitcode) {
302     obj =
303         make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false);
304   } else if (magic == file_magic::coff_cl_gl_object) {
305     error(mb.getBufferIdentifier() +
306           ": is not a native COFF file. Recompile without /GL?");
307     return;
308   } else {
309     error("unknown file type: " + mb.getBufferIdentifier());
310     return;
311   }
312 
313   obj->parentName = parentName;
314   ctx.symtab.addFile(obj);
315   log("Loaded " + toString(obj) + " for " + symName);
316 }
317 
318 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
319                                         const Archive::Symbol &sym,
320                                         StringRef parentName) {
321 
322   auto reportBufferError = [=](Error &&e, StringRef childName) {
323     fatal("could not get the buffer for the member defining symbol " +
324           toCOFFString(ctx, sym) + ": " + parentName + "(" + childName +
325           "): " + toString(std::move(e)));
326   };
327 
328   if (!c.getParent()->isThin()) {
329     uint64_t offsetInArchive = c.getChildOffset();
330     Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
331     if (!mbOrErr)
332       reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
333     MemoryBufferRef mb = mbOrErr.get();
334     enqueueTask([=]() {
335       ctx.driver.addArchiveBuffer(mb, toCOFFString(ctx, sym), parentName,
336                                   offsetInArchive);
337     });
338     return;
339   }
340 
341   std::string childName =
342       CHECK(c.getFullName(),
343             "could not get the filename for the member defining symbol " +
344                 toCOFFString(ctx, sym));
345   auto future =
346       std::make_shared<std::future<MBErrPair>>(createFutureForFile(childName));
347   enqueueTask([=]() {
348     auto mbOrErr = future->get();
349     if (mbOrErr.second)
350       reportBufferError(errorCodeToError(mbOrErr.second), childName);
351     // Pass empty string as archive name so that the original filename is
352     // used as the buffer identifier.
353     ctx.driver.addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
354                                 toCOFFString(ctx, sym), "",
355                                 /*OffsetInArchive=*/0);
356   });
357 }
358 
359 bool LinkerDriver::isDecorated(StringRef sym) {
360   return sym.starts_with("@") || sym.contains("@@") || sym.starts_with("?") ||
361          (!ctx.config.mingw && sym.contains('@'));
362 }
363 
364 // Parses .drectve section contents and returns a list of files
365 // specified by /defaultlib.
366 void LinkerDriver::parseDirectives(InputFile *file) {
367   StringRef s = file->getDirectives();
368   if (s.empty())
369     return;
370 
371   log("Directives: " + toString(file) + ": " + s);
372 
373   ArgParser parser(ctx);
374   // .drectve is always tokenized using Windows shell rules.
375   // /EXPORT: option can appear too many times, processing in fastpath.
376   ParsedDirectives directives = parser.parseDirectives(s);
377 
378   for (StringRef e : directives.exports) {
379     // If a common header file contains dllexported function
380     // declarations, many object files may end up with having the
381     // same /EXPORT options. In order to save cost of parsing them,
382     // we dedup them first.
383     if (!directivesExports.insert(e).second)
384       continue;
385 
386     Export exp = parseExport(e);
387     if (ctx.config.machine == I386 && ctx.config.mingw) {
388       if (!isDecorated(exp.name))
389         exp.name = saver().save("_" + exp.name);
390       if (!exp.extName.empty() && !isDecorated(exp.extName))
391         exp.extName = saver().save("_" + exp.extName);
392     }
393     exp.source = ExportSource::Directives;
394     ctx.config.exports.push_back(exp);
395   }
396 
397   // Handle /include: in bulk.
398   for (StringRef inc : directives.includes)
399     addUndefined(inc);
400 
401   // Handle /exclude-symbols: in bulk.
402   for (StringRef e : directives.excludes) {
403     SmallVector<StringRef, 2> vec;
404     e.split(vec, ',');
405     for (StringRef sym : vec)
406       excludedSymbols.insert(mangle(sym));
407   }
408 
409   // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
410   for (auto *arg : directives.args) {
411     switch (arg->getOption().getID()) {
412     case OPT_aligncomm:
413       parseAligncomm(arg->getValue());
414       break;
415     case OPT_alternatename:
416       parseAlternateName(arg->getValue());
417       break;
418     case OPT_defaultlib:
419       if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
420         enqueuePath(*path, false, false);
421       break;
422     case OPT_entry:
423       ctx.config.entry = addUndefined(mangle(arg->getValue()));
424       break;
425     case OPT_failifmismatch:
426       checkFailIfMismatch(arg->getValue(), file);
427       break;
428     case OPT_incl:
429       addUndefined(arg->getValue());
430       break;
431     case OPT_manifestdependency:
432       ctx.config.manifestDependencies.insert(arg->getValue());
433       break;
434     case OPT_merge:
435       parseMerge(arg->getValue());
436       break;
437     case OPT_nodefaultlib:
438       ctx.config.noDefaultLibs.insert(findLib(arg->getValue()).lower());
439       break;
440     case OPT_release:
441       ctx.config.writeCheckSum = true;
442       break;
443     case OPT_section:
444       parseSection(arg->getValue());
445       break;
446     case OPT_stack:
447       parseNumbers(arg->getValue(), &ctx.config.stackReserve,
448                    &ctx.config.stackCommit);
449       break;
450     case OPT_subsystem: {
451       bool gotVersion = false;
452       parseSubsystem(arg->getValue(), &ctx.config.subsystem,
453                      &ctx.config.majorSubsystemVersion,
454                      &ctx.config.minorSubsystemVersion, &gotVersion);
455       if (gotVersion) {
456         ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion;
457         ctx.config.minorOSVersion = ctx.config.minorSubsystemVersion;
458       }
459       break;
460     }
461     // Only add flags here that link.exe accepts in
462     // `#pragma comment(linker, "/flag")`-generated sections.
463     case OPT_editandcontinue:
464     case OPT_guardsym:
465     case OPT_throwingnew:
466     case OPT_inferasanlibs:
467     case OPT_inferasanlibs_no:
468       break;
469     default:
470       error(arg->getSpelling() + " is not allowed in .drectve (" +
471             toString(file) + ")");
472     }
473   }
474 }
475 
476 // Find file from search paths. You can omit ".obj", this function takes
477 // care of that. Note that the returned path is not guaranteed to exist.
478 StringRef LinkerDriver::findFile(StringRef filename) {
479   auto getFilename = [this](StringRef filename) -> StringRef {
480     if (ctx.config.vfs)
481       if (auto statOrErr = ctx.config.vfs->status(filename))
482         return saver().save(statOrErr->getName());
483     return filename;
484   };
485 
486   if (sys::path::is_absolute(filename))
487     return getFilename(filename);
488   bool hasExt = filename.contains('.');
489   for (StringRef dir : searchPaths) {
490     SmallString<128> path = dir;
491     sys::path::append(path, filename);
492     path = SmallString<128>{getFilename(path.str())};
493     if (sys::fs::exists(path.str()))
494       return saver().save(path.str());
495     if (!hasExt) {
496       path.append(".obj");
497       path = SmallString<128>{getFilename(path.str())};
498       if (sys::fs::exists(path.str()))
499         return saver().save(path.str());
500     }
501   }
502   return filename;
503 }
504 
505 static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
506   sys::fs::UniqueID ret;
507   if (sys::fs::getUniqueID(path, ret))
508     return std::nullopt;
509   return ret;
510 }
511 
512 // Resolves a file path. This never returns the same path
513 // (in that case, it returns std::nullopt).
514 std::optional<StringRef> LinkerDriver::findFileIfNew(StringRef filename) {
515   StringRef path = findFile(filename);
516 
517   if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) {
518     bool seen = !visitedFiles.insert(*id).second;
519     if (seen)
520       return std::nullopt;
521   }
522 
523   if (path.ends_with_insensitive(".lib"))
524     visitedLibs.insert(std::string(sys::path::filename(path).lower()));
525   return path;
526 }
527 
528 // MinGW specific. If an embedded directive specified to link to
529 // foo.lib, but it isn't found, try libfoo.a instead.
530 StringRef LinkerDriver::findLibMinGW(StringRef filename) {
531   if (filename.contains('/') || filename.contains('\\'))
532     return filename;
533 
534   SmallString<128> s = filename;
535   sys::path::replace_extension(s, ".a");
536   StringRef libName = saver().save("lib" + s.str());
537   return findFile(libName);
538 }
539 
540 // Find library file from search path.
541 StringRef LinkerDriver::findLib(StringRef filename) {
542   // Add ".lib" to Filename if that has no file extension.
543   bool hasExt = filename.contains('.');
544   if (!hasExt)
545     filename = saver().save(filename + ".lib");
546   StringRef ret = findFile(filename);
547   // For MinGW, if the find above didn't turn up anything, try
548   // looking for a MinGW formatted library name.
549   if (ctx.config.mingw && ret == filename)
550     return findLibMinGW(filename);
551   return ret;
552 }
553 
554 // Resolves a library path. /nodefaultlib options are taken into
555 // consideration. This never returns the same path (in that case,
556 // it returns std::nullopt).
557 std::optional<StringRef> LinkerDriver::findLibIfNew(StringRef filename) {
558   if (ctx.config.noDefaultLibAll)
559     return std::nullopt;
560   if (!visitedLibs.insert(filename.lower()).second)
561     return std::nullopt;
562 
563   StringRef path = findLib(filename);
564   if (ctx.config.noDefaultLibs.count(path.lower()))
565     return std::nullopt;
566 
567   if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
568     if (!visitedFiles.insert(*id).second)
569       return std::nullopt;
570   return path;
571 }
572 
573 void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
574   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
575 
576   // Check the command line first, that's the user explicitly telling us what to
577   // use. Check the environment next, in case we're being invoked from a VS
578   // command prompt. Failing that, just try to find the newest Visual Studio
579   // version we can and use its default VC toolchain.
580   std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
581   if (auto *A = Args.getLastArg(OPT_vctoolsdir))
582     VCToolsDir = A->getValue();
583   if (auto *A = Args.getLastArg(OPT_vctoolsversion))
584     VCToolsVersion = A->getValue();
585   if (auto *A = Args.getLastArg(OPT_winsysroot))
586     WinSysRoot = A->getValue();
587   if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
588                                      WinSysRoot, vcToolChainPath, vsLayout) &&
589       (Args.hasArg(OPT_lldignoreenv) ||
590        !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
591       !findVCToolChainViaSetupConfig(*VFS, {}, vcToolChainPath, vsLayout) &&
592       !findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
593     return;
594 
595   // If the VC environment hasn't been configured (perhaps because the user did
596   // not run vcvarsall), try to build a consistent link environment.  If the
597   // environment variable is set however, assume the user knows what they're
598   // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
599   // vars.
600   if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
601     diaPath = A->getValue();
602     if (A->getOption().getID() == OPT_winsysroot)
603       path::append(diaPath, "DIA SDK");
604   }
605   useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
606                          !Process::GetEnv("LIB") ||
607                          Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
608   if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
609       Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
610     std::optional<StringRef> WinSdkDir, WinSdkVersion;
611     if (auto *A = Args.getLastArg(OPT_winsdkdir))
612       WinSdkDir = A->getValue();
613     if (auto *A = Args.getLastArg(OPT_winsdkversion))
614       WinSdkVersion = A->getValue();
615 
616     if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
617       std::string UniversalCRTSdkPath;
618       std::string UCRTVersion;
619       if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
620                                 UniversalCRTSdkPath, UCRTVersion)) {
621         universalCRTLibPath = UniversalCRTSdkPath;
622         path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
623       }
624     }
625 
626     std::string sdkPath;
627     std::string windowsSDKIncludeVersion;
628     std::string windowsSDKLibVersion;
629     if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
630                          sdkMajor, windowsSDKIncludeVersion,
631                          windowsSDKLibVersion)) {
632       windowsSdkLibPath = sdkPath;
633       path::append(windowsSdkLibPath, "Lib");
634       if (sdkMajor >= 8)
635         path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
636     }
637   }
638 }
639 
640 void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
641   std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
642   SmallString<128> binDir(lldBinary);
643   sys::path::remove_filename(binDir);                 // remove lld-link.exe
644   StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
645 
646   SmallString<128> libDir(rootDir);
647   sys::path::append(libDir, "lib");
648 
649   // Add the resource dir library path
650   SmallString<128> runtimeLibDir(rootDir);
651   sys::path::append(runtimeLibDir, "lib", "clang",
652                     std::to_string(LLVM_VERSION_MAJOR), "lib");
653   // Resource dir + osname, which is hardcoded to windows since we are in the
654   // COFF driver.
655   SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
656   sys::path::append(runtimeLibDirWithOS, "windows");
657 
658   searchPaths.push_back(saver().save(runtimeLibDirWithOS.str()));
659   searchPaths.push_back(saver().save(runtimeLibDir.str()));
660   searchPaths.push_back(saver().save(libDir.str()));
661 }
662 
663 void LinkerDriver::addWinSysRootLibSearchPaths() {
664   if (!diaPath.empty()) {
665     // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
666     path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
667     searchPaths.push_back(saver().save(diaPath.str()));
668   }
669   if (useWinSysRootLibPath) {
670     searchPaths.push_back(saver().save(getSubDirectoryPath(
671         SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
672     searchPaths.push_back(saver().save(
673         getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
674                             getArch(), "atlmfc")));
675   }
676   if (!universalCRTLibPath.empty()) {
677     StringRef ArchName = archToWindowsSDKArch(getArch());
678     if (!ArchName.empty()) {
679       path::append(universalCRTLibPath, ArchName);
680       searchPaths.push_back(saver().save(universalCRTLibPath.str()));
681     }
682   }
683   if (!windowsSdkLibPath.empty()) {
684     std::string path;
685     if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
686                                       path))
687       searchPaths.push_back(saver().save(path));
688   }
689 }
690 
691 // Parses LIB environment which contains a list of search paths.
692 void LinkerDriver::addLibSearchPaths() {
693   std::optional<std::string> envOpt = Process::GetEnv("LIB");
694   if (!envOpt)
695     return;
696   StringRef env = saver().save(*envOpt);
697   while (!env.empty()) {
698     StringRef path;
699     std::tie(path, env) = env.split(';');
700     searchPaths.push_back(path);
701   }
702 }
703 
704 Symbol *LinkerDriver::addUndefined(StringRef name) {
705   Symbol *b = ctx.symtab.addUndefined(name);
706   if (!b->isGCRoot) {
707     b->isGCRoot = true;
708     ctx.config.gcroot.push_back(b);
709   }
710   return b;
711 }
712 
713 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
714   // If the plain symbol name has already been resolved, do nothing.
715   Undefined *unmangled = dyn_cast<Undefined>(s);
716   if (!unmangled)
717     return "";
718 
719   // Otherwise, see if a similar, mangled symbol exists in the symbol table.
720   Symbol *mangled = ctx.symtab.findMangle(unmangled->getName());
721   if (!mangled)
722     return "";
723 
724   // If we find a similar mangled symbol, make this an alias to it and return
725   // its name.
726   log(unmangled->getName() + " aliased to " + mangled->getName());
727   unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName());
728   return mangled->getName();
729 }
730 
731 // Windows specific -- find default entry point name.
732 //
733 // There are four different entry point functions for Windows executables,
734 // each of which corresponds to a user-defined "main" function. This function
735 // infers an entry point from a user-defined "main" function.
736 StringRef LinkerDriver::findDefaultEntry() {
737   assert(ctx.config.subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
738          "must handle /subsystem before calling this");
739 
740   if (ctx.config.mingw)
741     return mangle(ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
742                       ? "WinMainCRTStartup"
743                       : "mainCRTStartup");
744 
745   if (ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
746     if (findUnderscoreMangle("wWinMain")) {
747       if (!findUnderscoreMangle("WinMain"))
748         return mangle("wWinMainCRTStartup");
749       warn("found both wWinMain and WinMain; using latter");
750     }
751     return mangle("WinMainCRTStartup");
752   }
753   if (findUnderscoreMangle("wmain")) {
754     if (!findUnderscoreMangle("main"))
755       return mangle("wmainCRTStartup");
756     warn("found both wmain and main; using latter");
757   }
758   return mangle("mainCRTStartup");
759 }
760 
761 WindowsSubsystem LinkerDriver::inferSubsystem() {
762   if (ctx.config.dll)
763     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
764   if (ctx.config.mingw)
765     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
766   // Note that link.exe infers the subsystem from the presence of these
767   // functions even if /entry: or /nodefaultlib are passed which causes them
768   // to not be called.
769   bool haveMain = findUnderscoreMangle("main");
770   bool haveWMain = findUnderscoreMangle("wmain");
771   bool haveWinMain = findUnderscoreMangle("WinMain");
772   bool haveWWinMain = findUnderscoreMangle("wWinMain");
773   if (haveMain || haveWMain) {
774     if (haveWinMain || haveWWinMain) {
775       warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
776            (haveWinMain ? "WinMain" : "wWinMain") +
777            "; defaulting to /subsystem:console");
778     }
779     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
780   }
781   if (haveWinMain || haveWWinMain)
782     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
783   return IMAGE_SUBSYSTEM_UNKNOWN;
784 }
785 
786 uint64_t LinkerDriver::getDefaultImageBase() {
787   if (ctx.config.is64())
788     return ctx.config.dll ? 0x180000000 : 0x140000000;
789   return ctx.config.dll ? 0x10000000 : 0x400000;
790 }
791 
792 static std::string rewritePath(StringRef s) {
793   if (fs::exists(s))
794     return relativeToRoot(s);
795   return std::string(s);
796 }
797 
798 // Reconstructs command line arguments so that so that you can re-run
799 // the same command with the same inputs. This is for --reproduce.
800 static std::string createResponseFile(const opt::InputArgList &args,
801                                       ArrayRef<StringRef> filePaths,
802                                       ArrayRef<StringRef> searchPaths) {
803   SmallString<0> data;
804   raw_svector_ostream os(data);
805 
806   for (auto *arg : args) {
807     switch (arg->getOption().getID()) {
808     case OPT_linkrepro:
809     case OPT_reproduce:
810     case OPT_INPUT:
811     case OPT_defaultlib:
812     case OPT_libpath:
813     case OPT_winsysroot:
814       break;
815     case OPT_call_graph_ordering_file:
816     case OPT_deffile:
817     case OPT_manifestinput:
818     case OPT_natvis:
819       os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
820       break;
821     case OPT_order: {
822       StringRef orderFile = arg->getValue();
823       orderFile.consume_front("@");
824       os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
825       break;
826     }
827     case OPT_pdbstream: {
828       const std::pair<StringRef, StringRef> nameFile =
829           StringRef(arg->getValue()).split("=");
830       os << arg->getSpelling() << nameFile.first << '='
831          << quote(rewritePath(nameFile.second)) << '\n';
832       break;
833     }
834     case OPT_implib:
835     case OPT_manifestfile:
836     case OPT_pdb:
837     case OPT_pdbstripped:
838     case OPT_out:
839       os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
840       break;
841     default:
842       os << toString(*arg) << "\n";
843     }
844   }
845 
846   for (StringRef path : searchPaths) {
847     std::string relPath = relativeToRoot(path);
848     os << "/libpath:" << quote(relPath) << "\n";
849   }
850 
851   for (StringRef path : filePaths)
852     os << quote(relativeToRoot(path)) << "\n";
853 
854   return std::string(data.str());
855 }
856 
857 enum class DebugKind {
858   Unknown,
859   None,
860   Full,
861   FastLink,
862   GHash,
863   NoGHash,
864   Dwarf,
865   Symtab
866 };
867 
868 static DebugKind parseDebugKind(const opt::InputArgList &args) {
869   auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
870   if (!a)
871     return DebugKind::None;
872   if (a->getNumValues() == 0)
873     return DebugKind::Full;
874 
875   DebugKind debug = StringSwitch<DebugKind>(a->getValue())
876                         .CaseLower("none", DebugKind::None)
877                         .CaseLower("full", DebugKind::Full)
878                         .CaseLower("fastlink", DebugKind::FastLink)
879                         // LLD extensions
880                         .CaseLower("ghash", DebugKind::GHash)
881                         .CaseLower("noghash", DebugKind::NoGHash)
882                         .CaseLower("dwarf", DebugKind::Dwarf)
883                         .CaseLower("symtab", DebugKind::Symtab)
884                         .Default(DebugKind::Unknown);
885 
886   if (debug == DebugKind::FastLink) {
887     warn("/debug:fastlink unsupported; using /debug:full");
888     return DebugKind::Full;
889   }
890   if (debug == DebugKind::Unknown) {
891     error("/debug: unknown option: " + Twine(a->getValue()));
892     return DebugKind::None;
893   }
894   return debug;
895 }
896 
897 static unsigned parseDebugTypes(const opt::InputArgList &args) {
898   unsigned debugTypes = static_cast<unsigned>(DebugType::None);
899 
900   if (auto *a = args.getLastArg(OPT_debugtype)) {
901     SmallVector<StringRef, 3> types;
902     StringRef(a->getValue())
903         .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
904 
905     for (StringRef type : types) {
906       unsigned v = StringSwitch<unsigned>(type.lower())
907                        .Case("cv", static_cast<unsigned>(DebugType::CV))
908                        .Case("pdata", static_cast<unsigned>(DebugType::PData))
909                        .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
910                        .Default(0);
911       if (v == 0) {
912         warn("/debugtype: unknown option '" + type + "'");
913         continue;
914       }
915       debugTypes |= v;
916     }
917     return debugTypes;
918   }
919 
920   // Default debug types
921   debugTypes = static_cast<unsigned>(DebugType::CV);
922   if (args.hasArg(OPT_driver))
923     debugTypes |= static_cast<unsigned>(DebugType::PData);
924   if (args.hasArg(OPT_profile))
925     debugTypes |= static_cast<unsigned>(DebugType::Fixup);
926 
927   return debugTypes;
928 }
929 
930 std::string LinkerDriver::getMapFile(const opt::InputArgList &args,
931                                      opt::OptSpecifier os,
932                                      opt::OptSpecifier osFile) {
933   auto *arg = args.getLastArg(os, osFile);
934   if (!arg)
935     return "";
936   if (arg->getOption().getID() == osFile.getID())
937     return arg->getValue();
938 
939   assert(arg->getOption().getID() == os.getID());
940   StringRef outFile = ctx.config.outputFile;
941   return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
942 }
943 
944 std::string LinkerDriver::getImplibPath() {
945   if (!ctx.config.implib.empty())
946     return std::string(ctx.config.implib);
947   SmallString<128> out = StringRef(ctx.config.outputFile);
948   sys::path::replace_extension(out, ".lib");
949   return std::string(out.str());
950 }
951 
952 // The import name is calculated as follows:
953 //
954 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
955 //   -----+----------------+---------------------+------------------
956 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
957 //    LIB | {value}        | {value}.dll         | {output name}.dll
958 //
959 std::string LinkerDriver::getImportName(bool asLib) {
960   SmallString<128> out;
961 
962   if (ctx.config.importName.empty()) {
963     out.assign(sys::path::filename(ctx.config.outputFile));
964     if (asLib)
965       sys::path::replace_extension(out, ".dll");
966   } else {
967     out.assign(ctx.config.importName);
968     if (!sys::path::has_extension(out))
969       sys::path::replace_extension(out,
970                                    (ctx.config.dll || asLib) ? ".dll" : ".exe");
971   }
972 
973   return std::string(out.str());
974 }
975 
976 void LinkerDriver::createImportLibrary(bool asLib) {
977   std::vector<COFFShortExport> exports;
978   for (Export &e1 : ctx.config.exports) {
979     COFFShortExport e2;
980     e2.Name = std::string(e1.name);
981     e2.SymbolName = std::string(e1.symbolName);
982     e2.ExtName = std::string(e1.extName);
983     e2.AliasTarget = std::string(e1.aliasTarget);
984     e2.Ordinal = e1.ordinal;
985     e2.Noname = e1.noname;
986     e2.Data = e1.data;
987     e2.Private = e1.isPrivate;
988     e2.Constant = e1.constant;
989     exports.push_back(e2);
990   }
991 
992   std::string libName = getImportName(asLib);
993   std::string path = getImplibPath();
994 
995   if (!ctx.config.incremental) {
996     checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
997                                   ctx.config.mingw));
998     return;
999   }
1000 
1001   // If the import library already exists, replace it only if the contents
1002   // have changed.
1003   ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
1004       path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1005   if (!oldBuf) {
1006     checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
1007                                   ctx.config.mingw));
1008     return;
1009   }
1010 
1011   SmallString<128> tmpName;
1012   if (std::error_code ec =
1013           sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
1014     fatal("cannot create temporary file for import library " + path + ": " +
1015           ec.message());
1016 
1017   if (Error e = writeImportLibrary(libName, tmpName, exports,
1018                                    ctx.config.machine, ctx.config.mingw)) {
1019     checkError(std::move(e));
1020     return;
1021   }
1022 
1023   std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
1024       tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
1025   if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
1026     oldBuf->reset();
1027     checkError(errorCodeToError(sys::fs::rename(tmpName, path)));
1028   } else {
1029     sys::fs::remove(tmpName);
1030   }
1031 }
1032 
1033 void LinkerDriver::parseModuleDefs(StringRef path) {
1034   std::unique_ptr<MemoryBuffer> mb =
1035       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1036                                   /*RequiresNullTerminator=*/false,
1037                                   /*IsVolatile=*/true),
1038             "could not open " + path);
1039   COFFModuleDefinition m = check(parseCOFFModuleDefinition(
1040       mb->getMemBufferRef(), ctx.config.machine, ctx.config.mingw));
1041 
1042   // Include in /reproduce: output if applicable.
1043   ctx.driver.takeBuffer(std::move(mb));
1044 
1045   if (ctx.config.outputFile.empty())
1046     ctx.config.outputFile = std::string(saver().save(m.OutputFile));
1047   ctx.config.importName = std::string(saver().save(m.ImportName));
1048   if (m.ImageBase)
1049     ctx.config.imageBase = m.ImageBase;
1050   if (m.StackReserve)
1051     ctx.config.stackReserve = m.StackReserve;
1052   if (m.StackCommit)
1053     ctx.config.stackCommit = m.StackCommit;
1054   if (m.HeapReserve)
1055     ctx.config.heapReserve = m.HeapReserve;
1056   if (m.HeapCommit)
1057     ctx.config.heapCommit = m.HeapCommit;
1058   if (m.MajorImageVersion)
1059     ctx.config.majorImageVersion = m.MajorImageVersion;
1060   if (m.MinorImageVersion)
1061     ctx.config.minorImageVersion = m.MinorImageVersion;
1062   if (m.MajorOSVersion)
1063     ctx.config.majorOSVersion = m.MajorOSVersion;
1064   if (m.MinorOSVersion)
1065     ctx.config.minorOSVersion = m.MinorOSVersion;
1066 
1067   for (COFFShortExport e1 : m.Exports) {
1068     Export e2;
1069     // In simple cases, only Name is set. Renamed exports are parsed
1070     // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
1071     // it shouldn't be a normal exported function but a forward to another
1072     // DLL instead. This is supported by both MS and GNU linkers.
1073     if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
1074         StringRef(e1.Name).contains('.')) {
1075       e2.name = saver().save(e1.ExtName);
1076       e2.forwardTo = saver().save(e1.Name);
1077       ctx.config.exports.push_back(e2);
1078       continue;
1079     }
1080     e2.name = saver().save(e1.Name);
1081     e2.extName = saver().save(e1.ExtName);
1082     e2.aliasTarget = saver().save(e1.AliasTarget);
1083     e2.ordinal = e1.Ordinal;
1084     e2.noname = e1.Noname;
1085     e2.data = e1.Data;
1086     e2.isPrivate = e1.Private;
1087     e2.constant = e1.Constant;
1088     e2.source = ExportSource::ModuleDefinition;
1089     ctx.config.exports.push_back(e2);
1090   }
1091 }
1092 
1093 void LinkerDriver::enqueueTask(std::function<void()> task) {
1094   taskQueue.push_back(std::move(task));
1095 }
1096 
1097 bool LinkerDriver::run() {
1098   ScopedTimer t(ctx.inputFileTimer);
1099 
1100   bool didWork = !taskQueue.empty();
1101   while (!taskQueue.empty()) {
1102     taskQueue.front()();
1103     taskQueue.pop_front();
1104   }
1105   return didWork;
1106 }
1107 
1108 // Parse an /order file. If an option is given, the linker places
1109 // COMDAT sections in the same order as their names appear in the
1110 // given file.
1111 void LinkerDriver::parseOrderFile(StringRef arg) {
1112   // For some reason, the MSVC linker requires a filename to be
1113   // preceded by "@".
1114   if (!arg.starts_with("@")) {
1115     error("malformed /order option: '@' missing");
1116     return;
1117   }
1118 
1119   // Get a list of all comdat sections for error checking.
1120   DenseSet<StringRef> set;
1121   for (Chunk *c : ctx.symtab.getChunks())
1122     if (auto *sec = dyn_cast<SectionChunk>(c))
1123       if (sec->sym)
1124         set.insert(sec->sym->getName());
1125 
1126   // Open a file.
1127   StringRef path = arg.substr(1);
1128   std::unique_ptr<MemoryBuffer> mb =
1129       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1130                                   /*RequiresNullTerminator=*/false,
1131                                   /*IsVolatile=*/true),
1132             "could not open " + path);
1133 
1134   // Parse a file. An order file contains one symbol per line.
1135   // All symbols that were not present in a given order file are
1136   // considered to have the lowest priority 0 and are placed at
1137   // end of an output section.
1138   for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
1139     std::string s(arg);
1140     if (ctx.config.machine == I386 && !isDecorated(s))
1141       s = "_" + s;
1142 
1143     if (set.count(s) == 0) {
1144       if (ctx.config.warnMissingOrderSymbol)
1145         warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
1146     } else
1147       ctx.config.order[s] = INT_MIN + ctx.config.order.size();
1148   }
1149 
1150   // Include in /reproduce: output if applicable.
1151   ctx.driver.takeBuffer(std::move(mb));
1152 }
1153 
1154 void LinkerDriver::parseCallGraphFile(StringRef path) {
1155   std::unique_ptr<MemoryBuffer> mb =
1156       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1157                                   /*RequiresNullTerminator=*/false,
1158                                   /*IsVolatile=*/true),
1159             "could not open " + path);
1160 
1161   // Build a map from symbol name to section.
1162   DenseMap<StringRef, Symbol *> map;
1163   for (ObjFile *file : ctx.objFileInstances)
1164     for (Symbol *sym : file->getSymbols())
1165       if (sym)
1166         map[sym->getName()] = sym;
1167 
1168   auto findSection = [&](StringRef name) -> SectionChunk * {
1169     Symbol *sym = map.lookup(name);
1170     if (!sym) {
1171       if (ctx.config.warnMissingOrderSymbol)
1172         warn(path + ": no such symbol: " + name);
1173       return nullptr;
1174     }
1175 
1176     if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1177       return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1178     return nullptr;
1179   };
1180 
1181   for (StringRef line : args::getLines(*mb)) {
1182     SmallVector<StringRef, 3> fields;
1183     line.split(fields, ' ');
1184     uint64_t count;
1185 
1186     if (fields.size() != 3 || !to_integer(fields[2], count)) {
1187       error(path + ": parse error");
1188       return;
1189     }
1190 
1191     if (SectionChunk *from = findSection(fields[0]))
1192       if (SectionChunk *to = findSection(fields[1]))
1193         ctx.config.callGraphProfile[{from, to}] += count;
1194   }
1195 
1196   // Include in /reproduce: output if applicable.
1197   ctx.driver.takeBuffer(std::move(mb));
1198 }
1199 
1200 static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) {
1201   for (ObjFile *obj : ctx.objFileInstances) {
1202     if (obj->callgraphSec) {
1203       ArrayRef<uint8_t> contents;
1204       cantFail(
1205           obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
1206       BinaryStreamReader reader(contents, support::little);
1207       while (!reader.empty()) {
1208         uint32_t fromIndex, toIndex;
1209         uint64_t count;
1210         if (Error err = reader.readInteger(fromIndex))
1211           fatal(toString(obj) + ": Expected 32-bit integer");
1212         if (Error err = reader.readInteger(toIndex))
1213           fatal(toString(obj) + ": Expected 32-bit integer");
1214         if (Error err = reader.readInteger(count))
1215           fatal(toString(obj) + ": Expected 64-bit integer");
1216         auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1217         auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1218         if (!fromSym || !toSym)
1219           continue;
1220         auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1221         auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1222         if (from && to)
1223           ctx.config.callGraphProfile[{from, to}] += count;
1224       }
1225     }
1226   }
1227 }
1228 
1229 static void markAddrsig(Symbol *s) {
1230   if (auto *d = dyn_cast_or_null<Defined>(s))
1231     if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
1232       c->keepUnique = true;
1233 }
1234 
1235 static void findKeepUniqueSections(COFFLinkerContext &ctx) {
1236   // Exported symbols could be address-significant in other executables or DSOs,
1237   // so we conservatively mark them as address-significant.
1238   for (Export &r : ctx.config.exports)
1239     markAddrsig(r.sym);
1240 
1241   // Visit the address-significance table in each object file and mark each
1242   // referenced symbol as address-significant.
1243   for (ObjFile *obj : ctx.objFileInstances) {
1244     ArrayRef<Symbol *> syms = obj->getSymbols();
1245     if (obj->addrsigSec) {
1246       ArrayRef<uint8_t> contents;
1247       cantFail(
1248           obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
1249       const uint8_t *cur = contents.begin();
1250       while (cur != contents.end()) {
1251         unsigned size;
1252         const char *err;
1253         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1254         if (err)
1255           fatal(toString(obj) + ": could not decode addrsig section: " + err);
1256         if (symIndex >= syms.size())
1257           fatal(toString(obj) + ": invalid symbol index in addrsig section");
1258         markAddrsig(syms[symIndex]);
1259         cur += size;
1260       }
1261     } else {
1262       // If an object file does not have an address-significance table,
1263       // conservatively mark all of its symbols as address-significant.
1264       for (Symbol *s : syms)
1265         markAddrsig(s);
1266     }
1267   }
1268 }
1269 
1270 // link.exe replaces each %foo% in altPath with the contents of environment
1271 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1272 // of pdb's output path) and _EXT (expands to the extension of the output
1273 // binary).
1274 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1275 // vars.
1276 void LinkerDriver::parsePDBAltPath() {
1277   SmallString<128> buf;
1278   StringRef pdbBasename =
1279       sys::path::filename(ctx.config.pdbPath, sys::path::Style::windows);
1280   StringRef binaryExtension =
1281       sys::path::extension(ctx.config.outputFile, sys::path::Style::windows);
1282   if (!binaryExtension.empty())
1283     binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
1284 
1285   // Invariant:
1286   //   +--------- cursor ('a...' might be the empty string).
1287   //   |   +----- firstMark
1288   //   |   |   +- secondMark
1289   //   v   v   v
1290   //   a...%...%...
1291   size_t cursor = 0;
1292   while (cursor < ctx.config.pdbAltPath.size()) {
1293     size_t firstMark, secondMark;
1294     if ((firstMark = ctx.config.pdbAltPath.find('%', cursor)) ==
1295             StringRef::npos ||
1296         (secondMark = ctx.config.pdbAltPath.find('%', firstMark + 1)) ==
1297             StringRef::npos) {
1298       // Didn't find another full fragment, treat rest of string as literal.
1299       buf.append(ctx.config.pdbAltPath.substr(cursor));
1300       break;
1301     }
1302 
1303     // Found a full fragment. Append text in front of first %, and interpret
1304     // text between first and second % as variable name.
1305     buf.append(ctx.config.pdbAltPath.substr(cursor, firstMark - cursor));
1306     StringRef var =
1307         ctx.config.pdbAltPath.substr(firstMark, secondMark - firstMark + 1);
1308     if (var.equals_insensitive("%_pdb%"))
1309       buf.append(pdbBasename);
1310     else if (var.equals_insensitive("%_ext%"))
1311       buf.append(binaryExtension);
1312     else {
1313       warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + var +
1314            " as literal");
1315       buf.append(var);
1316     }
1317 
1318     cursor = secondMark + 1;
1319   }
1320 
1321   ctx.config.pdbAltPath = buf;
1322 }
1323 
1324 /// Convert resource files and potentially merge input resource object
1325 /// trees into one resource tree.
1326 /// Call after ObjFile::Instances is complete.
1327 void LinkerDriver::convertResources() {
1328   std::vector<ObjFile *> resourceObjFiles;
1329 
1330   for (ObjFile *f : ctx.objFileInstances) {
1331     if (f->isResourceObjFile())
1332       resourceObjFiles.push_back(f);
1333   }
1334 
1335   if (!ctx.config.mingw &&
1336       (resourceObjFiles.size() > 1 ||
1337        (resourceObjFiles.size() == 1 && !resources.empty()))) {
1338     error((!resources.empty() ? "internal .obj file created from .res files"
1339                               : toString(resourceObjFiles[1])) +
1340           ": more than one resource obj file not allowed, already got " +
1341           toString(resourceObjFiles.front()));
1342     return;
1343   }
1344 
1345   if (resources.empty() && resourceObjFiles.size() <= 1) {
1346     // No resources to convert, and max one resource object file in
1347     // the input. Keep that preconverted resource section as is.
1348     for (ObjFile *f : resourceObjFiles)
1349       f->includeResourceChunks();
1350     return;
1351   }
1352   ObjFile *f =
1353       make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles));
1354   ctx.symtab.addFile(f);
1355   f->includeResourceChunks();
1356 }
1357 
1358 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1359 // automatically exported by default. This behavior can be forced by the
1360 // -export-all-symbols option, so that it happens even when exports are
1361 // explicitly specified. The automatic behavior can be disabled using the
1362 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1363 // than MinGW in the case that nothing is explicitly exported.
1364 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1365   if (!args.hasArg(OPT_export_all_symbols)) {
1366     if (!ctx.config.dll)
1367       return;
1368 
1369     if (!ctx.config.exports.empty())
1370       return;
1371     if (args.hasArg(OPT_exclude_all_symbols))
1372       return;
1373   }
1374 
1375   AutoExporter exporter(ctx, excludedSymbols);
1376 
1377   for (auto *arg : args.filtered(OPT_wholearchive_file))
1378     if (std::optional<StringRef> path = findFile(arg->getValue()))
1379       exporter.addWholeArchive(*path);
1380 
1381   for (auto *arg : args.filtered(OPT_exclude_symbols)) {
1382     SmallVector<StringRef, 2> vec;
1383     StringRef(arg->getValue()).split(vec, ',');
1384     for (StringRef sym : vec)
1385       exporter.addExcludedSymbol(mangle(sym));
1386   }
1387 
1388   ctx.symtab.forEachSymbol([&](Symbol *s) {
1389     auto *def = dyn_cast<Defined>(s);
1390     if (!exporter.shouldExport(def))
1391       return;
1392 
1393     if (!def->isGCRoot) {
1394       def->isGCRoot = true;
1395       ctx.config.gcroot.push_back(def);
1396     }
1397 
1398     Export e;
1399     e.name = def->getName();
1400     e.sym = def;
1401     if (Chunk *c = def->getChunk())
1402       if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1403         e.data = true;
1404     s->isUsedInRegularObj = true;
1405     ctx.config.exports.push_back(e);
1406   });
1407 }
1408 
1409 // lld has a feature to create a tar file containing all input files as well as
1410 // all command line options, so that other people can run lld again with exactly
1411 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1412 //
1413 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1414 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1415 // with Microsoft link.exe.
1416 std::optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1417   if (auto *arg = args.getLastArg(OPT_reproduce))
1418     return std::string(arg->getValue());
1419 
1420   if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1421     SmallString<64> path = StringRef(arg->getValue());
1422     sys::path::append(path, "repro.tar");
1423     return std::string(path);
1424   }
1425 
1426   // This is intentionally not guarded by OPT_lldignoreenv since writing
1427   // a repro tar file doesn't affect the main output.
1428   if (auto *path = getenv("LLD_REPRODUCE"))
1429     return std::string(path);
1430 
1431   return std::nullopt;
1432 }
1433 
1434 static std::unique_ptr<llvm::vfs::FileSystem>
1435 getVFS(const opt::InputArgList &args) {
1436   using namespace llvm::vfs;
1437 
1438   const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay);
1439   if (!arg)
1440     return nullptr;
1441 
1442   auto bufOrErr = llvm::MemoryBuffer::getFile(arg->getValue());
1443   if (!bufOrErr) {
1444     checkError(errorCodeToError(bufOrErr.getError()));
1445     return nullptr;
1446   }
1447 
1448   if (auto ret = vfs::getVFSFromYAML(std::move(*bufOrErr),
1449                                      /*DiagHandler*/ nullptr, arg->getValue()))
1450     return ret;
1451 
1452   error("Invalid vfs overlay");
1453   return nullptr;
1454 }
1455 
1456 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1457   ScopedTimer rootTimer(ctx.rootTimer);
1458   Configuration *config = &ctx.config;
1459 
1460   // Needed for LTO.
1461   InitializeAllTargetInfos();
1462   InitializeAllTargets();
1463   InitializeAllTargetMCs();
1464   InitializeAllAsmParsers();
1465   InitializeAllAsmPrinters();
1466 
1467   // If the first command line argument is "/lib", link.exe acts like lib.exe.
1468   // We call our own implementation of lib.exe that understands bitcode files.
1469   if (argsArr.size() > 1 &&
1470       (StringRef(argsArr[1]).equals_insensitive("/lib") ||
1471        StringRef(argsArr[1]).equals_insensitive("-lib"))) {
1472     if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1473       fatal("lib failed");
1474     return;
1475   }
1476 
1477   // Parse command line options.
1478   ArgParser parser(ctx);
1479   opt::InputArgList args = parser.parse(argsArr);
1480 
1481   // Parse and evaluate -mllvm options.
1482   std::vector<const char *> v;
1483   v.push_back("lld-link (LLVM option parsing)");
1484   for (const auto *arg : args.filtered(OPT_mllvm)) {
1485     v.push_back(arg->getValue());
1486     config->mllvmOpts.emplace_back(arg->getValue());
1487   }
1488   cl::ResetAllOptionOccurrences();
1489   cl::ParseCommandLineOptions(v.size(), v.data());
1490 
1491   // Handle /errorlimit early, because error() depends on it.
1492   if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1493     int n = 20;
1494     StringRef s = arg->getValue();
1495     if (s.getAsInteger(10, n))
1496       error(arg->getSpelling() + " number expected, but got " + s);
1497     errorHandler().errorLimit = n;
1498   }
1499 
1500   config->vfs = getVFS(args);
1501 
1502   // Handle /help
1503   if (args.hasArg(OPT_help)) {
1504     printHelp(argsArr[0]);
1505     return;
1506   }
1507 
1508   // /threads: takes a positive integer and provides the default value for
1509   // /opt:lldltojobs=.
1510   if (auto *arg = args.getLastArg(OPT_threads)) {
1511     StringRef v(arg->getValue());
1512     unsigned threads = 0;
1513     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1514       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1515             arg->getValue() + "'");
1516     parallel::strategy = hardware_concurrency(threads);
1517     config->thinLTOJobs = v.str();
1518   }
1519 
1520   if (args.hasArg(OPT_show_timing))
1521     config->showTiming = true;
1522 
1523   config->showSummary = args.hasArg(OPT_summary);
1524   config->printSearchPaths = args.hasArg(OPT_print_search_paths);
1525 
1526   // Handle --version, which is an lld extension. This option is a bit odd
1527   // because it doesn't start with "/", but we deliberately chose "--" to
1528   // avoid conflict with /version and for compatibility with clang-cl.
1529   if (args.hasArg(OPT_dash_dash_version)) {
1530     message(getLLDVersion());
1531     return;
1532   }
1533 
1534   // Handle /lldmingw early, since it can potentially affect how other
1535   // options are handled.
1536   config->mingw = args.hasArg(OPT_lldmingw);
1537   if (config->mingw)
1538     ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now"
1539                                   " (use --error-limit=0 to see all errors)";
1540 
1541   // Handle /linkrepro and /reproduce.
1542   if (std::optional<std::string> path = getReproduceFile(args)) {
1543     Expected<std::unique_ptr<TarWriter>> errOrWriter =
1544         TarWriter::create(*path, sys::path::stem(*path));
1545 
1546     if (errOrWriter) {
1547       tar = std::move(*errOrWriter);
1548     } else {
1549       error("/linkrepro: failed to open " + *path + ": " +
1550             toString(errOrWriter.takeError()));
1551     }
1552   }
1553 
1554   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1555     if (args.hasArg(OPT_deffile))
1556       config->noEntry = true;
1557     else
1558       fatal("no input files");
1559   }
1560 
1561   // Construct search path list.
1562   searchPaths.emplace_back("");
1563   // Prefer the Clang provided builtins over the ones bundled with MSVC.
1564   addClangLibSearchPaths(argsArr[0]);
1565   for (auto *arg : args.filtered(OPT_libpath))
1566     searchPaths.push_back(arg->getValue());
1567   detectWinSysRoot(args);
1568   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
1569     addLibSearchPaths();
1570 
1571   // Handle /ignore
1572   for (auto *arg : args.filtered(OPT_ignore)) {
1573     SmallVector<StringRef, 8> vec;
1574     StringRef(arg->getValue()).split(vec, ',');
1575     for (StringRef s : vec) {
1576       if (s == "4037")
1577         config->warnMissingOrderSymbol = false;
1578       else if (s == "4099")
1579         config->warnDebugInfoUnusable = false;
1580       else if (s == "4217")
1581         config->warnLocallyDefinedImported = false;
1582       else if (s == "longsections")
1583         config->warnLongSectionNames = false;
1584       // Other warning numbers are ignored.
1585     }
1586   }
1587 
1588   // Handle /out
1589   if (auto *arg = args.getLastArg(OPT_out))
1590     config->outputFile = arg->getValue();
1591 
1592   // Handle /verbose
1593   if (args.hasArg(OPT_verbose))
1594     config->verbose = true;
1595   errorHandler().verbose = config->verbose;
1596 
1597   // Handle /force or /force:unresolved
1598   if (args.hasArg(OPT_force, OPT_force_unresolved))
1599     config->forceUnresolved = true;
1600 
1601   // Handle /force or /force:multiple
1602   if (args.hasArg(OPT_force, OPT_force_multiple))
1603     config->forceMultiple = true;
1604 
1605   // Handle /force or /force:multipleres
1606   if (args.hasArg(OPT_force, OPT_force_multipleres))
1607     config->forceMultipleRes = true;
1608 
1609   // Handle /debug
1610   DebugKind debug = parseDebugKind(args);
1611   if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1612       debug == DebugKind::GHash || debug == DebugKind::NoGHash) {
1613     config->debug = true;
1614     config->incremental = true;
1615   }
1616 
1617   // Handle /demangle
1618   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true);
1619 
1620   // Handle /debugtype
1621   config->debugTypes = parseDebugTypes(args);
1622 
1623   // Handle /driver[:uponly|:wdm].
1624   config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1625                          args.hasArg(OPT_driver_uponly_wdm) ||
1626                          args.hasArg(OPT_driver_wdm_uponly);
1627   config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1628                       args.hasArg(OPT_driver_uponly_wdm) ||
1629                       args.hasArg(OPT_driver_wdm_uponly);
1630   config->driver =
1631       config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1632 
1633   // Handle /pdb
1634   bool shouldCreatePDB =
1635       (debug == DebugKind::Full || debug == DebugKind::GHash ||
1636        debug == DebugKind::NoGHash);
1637   if (shouldCreatePDB) {
1638     if (auto *arg = args.getLastArg(OPT_pdb))
1639       config->pdbPath = arg->getValue();
1640     if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1641       config->pdbAltPath = arg->getValue();
1642     if (auto *arg = args.getLastArg(OPT_pdbpagesize))
1643       parsePDBPageSize(arg->getValue());
1644     if (args.hasArg(OPT_natvis))
1645       config->natvisFiles = args.getAllArgValues(OPT_natvis);
1646     if (args.hasArg(OPT_pdbstream)) {
1647       for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
1648         const std::pair<StringRef, StringRef> nameFile = value.split("=");
1649         const StringRef name = nameFile.first;
1650         const std::string file = nameFile.second.str();
1651         config->namedStreams[name] = file;
1652       }
1653     }
1654 
1655     if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1656       config->pdbSourcePath = arg->getValue();
1657   }
1658 
1659   // Handle /pdbstripped
1660   if (args.hasArg(OPT_pdbstripped))
1661     warn("ignoring /pdbstripped flag, it is not yet supported");
1662 
1663   // Handle /noentry
1664   if (args.hasArg(OPT_noentry)) {
1665     if (args.hasArg(OPT_dll))
1666       config->noEntry = true;
1667     else
1668       error("/noentry must be specified with /dll");
1669   }
1670 
1671   // Handle /dll
1672   if (args.hasArg(OPT_dll)) {
1673     config->dll = true;
1674     config->manifestID = 2;
1675   }
1676 
1677   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1678   // because we need to explicitly check whether that option or its inverse was
1679   // present in the argument list in order to handle /fixed.
1680   auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1681   if (dynamicBaseArg &&
1682       dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1683     config->dynamicBase = false;
1684 
1685   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1686   // default setting for any other project type.", but link.exe defaults to
1687   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1688   bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1689   if (fixed) {
1690     if (dynamicBaseArg &&
1691         dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1692       error("/fixed must not be specified with /dynamicbase");
1693     } else {
1694       config->relocatable = false;
1695       config->dynamicBase = false;
1696     }
1697   }
1698 
1699   // Handle /appcontainer
1700   config->appContainer =
1701       args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1702 
1703   // Handle /machine
1704   if (auto *arg = args.getLastArg(OPT_machine)) {
1705     config->machine = getMachineType(arg->getValue());
1706     if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1707       fatal(Twine("unknown /machine argument: ") + arg->getValue());
1708     addWinSysRootLibSearchPaths();
1709   }
1710 
1711   // Handle /nodefaultlib:<filename>
1712   for (auto *arg : args.filtered(OPT_nodefaultlib))
1713     config->noDefaultLibs.insert(findLib(arg->getValue()).lower());
1714 
1715   // Handle /nodefaultlib
1716   if (args.hasArg(OPT_nodefaultlib_all))
1717     config->noDefaultLibAll = true;
1718 
1719   // Handle /base
1720   if (auto *arg = args.getLastArg(OPT_base))
1721     parseNumbers(arg->getValue(), &config->imageBase);
1722 
1723   // Handle /filealign
1724   if (auto *arg = args.getLastArg(OPT_filealign)) {
1725     parseNumbers(arg->getValue(), &config->fileAlign);
1726     if (!isPowerOf2_64(config->fileAlign))
1727       error("/filealign: not a power of two: " + Twine(config->fileAlign));
1728   }
1729 
1730   // Handle /stack
1731   if (auto *arg = args.getLastArg(OPT_stack))
1732     parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1733 
1734   // Handle /guard:cf
1735   if (auto *arg = args.getLastArg(OPT_guard))
1736     parseGuard(arg->getValue());
1737 
1738   // Handle /heap
1739   if (auto *arg = args.getLastArg(OPT_heap))
1740     parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1741 
1742   // Handle /version
1743   if (auto *arg = args.getLastArg(OPT_version))
1744     parseVersion(arg->getValue(), &config->majorImageVersion,
1745                  &config->minorImageVersion);
1746 
1747   // Handle /subsystem
1748   if (auto *arg = args.getLastArg(OPT_subsystem))
1749     parseSubsystem(arg->getValue(), &config->subsystem,
1750                    &config->majorSubsystemVersion,
1751                    &config->minorSubsystemVersion);
1752 
1753   // Handle /osversion
1754   if (auto *arg = args.getLastArg(OPT_osversion)) {
1755     parseVersion(arg->getValue(), &config->majorOSVersion,
1756                  &config->minorOSVersion);
1757   } else {
1758     config->majorOSVersion = config->majorSubsystemVersion;
1759     config->minorOSVersion = config->minorSubsystemVersion;
1760   }
1761 
1762   // Handle /timestamp
1763   if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1764     if (arg->getOption().getID() == OPT_repro) {
1765       config->timestamp = 0;
1766       config->repro = true;
1767     } else {
1768       config->repro = false;
1769       StringRef value(arg->getValue());
1770       if (value.getAsInteger(0, config->timestamp))
1771         fatal(Twine("invalid timestamp: ") + value +
1772               ".  Expected 32-bit integer");
1773     }
1774   } else {
1775     config->repro = false;
1776     config->timestamp = time(nullptr);
1777   }
1778 
1779   // Handle /alternatename
1780   for (auto *arg : args.filtered(OPT_alternatename))
1781     parseAlternateName(arg->getValue());
1782 
1783   // Handle /include
1784   for (auto *arg : args.filtered(OPT_incl))
1785     addUndefined(arg->getValue());
1786 
1787   // Handle /implib
1788   if (auto *arg = args.getLastArg(OPT_implib))
1789     config->implib = arg->getValue();
1790 
1791   config->noimplib = args.hasArg(OPT_noimplib);
1792 
1793   // Handle /opt.
1794   bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1795   std::optional<ICFLevel> icfLevel;
1796   if (args.hasArg(OPT_profile))
1797     icfLevel = ICFLevel::None;
1798   unsigned tailMerge = 1;
1799   bool ltoDebugPM = false;
1800   for (auto *arg : args.filtered(OPT_opt)) {
1801     std::string str = StringRef(arg->getValue()).lower();
1802     SmallVector<StringRef, 1> vec;
1803     StringRef(str).split(vec, ',');
1804     for (StringRef s : vec) {
1805       if (s == "ref") {
1806         doGC = true;
1807       } else if (s == "noref") {
1808         doGC = false;
1809       } else if (s == "icf" || s.starts_with("icf=")) {
1810         icfLevel = ICFLevel::All;
1811       } else if (s == "safeicf") {
1812         icfLevel = ICFLevel::Safe;
1813       } else if (s == "noicf") {
1814         icfLevel = ICFLevel::None;
1815       } else if (s == "lldtailmerge") {
1816         tailMerge = 2;
1817       } else if (s == "nolldtailmerge") {
1818         tailMerge = 0;
1819       } else if (s == "ltodebugpassmanager") {
1820         ltoDebugPM = true;
1821       } else if (s == "noltodebugpassmanager") {
1822         ltoDebugPM = false;
1823       } else if (s.consume_front("lldlto=")) {
1824         if (s.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1825           error("/opt:lldlto: invalid optimization level: " + s);
1826       } else if (s.consume_front("lldltocgo=")) {
1827         config->ltoCgo.emplace();
1828         if (s.getAsInteger(10, *config->ltoCgo) || *config->ltoCgo > 3)
1829           error("/opt:lldltocgo: invalid codegen optimization level: " + s);
1830       } else if (s.consume_front("lldltojobs=")) {
1831         if (!get_threadpool_strategy(s))
1832           error("/opt:lldltojobs: invalid job count: " + s);
1833         config->thinLTOJobs = s.str();
1834       } else if (s.consume_front("lldltopartitions=")) {
1835         if (s.getAsInteger(10, config->ltoPartitions) ||
1836             config->ltoPartitions == 0)
1837           error("/opt:lldltopartitions: invalid partition count: " + s);
1838       } else if (s != "lbr" && s != "nolbr")
1839         error("/opt: unknown option: " + s);
1840     }
1841   }
1842 
1843   if (!icfLevel)
1844     icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
1845   config->doGC = doGC;
1846   config->doICF = *icfLevel;
1847   config->tailMerge =
1848       (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
1849   config->ltoDebugPassManager = ltoDebugPM;
1850 
1851   // Handle /lldsavetemps
1852   if (args.hasArg(OPT_lldsavetemps))
1853     config->saveTemps = true;
1854 
1855   // Handle /kill-at
1856   if (args.hasArg(OPT_kill_at))
1857     config->killAt = true;
1858 
1859   // Handle /lldltocache
1860   if (auto *arg = args.getLastArg(OPT_lldltocache))
1861     config->ltoCache = arg->getValue();
1862 
1863   // Handle /lldsavecachepolicy
1864   if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1865     config->ltoCachePolicy = CHECK(
1866         parseCachePruningPolicy(arg->getValue()),
1867         Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1868 
1869   // Handle /failifmismatch
1870   for (auto *arg : args.filtered(OPT_failifmismatch))
1871     checkFailIfMismatch(arg->getValue(), nullptr);
1872 
1873   // Handle /merge
1874   for (auto *arg : args.filtered(OPT_merge))
1875     parseMerge(arg->getValue());
1876 
1877   // Add default section merging rules after user rules. User rules take
1878   // precedence, but we will emit a warning if there is a conflict.
1879   parseMerge(".idata=.rdata");
1880   parseMerge(".didat=.rdata");
1881   parseMerge(".edata=.rdata");
1882   parseMerge(".xdata=.rdata");
1883   parseMerge(".bss=.data");
1884 
1885   if (config->mingw) {
1886     parseMerge(".ctors=.rdata");
1887     parseMerge(".dtors=.rdata");
1888     parseMerge(".CRT=.rdata");
1889   }
1890 
1891   // Handle /section
1892   for (auto *arg : args.filtered(OPT_section))
1893     parseSection(arg->getValue());
1894 
1895   // Handle /align
1896   if (auto *arg = args.getLastArg(OPT_align)) {
1897     parseNumbers(arg->getValue(), &config->align);
1898     if (!isPowerOf2_64(config->align))
1899       error("/align: not a power of two: " + StringRef(arg->getValue()));
1900     if (!args.hasArg(OPT_driver))
1901       warn("/align specified without /driver; image may not run");
1902   }
1903 
1904   // Handle /aligncomm
1905   for (auto *arg : args.filtered(OPT_aligncomm))
1906     parseAligncomm(arg->getValue());
1907 
1908   // Handle /manifestdependency.
1909   for (auto *arg : args.filtered(OPT_manifestdependency))
1910     config->manifestDependencies.insert(arg->getValue());
1911 
1912   // Handle /manifest and /manifest:
1913   if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1914     if (arg->getOption().getID() == OPT_manifest)
1915       config->manifest = Configuration::SideBySide;
1916     else
1917       parseManifest(arg->getValue());
1918   }
1919 
1920   // Handle /manifestuac
1921   if (auto *arg = args.getLastArg(OPT_manifestuac))
1922     parseManifestUAC(arg->getValue());
1923 
1924   // Handle /manifestfile
1925   if (auto *arg = args.getLastArg(OPT_manifestfile))
1926     config->manifestFile = arg->getValue();
1927 
1928   // Handle /manifestinput
1929   for (auto *arg : args.filtered(OPT_manifestinput))
1930     config->manifestInput.push_back(arg->getValue());
1931 
1932   if (!config->manifestInput.empty() &&
1933       config->manifest != Configuration::Embed) {
1934     fatal("/manifestinput: requires /manifest:embed");
1935   }
1936 
1937   // Handle /dwodir
1938   config->dwoDir = args.getLastArgValue(OPT_dwodir);
1939 
1940   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1941   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1942                              args.hasArg(OPT_thinlto_index_only_arg);
1943   config->thinLTOIndexOnlyArg =
1944       args.getLastArgValue(OPT_thinlto_index_only_arg);
1945   std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
1946            config->thinLTOPrefixReplaceNativeObject) =
1947       getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace);
1948   config->thinLTOObjectSuffixReplace =
1949       getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1950   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1951   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1952   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1953   // Handle miscellaneous boolean flags.
1954   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1955                                             OPT_lto_pgo_warn_mismatch_no, true);
1956   config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1957   config->allowIsolation =
1958       args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1959   config->incremental =
1960       args.hasFlag(OPT_incremental, OPT_incremental_no,
1961                    !config->doGC && config->doICF == ICFLevel::None &&
1962                        !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
1963   config->integrityCheck =
1964       args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1965   config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
1966   config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1967   for (auto *arg : args.filtered(OPT_swaprun))
1968     parseSwaprun(arg->getValue());
1969   config->terminalServerAware =
1970       !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1971   config->debugDwarf = debug == DebugKind::Dwarf;
1972   config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full;
1973   config->debugSymtab = debug == DebugKind::Symtab;
1974   config->autoImport =
1975       args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
1976   config->pseudoRelocs = args.hasFlag(
1977       OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
1978   config->callGraphProfileSort = args.hasFlag(
1979       OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
1980   config->stdcallFixup =
1981       args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
1982   config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
1983 
1984   if (args.hasFlag(OPT_inferasanlibs, OPT_inferasanlibs_no, false))
1985     warn("ignoring '/inferasanlibs', this flag is not supported");
1986 
1987   // Don't warn about long section names, such as .debug_info, for mingw or
1988   // when -debug:dwarf is requested.
1989   if (config->mingw || config->debugDwarf)
1990     config->warnLongSectionNames = false;
1991 
1992   if (config->incremental && args.hasArg(OPT_profile)) {
1993     warn("ignoring '/incremental' due to '/profile' specification");
1994     config->incremental = false;
1995   }
1996 
1997   if (config->incremental && args.hasArg(OPT_order)) {
1998     warn("ignoring '/incremental' due to '/order' specification");
1999     config->incremental = false;
2000   }
2001 
2002   if (config->incremental && config->doGC) {
2003     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
2004          "disable");
2005     config->incremental = false;
2006   }
2007 
2008   if (config->incremental && config->doICF != ICFLevel::None) {
2009     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
2010          "disable");
2011     config->incremental = false;
2012   }
2013 
2014   if (errorCount())
2015     return;
2016 
2017   std::set<sys::fs::UniqueID> wholeArchives;
2018   for (auto *arg : args.filtered(OPT_wholearchive_file))
2019     if (std::optional<StringRef> path = findFile(arg->getValue()))
2020       if (std::optional<sys::fs::UniqueID> id = getUniqueID(*path))
2021         wholeArchives.insert(*id);
2022 
2023   // A predicate returning true if a given path is an argument for
2024   // /wholearchive:, or /wholearchive is enabled globally.
2025   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
2026   // needs to be handled as "/wholearchive:foo.obj foo.obj".
2027   auto isWholeArchive = [&](StringRef path) -> bool {
2028     if (args.hasArg(OPT_wholearchive_flag))
2029       return true;
2030     if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
2031       return wholeArchives.count(*id);
2032     return false;
2033   };
2034 
2035   // Create a list of input files. These can be given as OPT_INPUT options
2036   // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
2037   // and OPT_end_lib.
2038   bool inLib = false;
2039   for (auto *arg : args) {
2040     switch (arg->getOption().getID()) {
2041     case OPT_end_lib:
2042       if (!inLib)
2043         error("stray " + arg->getSpelling());
2044       inLib = false;
2045       break;
2046     case OPT_start_lib:
2047       if (inLib)
2048         error("nested " + arg->getSpelling());
2049       inLib = true;
2050       break;
2051     case OPT_wholearchive_file:
2052       if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
2053         enqueuePath(*path, true, inLib);
2054       break;
2055     case OPT_INPUT:
2056       if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
2057         enqueuePath(*path, isWholeArchive(*path), inLib);
2058       break;
2059     default:
2060       // Ignore other options.
2061       break;
2062     }
2063   }
2064 
2065   // Read all input files given via the command line.
2066   run();
2067   if (errorCount())
2068     return;
2069 
2070   // We should have inferred a machine type by now from the input files, but if
2071   // not we assume x64.
2072   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
2073     warn("/machine is not specified. x64 is assumed");
2074     config->machine = AMD64;
2075     addWinSysRootLibSearchPaths();
2076   }
2077   config->wordsize = config->is64() ? 8 : 4;
2078 
2079   if (config->printSearchPaths) {
2080     SmallString<256> buffer;
2081     raw_svector_ostream stream(buffer);
2082     stream << "Library search paths:\n";
2083 
2084     for (StringRef path : searchPaths) {
2085       if (path == "")
2086         path = "(cwd)";
2087       stream << "  " << path << "\n";
2088     }
2089 
2090     message(buffer);
2091   }
2092 
2093   // Process files specified as /defaultlib. These must be processed after
2094   // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
2095   for (auto *arg : args.filtered(OPT_defaultlib))
2096     if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
2097       enqueuePath(*path, false, false);
2098   run();
2099   if (errorCount())
2100     return;
2101 
2102   // Handle /RELEASE
2103   if (args.hasArg(OPT_release))
2104     config->writeCheckSum = true;
2105 
2106   // Handle /safeseh, x86 only, on by default, except for mingw.
2107   if (config->machine == I386) {
2108     config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
2109     config->noSEH = args.hasArg(OPT_noseh);
2110   }
2111 
2112   // Handle /functionpadmin
2113   for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
2114     parseFunctionPadMin(arg);
2115 
2116   if (tar) {
2117     tar->append("response.txt",
2118                 createResponseFile(args, filePaths,
2119                                    ArrayRef<StringRef>(searchPaths).slice(1)));
2120   }
2121 
2122   // Handle /largeaddressaware
2123   config->largeAddressAware = args.hasFlag(
2124       OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
2125 
2126   // Handle /highentropyva
2127   config->highEntropyVA =
2128       config->is64() &&
2129       args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
2130 
2131   if (!config->dynamicBase &&
2132       (config->machine == ARMNT || config->machine == ARM64))
2133     error("/dynamicbase:no is not compatible with " +
2134           machineToStr(config->machine));
2135 
2136   // Handle /export
2137   for (auto *arg : args.filtered(OPT_export)) {
2138     Export e = parseExport(arg->getValue());
2139     if (config->machine == I386) {
2140       if (!isDecorated(e.name))
2141         e.name = saver().save("_" + e.name);
2142       if (!e.extName.empty() && !isDecorated(e.extName))
2143         e.extName = saver().save("_" + e.extName);
2144     }
2145     config->exports.push_back(e);
2146   }
2147 
2148   // Handle /def
2149   if (auto *arg = args.getLastArg(OPT_deffile)) {
2150     // parseModuleDefs mutates Config object.
2151     parseModuleDefs(arg->getValue());
2152   }
2153 
2154   // Handle generation of import library from a def file.
2155   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
2156     fixupExports();
2157     if (!config->noimplib)
2158       createImportLibrary(/*asLib=*/true);
2159     return;
2160   }
2161 
2162   // Windows specific -- if no /subsystem is given, we need to infer
2163   // that from entry point name.  Must happen before /entry handling,
2164   // and after the early return when just writing an import library.
2165   if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
2166     config->subsystem = inferSubsystem();
2167     if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
2168       fatal("subsystem must be defined");
2169   }
2170 
2171   // Handle /entry and /dll
2172   if (auto *arg = args.getLastArg(OPT_entry)) {
2173     config->entry = addUndefined(mangle(arg->getValue()));
2174   } else if (!config->entry && !config->noEntry) {
2175     if (args.hasArg(OPT_dll)) {
2176       StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
2177                                               : "_DllMainCRTStartup";
2178       config->entry = addUndefined(s);
2179     } else if (config->driverWdm) {
2180       // /driver:wdm implies /entry:_NtProcessStartup
2181       config->entry = addUndefined(mangle("_NtProcessStartup"));
2182     } else {
2183       // Windows specific -- If entry point name is not given, we need to
2184       // infer that from user-defined entry name.
2185       StringRef s = findDefaultEntry();
2186       if (s.empty())
2187         fatal("entry point must be defined");
2188       config->entry = addUndefined(s);
2189       log("Entry name inferred: " + s);
2190     }
2191   }
2192 
2193   // Handle /delayload
2194   for (auto *arg : args.filtered(OPT_delayload)) {
2195     config->delayLoads.insert(StringRef(arg->getValue()).lower());
2196     if (config->machine == I386) {
2197       config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
2198     } else {
2199       config->delayLoadHelper = addUndefined("__delayLoadHelper2");
2200     }
2201   }
2202 
2203   // Set default image name if neither /out or /def set it.
2204   if (config->outputFile.empty()) {
2205     config->outputFile = getOutputPath(
2206         (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue(),
2207         config->dll, config->driver);
2208   }
2209 
2210   // Fail early if an output file is not writable.
2211   if (auto e = tryCreateFile(config->outputFile)) {
2212     error("cannot open output file " + config->outputFile + ": " + e.message());
2213     return;
2214   }
2215 
2216   config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
2217   config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
2218 
2219   if (config->mapFile != "" && args.hasArg(OPT_map_info)) {
2220     for (auto *arg : args.filtered(OPT_map_info)) {
2221       std::string s = StringRef(arg->getValue()).lower();
2222       if (s == "exports")
2223         config->mapInfo = true;
2224       else
2225         error("unknown option: /mapinfo:" + s);
2226     }
2227   }
2228 
2229   if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
2230     warn("/lldmap and /map have the same output file '" + config->mapFile +
2231          "'.\n>>> ignoring /lldmap");
2232     config->lldmapFile.clear();
2233   }
2234 
2235   if (shouldCreatePDB) {
2236     // Put the PDB next to the image if no /pdb flag was passed.
2237     if (config->pdbPath.empty()) {
2238       config->pdbPath = config->outputFile;
2239       sys::path::replace_extension(config->pdbPath, ".pdb");
2240     }
2241 
2242     // The embedded PDB path should be the absolute path to the PDB if no
2243     // /pdbaltpath flag was passed.
2244     if (config->pdbAltPath.empty()) {
2245       config->pdbAltPath = config->pdbPath;
2246 
2247       // It's important to make the path absolute and remove dots.  This path
2248       // will eventually be written into the PE header, and certain Microsoft
2249       // tools won't work correctly if these assumptions are not held.
2250       sys::fs::make_absolute(config->pdbAltPath);
2251       sys::path::remove_dots(config->pdbAltPath);
2252     } else {
2253       // Don't do this earlier, so that ctx.OutputFile is ready.
2254       parsePDBAltPath();
2255     }
2256   }
2257 
2258   // Set default image base if /base is not given.
2259   if (config->imageBase == uint64_t(-1))
2260     config->imageBase = getDefaultImageBase();
2261 
2262   ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr);
2263   if (config->machine == I386) {
2264     ctx.symtab.addAbsolute("___safe_se_handler_table", 0);
2265     ctx.symtab.addAbsolute("___safe_se_handler_count", 0);
2266   }
2267 
2268   ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0);
2269   ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0);
2270   ctx.symtab.addAbsolute(mangle("__guard_flags"), 0);
2271   ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0);
2272   ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0);
2273   ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
2274   ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
2275   // Needed for MSVC 2017 15.5 CRT.
2276   ctx.symtab.addAbsolute(mangle("__enclave_config"), 0);
2277   // Needed for MSVC 2019 16.8 CRT.
2278   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2279   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0);
2280 
2281   if (config->pseudoRelocs) {
2282     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2283     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2284   }
2285   if (config->mingw) {
2286     ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0);
2287     ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0);
2288   }
2289 
2290   // This code may add new undefined symbols to the link, which may enqueue more
2291   // symbol resolution tasks, so we need to continue executing tasks until we
2292   // converge.
2293   do {
2294     // Windows specific -- if entry point is not found,
2295     // search for its mangled names.
2296     if (config->entry)
2297       mangleMaybe(config->entry);
2298 
2299     // Windows specific -- Make sure we resolve all dllexported symbols.
2300     for (Export &e : config->exports) {
2301       if (!e.forwardTo.empty())
2302         continue;
2303       e.sym = addUndefined(e.name);
2304       if (e.source != ExportSource::Directives)
2305         e.symbolName = mangleMaybe(e.sym);
2306     }
2307 
2308     // Add weak aliases. Weak aliases is a mechanism to give remaining
2309     // undefined symbols final chance to be resolved successfully.
2310     for (auto pair : config->alternateNames) {
2311       StringRef from = pair.first;
2312       StringRef to = pair.second;
2313       Symbol *sym = ctx.symtab.find(from);
2314       if (!sym)
2315         continue;
2316       if (auto *u = dyn_cast<Undefined>(sym))
2317         if (!u->weakAlias)
2318           u->weakAlias = ctx.symtab.addUndefined(to);
2319     }
2320 
2321     // If any inputs are bitcode files, the LTO code generator may create
2322     // references to library functions that are not explicit in the bitcode
2323     // file's symbol table. If any of those library functions are defined in a
2324     // bitcode file in an archive member, we need to arrange to use LTO to
2325     // compile those archive members by adding them to the link beforehand.
2326     if (!ctx.bitcodeFileInstances.empty())
2327       for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2328         ctx.symtab.addLibcall(s);
2329 
2330     // Windows specific -- if __load_config_used can be resolved, resolve it.
2331     if (ctx.symtab.findUnderscore("_load_config_used"))
2332       addUndefined(mangle("_load_config_used"));
2333 
2334     if (args.hasArg(OPT_include_optional)) {
2335       // Handle /includeoptional
2336       for (auto *arg : args.filtered(OPT_include_optional))
2337         if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue())))
2338           addUndefined(arg->getValue());
2339     }
2340   } while (run());
2341 
2342   // Create wrapped symbols for -wrap option.
2343   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2344   // Load more object files that might be needed for wrapped symbols.
2345   if (!wrapped.empty())
2346     while (run())
2347       ;
2348 
2349   if (config->autoImport || config->stdcallFixup) {
2350     // MinGW specific.
2351     // Load any further object files that might be needed for doing automatic
2352     // imports, and do stdcall fixups.
2353     //
2354     // For cases with no automatically imported symbols, this iterates once
2355     // over the symbol table and doesn't do anything.
2356     //
2357     // For the normal case with a few automatically imported symbols, this
2358     // should only need to be run once, since each new object file imported
2359     // is an import library and wouldn't add any new undefined references,
2360     // but there's nothing stopping the __imp_ symbols from coming from a
2361     // normal object file as well (although that won't be used for the
2362     // actual autoimport later on). If this pass adds new undefined references,
2363     // we won't iterate further to resolve them.
2364     //
2365     // If stdcall fixups only are needed for loading import entries from
2366     // a DLL without import library, this also just needs running once.
2367     // If it ends up pulling in more object files from static libraries,
2368     // (and maybe doing more stdcall fixups along the way), this would need
2369     // to loop these two calls.
2370     ctx.symtab.loadMinGWSymbols();
2371     run();
2372   }
2373 
2374   // At this point, we should not have any symbols that cannot be resolved.
2375   // If we are going to do codegen for link-time optimization, check for
2376   // unresolvable symbols first, so we don't spend time generating code that
2377   // will fail to link anyway.
2378   if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved)
2379     ctx.symtab.reportUnresolvable();
2380   if (errorCount())
2381     return;
2382 
2383   config->hadExplicitExports = !config->exports.empty();
2384   if (config->mingw) {
2385     // In MinGW, all symbols are automatically exported if no symbols
2386     // are chosen to be exported.
2387     maybeExportMinGWSymbols(args);
2388   }
2389 
2390   // Do LTO by compiling bitcode input files to a set of native COFF files then
2391   // link those files (unless -thinlto-index-only was given, in which case we
2392   // resolve symbols and write indices, but don't generate native code or link).
2393   ctx.symtab.compileBitcodeFiles();
2394 
2395   // If -thinlto-index-only is given, we should create only "index
2396   // files" and not object files. Index file creation is already done
2397   // in addCombinedLTOObject, so we are done if that's the case.
2398   if (config->thinLTOIndexOnly)
2399     return;
2400 
2401   // If we generated native object files from bitcode files, this resolves
2402   // references to the symbols we use from them.
2403   run();
2404 
2405   // Apply symbol renames for -wrap.
2406   if (!wrapped.empty())
2407     wrapSymbols(ctx, wrapped);
2408 
2409   // Resolve remaining undefined symbols and warn about imported locals.
2410   ctx.symtab.resolveRemainingUndefines();
2411   if (errorCount())
2412     return;
2413 
2414   if (config->mingw) {
2415     // Make sure the crtend.o object is the last object file. This object
2416     // file can contain terminating section chunks that need to be placed
2417     // last. GNU ld processes files and static libraries explicitly in the
2418     // order provided on the command line, while lld will pull in needed
2419     // files from static libraries only after the last object file on the
2420     // command line.
2421     for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end();
2422          i != e; i++) {
2423       ObjFile *file = *i;
2424       if (isCrtend(file->getName())) {
2425         ctx.objFileInstances.erase(i);
2426         ctx.objFileInstances.push_back(file);
2427         break;
2428       }
2429     }
2430   }
2431 
2432   // Windows specific -- when we are creating a .dll file, we also
2433   // need to create a .lib file. In MinGW mode, we only do that when the
2434   // -implib option is given explicitly, for compatibility with GNU ld.
2435   if (!config->exports.empty() || config->dll) {
2436     fixupExports();
2437     if (!config->noimplib && (!config->mingw || !config->implib.empty()))
2438       createImportLibrary(/*asLib=*/false);
2439     assignExportOrdinals();
2440   }
2441 
2442   // Handle /output-def (MinGW specific).
2443   if (auto *arg = args.getLastArg(OPT_output_def))
2444     writeDefFile(arg->getValue(), config->exports);
2445 
2446   // Set extra alignment for .comm symbols
2447   for (auto pair : config->alignComm) {
2448     StringRef name = pair.first;
2449     uint32_t alignment = pair.second;
2450 
2451     Symbol *sym = ctx.symtab.find(name);
2452     if (!sym) {
2453       warn("/aligncomm symbol " + name + " not found");
2454       continue;
2455     }
2456 
2457     // If the symbol isn't common, it must have been replaced with a regular
2458     // symbol, which will carry its own alignment.
2459     auto *dc = dyn_cast<DefinedCommon>(sym);
2460     if (!dc)
2461       continue;
2462 
2463     CommonChunk *c = dc->getChunk();
2464     c->setAlignment(std::max(c->getAlignment(), alignment));
2465   }
2466 
2467   // Windows specific -- Create an embedded or side-by-side manifest.
2468   // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2469   // also passed.
2470   if (config->manifest == Configuration::Embed)
2471     addBuffer(createManifestRes(), false, false);
2472   else if (config->manifest == Configuration::SideBySide ||
2473            (config->manifest == Configuration::Default &&
2474             !config->manifestDependencies.empty()))
2475     createSideBySideManifest();
2476 
2477   // Handle /order. We want to do this at this moment because we
2478   // need a complete list of comdat sections to warn on nonexistent
2479   // functions.
2480   if (auto *arg = args.getLastArg(OPT_order)) {
2481     if (args.hasArg(OPT_call_graph_ordering_file))
2482       error("/order and /call-graph-order-file may not be used together");
2483     parseOrderFile(arg->getValue());
2484     config->callGraphProfileSort = false;
2485   }
2486 
2487   // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2488   if (config->callGraphProfileSort) {
2489     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2490       parseCallGraphFile(arg->getValue());
2491     }
2492     readCallGraphsFromObjectFiles(ctx);
2493   }
2494 
2495   // Handle /print-symbol-order.
2496   if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2497     config->printSymbolOrder = arg->getValue();
2498 
2499   // Identify unreferenced COMDAT sections.
2500   if (config->doGC) {
2501     if (config->mingw) {
2502       // markLive doesn't traverse .eh_frame, but the personality function is
2503       // only reached that way. The proper solution would be to parse and
2504       // traverse the .eh_frame section, like the ELF linker does.
2505       // For now, just manually try to retain the known possible personality
2506       // functions. This doesn't bring in more object files, but only marks
2507       // functions that already have been included to be retained.
2508       for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0",
2509                             "rust_eh_personality"}) {
2510         Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n));
2511         if (d && !d->isGCRoot) {
2512           d->isGCRoot = true;
2513           config->gcroot.push_back(d);
2514         }
2515       }
2516     }
2517 
2518     markLive(ctx);
2519   }
2520 
2521   // Needs to happen after the last call to addFile().
2522   convertResources();
2523 
2524   // Identify identical COMDAT sections to merge them.
2525   if (config->doICF != ICFLevel::None) {
2526     findKeepUniqueSections(ctx);
2527     doICF(ctx);
2528   }
2529 
2530   // Write the result.
2531   writeResult(ctx);
2532 
2533   // Stop early so we can print the results.
2534   rootTimer.stop();
2535   if (config->showTiming)
2536     ctx.rootTimer.print();
2537 }
2538 
2539 } // namespace lld::coff
2540