xref: /freebsd/contrib/llvm-project/lld/COFF/Driver.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- Driver.cpp ---------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "Driver.h"
10349cc55cSDimitry Andric #include "COFFLinkerContext.h"
110b57cec5SDimitry Andric #include "Config.h"
120b57cec5SDimitry Andric #include "DebugTypes.h"
130b57cec5SDimitry Andric #include "ICF.h"
140b57cec5SDimitry Andric #include "InputFiles.h"
150b57cec5SDimitry Andric #include "MarkLive.h"
160b57cec5SDimitry Andric #include "MinGW.h"
170b57cec5SDimitry Andric #include "SymbolTable.h"
180b57cec5SDimitry Andric #include "Symbols.h"
190b57cec5SDimitry Andric #include "Writer.h"
200b57cec5SDimitry Andric #include "lld/Common/Args.h"
21bdd1243dSDimitry Andric #include "lld/Common/CommonLinkerContext.h"
220b57cec5SDimitry Andric #include "lld/Common/Driver.h"
230b57cec5SDimitry Andric #include "lld/Common/Filesystem.h"
240b57cec5SDimitry Andric #include "lld/Common/Timer.h"
250b57cec5SDimitry Andric #include "lld/Common/Version.h"
2681ad6265SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h"
270b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
280b57cec5SDimitry Andric #include "llvm/BinaryFormat/Magic.h"
29e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
3085868e8aSDimitry Andric #include "llvm/LTO/LTO.h"
310b57cec5SDimitry Andric #include "llvm/Object/ArchiveWriter.h"
320b57cec5SDimitry Andric #include "llvm/Object/COFFImportFile.h"
330b57cec5SDimitry Andric #include "llvm/Object/COFFModuleDefinition.h"
340b57cec5SDimitry Andric #include "llvm/Option/Arg.h"
350b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
360b57cec5SDimitry Andric #include "llvm/Option/Option.h"
37e8d8bef9SDimitry Andric #include "llvm/Support/BinaryStreamReader.h"
38480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
390b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
400b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
410b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
425ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
430b57cec5SDimitry Andric #include "llvm/Support/Path.h"
440b57cec5SDimitry Andric #include "llvm/Support/Process.h"
450b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
460b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
47*0fca6ea1SDimitry Andric #include "llvm/Support/TimeProfiler.h"
4881ad6265SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
490b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
5006c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
510b57cec5SDimitry Andric #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
520b57cec5SDimitry Andric #include <algorithm>
530b57cec5SDimitry Andric #include <future>
540b57cec5SDimitry Andric #include <memory>
55bdd1243dSDimitry Andric #include <optional>
5606c3fb27SDimitry Andric #include <tuple>
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric using namespace llvm;
590b57cec5SDimitry Andric using namespace llvm::object;
600b57cec5SDimitry Andric using namespace llvm::COFF;
61fe6060f1SDimitry Andric using namespace llvm::sys;
620b57cec5SDimitry Andric 
63bdd1243dSDimitry Andric namespace lld::coff {
640b57cec5SDimitry Andric 
link(ArrayRef<const char * > args,llvm::raw_ostream & stdoutOS,llvm::raw_ostream & stderrOS,bool exitEarly,bool disableOutput)6504eeddc0SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
6604eeddc0SDimitry Andric           llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
6706c3fb27SDimitry Andric   // This driver-specific context will be freed later by unsafeLldMain().
6804eeddc0SDimitry Andric   auto *ctx = new COFFLinkerContext;
69480093f4SDimitry Andric 
7004eeddc0SDimitry Andric   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
7104eeddc0SDimitry Andric   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
7204eeddc0SDimitry Andric   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now"
730b57cec5SDimitry Andric                                  " (use /errorlimit:0 to see all errors)";
7485868e8aSDimitry Andric 
75bdd1243dSDimitry Andric   ctx->driver.linkerMain(args);
760b57cec5SDimitry Andric 
7704eeddc0SDimitry Andric   return errorCount() == 0;
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric // Parse options of the form "old;new".
getOldNewOptions(opt::InputArgList & args,unsigned id)810b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
820b57cec5SDimitry Andric                                                         unsigned id) {
830b57cec5SDimitry Andric   auto *arg = args.getLastArg(id);
840b57cec5SDimitry Andric   if (!arg)
850b57cec5SDimitry Andric     return {"", ""};
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric   StringRef s = arg->getValue();
880b57cec5SDimitry Andric   std::pair<StringRef, StringRef> ret = s.split(';');
890b57cec5SDimitry Andric   if (ret.second.empty())
900b57cec5SDimitry Andric     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
910b57cec5SDimitry Andric   return ret;
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
9406c3fb27SDimitry Andric // Parse options of the form "old;new[;extra]".
9506c3fb27SDimitry Andric static std::tuple<StringRef, StringRef, StringRef>
getOldNewOptionsExtra(opt::InputArgList & args,unsigned id)9606c3fb27SDimitry Andric getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
9706c3fb27SDimitry Andric   auto [oldDir, second] = getOldNewOptions(args, id);
9806c3fb27SDimitry Andric   auto [newDir, extraDir] = second.split(';');
9906c3fb27SDimitry Andric   return {oldDir, newDir, extraDir};
10006c3fb27SDimitry Andric }
10106c3fb27SDimitry Andric 
102480093f4SDimitry Andric // Drop directory components and replace extension with
103480093f4SDimitry Andric // ".exe", ".dll" or ".sys".
getOutputPath(StringRef path,bool isDll,bool isDriver)104bdd1243dSDimitry Andric static std::string getOutputPath(StringRef path, bool isDll, bool isDriver) {
105480093f4SDimitry Andric   StringRef ext = ".exe";
106bdd1243dSDimitry Andric   if (isDll)
107480093f4SDimitry Andric     ext = ".dll";
108bdd1243dSDimitry Andric   else if (isDriver)
109480093f4SDimitry Andric     ext = ".sys";
110480093f4SDimitry Andric 
111480093f4SDimitry Andric   return (sys::path::stem(path) + ext).str();
1120b57cec5SDimitry Andric }
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric // Returns true if S matches /crtend.?\.o$/.
isCrtend(StringRef s)1150b57cec5SDimitry Andric static bool isCrtend(StringRef s) {
11606c3fb27SDimitry Andric   if (!s.ends_with(".o"))
1170b57cec5SDimitry Andric     return false;
1180b57cec5SDimitry Andric   s = s.drop_back(2);
11906c3fb27SDimitry Andric   if (s.ends_with("crtend"))
1200b57cec5SDimitry Andric     return true;
12106c3fb27SDimitry Andric   return !s.empty() && s.drop_back().ends_with("crtend");
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric // ErrorOr is not default constructible, so it cannot be used as the type
1250b57cec5SDimitry Andric // parameter of a future.
1260b57cec5SDimitry Andric // FIXME: We could open the file in createFutureForFile and avoid needing to
1270b57cec5SDimitry Andric // return an error here, but for the moment that would cost us a file descriptor
1280b57cec5SDimitry Andric // (a limited resource on Windows) for the duration that the future is pending.
1290b57cec5SDimitry Andric using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric // Create a std::future that opens and maps a file using the best strategy for
1320b57cec5SDimitry Andric // the host platform.
createFutureForFile(std::string path)1330b57cec5SDimitry Andric static std::future<MBErrPair> createFutureForFile(std::string path) {
134fe6060f1SDimitry Andric #if _WIN64
1350b57cec5SDimitry Andric   // On Windows, file I/O is relatively slow so it is best to do this
136fe6060f1SDimitry Andric   // asynchronously.  But 32-bit has issues with potentially launching tons
137fe6060f1SDimitry Andric   // of threads
1380b57cec5SDimitry Andric   auto strategy = std::launch::async;
1390b57cec5SDimitry Andric #else
1400b57cec5SDimitry Andric   auto strategy = std::launch::deferred;
1410b57cec5SDimitry Andric #endif
1420b57cec5SDimitry Andric   return std::async(strategy, [=]() {
143fe6060f1SDimitry Andric     auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
144fe6060f1SDimitry Andric                                          /*RequiresNullTerminator=*/false);
1450b57cec5SDimitry Andric     if (!mbOrErr)
1460b57cec5SDimitry Andric       return MBErrPair{nullptr, mbOrErr.getError()};
1470b57cec5SDimitry Andric     return MBErrPair{std::move(*mbOrErr), std::error_code()};
1480b57cec5SDimitry Andric   });
1490b57cec5SDimitry Andric }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric // Symbol names are mangled by prepending "_" on x86.
mangle(StringRef sym)152bdd1243dSDimitry Andric StringRef LinkerDriver::mangle(StringRef sym) {
153bdd1243dSDimitry Andric   assert(ctx.config.machine != IMAGE_FILE_MACHINE_UNKNOWN);
154bdd1243dSDimitry Andric   if (ctx.config.machine == I386)
15504eeddc0SDimitry Andric     return saver().save("_" + sym);
1560b57cec5SDimitry Andric   return sym;
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric 
getArch()159bdd1243dSDimitry Andric llvm::Triple::ArchType LinkerDriver::getArch() {
160*0fca6ea1SDimitry Andric   return getMachineArchType(ctx.config.machine);
16181ad6265SDimitry Andric }
16281ad6265SDimitry Andric 
findUnderscoreMangle(StringRef sym)163349cc55cSDimitry Andric bool LinkerDriver::findUnderscoreMangle(StringRef sym) {
164349cc55cSDimitry Andric   Symbol *s = ctx.symtab.findMangle(mangle(sym));
1650b57cec5SDimitry Andric   return s && !isa<Undefined>(s);
1660b57cec5SDimitry Andric }
1670b57cec5SDimitry Andric 
takeBuffer(std::unique_ptr<MemoryBuffer> mb)1680b57cec5SDimitry Andric MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
1690b57cec5SDimitry Andric   MemoryBufferRef mbref = *mb;
1700b57cec5SDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
1710b57cec5SDimitry Andric 
172bdd1243dSDimitry Andric   if (ctx.driver.tar)
173bdd1243dSDimitry Andric     ctx.driver.tar->append(relativeToRoot(mbref.getBufferIdentifier()),
1740b57cec5SDimitry Andric                            mbref.getBuffer());
1750b57cec5SDimitry Andric   return mbref;
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
addBuffer(std::unique_ptr<MemoryBuffer> mb,bool wholeArchive,bool lazy)1780b57cec5SDimitry Andric void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
17985868e8aSDimitry Andric                              bool wholeArchive, bool lazy) {
1800b57cec5SDimitry Andric   StringRef filename = mb->getBufferIdentifier();
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric   MemoryBufferRef mbref = takeBuffer(std::move(mb));
1830b57cec5SDimitry Andric   filePaths.push_back(filename);
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   // File type is detected by contents, not by file extension.
1860b57cec5SDimitry Andric   switch (identify_magic(mbref.getBuffer())) {
1870b57cec5SDimitry Andric   case file_magic::windows_resource:
1880b57cec5SDimitry Andric     resources.push_back(mbref);
1890b57cec5SDimitry Andric     break;
1900b57cec5SDimitry Andric   case file_magic::archive:
1910b57cec5SDimitry Andric     if (wholeArchive) {
1920b57cec5SDimitry Andric       std::unique_ptr<Archive> file =
1930b57cec5SDimitry Andric           CHECK(Archive::create(mbref), filename + ": failed to parse archive");
1940b57cec5SDimitry Andric       Archive *archive = file.get();
1950b57cec5SDimitry Andric       make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
1960b57cec5SDimitry Andric 
19785868e8aSDimitry Andric       int memberIndex = 0;
1980b57cec5SDimitry Andric       for (MemoryBufferRef m : getArchiveMembers(archive))
19985868e8aSDimitry Andric         addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
2000b57cec5SDimitry Andric       return;
2010b57cec5SDimitry Andric     }
202349cc55cSDimitry Andric     ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref));
2030b57cec5SDimitry Andric     break;
2040b57cec5SDimitry Andric   case file_magic::bitcode:
20504eeddc0SDimitry Andric     ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy));
2060b57cec5SDimitry Andric     break;
2070b57cec5SDimitry Andric   case file_magic::coff_object:
2080b57cec5SDimitry Andric   case file_magic::coff_import_library:
20904eeddc0SDimitry Andric     ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy));
2100b57cec5SDimitry Andric     break;
2110b57cec5SDimitry Andric   case file_magic::pdb:
212349cc55cSDimitry Andric     ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref));
2130b57cec5SDimitry Andric     break;
2140b57cec5SDimitry Andric   case file_magic::coff_cl_gl_object:
2150b57cec5SDimitry Andric     error(filename + ": is not a native COFF file. Recompile without /GL");
2160b57cec5SDimitry Andric     break;
2170b57cec5SDimitry Andric   case file_magic::pecoff_executable:
218bdd1243dSDimitry Andric     if (ctx.config.mingw) {
219349cc55cSDimitry Andric       ctx.symtab.addFile(make<DLLFile>(ctx, mbref));
220fe6060f1SDimitry Andric       break;
221fe6060f1SDimitry Andric     }
22206c3fb27SDimitry Andric     if (filename.ends_with_insensitive(".dll")) {
2230b57cec5SDimitry Andric       error(filename + ": bad file type. Did you specify a DLL instead of an "
2240b57cec5SDimitry Andric                        "import library?");
2250b57cec5SDimitry Andric       break;
2260b57cec5SDimitry Andric     }
227bdd1243dSDimitry Andric     [[fallthrough]];
2280b57cec5SDimitry Andric   default:
2290b57cec5SDimitry Andric     error(mbref.getBufferIdentifier() + ": unknown file type");
2300b57cec5SDimitry Andric     break;
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
enqueuePath(StringRef path,bool wholeArchive,bool lazy)23485868e8aSDimitry Andric void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
2355ffd83dbSDimitry Andric   auto future = std::make_shared<std::future<MBErrPair>>(
2365ffd83dbSDimitry Andric       createFutureForFile(std::string(path)));
2375ffd83dbSDimitry Andric   std::string pathStr = std::string(path);
2380b57cec5SDimitry Andric   enqueueTask([=]() {
2395f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("File: ", path);
24006c3fb27SDimitry Andric     auto [mb, ec] = future->get();
24106c3fb27SDimitry Andric     if (ec) {
24206c3fb27SDimitry Andric       // Retry reading the file (synchronously) now that we may have added
24306c3fb27SDimitry Andric       // winsysroot search paths from SymbolTable::addFile().
24406c3fb27SDimitry Andric       // Retrying synchronously is important for keeping the order of inputs
24506c3fb27SDimitry Andric       // consistent.
24606c3fb27SDimitry Andric       // This makes it so that if the user passes something in the winsysroot
24706c3fb27SDimitry Andric       // before something we can find with an architecture, we won't find the
24806c3fb27SDimitry Andric       // winsysroot file.
24906c3fb27SDimitry Andric       if (std::optional<StringRef> retryPath = findFileIfNew(pathStr)) {
25006c3fb27SDimitry Andric         auto retryMb = MemoryBuffer::getFile(*retryPath, /*IsText=*/false,
25106c3fb27SDimitry Andric                                              /*RequiresNullTerminator=*/false);
25206c3fb27SDimitry Andric         ec = retryMb.getError();
25306c3fb27SDimitry Andric         if (!ec)
25406c3fb27SDimitry Andric           mb = std::move(*retryMb);
25506c3fb27SDimitry Andric       } else {
25606c3fb27SDimitry Andric         // We've already handled this file.
25706c3fb27SDimitry Andric         return;
25806c3fb27SDimitry Andric       }
25906c3fb27SDimitry Andric     }
26006c3fb27SDimitry Andric     if (ec) {
26106c3fb27SDimitry Andric       std::string msg = "could not open '" + pathStr + "': " + ec.message();
2620b57cec5SDimitry Andric       // Check if the filename is a typo for an option flag. OptTable thinks
2630b57cec5SDimitry Andric       // that all args that are not known options and that start with / are
2640b57cec5SDimitry Andric       // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
2650b57cec5SDimitry Andric       // the option `/nodefaultlib` than a reference to a file in the root
2660b57cec5SDimitry Andric       // directory.
2670b57cec5SDimitry Andric       std::string nearest;
268bdd1243dSDimitry Andric       if (ctx.optTable.findNearest(pathStr, nearest) > 1)
2690b57cec5SDimitry Andric         error(msg);
2700b57cec5SDimitry Andric       else
2710b57cec5SDimitry Andric         error(msg + "; did you mean '" + nearest + "'");
2720b57cec5SDimitry Andric     } else
27306c3fb27SDimitry Andric       ctx.driver.addBuffer(std::move(mb), wholeArchive, lazy);
2740b57cec5SDimitry Andric   });
2750b57cec5SDimitry Andric }
2760b57cec5SDimitry Andric 
addArchiveBuffer(MemoryBufferRef mb,StringRef symName,StringRef parentName,uint64_t offsetInArchive)2770b57cec5SDimitry Andric void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
2780b57cec5SDimitry Andric                                     StringRef parentName,
2790b57cec5SDimitry Andric                                     uint64_t offsetInArchive) {
2800b57cec5SDimitry Andric   file_magic magic = identify_magic(mb.getBuffer());
2810b57cec5SDimitry Andric   if (magic == file_magic::coff_import_library) {
282349cc55cSDimitry Andric     InputFile *imp = make<ImportFile>(ctx, mb);
2830b57cec5SDimitry Andric     imp->parentName = parentName;
284349cc55cSDimitry Andric     ctx.symtab.addFile(imp);
2850b57cec5SDimitry Andric     return;
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   InputFile *obj;
2890b57cec5SDimitry Andric   if (magic == file_magic::coff_object) {
290349cc55cSDimitry Andric     obj = make<ObjFile>(ctx, mb);
2910b57cec5SDimitry Andric   } else if (magic == file_magic::bitcode) {
29204eeddc0SDimitry Andric     obj =
29304eeddc0SDimitry Andric         make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false);
294bdd1243dSDimitry Andric   } else if (magic == file_magic::coff_cl_gl_object) {
295bdd1243dSDimitry Andric     error(mb.getBufferIdentifier() +
296bdd1243dSDimitry Andric           ": is not a native COFF file. Recompile without /GL?");
297bdd1243dSDimitry Andric     return;
2980b57cec5SDimitry Andric   } else {
2990b57cec5SDimitry Andric     error("unknown file type: " + mb.getBufferIdentifier());
3000b57cec5SDimitry Andric     return;
3010b57cec5SDimitry Andric   }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   obj->parentName = parentName;
304349cc55cSDimitry Andric   ctx.symtab.addFile(obj);
3050b57cec5SDimitry Andric   log("Loaded " + toString(obj) + " for " + symName);
3060b57cec5SDimitry Andric }
3070b57cec5SDimitry Andric 
enqueueArchiveMember(const Archive::Child & c,const Archive::Symbol & sym,StringRef parentName)3080b57cec5SDimitry Andric void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
3090b57cec5SDimitry Andric                                         const Archive::Symbol &sym,
3100b57cec5SDimitry Andric                                         StringRef parentName) {
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric   auto reportBufferError = [=](Error &&e, StringRef childName) {
3130b57cec5SDimitry Andric     fatal("could not get the buffer for the member defining symbol " +
314bdd1243dSDimitry Andric           toCOFFString(ctx, sym) + ": " + parentName + "(" + childName +
315bdd1243dSDimitry Andric           "): " + toString(std::move(e)));
3160b57cec5SDimitry Andric   };
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   if (!c.getParent()->isThin()) {
3190b57cec5SDimitry Andric     uint64_t offsetInArchive = c.getChildOffset();
3200b57cec5SDimitry Andric     Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
3210b57cec5SDimitry Andric     if (!mbOrErr)
3220b57cec5SDimitry Andric       reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
3230b57cec5SDimitry Andric     MemoryBufferRef mb = mbOrErr.get();
3240b57cec5SDimitry Andric     enqueueTask([=]() {
3255f757f3fSDimitry Andric       llvm::TimeTraceScope timeScope("Archive: ", mb.getBufferIdentifier());
326bdd1243dSDimitry Andric       ctx.driver.addArchiveBuffer(mb, toCOFFString(ctx, sym), parentName,
3270b57cec5SDimitry Andric                                   offsetInArchive);
3280b57cec5SDimitry Andric     });
3290b57cec5SDimitry Andric     return;
3300b57cec5SDimitry Andric   }
3310b57cec5SDimitry Andric 
332bdd1243dSDimitry Andric   std::string childName =
333bdd1243dSDimitry Andric       CHECK(c.getFullName(),
3340b57cec5SDimitry Andric             "could not get the filename for the member defining symbol " +
335bdd1243dSDimitry Andric                 toCOFFString(ctx, sym));
3363bd749dbSDimitry Andric   auto future =
3373bd749dbSDimitry Andric       std::make_shared<std::future<MBErrPair>>(createFutureForFile(childName));
3380b57cec5SDimitry Andric   enqueueTask([=]() {
3390b57cec5SDimitry Andric     auto mbOrErr = future->get();
3400b57cec5SDimitry Andric     if (mbOrErr.second)
3410b57cec5SDimitry Andric       reportBufferError(errorCodeToError(mbOrErr.second), childName);
3425f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Archive: ",
3435f757f3fSDimitry Andric                                    mbOrErr.first->getBufferIdentifier());
34485868e8aSDimitry Andric     // Pass empty string as archive name so that the original filename is
34585868e8aSDimitry Andric     // used as the buffer identifier.
346bdd1243dSDimitry Andric     ctx.driver.addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
347bdd1243dSDimitry Andric                                 toCOFFString(ctx, sym), "",
348bdd1243dSDimitry Andric                                 /*OffsetInArchive=*/0);
3490b57cec5SDimitry Andric   });
3500b57cec5SDimitry Andric }
3510b57cec5SDimitry Andric 
isDecorated(StringRef sym)352bdd1243dSDimitry Andric bool LinkerDriver::isDecorated(StringRef sym) {
35306c3fb27SDimitry Andric   return sym.starts_with("@") || sym.contains("@@") || sym.starts_with("?") ||
354bdd1243dSDimitry Andric          (!ctx.config.mingw && sym.contains('@'));
3550b57cec5SDimitry Andric }
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric // Parses .drectve section contents and returns a list of files
3580b57cec5SDimitry Andric // specified by /defaultlib.
parseDirectives(InputFile * file)3590b57cec5SDimitry Andric void LinkerDriver::parseDirectives(InputFile *file) {
3600b57cec5SDimitry Andric   StringRef s = file->getDirectives();
3610b57cec5SDimitry Andric   if (s.empty())
3620b57cec5SDimitry Andric     return;
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   log("Directives: " + toString(file) + ": " + s);
3650b57cec5SDimitry Andric 
366bdd1243dSDimitry Andric   ArgParser parser(ctx);
3670b57cec5SDimitry Andric   // .drectve is always tokenized using Windows shell rules.
3680b57cec5SDimitry Andric   // /EXPORT: option can appear too many times, processing in fastpath.
3695ffd83dbSDimitry Andric   ParsedDirectives directives = parser.parseDirectives(s);
3700b57cec5SDimitry Andric 
3715ffd83dbSDimitry Andric   for (StringRef e : directives.exports) {
3720b57cec5SDimitry Andric     // If a common header file contains dllexported function
3730b57cec5SDimitry Andric     // declarations, many object files may end up with having the
3740b57cec5SDimitry Andric     // same /EXPORT options. In order to save cost of parsing them,
3750b57cec5SDimitry Andric     // we dedup them first.
3760b57cec5SDimitry Andric     if (!directivesExports.insert(e).second)
3770b57cec5SDimitry Andric       continue;
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric     Export exp = parseExport(e);
380bdd1243dSDimitry Andric     if (ctx.config.machine == I386 && ctx.config.mingw) {
3810b57cec5SDimitry Andric       if (!isDecorated(exp.name))
38204eeddc0SDimitry Andric         exp.name = saver().save("_" + exp.name);
3830b57cec5SDimitry Andric       if (!exp.extName.empty() && !isDecorated(exp.extName))
38404eeddc0SDimitry Andric         exp.extName = saver().save("_" + exp.extName);
3850b57cec5SDimitry Andric     }
38606c3fb27SDimitry Andric     exp.source = ExportSource::Directives;
387bdd1243dSDimitry Andric     ctx.config.exports.push_back(exp);
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3905ffd83dbSDimitry Andric   // Handle /include: in bulk.
3915ffd83dbSDimitry Andric   for (StringRef inc : directives.includes)
3925ffd83dbSDimitry Andric     addUndefined(inc);
3935ffd83dbSDimitry Andric 
39461cfbce3SDimitry Andric   // Handle /exclude-symbols: in bulk.
39561cfbce3SDimitry Andric   for (StringRef e : directives.excludes) {
39661cfbce3SDimitry Andric     SmallVector<StringRef, 2> vec;
39761cfbce3SDimitry Andric     e.split(vec, ',');
39861cfbce3SDimitry Andric     for (StringRef sym : vec)
39961cfbce3SDimitry Andric       excludedSymbols.insert(mangle(sym));
40061cfbce3SDimitry Andric   }
40161cfbce3SDimitry Andric 
402349cc55cSDimitry Andric   // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
4035ffd83dbSDimitry Andric   for (auto *arg : directives.args) {
4040b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
4050b57cec5SDimitry Andric     case OPT_aligncomm:
4060b57cec5SDimitry Andric       parseAligncomm(arg->getValue());
4070b57cec5SDimitry Andric       break;
4080b57cec5SDimitry Andric     case OPT_alternatename:
4090b57cec5SDimitry Andric       parseAlternateName(arg->getValue());
4100b57cec5SDimitry Andric       break;
4110b57cec5SDimitry Andric     case OPT_defaultlib:
41206c3fb27SDimitry Andric       if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
41385868e8aSDimitry Andric         enqueuePath(*path, false, false);
4140b57cec5SDimitry Andric       break;
4150b57cec5SDimitry Andric     case OPT_entry:
416*0fca6ea1SDimitry Andric       if (!arg->getValue()[0])
417*0fca6ea1SDimitry Andric         fatal("missing entry point symbol name");
418bdd1243dSDimitry Andric       ctx.config.entry = addUndefined(mangle(arg->getValue()));
4190b57cec5SDimitry Andric       break;
4200b57cec5SDimitry Andric     case OPT_failifmismatch:
4210b57cec5SDimitry Andric       checkFailIfMismatch(arg->getValue(), file);
4220b57cec5SDimitry Andric       break;
4230b57cec5SDimitry Andric     case OPT_incl:
4240b57cec5SDimitry Andric       addUndefined(arg->getValue());
4250b57cec5SDimitry Andric       break;
426349cc55cSDimitry Andric     case OPT_manifestdependency:
427bdd1243dSDimitry Andric       ctx.config.manifestDependencies.insert(arg->getValue());
428349cc55cSDimitry Andric       break;
4290b57cec5SDimitry Andric     case OPT_merge:
4300b57cec5SDimitry Andric       parseMerge(arg->getValue());
4310b57cec5SDimitry Andric       break;
4320b57cec5SDimitry Andric     case OPT_nodefaultlib:
43306c3fb27SDimitry Andric       ctx.config.noDefaultLibs.insert(findLib(arg->getValue()).lower());
434bdd1243dSDimitry Andric       break;
435bdd1243dSDimitry Andric     case OPT_release:
436bdd1243dSDimitry Andric       ctx.config.writeCheckSum = true;
4370b57cec5SDimitry Andric       break;
4380b57cec5SDimitry Andric     case OPT_section:
4390b57cec5SDimitry Andric       parseSection(arg->getValue());
4400b57cec5SDimitry Andric       break;
441fe6060f1SDimitry Andric     case OPT_stack:
442bdd1243dSDimitry Andric       parseNumbers(arg->getValue(), &ctx.config.stackReserve,
443bdd1243dSDimitry Andric                    &ctx.config.stackCommit);
444fe6060f1SDimitry Andric       break;
445e8d8bef9SDimitry Andric     case OPT_subsystem: {
446e8d8bef9SDimitry Andric       bool gotVersion = false;
447bdd1243dSDimitry Andric       parseSubsystem(arg->getValue(), &ctx.config.subsystem,
448bdd1243dSDimitry Andric                      &ctx.config.majorSubsystemVersion,
449bdd1243dSDimitry Andric                      &ctx.config.minorSubsystemVersion, &gotVersion);
450e8d8bef9SDimitry Andric       if (gotVersion) {
451bdd1243dSDimitry Andric         ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion;
452bdd1243dSDimitry Andric         ctx.config.minorOSVersion = ctx.config.minorSubsystemVersion;
453e8d8bef9SDimitry Andric       }
4540b57cec5SDimitry Andric       break;
455e8d8bef9SDimitry Andric     }
4560b57cec5SDimitry Andric     // Only add flags here that link.exe accepts in
4570b57cec5SDimitry Andric     // `#pragma comment(linker, "/flag")`-generated sections.
4580b57cec5SDimitry Andric     case OPT_editandcontinue:
4590b57cec5SDimitry Andric     case OPT_guardsym:
4600b57cec5SDimitry Andric     case OPT_throwingnew:
461cbe9438cSDimitry Andric     case OPT_inferasanlibs:
462cbe9438cSDimitry Andric     case OPT_inferasanlibs_no:
4630b57cec5SDimitry Andric       break;
4640b57cec5SDimitry Andric     default:
465cbe9438cSDimitry Andric       error(arg->getSpelling() + " is not allowed in .drectve (" +
466cbe9438cSDimitry Andric             toString(file) + ")");
4670b57cec5SDimitry Andric     }
4680b57cec5SDimitry Andric   }
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes
4720b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist.
findFile(StringRef filename)47306c3fb27SDimitry Andric StringRef LinkerDriver::findFile(StringRef filename) {
474bdd1243dSDimitry Andric   auto getFilename = [this](StringRef filename) -> StringRef {
475bdd1243dSDimitry Andric     if (ctx.config.vfs)
476bdd1243dSDimitry Andric       if (auto statOrErr = ctx.config.vfs->status(filename))
477753f127fSDimitry Andric         return saver().save(statOrErr->getName());
478753f127fSDimitry Andric     return filename;
479753f127fSDimitry Andric   };
480753f127fSDimitry Andric 
48106c3fb27SDimitry Andric   if (sys::path::is_absolute(filename))
482753f127fSDimitry Andric     return getFilename(filename);
4830b57cec5SDimitry Andric   bool hasExt = filename.contains('.');
4840b57cec5SDimitry Andric   for (StringRef dir : searchPaths) {
4850b57cec5SDimitry Andric     SmallString<128> path = dir;
4860b57cec5SDimitry Andric     sys::path::append(path, filename);
487753f127fSDimitry Andric     path = SmallString<128>{getFilename(path.str())};
4880b57cec5SDimitry Andric     if (sys::fs::exists(path.str()))
48904eeddc0SDimitry Andric       return saver().save(path.str());
4900b57cec5SDimitry Andric     if (!hasExt) {
4910b57cec5SDimitry Andric       path.append(".obj");
492753f127fSDimitry Andric       path = SmallString<128>{getFilename(path.str())};
4930b57cec5SDimitry Andric       if (sys::fs::exists(path.str()))
49404eeddc0SDimitry Andric         return saver().save(path.str());
4950b57cec5SDimitry Andric     }
4960b57cec5SDimitry Andric   }
4970b57cec5SDimitry Andric   return filename;
4980b57cec5SDimitry Andric }
4990b57cec5SDimitry Andric 
getUniqueID(StringRef path)500bdd1243dSDimitry Andric static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
5010b57cec5SDimitry Andric   sys::fs::UniqueID ret;
5020b57cec5SDimitry Andric   if (sys::fs::getUniqueID(path, ret))
503bdd1243dSDimitry Andric     return std::nullopt;
5040b57cec5SDimitry Andric   return ret;
5050b57cec5SDimitry Andric }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric // Resolves a file path. This never returns the same path
508bdd1243dSDimitry Andric // (in that case, it returns std::nullopt).
findFileIfNew(StringRef filename)50906c3fb27SDimitry Andric std::optional<StringRef> LinkerDriver::findFileIfNew(StringRef filename) {
51006c3fb27SDimitry Andric   StringRef path = findFile(filename);
5110b57cec5SDimitry Andric 
512bdd1243dSDimitry Andric   if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) {
5130b57cec5SDimitry Andric     bool seen = !visitedFiles.insert(*id).second;
5140b57cec5SDimitry Andric     if (seen)
515bdd1243dSDimitry Andric       return std::nullopt;
5160b57cec5SDimitry Andric   }
5170b57cec5SDimitry Andric 
51806c3fb27SDimitry Andric   if (path.ends_with_insensitive(".lib"))
51981ad6265SDimitry Andric     visitedLibs.insert(std::string(sys::path::filename(path).lower()));
5200b57cec5SDimitry Andric   return path;
5210b57cec5SDimitry Andric }
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to
5240b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead.
findLibMinGW(StringRef filename)52506c3fb27SDimitry Andric StringRef LinkerDriver::findLibMinGW(StringRef filename) {
5260b57cec5SDimitry Andric   if (filename.contains('/') || filename.contains('\\'))
5270b57cec5SDimitry Andric     return filename;
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric   SmallString<128> s = filename;
5300b57cec5SDimitry Andric   sys::path::replace_extension(s, ".a");
53104eeddc0SDimitry Andric   StringRef libName = saver().save("lib" + s.str());
53206c3fb27SDimitry Andric   return findFile(libName);
5330b57cec5SDimitry Andric }
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric // Find library file from search path.
findLib(StringRef filename)53606c3fb27SDimitry Andric StringRef LinkerDriver::findLib(StringRef filename) {
5370b57cec5SDimitry Andric   // Add ".lib" to Filename if that has no file extension.
5380b57cec5SDimitry Andric   bool hasExt = filename.contains('.');
5390b57cec5SDimitry Andric   if (!hasExt)
54004eeddc0SDimitry Andric     filename = saver().save(filename + ".lib");
54106c3fb27SDimitry Andric   StringRef ret = findFile(filename);
5420b57cec5SDimitry Andric   // For MinGW, if the find above didn't turn up anything, try
5430b57cec5SDimitry Andric   // looking for a MinGW formatted library name.
544bdd1243dSDimitry Andric   if (ctx.config.mingw && ret == filename)
54506c3fb27SDimitry Andric     return findLibMinGW(filename);
5460b57cec5SDimitry Andric   return ret;
5470b57cec5SDimitry Andric }
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into
5500b57cec5SDimitry Andric // consideration. This never returns the same path (in that case,
551bdd1243dSDimitry Andric // it returns std::nullopt).
findLibIfNew(StringRef filename)55206c3fb27SDimitry Andric std::optional<StringRef> LinkerDriver::findLibIfNew(StringRef filename) {
553bdd1243dSDimitry Andric   if (ctx.config.noDefaultLibAll)
554bdd1243dSDimitry Andric     return std::nullopt;
5550b57cec5SDimitry Andric   if (!visitedLibs.insert(filename.lower()).second)
556bdd1243dSDimitry Andric     return std::nullopt;
5570b57cec5SDimitry Andric 
55806c3fb27SDimitry Andric   StringRef path = findLib(filename);
559bdd1243dSDimitry Andric   if (ctx.config.noDefaultLibs.count(path.lower()))
560bdd1243dSDimitry Andric     return std::nullopt;
5610b57cec5SDimitry Andric 
562bdd1243dSDimitry Andric   if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
5630b57cec5SDimitry Andric     if (!visitedFiles.insert(*id).second)
564bdd1243dSDimitry Andric       return std::nullopt;
5650b57cec5SDimitry Andric   return path;
5660b57cec5SDimitry Andric }
5670b57cec5SDimitry Andric 
detectWinSysRoot(const opt::InputArgList & Args)56881ad6265SDimitry Andric void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
56981ad6265SDimitry Andric   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
57081ad6265SDimitry Andric 
57181ad6265SDimitry Andric   // Check the command line first, that's the user explicitly telling us what to
57281ad6265SDimitry Andric   // use. Check the environment next, in case we're being invoked from a VS
57381ad6265SDimitry Andric   // command prompt. Failing that, just try to find the newest Visual Studio
57481ad6265SDimitry Andric   // version we can and use its default VC toolchain.
575bdd1243dSDimitry Andric   std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
57681ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_vctoolsdir))
57781ad6265SDimitry Andric     VCToolsDir = A->getValue();
57881ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_vctoolsversion))
57981ad6265SDimitry Andric     VCToolsVersion = A->getValue();
58081ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_winsysroot))
58181ad6265SDimitry Andric     WinSysRoot = A->getValue();
58281ad6265SDimitry Andric   if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
58381ad6265SDimitry Andric                                      WinSysRoot, vcToolChainPath, vsLayout) &&
58481ad6265SDimitry Andric       (Args.hasArg(OPT_lldignoreenv) ||
58581ad6265SDimitry Andric        !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
58606c3fb27SDimitry Andric       !findVCToolChainViaSetupConfig(*VFS, {}, vcToolChainPath, vsLayout) &&
58781ad6265SDimitry Andric       !findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
58881ad6265SDimitry Andric     return;
58981ad6265SDimitry Andric 
59081ad6265SDimitry Andric   // If the VC environment hasn't been configured (perhaps because the user did
59181ad6265SDimitry Andric   // not run vcvarsall), try to build a consistent link environment.  If the
59281ad6265SDimitry Andric   // environment variable is set however, assume the user knows what they're
59381ad6265SDimitry Andric   // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
59481ad6265SDimitry Andric   // vars.
59581ad6265SDimitry Andric   if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
59681ad6265SDimitry Andric     diaPath = A->getValue();
59781ad6265SDimitry Andric     if (A->getOption().getID() == OPT_winsysroot)
59881ad6265SDimitry Andric       path::append(diaPath, "DIA SDK");
59981ad6265SDimitry Andric   }
60081ad6265SDimitry Andric   useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
60181ad6265SDimitry Andric                          !Process::GetEnv("LIB") ||
60281ad6265SDimitry Andric                          Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
60381ad6265SDimitry Andric   if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
60481ad6265SDimitry Andric       Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
605bdd1243dSDimitry Andric     std::optional<StringRef> WinSdkDir, WinSdkVersion;
60681ad6265SDimitry Andric     if (auto *A = Args.getLastArg(OPT_winsdkdir))
60781ad6265SDimitry Andric       WinSdkDir = A->getValue();
60881ad6265SDimitry Andric     if (auto *A = Args.getLastArg(OPT_winsdkversion))
60981ad6265SDimitry Andric       WinSdkVersion = A->getValue();
61081ad6265SDimitry Andric 
61181ad6265SDimitry Andric     if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
61281ad6265SDimitry Andric       std::string UniversalCRTSdkPath;
61381ad6265SDimitry Andric       std::string UCRTVersion;
61481ad6265SDimitry Andric       if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
61581ad6265SDimitry Andric                                 UniversalCRTSdkPath, UCRTVersion)) {
61681ad6265SDimitry Andric         universalCRTLibPath = UniversalCRTSdkPath;
61781ad6265SDimitry Andric         path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
61881ad6265SDimitry Andric       }
61981ad6265SDimitry Andric     }
62081ad6265SDimitry Andric 
62181ad6265SDimitry Andric     std::string sdkPath;
62281ad6265SDimitry Andric     std::string windowsSDKIncludeVersion;
62381ad6265SDimitry Andric     std::string windowsSDKLibVersion;
62481ad6265SDimitry Andric     if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
62581ad6265SDimitry Andric                          sdkMajor, windowsSDKIncludeVersion,
62681ad6265SDimitry Andric                          windowsSDKLibVersion)) {
62781ad6265SDimitry Andric       windowsSdkLibPath = sdkPath;
62881ad6265SDimitry Andric       path::append(windowsSdkLibPath, "Lib");
62981ad6265SDimitry Andric       if (sdkMajor >= 8)
63081ad6265SDimitry Andric         path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
63181ad6265SDimitry Andric     }
63281ad6265SDimitry Andric   }
63381ad6265SDimitry Andric }
63481ad6265SDimitry Andric 
addClangLibSearchPaths(const std::string & argv0)63506c3fb27SDimitry Andric void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
63606c3fb27SDimitry Andric   std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
63706c3fb27SDimitry Andric   SmallString<128> binDir(lldBinary);
63806c3fb27SDimitry Andric   sys::path::remove_filename(binDir);                 // remove lld-link.exe
63906c3fb27SDimitry Andric   StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
64006c3fb27SDimitry Andric 
64106c3fb27SDimitry Andric   SmallString<128> libDir(rootDir);
64206c3fb27SDimitry Andric   sys::path::append(libDir, "lib");
64306c3fb27SDimitry Andric 
64406c3fb27SDimitry Andric   // Add the resource dir library path
64506c3fb27SDimitry Andric   SmallString<128> runtimeLibDir(rootDir);
6463bd749dbSDimitry Andric   sys::path::append(runtimeLibDir, "lib", "clang",
6473bd749dbSDimitry Andric                     std::to_string(LLVM_VERSION_MAJOR), "lib");
64806c3fb27SDimitry Andric   // Resource dir + osname, which is hardcoded to windows since we are in the
64906c3fb27SDimitry Andric   // COFF driver.
65006c3fb27SDimitry Andric   SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
65106c3fb27SDimitry Andric   sys::path::append(runtimeLibDirWithOS, "windows");
65206c3fb27SDimitry Andric 
6533bd749dbSDimitry Andric   searchPaths.push_back(saver().save(runtimeLibDirWithOS.str()));
6543bd749dbSDimitry Andric   searchPaths.push_back(saver().save(runtimeLibDir.str()));
6553bd749dbSDimitry Andric   searchPaths.push_back(saver().save(libDir.str()));
65606c3fb27SDimitry Andric }
65706c3fb27SDimitry Andric 
addWinSysRootLibSearchPaths()65881ad6265SDimitry Andric void LinkerDriver::addWinSysRootLibSearchPaths() {
65981ad6265SDimitry Andric   if (!diaPath.empty()) {
66081ad6265SDimitry Andric     // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
66181ad6265SDimitry Andric     path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
66281ad6265SDimitry Andric     searchPaths.push_back(saver().save(diaPath.str()));
66381ad6265SDimitry Andric   }
66481ad6265SDimitry Andric   if (useWinSysRootLibPath) {
66581ad6265SDimitry Andric     searchPaths.push_back(saver().save(getSubDirectoryPath(
66681ad6265SDimitry Andric         SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
66781ad6265SDimitry Andric     searchPaths.push_back(saver().save(
66881ad6265SDimitry Andric         getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
66981ad6265SDimitry Andric                             getArch(), "atlmfc")));
67081ad6265SDimitry Andric   }
67181ad6265SDimitry Andric   if (!universalCRTLibPath.empty()) {
67281ad6265SDimitry Andric     StringRef ArchName = archToWindowsSDKArch(getArch());
67381ad6265SDimitry Andric     if (!ArchName.empty()) {
67481ad6265SDimitry Andric       path::append(universalCRTLibPath, ArchName);
67581ad6265SDimitry Andric       searchPaths.push_back(saver().save(universalCRTLibPath.str()));
67681ad6265SDimitry Andric     }
67781ad6265SDimitry Andric   }
67881ad6265SDimitry Andric   if (!windowsSdkLibPath.empty()) {
67981ad6265SDimitry Andric     std::string path;
68081ad6265SDimitry Andric     if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
68181ad6265SDimitry Andric                                       path))
68281ad6265SDimitry Andric       searchPaths.push_back(saver().save(path));
68381ad6265SDimitry Andric   }
68481ad6265SDimitry Andric }
68581ad6265SDimitry Andric 
6860b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths.
addLibSearchPaths()6870b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() {
688bdd1243dSDimitry Andric   std::optional<std::string> envOpt = Process::GetEnv("LIB");
68981ad6265SDimitry Andric   if (!envOpt)
6900b57cec5SDimitry Andric     return;
69104eeddc0SDimitry Andric   StringRef env = saver().save(*envOpt);
6920b57cec5SDimitry Andric   while (!env.empty()) {
6930b57cec5SDimitry Andric     StringRef path;
6940b57cec5SDimitry Andric     std::tie(path, env) = env.split(';');
6950b57cec5SDimitry Andric     searchPaths.push_back(path);
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric 
addUndefined(StringRef name)6990b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) {
700349cc55cSDimitry Andric   Symbol *b = ctx.symtab.addUndefined(name);
7010b57cec5SDimitry Andric   if (!b->isGCRoot) {
7020b57cec5SDimitry Andric     b->isGCRoot = true;
703bdd1243dSDimitry Andric     ctx.config.gcroot.push_back(b);
7040b57cec5SDimitry Andric   }
7050b57cec5SDimitry Andric   return b;
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
mangleMaybe(Symbol * s)7080b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) {
7090b57cec5SDimitry Andric   // If the plain symbol name has already been resolved, do nothing.
7100b57cec5SDimitry Andric   Undefined *unmangled = dyn_cast<Undefined>(s);
7110b57cec5SDimitry Andric   if (!unmangled)
7120b57cec5SDimitry Andric     return "";
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric   // Otherwise, see if a similar, mangled symbol exists in the symbol table.
715349cc55cSDimitry Andric   Symbol *mangled = ctx.symtab.findMangle(unmangled->getName());
7160b57cec5SDimitry Andric   if (!mangled)
7170b57cec5SDimitry Andric     return "";
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   // If we find a similar mangled symbol, make this an alias to it and return
7200b57cec5SDimitry Andric   // its name.
7210b57cec5SDimitry Andric   log(unmangled->getName() + " aliased to " + mangled->getName());
722349cc55cSDimitry Andric   unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName());
7230b57cec5SDimitry Andric   return mangled->getName();
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric // Windows specific -- find default entry point name.
7270b57cec5SDimitry Andric //
7280b57cec5SDimitry Andric // There are four different entry point functions for Windows executables,
7290b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function
7300b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function.
findDefaultEntry()7310b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() {
732bdd1243dSDimitry Andric   assert(ctx.config.subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
7330b57cec5SDimitry Andric          "must handle /subsystem before calling this");
7340b57cec5SDimitry Andric 
735bdd1243dSDimitry Andric   if (ctx.config.mingw)
736bdd1243dSDimitry Andric     return mangle(ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
7370b57cec5SDimitry Andric                       ? "WinMainCRTStartup"
7380b57cec5SDimitry Andric                       : "mainCRTStartup");
7390b57cec5SDimitry Andric 
740bdd1243dSDimitry Andric   if (ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
7410b57cec5SDimitry Andric     if (findUnderscoreMangle("wWinMain")) {
7420b57cec5SDimitry Andric       if (!findUnderscoreMangle("WinMain"))
7430b57cec5SDimitry Andric         return mangle("wWinMainCRTStartup");
7440b57cec5SDimitry Andric       warn("found both wWinMain and WinMain; using latter");
7450b57cec5SDimitry Andric     }
7460b57cec5SDimitry Andric     return mangle("WinMainCRTStartup");
7470b57cec5SDimitry Andric   }
7480b57cec5SDimitry Andric   if (findUnderscoreMangle("wmain")) {
7490b57cec5SDimitry Andric     if (!findUnderscoreMangle("main"))
7500b57cec5SDimitry Andric       return mangle("wmainCRTStartup");
7510b57cec5SDimitry Andric     warn("found both wmain and main; using latter");
7520b57cec5SDimitry Andric   }
7530b57cec5SDimitry Andric   return mangle("mainCRTStartup");
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric 
inferSubsystem()7560b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() {
757bdd1243dSDimitry Andric   if (ctx.config.dll)
7580b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
759bdd1243dSDimitry Andric   if (ctx.config.mingw)
7600b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
7610b57cec5SDimitry Andric   // Note that link.exe infers the subsystem from the presence of these
7620b57cec5SDimitry Andric   // functions even if /entry: or /nodefaultlib are passed which causes them
7630b57cec5SDimitry Andric   // to not be called.
7640b57cec5SDimitry Andric   bool haveMain = findUnderscoreMangle("main");
7650b57cec5SDimitry Andric   bool haveWMain = findUnderscoreMangle("wmain");
7660b57cec5SDimitry Andric   bool haveWinMain = findUnderscoreMangle("WinMain");
7670b57cec5SDimitry Andric   bool haveWWinMain = findUnderscoreMangle("wWinMain");
7680b57cec5SDimitry Andric   if (haveMain || haveWMain) {
7690b57cec5SDimitry Andric     if (haveWinMain || haveWWinMain) {
7700b57cec5SDimitry Andric       warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
7710b57cec5SDimitry Andric            (haveWinMain ? "WinMain" : "wWinMain") +
7720b57cec5SDimitry Andric            "; defaulting to /subsystem:console");
7730b57cec5SDimitry Andric     }
7740b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
7750b57cec5SDimitry Andric   }
7760b57cec5SDimitry Andric   if (haveWinMain || haveWWinMain)
7770b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
7780b57cec5SDimitry Andric   return IMAGE_SUBSYSTEM_UNKNOWN;
7790b57cec5SDimitry Andric }
7800b57cec5SDimitry Andric 
getDefaultImageBase()781bdd1243dSDimitry Andric uint64_t LinkerDriver::getDefaultImageBase() {
782bdd1243dSDimitry Andric   if (ctx.config.is64())
783bdd1243dSDimitry Andric     return ctx.config.dll ? 0x180000000 : 0x140000000;
784bdd1243dSDimitry Andric   return ctx.config.dll ? 0x10000000 : 0x400000;
7850b57cec5SDimitry Andric }
7860b57cec5SDimitry Andric 
rewritePath(StringRef s)787fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) {
788fe6060f1SDimitry Andric   if (fs::exists(s))
789fe6060f1SDimitry Andric     return relativeToRoot(s);
790fe6060f1SDimitry Andric   return std::string(s);
791fe6060f1SDimitry Andric }
792fe6060f1SDimitry Andric 
793fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run
794fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce.
createResponseFile(const opt::InputArgList & args,ArrayRef<StringRef> filePaths,ArrayRef<StringRef> searchPaths)7950b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args,
7960b57cec5SDimitry Andric                                       ArrayRef<StringRef> filePaths,
7970b57cec5SDimitry Andric                                       ArrayRef<StringRef> searchPaths) {
7980b57cec5SDimitry Andric   SmallString<0> data;
7990b57cec5SDimitry Andric   raw_svector_ostream os(data);
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric   for (auto *arg : args) {
8020b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
8030b57cec5SDimitry Andric     case OPT_linkrepro:
80485868e8aSDimitry Andric     case OPT_reproduce:
8050b57cec5SDimitry Andric     case OPT_INPUT:
8060b57cec5SDimitry Andric     case OPT_defaultlib:
8070b57cec5SDimitry Andric     case OPT_libpath:
80881ad6265SDimitry Andric     case OPT_winsysroot:
8090b57cec5SDimitry Andric       break;
810fe6060f1SDimitry Andric     case OPT_call_graph_ordering_file:
811fe6060f1SDimitry Andric     case OPT_deffile:
812349cc55cSDimitry Andric     case OPT_manifestinput:
813fe6060f1SDimitry Andric     case OPT_natvis:
814fe6060f1SDimitry Andric       os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
815fe6060f1SDimitry Andric       break;
816fe6060f1SDimitry Andric     case OPT_order: {
817fe6060f1SDimitry Andric       StringRef orderFile = arg->getValue();
818fe6060f1SDimitry Andric       orderFile.consume_front("@");
819fe6060f1SDimitry Andric       os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
820fe6060f1SDimitry Andric       break;
821fe6060f1SDimitry Andric     }
822fe6060f1SDimitry Andric     case OPT_pdbstream: {
823fe6060f1SDimitry Andric       const std::pair<StringRef, StringRef> nameFile =
824fe6060f1SDimitry Andric           StringRef(arg->getValue()).split("=");
825fe6060f1SDimitry Andric       os << arg->getSpelling() << nameFile.first << '='
826fe6060f1SDimitry Andric          << quote(rewritePath(nameFile.second)) << '\n';
827fe6060f1SDimitry Andric       break;
828fe6060f1SDimitry Andric     }
8290b57cec5SDimitry Andric     case OPT_implib:
830349cc55cSDimitry Andric     case OPT_manifestfile:
8310b57cec5SDimitry Andric     case OPT_pdb:
8325ffd83dbSDimitry Andric     case OPT_pdbstripped:
8330b57cec5SDimitry Andric     case OPT_out:
8340b57cec5SDimitry Andric       os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
8350b57cec5SDimitry Andric       break;
8360b57cec5SDimitry Andric     default:
8370b57cec5SDimitry Andric       os << toString(*arg) << "\n";
8380b57cec5SDimitry Andric     }
8390b57cec5SDimitry Andric   }
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   for (StringRef path : searchPaths) {
8420b57cec5SDimitry Andric     std::string relPath = relativeToRoot(path);
8430b57cec5SDimitry Andric     os << "/libpath:" << quote(relPath) << "\n";
8440b57cec5SDimitry Andric   }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   for (StringRef path : filePaths)
8470b57cec5SDimitry Andric     os << quote(relativeToRoot(path)) << "\n";
8480b57cec5SDimitry Andric 
8497a6dacacSDimitry Andric   return std::string(data);
8500b57cec5SDimitry Andric }
8510b57cec5SDimitry Andric 
parseDebugTypes(const opt::InputArgList & args)8520b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) {
8530b57cec5SDimitry Andric   unsigned debugTypes = static_cast<unsigned>(DebugType::None);
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric   if (auto *a = args.getLastArg(OPT_debugtype)) {
8560b57cec5SDimitry Andric     SmallVector<StringRef, 3> types;
8570b57cec5SDimitry Andric     StringRef(a->getValue())
8580b57cec5SDimitry Andric         .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric     for (StringRef type : types) {
8610b57cec5SDimitry Andric       unsigned v = StringSwitch<unsigned>(type.lower())
8620b57cec5SDimitry Andric                        .Case("cv", static_cast<unsigned>(DebugType::CV))
8630b57cec5SDimitry Andric                        .Case("pdata", static_cast<unsigned>(DebugType::PData))
8640b57cec5SDimitry Andric                        .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
8650b57cec5SDimitry Andric                        .Default(0);
8660b57cec5SDimitry Andric       if (v == 0) {
8670b57cec5SDimitry Andric         warn("/debugtype: unknown option '" + type + "'");
8680b57cec5SDimitry Andric         continue;
8690b57cec5SDimitry Andric       }
8700b57cec5SDimitry Andric       debugTypes |= v;
8710b57cec5SDimitry Andric     }
8720b57cec5SDimitry Andric     return debugTypes;
8730b57cec5SDimitry Andric   }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric   // Default debug types
8760b57cec5SDimitry Andric   debugTypes = static_cast<unsigned>(DebugType::CV);
8770b57cec5SDimitry Andric   if (args.hasArg(OPT_driver))
8780b57cec5SDimitry Andric     debugTypes |= static_cast<unsigned>(DebugType::PData);
8790b57cec5SDimitry Andric   if (args.hasArg(OPT_profile))
8800b57cec5SDimitry Andric     debugTypes |= static_cast<unsigned>(DebugType::Fixup);
8810b57cec5SDimitry Andric 
8820b57cec5SDimitry Andric   return debugTypes;
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
getMapFile(const opt::InputArgList & args,opt::OptSpecifier os,opt::OptSpecifier osFile)885bdd1243dSDimitry Andric std::string LinkerDriver::getMapFile(const opt::InputArgList &args,
886bdd1243dSDimitry Andric                                      opt::OptSpecifier os,
887bdd1243dSDimitry Andric                                      opt::OptSpecifier osFile) {
8885ffd83dbSDimitry Andric   auto *arg = args.getLastArg(os, osFile);
8890b57cec5SDimitry Andric   if (!arg)
8900b57cec5SDimitry Andric     return "";
8915ffd83dbSDimitry Andric   if (arg->getOption().getID() == osFile.getID())
8920b57cec5SDimitry Andric     return arg->getValue();
8930b57cec5SDimitry Andric 
8945ffd83dbSDimitry Andric   assert(arg->getOption().getID() == os.getID());
895bdd1243dSDimitry Andric   StringRef outFile = ctx.config.outputFile;
8960b57cec5SDimitry Andric   return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
8970b57cec5SDimitry Andric }
8980b57cec5SDimitry Andric 
getImplibPath()899bdd1243dSDimitry Andric std::string LinkerDriver::getImplibPath() {
900bdd1243dSDimitry Andric   if (!ctx.config.implib.empty())
901bdd1243dSDimitry Andric     return std::string(ctx.config.implib);
902bdd1243dSDimitry Andric   SmallString<128> out = StringRef(ctx.config.outputFile);
9030b57cec5SDimitry Andric   sys::path::replace_extension(out, ".lib");
9047a6dacacSDimitry Andric   return std::string(out);
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric 
90785868e8aSDimitry Andric // The import name is calculated as follows:
9080b57cec5SDimitry Andric //
9090b57cec5SDimitry Andric //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
9100b57cec5SDimitry Andric //   -----+----------------+---------------------+------------------
9110b57cec5SDimitry Andric //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
9120b57cec5SDimitry Andric //    LIB | {value}        | {value}.dll         | {output name}.dll
9130b57cec5SDimitry Andric //
getImportName(bool asLib)914bdd1243dSDimitry Andric std::string LinkerDriver::getImportName(bool asLib) {
9150b57cec5SDimitry Andric   SmallString<128> out;
9160b57cec5SDimitry Andric 
917bdd1243dSDimitry Andric   if (ctx.config.importName.empty()) {
918bdd1243dSDimitry Andric     out.assign(sys::path::filename(ctx.config.outputFile));
9190b57cec5SDimitry Andric     if (asLib)
9200b57cec5SDimitry Andric       sys::path::replace_extension(out, ".dll");
9210b57cec5SDimitry Andric   } else {
922bdd1243dSDimitry Andric     out.assign(ctx.config.importName);
9230b57cec5SDimitry Andric     if (!sys::path::has_extension(out))
9240b57cec5SDimitry Andric       sys::path::replace_extension(out,
925bdd1243dSDimitry Andric                                    (ctx.config.dll || asLib) ? ".dll" : ".exe");
9260b57cec5SDimitry Andric   }
9270b57cec5SDimitry Andric 
9287a6dacacSDimitry Andric   return std::string(out);
9290b57cec5SDimitry Andric }
9300b57cec5SDimitry Andric 
createImportLibrary(bool asLib)931bdd1243dSDimitry Andric void LinkerDriver::createImportLibrary(bool asLib) {
9325f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Create import library");
9330b57cec5SDimitry Andric   std::vector<COFFShortExport> exports;
934bdd1243dSDimitry Andric   for (Export &e1 : ctx.config.exports) {
9350b57cec5SDimitry Andric     COFFShortExport e2;
9365ffd83dbSDimitry Andric     e2.Name = std::string(e1.name);
9375ffd83dbSDimitry Andric     e2.SymbolName = std::string(e1.symbolName);
9385ffd83dbSDimitry Andric     e2.ExtName = std::string(e1.extName);
939*0fca6ea1SDimitry Andric     e2.ExportAs = std::string(e1.exportAs);
940*0fca6ea1SDimitry Andric     e2.ImportName = std::string(e1.importName);
9410b57cec5SDimitry Andric     e2.Ordinal = e1.ordinal;
9420b57cec5SDimitry Andric     e2.Noname = e1.noname;
9430b57cec5SDimitry Andric     e2.Data = e1.data;
9440b57cec5SDimitry Andric     e2.Private = e1.isPrivate;
9450b57cec5SDimitry Andric     e2.Constant = e1.constant;
9460b57cec5SDimitry Andric     exports.push_back(e2);
9470b57cec5SDimitry Andric   }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric   std::string libName = getImportName(asLib);
9500b57cec5SDimitry Andric   std::string path = getImplibPath();
9510b57cec5SDimitry Andric 
952bdd1243dSDimitry Andric   if (!ctx.config.incremental) {
953bdd1243dSDimitry Andric     checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
954bdd1243dSDimitry Andric                                   ctx.config.mingw));
9550b57cec5SDimitry Andric     return;
9560b57cec5SDimitry Andric   }
9570b57cec5SDimitry Andric 
9580b57cec5SDimitry Andric   // If the import library already exists, replace it only if the contents
9590b57cec5SDimitry Andric   // have changed.
9600b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
961fe6060f1SDimitry Andric       path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
9620b57cec5SDimitry Andric   if (!oldBuf) {
963bdd1243dSDimitry Andric     checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
964bdd1243dSDimitry Andric                                   ctx.config.mingw));
9650b57cec5SDimitry Andric     return;
9660b57cec5SDimitry Andric   }
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric   SmallString<128> tmpName;
9690b57cec5SDimitry Andric   if (std::error_code ec =
9700b57cec5SDimitry Andric           sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
9710b57cec5SDimitry Andric     fatal("cannot create temporary file for import library " + path + ": " +
9720b57cec5SDimitry Andric           ec.message());
9730b57cec5SDimitry Andric 
974bdd1243dSDimitry Andric   if (Error e = writeImportLibrary(libName, tmpName, exports,
975bdd1243dSDimitry Andric                                    ctx.config.machine, ctx.config.mingw)) {
976349cc55cSDimitry Andric     checkError(std::move(e));
9770b57cec5SDimitry Andric     return;
9780b57cec5SDimitry Andric   }
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
981fe6060f1SDimitry Andric       tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
9820b57cec5SDimitry Andric   if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
9830b57cec5SDimitry Andric     oldBuf->reset();
984349cc55cSDimitry Andric     checkError(errorCodeToError(sys::fs::rename(tmpName, path)));
9850b57cec5SDimitry Andric   } else {
9860b57cec5SDimitry Andric     sys::fs::remove(tmpName);
9870b57cec5SDimitry Andric   }
9880b57cec5SDimitry Andric }
9890b57cec5SDimitry Andric 
parseModuleDefs(StringRef path)990bdd1243dSDimitry Andric void LinkerDriver::parseModuleDefs(StringRef path) {
9915f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Parse def file");
992fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
993fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
994fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
995fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
996fe6060f1SDimitry Andric             "could not open " + path);
9970b57cec5SDimitry Andric   COFFModuleDefinition m = check(parseCOFFModuleDefinition(
998bdd1243dSDimitry Andric       mb->getMemBufferRef(), ctx.config.machine, ctx.config.mingw));
9990b57cec5SDimitry Andric 
1000fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1001bdd1243dSDimitry Andric   ctx.driver.takeBuffer(std::move(mb));
1002fe6060f1SDimitry Andric 
1003bdd1243dSDimitry Andric   if (ctx.config.outputFile.empty())
1004bdd1243dSDimitry Andric     ctx.config.outputFile = std::string(saver().save(m.OutputFile));
1005bdd1243dSDimitry Andric   ctx.config.importName = std::string(saver().save(m.ImportName));
10060b57cec5SDimitry Andric   if (m.ImageBase)
1007bdd1243dSDimitry Andric     ctx.config.imageBase = m.ImageBase;
10080b57cec5SDimitry Andric   if (m.StackReserve)
1009bdd1243dSDimitry Andric     ctx.config.stackReserve = m.StackReserve;
10100b57cec5SDimitry Andric   if (m.StackCommit)
1011bdd1243dSDimitry Andric     ctx.config.stackCommit = m.StackCommit;
10120b57cec5SDimitry Andric   if (m.HeapReserve)
1013bdd1243dSDimitry Andric     ctx.config.heapReserve = m.HeapReserve;
10140b57cec5SDimitry Andric   if (m.HeapCommit)
1015bdd1243dSDimitry Andric     ctx.config.heapCommit = m.HeapCommit;
10160b57cec5SDimitry Andric   if (m.MajorImageVersion)
1017bdd1243dSDimitry Andric     ctx.config.majorImageVersion = m.MajorImageVersion;
10180b57cec5SDimitry Andric   if (m.MinorImageVersion)
1019bdd1243dSDimitry Andric     ctx.config.minorImageVersion = m.MinorImageVersion;
10200b57cec5SDimitry Andric   if (m.MajorOSVersion)
1021bdd1243dSDimitry Andric     ctx.config.majorOSVersion = m.MajorOSVersion;
10220b57cec5SDimitry Andric   if (m.MinorOSVersion)
1023bdd1243dSDimitry Andric     ctx.config.minorOSVersion = m.MinorOSVersion;
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   for (COFFShortExport e1 : m.Exports) {
10260b57cec5SDimitry Andric     Export e2;
1027*0fca6ea1SDimitry Andric     // Renamed exports are parsed and set as "ExtName = Name". If Name has
1028*0fca6ea1SDimitry Andric     // the form "OtherDll.Func", it shouldn't be a normal exported
1029*0fca6ea1SDimitry Andric     // function but a forward to another DLL instead. This is supported
1030*0fca6ea1SDimitry Andric     // by both MS and GNU linkers.
10315ffd83dbSDimitry Andric     if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
10325ffd83dbSDimitry Andric         StringRef(e1.Name).contains('.')) {
103304eeddc0SDimitry Andric       e2.name = saver().save(e1.ExtName);
103404eeddc0SDimitry Andric       e2.forwardTo = saver().save(e1.Name);
1035*0fca6ea1SDimitry Andric     } else {
103604eeddc0SDimitry Andric       e2.name = saver().save(e1.Name);
103704eeddc0SDimitry Andric       e2.extName = saver().save(e1.ExtName);
1038*0fca6ea1SDimitry Andric     }
1039*0fca6ea1SDimitry Andric     e2.exportAs = saver().save(e1.ExportAs);
1040*0fca6ea1SDimitry Andric     e2.importName = saver().save(e1.ImportName);
10410b57cec5SDimitry Andric     e2.ordinal = e1.Ordinal;
10420b57cec5SDimitry Andric     e2.noname = e1.Noname;
10430b57cec5SDimitry Andric     e2.data = e1.Data;
10440b57cec5SDimitry Andric     e2.isPrivate = e1.Private;
10450b57cec5SDimitry Andric     e2.constant = e1.Constant;
104606c3fb27SDimitry Andric     e2.source = ExportSource::ModuleDefinition;
1047bdd1243dSDimitry Andric     ctx.config.exports.push_back(e2);
10480b57cec5SDimitry Andric   }
10490b57cec5SDimitry Andric }
10500b57cec5SDimitry Andric 
enqueueTask(std::function<void ()> task)10510b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) {
10520b57cec5SDimitry Andric   taskQueue.push_back(std::move(task));
10530b57cec5SDimitry Andric }
10540b57cec5SDimitry Andric 
run()10550b57cec5SDimitry Andric bool LinkerDriver::run() {
10565f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Read input files");
1057349cc55cSDimitry Andric   ScopedTimer t(ctx.inputFileTimer);
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric   bool didWork = !taskQueue.empty();
10600b57cec5SDimitry Andric   while (!taskQueue.empty()) {
10610b57cec5SDimitry Andric     taskQueue.front()();
10620b57cec5SDimitry Andric     taskQueue.pop_front();
10630b57cec5SDimitry Andric   }
10640b57cec5SDimitry Andric   return didWork;
10650b57cec5SDimitry Andric }
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places
10680b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the
10690b57cec5SDimitry Andric // given file.
parseOrderFile(StringRef arg)1070bdd1243dSDimitry Andric void LinkerDriver::parseOrderFile(StringRef arg) {
10710b57cec5SDimitry Andric   // For some reason, the MSVC linker requires a filename to be
10720b57cec5SDimitry Andric   // preceded by "@".
107306c3fb27SDimitry Andric   if (!arg.starts_with("@")) {
10740b57cec5SDimitry Andric     error("malformed /order option: '@' missing");
10750b57cec5SDimitry Andric     return;
10760b57cec5SDimitry Andric   }
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric   // Get a list of all comdat sections for error checking.
10790b57cec5SDimitry Andric   DenseSet<StringRef> set;
1080349cc55cSDimitry Andric   for (Chunk *c : ctx.symtab.getChunks())
10810b57cec5SDimitry Andric     if (auto *sec = dyn_cast<SectionChunk>(c))
10820b57cec5SDimitry Andric       if (sec->sym)
10830b57cec5SDimitry Andric         set.insert(sec->sym->getName());
10840b57cec5SDimitry Andric 
10850b57cec5SDimitry Andric   // Open a file.
10860b57cec5SDimitry Andric   StringRef path = arg.substr(1);
1087fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
1088fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1089fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
1090fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
1091fe6060f1SDimitry Andric             "could not open " + path);
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric   // Parse a file. An order file contains one symbol per line.
10940b57cec5SDimitry Andric   // All symbols that were not present in a given order file are
10950b57cec5SDimitry Andric   // considered to have the lowest priority 0 and are placed at
10960b57cec5SDimitry Andric   // end of an output section.
10975ffd83dbSDimitry Andric   for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
10985ffd83dbSDimitry Andric     std::string s(arg);
1099bdd1243dSDimitry Andric     if (ctx.config.machine == I386 && !isDecorated(s))
11000b57cec5SDimitry Andric       s = "_" + s;
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric     if (set.count(s) == 0) {
1103bdd1243dSDimitry Andric       if (ctx.config.warnMissingOrderSymbol)
11040b57cec5SDimitry Andric         warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
11053bd749dbSDimitry Andric     } else
1106bdd1243dSDimitry Andric       ctx.config.order[s] = INT_MIN + ctx.config.order.size();
11070b57cec5SDimitry Andric   }
1108fe6060f1SDimitry Andric 
1109fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1110bdd1243dSDimitry Andric   ctx.driver.takeBuffer(std::move(mb));
11110b57cec5SDimitry Andric }
11120b57cec5SDimitry Andric 
parseCallGraphFile(StringRef path)1113bdd1243dSDimitry Andric void LinkerDriver::parseCallGraphFile(StringRef path) {
1114fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
1115fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1116fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
1117fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
1118fe6060f1SDimitry Andric             "could not open " + path);
1119e8d8bef9SDimitry Andric 
1120e8d8bef9SDimitry Andric   // Build a map from symbol name to section.
1121e8d8bef9SDimitry Andric   DenseMap<StringRef, Symbol *> map;
1122349cc55cSDimitry Andric   for (ObjFile *file : ctx.objFileInstances)
1123e8d8bef9SDimitry Andric     for (Symbol *sym : file->getSymbols())
1124e8d8bef9SDimitry Andric       if (sym)
1125e8d8bef9SDimitry Andric         map[sym->getName()] = sym;
1126e8d8bef9SDimitry Andric 
1127e8d8bef9SDimitry Andric   auto findSection = [&](StringRef name) -> SectionChunk * {
1128e8d8bef9SDimitry Andric     Symbol *sym = map.lookup(name);
1129e8d8bef9SDimitry Andric     if (!sym) {
1130bdd1243dSDimitry Andric       if (ctx.config.warnMissingOrderSymbol)
1131e8d8bef9SDimitry Andric         warn(path + ": no such symbol: " + name);
1132e8d8bef9SDimitry Andric       return nullptr;
1133e8d8bef9SDimitry Andric     }
1134e8d8bef9SDimitry Andric 
1135e8d8bef9SDimitry Andric     if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1136e8d8bef9SDimitry Andric       return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1137e8d8bef9SDimitry Andric     return nullptr;
1138e8d8bef9SDimitry Andric   };
1139e8d8bef9SDimitry Andric 
1140e8d8bef9SDimitry Andric   for (StringRef line : args::getLines(*mb)) {
1141e8d8bef9SDimitry Andric     SmallVector<StringRef, 3> fields;
1142e8d8bef9SDimitry Andric     line.split(fields, ' ');
1143e8d8bef9SDimitry Andric     uint64_t count;
1144e8d8bef9SDimitry Andric 
1145e8d8bef9SDimitry Andric     if (fields.size() != 3 || !to_integer(fields[2], count)) {
1146e8d8bef9SDimitry Andric       error(path + ": parse error");
1147e8d8bef9SDimitry Andric       return;
1148e8d8bef9SDimitry Andric     }
1149e8d8bef9SDimitry Andric 
1150e8d8bef9SDimitry Andric     if (SectionChunk *from = findSection(fields[0]))
1151e8d8bef9SDimitry Andric       if (SectionChunk *to = findSection(fields[1]))
1152bdd1243dSDimitry Andric         ctx.config.callGraphProfile[{from, to}] += count;
1153e8d8bef9SDimitry Andric   }
1154fe6060f1SDimitry Andric 
1155fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1156bdd1243dSDimitry Andric   ctx.driver.takeBuffer(std::move(mb));
1157e8d8bef9SDimitry Andric }
1158e8d8bef9SDimitry Andric 
readCallGraphsFromObjectFiles(COFFLinkerContext & ctx)1159349cc55cSDimitry Andric static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) {
1160349cc55cSDimitry Andric   for (ObjFile *obj : ctx.objFileInstances) {
1161e8d8bef9SDimitry Andric     if (obj->callgraphSec) {
1162e8d8bef9SDimitry Andric       ArrayRef<uint8_t> contents;
1163e8d8bef9SDimitry Andric       cantFail(
1164e8d8bef9SDimitry Andric           obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
11655f757f3fSDimitry Andric       BinaryStreamReader reader(contents, llvm::endianness::little);
1166e8d8bef9SDimitry Andric       while (!reader.empty()) {
1167e8d8bef9SDimitry Andric         uint32_t fromIndex, toIndex;
1168e8d8bef9SDimitry Andric         uint64_t count;
1169e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(fromIndex))
1170e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 32-bit integer");
1171e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(toIndex))
1172e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 32-bit integer");
1173e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(count))
1174e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 64-bit integer");
1175e8d8bef9SDimitry Andric         auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1176e8d8bef9SDimitry Andric         auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1177e8d8bef9SDimitry Andric         if (!fromSym || !toSym)
1178e8d8bef9SDimitry Andric           continue;
1179e8d8bef9SDimitry Andric         auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1180e8d8bef9SDimitry Andric         auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1181e8d8bef9SDimitry Andric         if (from && to)
1182bdd1243dSDimitry Andric           ctx.config.callGraphProfile[{from, to}] += count;
1183e8d8bef9SDimitry Andric       }
1184e8d8bef9SDimitry Andric     }
1185e8d8bef9SDimitry Andric   }
1186e8d8bef9SDimitry Andric }
1187e8d8bef9SDimitry Andric 
markAddrsig(Symbol * s)11880b57cec5SDimitry Andric static void markAddrsig(Symbol *s) {
11890b57cec5SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
11900b57cec5SDimitry Andric     if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
11910b57cec5SDimitry Andric       c->keepUnique = true;
11920b57cec5SDimitry Andric }
11930b57cec5SDimitry Andric 
findKeepUniqueSections(COFFLinkerContext & ctx)1194349cc55cSDimitry Andric static void findKeepUniqueSections(COFFLinkerContext &ctx) {
11955f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Find keep unique sections");
11965f757f3fSDimitry Andric 
11970b57cec5SDimitry Andric   // Exported symbols could be address-significant in other executables or DSOs,
11980b57cec5SDimitry Andric   // so we conservatively mark them as address-significant.
1199bdd1243dSDimitry Andric   for (Export &r : ctx.config.exports)
12000b57cec5SDimitry Andric     markAddrsig(r.sym);
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric   // Visit the address-significance table in each object file and mark each
12030b57cec5SDimitry Andric   // referenced symbol as address-significant.
1204349cc55cSDimitry Andric   for (ObjFile *obj : ctx.objFileInstances) {
12050b57cec5SDimitry Andric     ArrayRef<Symbol *> syms = obj->getSymbols();
12060b57cec5SDimitry Andric     if (obj->addrsigSec) {
12070b57cec5SDimitry Andric       ArrayRef<uint8_t> contents;
12080b57cec5SDimitry Andric       cantFail(
12090b57cec5SDimitry Andric           obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
12100b57cec5SDimitry Andric       const uint8_t *cur = contents.begin();
12110b57cec5SDimitry Andric       while (cur != contents.end()) {
12120b57cec5SDimitry Andric         unsigned size;
12135f757f3fSDimitry Andric         const char *err = nullptr;
12140b57cec5SDimitry Andric         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
12150b57cec5SDimitry Andric         if (err)
12160b57cec5SDimitry Andric           fatal(toString(obj) + ": could not decode addrsig section: " + err);
12170b57cec5SDimitry Andric         if (symIndex >= syms.size())
12180b57cec5SDimitry Andric           fatal(toString(obj) + ": invalid symbol index in addrsig section");
12190b57cec5SDimitry Andric         markAddrsig(syms[symIndex]);
12200b57cec5SDimitry Andric         cur += size;
12210b57cec5SDimitry Andric       }
12220b57cec5SDimitry Andric     } else {
12230b57cec5SDimitry Andric       // If an object file does not have an address-significance table,
12240b57cec5SDimitry Andric       // conservatively mark all of its symbols as address-significant.
12250b57cec5SDimitry Andric       for (Symbol *s : syms)
12260b57cec5SDimitry Andric         markAddrsig(s);
12270b57cec5SDimitry Andric     }
12280b57cec5SDimitry Andric   }
12290b57cec5SDimitry Andric }
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment
12320b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename
12330b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output
12340b57cec5SDimitry Andric // binary).
12350b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env
12360b57cec5SDimitry Andric // vars.
parsePDBAltPath()1237bdd1243dSDimitry Andric void LinkerDriver::parsePDBAltPath() {
12380b57cec5SDimitry Andric   SmallString<128> buf;
12390b57cec5SDimitry Andric   StringRef pdbBasename =
1240bdd1243dSDimitry Andric       sys::path::filename(ctx.config.pdbPath, sys::path::Style::windows);
12410b57cec5SDimitry Andric   StringRef binaryExtension =
1242bdd1243dSDimitry Andric       sys::path::extension(ctx.config.outputFile, sys::path::Style::windows);
12430b57cec5SDimitry Andric   if (!binaryExtension.empty())
12440b57cec5SDimitry Andric     binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric   // Invariant:
12470b57cec5SDimitry Andric   //   +--------- cursor ('a...' might be the empty string).
12480b57cec5SDimitry Andric   //   |   +----- firstMark
12490b57cec5SDimitry Andric   //   |   |   +- secondMark
12500b57cec5SDimitry Andric   //   v   v   v
12510b57cec5SDimitry Andric   //   a...%...%...
12520b57cec5SDimitry Andric   size_t cursor = 0;
1253bdd1243dSDimitry Andric   while (cursor < ctx.config.pdbAltPath.size()) {
12540b57cec5SDimitry Andric     size_t firstMark, secondMark;
1255bdd1243dSDimitry Andric     if ((firstMark = ctx.config.pdbAltPath.find('%', cursor)) ==
1256bdd1243dSDimitry Andric             StringRef::npos ||
1257bdd1243dSDimitry Andric         (secondMark = ctx.config.pdbAltPath.find('%', firstMark + 1)) ==
1258bdd1243dSDimitry Andric             StringRef::npos) {
12590b57cec5SDimitry Andric       // Didn't find another full fragment, treat rest of string as literal.
1260bdd1243dSDimitry Andric       buf.append(ctx.config.pdbAltPath.substr(cursor));
12610b57cec5SDimitry Andric       break;
12620b57cec5SDimitry Andric     }
12630b57cec5SDimitry Andric 
12640b57cec5SDimitry Andric     // Found a full fragment. Append text in front of first %, and interpret
12650b57cec5SDimitry Andric     // text between first and second % as variable name.
1266bdd1243dSDimitry Andric     buf.append(ctx.config.pdbAltPath.substr(cursor, firstMark - cursor));
1267bdd1243dSDimitry Andric     StringRef var =
1268bdd1243dSDimitry Andric         ctx.config.pdbAltPath.substr(firstMark, secondMark - firstMark + 1);
1269fe6060f1SDimitry Andric     if (var.equals_insensitive("%_pdb%"))
12700b57cec5SDimitry Andric       buf.append(pdbBasename);
1271fe6060f1SDimitry Andric     else if (var.equals_insensitive("%_ext%"))
12720b57cec5SDimitry Andric       buf.append(binaryExtension);
12730b57cec5SDimitry Andric     else {
12743bd749dbSDimitry Andric       warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + var +
12753bd749dbSDimitry Andric            " as literal");
12760b57cec5SDimitry Andric       buf.append(var);
12770b57cec5SDimitry Andric     }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric     cursor = secondMark + 1;
12800b57cec5SDimitry Andric   }
12810b57cec5SDimitry Andric 
1282bdd1243dSDimitry Andric   ctx.config.pdbAltPath = buf;
12830b57cec5SDimitry Andric }
12840b57cec5SDimitry Andric 
128585868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object
128685868e8aSDimitry Andric /// trees into one resource tree.
12870b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete.
convertResources()128885868e8aSDimitry Andric void LinkerDriver::convertResources() {
12895f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Convert resources");
129085868e8aSDimitry Andric   std::vector<ObjFile *> resourceObjFiles;
129185868e8aSDimitry Andric 
1292349cc55cSDimitry Andric   for (ObjFile *f : ctx.objFileInstances) {
129385868e8aSDimitry Andric     if (f->isResourceObjFile())
129485868e8aSDimitry Andric       resourceObjFiles.push_back(f);
12950b57cec5SDimitry Andric   }
12960b57cec5SDimitry Andric 
1297bdd1243dSDimitry Andric   if (!ctx.config.mingw &&
129885868e8aSDimitry Andric       (resourceObjFiles.size() > 1 ||
129985868e8aSDimitry Andric        (resourceObjFiles.size() == 1 && !resources.empty()))) {
130085868e8aSDimitry Andric     error((!resources.empty() ? "internal .obj file created from .res files"
130185868e8aSDimitry Andric                               : toString(resourceObjFiles[1])) +
13020b57cec5SDimitry Andric           ": more than one resource obj file not allowed, already got " +
130385868e8aSDimitry Andric           toString(resourceObjFiles.front()));
130485868e8aSDimitry Andric     return;
13050b57cec5SDimitry Andric   }
130685868e8aSDimitry Andric 
130785868e8aSDimitry Andric   if (resources.empty() && resourceObjFiles.size() <= 1) {
130885868e8aSDimitry Andric     // No resources to convert, and max one resource object file in
130985868e8aSDimitry Andric     // the input. Keep that preconverted resource section as is.
131085868e8aSDimitry Andric     for (ObjFile *f : resourceObjFiles)
131185868e8aSDimitry Andric       f->includeResourceChunks();
131285868e8aSDimitry Andric     return;
131385868e8aSDimitry Andric   }
1314349cc55cSDimitry Andric   ObjFile *f =
1315349cc55cSDimitry Andric       make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles));
1316349cc55cSDimitry Andric   ctx.symtab.addFile(f);
131785868e8aSDimitry Andric   f->includeResourceChunks();
13180b57cec5SDimitry Andric }
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are
13210b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the
13220b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are
13230b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the
13240b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
13250b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported.
maybeExportMinGWSymbols(const opt::InputArgList & args)13260b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1327fe6060f1SDimitry Andric   if (!args.hasArg(OPT_export_all_symbols)) {
1328bdd1243dSDimitry Andric     if (!ctx.config.dll)
13290b57cec5SDimitry Andric       return;
13300b57cec5SDimitry Andric 
1331bdd1243dSDimitry Andric     if (!ctx.config.exports.empty())
13320b57cec5SDimitry Andric       return;
13330b57cec5SDimitry Andric     if (args.hasArg(OPT_exclude_all_symbols))
13340b57cec5SDimitry Andric       return;
13350b57cec5SDimitry Andric   }
13360b57cec5SDimitry Andric 
1337bdd1243dSDimitry Andric   AutoExporter exporter(ctx, excludedSymbols);
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wholearchive_file))
134006c3fb27SDimitry Andric     if (std::optional<StringRef> path = findFile(arg->getValue()))
13410b57cec5SDimitry Andric       exporter.addWholeArchive(*path);
13420b57cec5SDimitry Andric 
134361cfbce3SDimitry Andric   for (auto *arg : args.filtered(OPT_exclude_symbols)) {
134461cfbce3SDimitry Andric     SmallVector<StringRef, 2> vec;
134561cfbce3SDimitry Andric     StringRef(arg->getValue()).split(vec, ',');
134661cfbce3SDimitry Andric     for (StringRef sym : vec)
134761cfbce3SDimitry Andric       exporter.addExcludedSymbol(mangle(sym));
134861cfbce3SDimitry Andric   }
134961cfbce3SDimitry Andric 
1350349cc55cSDimitry Andric   ctx.symtab.forEachSymbol([&](Symbol *s) {
13510b57cec5SDimitry Andric     auto *def = dyn_cast<Defined>(s);
1352bdd1243dSDimitry Andric     if (!exporter.shouldExport(def))
13530b57cec5SDimitry Andric       return;
13540b57cec5SDimitry Andric 
1355fe6060f1SDimitry Andric     if (!def->isGCRoot) {
1356fe6060f1SDimitry Andric       def->isGCRoot = true;
1357bdd1243dSDimitry Andric       ctx.config.gcroot.push_back(def);
1358fe6060f1SDimitry Andric     }
1359fe6060f1SDimitry Andric 
13600b57cec5SDimitry Andric     Export e;
13610b57cec5SDimitry Andric     e.name = def->getName();
13620b57cec5SDimitry Andric     e.sym = def;
13630b57cec5SDimitry Andric     if (Chunk *c = def->getChunk())
13640b57cec5SDimitry Andric       if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
13650b57cec5SDimitry Andric         e.data = true;
1366fe6060f1SDimitry Andric     s->isUsedInRegularObj = true;
1367bdd1243dSDimitry Andric     ctx.config.exports.push_back(e);
13680b57cec5SDimitry Andric   });
13690b57cec5SDimitry Andric }
13700b57cec5SDimitry Andric 
137185868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as
137285868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly
137385868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce.
137485868e8aSDimitry Andric //
137585868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
137685868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility
137785868e8aSDimitry Andric // with Microsoft link.exe.
getReproduceFile(const opt::InputArgList & args)1378bdd1243dSDimitry Andric std::optional<std::string> getReproduceFile(const opt::InputArgList &args) {
137985868e8aSDimitry Andric   if (auto *arg = args.getLastArg(OPT_reproduce))
138085868e8aSDimitry Andric     return std::string(arg->getValue());
138185868e8aSDimitry Andric 
138285868e8aSDimitry Andric   if (auto *arg = args.getLastArg(OPT_linkrepro)) {
138385868e8aSDimitry Andric     SmallString<64> path = StringRef(arg->getValue());
138485868e8aSDimitry Andric     sys::path::append(path, "repro.tar");
13855ffd83dbSDimitry Andric     return std::string(path);
138685868e8aSDimitry Andric   }
138785868e8aSDimitry Andric 
1388e8d8bef9SDimitry Andric   // This is intentionally not guarded by OPT_lldignoreenv since writing
1389e8d8bef9SDimitry Andric   // a repro tar file doesn't affect the main output.
1390e8d8bef9SDimitry Andric   if (auto *path = getenv("LLD_REPRODUCE"))
1391e8d8bef9SDimitry Andric     return std::string(path);
1392e8d8bef9SDimitry Andric 
1393bdd1243dSDimitry Andric   return std::nullopt;
139485868e8aSDimitry Andric }
13950b57cec5SDimitry Andric 
1396753f127fSDimitry Andric static std::unique_ptr<llvm::vfs::FileSystem>
getVFS(const opt::InputArgList & args)1397753f127fSDimitry Andric getVFS(const opt::InputArgList &args) {
1398753f127fSDimitry Andric   using namespace llvm::vfs;
1399753f127fSDimitry Andric 
1400753f127fSDimitry Andric   const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay);
1401753f127fSDimitry Andric   if (!arg)
1402753f127fSDimitry Andric     return nullptr;
1403753f127fSDimitry Andric 
1404753f127fSDimitry Andric   auto bufOrErr = llvm::MemoryBuffer::getFile(arg->getValue());
1405753f127fSDimitry Andric   if (!bufOrErr) {
1406753f127fSDimitry Andric     checkError(errorCodeToError(bufOrErr.getError()));
1407753f127fSDimitry Andric     return nullptr;
1408753f127fSDimitry Andric   }
1409753f127fSDimitry Andric 
14103bd749dbSDimitry Andric   if (auto ret = vfs::getVFSFromYAML(std::move(*bufOrErr),
14113bd749dbSDimitry Andric                                      /*DiagHandler*/ nullptr, arg->getValue()))
1412753f127fSDimitry Andric     return ret;
1413753f127fSDimitry Andric 
1414753f127fSDimitry Andric   error("Invalid vfs overlay");
1415753f127fSDimitry Andric   return nullptr;
1416753f127fSDimitry Andric }
1417753f127fSDimitry Andric 
linkerMain(ArrayRef<const char * > argsArr)1418e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1419349cc55cSDimitry Andric   ScopedTimer rootTimer(ctx.rootTimer);
1420bdd1243dSDimitry Andric   Configuration *config = &ctx.config;
14215ffd83dbSDimitry Andric 
14220b57cec5SDimitry Andric   // Needed for LTO.
14230b57cec5SDimitry Andric   InitializeAllTargetInfos();
14240b57cec5SDimitry Andric   InitializeAllTargets();
14250b57cec5SDimitry Andric   InitializeAllTargetMCs();
14260b57cec5SDimitry Andric   InitializeAllAsmParsers();
14270b57cec5SDimitry Andric   InitializeAllAsmPrinters();
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric   // If the first command line argument is "/lib", link.exe acts like lib.exe.
14300b57cec5SDimitry Andric   // We call our own implementation of lib.exe that understands bitcode files.
1431fe6060f1SDimitry Andric   if (argsArr.size() > 1 &&
1432fe6060f1SDimitry Andric       (StringRef(argsArr[1]).equals_insensitive("/lib") ||
1433fe6060f1SDimitry Andric        StringRef(argsArr[1]).equals_insensitive("-lib"))) {
14340b57cec5SDimitry Andric     if (llvm::libDriverMain(argsArr.slice(1)) != 0)
14350b57cec5SDimitry Andric       fatal("lib failed");
14360b57cec5SDimitry Andric     return;
14370b57cec5SDimitry Andric   }
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric   // Parse command line options.
1440bdd1243dSDimitry Andric   ArgParser parser(ctx);
144185868e8aSDimitry Andric   opt::InputArgList args = parser.parse(argsArr);
14420b57cec5SDimitry Andric 
14435f757f3fSDimitry Andric   // Initialize time trace profiler.
14445f757f3fSDimitry Andric   config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
14455f757f3fSDimitry Andric   config->timeTraceGranularity =
14465f757f3fSDimitry Andric       args::getInteger(args, OPT_time_trace_granularity_eq, 500);
14475f757f3fSDimitry Andric 
14485f757f3fSDimitry Andric   if (config->timeTraceEnabled)
14495f757f3fSDimitry Andric     timeTraceProfilerInitialize(config->timeTraceGranularity, argsArr[0]);
14505f757f3fSDimitry Andric 
14515f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("COFF link");
14525f757f3fSDimitry Andric 
14530b57cec5SDimitry Andric   // Parse and evaluate -mllvm options.
14540b57cec5SDimitry Andric   std::vector<const char *> v;
14550b57cec5SDimitry Andric   v.push_back("lld-link (LLVM option parsing)");
1456bdd1243dSDimitry Andric   for (const auto *arg : args.filtered(OPT_mllvm)) {
14570b57cec5SDimitry Andric     v.push_back(arg->getValue());
1458bdd1243dSDimitry Andric     config->mllvmOpts.emplace_back(arg->getValue());
1459bdd1243dSDimitry Andric   }
14605f757f3fSDimitry Andric   {
14615f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Parse cl::opt");
1462e8d8bef9SDimitry Andric     cl::ResetAllOptionOccurrences();
14630b57cec5SDimitry Andric     cl::ParseCommandLineOptions(v.size(), v.data());
14645f757f3fSDimitry Andric   }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric   // Handle /errorlimit early, because error() depends on it.
14670b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_errorlimit)) {
14680b57cec5SDimitry Andric     int n = 20;
14690b57cec5SDimitry Andric     StringRef s = arg->getValue();
14700b57cec5SDimitry Andric     if (s.getAsInteger(10, n))
14710b57cec5SDimitry Andric       error(arg->getSpelling() + " number expected, but got " + s);
14720b57cec5SDimitry Andric     errorHandler().errorLimit = n;
14730b57cec5SDimitry Andric   }
14740b57cec5SDimitry Andric 
1475753f127fSDimitry Andric   config->vfs = getVFS(args);
1476753f127fSDimitry Andric 
14770b57cec5SDimitry Andric   // Handle /help
14780b57cec5SDimitry Andric   if (args.hasArg(OPT_help)) {
14790b57cec5SDimitry Andric     printHelp(argsArr[0]);
14800b57cec5SDimitry Andric     return;
14810b57cec5SDimitry Andric   }
14820b57cec5SDimitry Andric 
14835ffd83dbSDimitry Andric   // /threads: takes a positive integer and provides the default value for
14845ffd83dbSDimitry Andric   // /opt:lldltojobs=.
14855ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_threads)) {
14865ffd83dbSDimitry Andric     StringRef v(arg->getValue());
14875ffd83dbSDimitry Andric     unsigned threads = 0;
14885ffd83dbSDimitry Andric     if (!llvm::to_integer(v, threads, 0) || threads == 0)
14895ffd83dbSDimitry Andric       error(arg->getSpelling() + ": expected a positive integer, but got '" +
14905ffd83dbSDimitry Andric             arg->getValue() + "'");
14915ffd83dbSDimitry Andric     parallel::strategy = hardware_concurrency(threads);
14925ffd83dbSDimitry Andric     config->thinLTOJobs = v.str();
14935ffd83dbSDimitry Andric   }
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   if (args.hasArg(OPT_show_timing))
14960b57cec5SDimitry Andric     config->showTiming = true;
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric   config->showSummary = args.hasArg(OPT_summary);
149906c3fb27SDimitry Andric   config->printSearchPaths = args.hasArg(OPT_print_search_paths);
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric   // Handle --version, which is an lld extension. This option is a bit odd
15020b57cec5SDimitry Andric   // because it doesn't start with "/", but we deliberately chose "--" to
15030b57cec5SDimitry Andric   // avoid conflict with /version and for compatibility with clang-cl.
15040b57cec5SDimitry Andric   if (args.hasArg(OPT_dash_dash_version)) {
1505e8d8bef9SDimitry Andric     message(getLLDVersion());
15060b57cec5SDimitry Andric     return;
15070b57cec5SDimitry Andric   }
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   // Handle /lldmingw early, since it can potentially affect how other
15100b57cec5SDimitry Andric   // options are handled.
15110b57cec5SDimitry Andric   config->mingw = args.hasArg(OPT_lldmingw);
1512bdd1243dSDimitry Andric   if (config->mingw)
1513bdd1243dSDimitry Andric     ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now"
1514bdd1243dSDimitry Andric                                   " (use --error-limit=0 to see all errors)";
15150b57cec5SDimitry Andric 
151685868e8aSDimitry Andric   // Handle /linkrepro and /reproduce.
15175f757f3fSDimitry Andric   {
15185f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Reproducer");
1519bdd1243dSDimitry Andric     if (std::optional<std::string> path = getReproduceFile(args)) {
15200b57cec5SDimitry Andric       Expected<std::unique_ptr<TarWriter>> errOrWriter =
152185868e8aSDimitry Andric           TarWriter::create(*path, sys::path::stem(*path));
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric       if (errOrWriter) {
15240b57cec5SDimitry Andric         tar = std::move(*errOrWriter);
15250b57cec5SDimitry Andric       } else {
152685868e8aSDimitry Andric         error("/linkrepro: failed to open " + *path + ": " +
15270b57cec5SDimitry Andric               toString(errOrWriter.takeError()));
15280b57cec5SDimitry Andric       }
15290b57cec5SDimitry Andric     }
15305f757f3fSDimitry Andric   }
15310b57cec5SDimitry Andric 
1532480093f4SDimitry Andric   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
15330b57cec5SDimitry Andric     if (args.hasArg(OPT_deffile))
15340b57cec5SDimitry Andric       config->noEntry = true;
15350b57cec5SDimitry Andric     else
15360b57cec5SDimitry Andric       fatal("no input files");
15370b57cec5SDimitry Andric   }
15380b57cec5SDimitry Andric 
15390b57cec5SDimitry Andric   // Construct search path list.
15405f757f3fSDimitry Andric   {
15415f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Search paths");
154206c3fb27SDimitry Andric     searchPaths.emplace_back("");
15437a6dacacSDimitry Andric     for (auto *arg : args.filtered(OPT_libpath))
15447a6dacacSDimitry Andric       searchPaths.push_back(arg->getValue());
15455f757f3fSDimitry Andric     if (!config->mingw) {
15463bd749dbSDimitry Andric       // Prefer the Clang provided builtins over the ones bundled with MSVC.
15475f757f3fSDimitry Andric       // In MinGW mode, the compiler driver passes the necessary libpath
15485f757f3fSDimitry Andric       // options explicitly.
15493bd749dbSDimitry Andric       addClangLibSearchPaths(argsArr[0]);
15505f757f3fSDimitry Andric       // Don't automatically deduce the lib path from the environment or MSVC
15515f757f3fSDimitry Andric       // installations when operating in mingw mode. (This also makes LLD ignore
15525f757f3fSDimitry Andric       // winsysroot and vctoolsdir arguments.)
155381ad6265SDimitry Andric       detectWinSysRoot(args);
155481ad6265SDimitry Andric       if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
15550b57cec5SDimitry Andric         addLibSearchPaths();
15565f757f3fSDimitry Andric     } else {
15575f757f3fSDimitry Andric       if (args.hasArg(OPT_vctoolsdir, OPT_winsysroot))
15585f757f3fSDimitry Andric         warn("ignoring /vctoolsdir or /winsysroot flags in MinGW mode");
15595f757f3fSDimitry Andric     }
15605f757f3fSDimitry Andric   }
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   // Handle /ignore
15630b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_ignore)) {
15640b57cec5SDimitry Andric     SmallVector<StringRef, 8> vec;
15650b57cec5SDimitry Andric     StringRef(arg->getValue()).split(vec, ',');
15660b57cec5SDimitry Andric     for (StringRef s : vec) {
15670b57cec5SDimitry Andric       if (s == "4037")
15680b57cec5SDimitry Andric         config->warnMissingOrderSymbol = false;
15690b57cec5SDimitry Andric       else if (s == "4099")
15700b57cec5SDimitry Andric         config->warnDebugInfoUnusable = false;
15710b57cec5SDimitry Andric       else if (s == "4217")
15720b57cec5SDimitry Andric         config->warnLocallyDefinedImported = false;
1573480093f4SDimitry Andric       else if (s == "longsections")
1574480093f4SDimitry Andric         config->warnLongSectionNames = false;
15750b57cec5SDimitry Andric       // Other warning numbers are ignored.
15760b57cec5SDimitry Andric     }
15770b57cec5SDimitry Andric   }
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric   // Handle /out
15800b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_out))
15810b57cec5SDimitry Andric     config->outputFile = arg->getValue();
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric   // Handle /verbose
15840b57cec5SDimitry Andric   if (args.hasArg(OPT_verbose))
15850b57cec5SDimitry Andric     config->verbose = true;
15860b57cec5SDimitry Andric   errorHandler().verbose = config->verbose;
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric   // Handle /force or /force:unresolved
15890b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_unresolved))
15900b57cec5SDimitry Andric     config->forceUnresolved = true;
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   // Handle /force or /force:multiple
15930b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_multiple))
15940b57cec5SDimitry Andric     config->forceMultiple = true;
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric   // Handle /force or /force:multipleres
15970b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_multipleres))
15980b57cec5SDimitry Andric     config->forceMultipleRes = true;
15990b57cec5SDimitry Andric 
16005f757f3fSDimitry Andric   // Don't warn about long section names, such as .debug_info, for mingw (or
16015f757f3fSDimitry Andric   // when -debug:dwarf is requested, handled below).
16025f757f3fSDimitry Andric   if (config->mingw)
16035f757f3fSDimitry Andric     config->warnLongSectionNames = false;
16045f757f3fSDimitry Andric 
16055f757f3fSDimitry Andric   bool doGC = true;
16065f757f3fSDimitry Andric 
16070b57cec5SDimitry Andric   // Handle /debug
16085f757f3fSDimitry Andric   bool shouldCreatePDB = false;
16095f757f3fSDimitry Andric   for (auto *arg : args.filtered(OPT_debug, OPT_debug_opt)) {
16105f757f3fSDimitry Andric     std::string str;
16115f757f3fSDimitry Andric     if (arg->getOption().getID() == OPT_debug)
16125f757f3fSDimitry Andric       str = "full";
16135f757f3fSDimitry Andric     else
16145f757f3fSDimitry Andric       str = StringRef(arg->getValue()).lower();
16155f757f3fSDimitry Andric     SmallVector<StringRef, 1> vec;
16165f757f3fSDimitry Andric     StringRef(str).split(vec, ',');
16175f757f3fSDimitry Andric     for (StringRef s : vec) {
16185f757f3fSDimitry Andric       if (s == "fastlink") {
16195f757f3fSDimitry Andric         warn("/debug:fastlink unsupported; using /debug:full");
16205f757f3fSDimitry Andric         s = "full";
16215f757f3fSDimitry Andric       }
16225f757f3fSDimitry Andric       if (s == "none") {
16235f757f3fSDimitry Andric         config->debug = false;
16245f757f3fSDimitry Andric         config->incremental = false;
16255f757f3fSDimitry Andric         config->includeDwarfChunks = false;
16265f757f3fSDimitry Andric         config->debugGHashes = false;
16275f757f3fSDimitry Andric         config->writeSymtab = false;
16285f757f3fSDimitry Andric         shouldCreatePDB = false;
16295f757f3fSDimitry Andric         doGC = true;
16305f757f3fSDimitry Andric       } else if (s == "full" || s == "ghash" || s == "noghash") {
16310b57cec5SDimitry Andric         config->debug = true;
16320b57cec5SDimitry Andric         config->incremental = true;
16335f757f3fSDimitry Andric         config->includeDwarfChunks = true;
16345f757f3fSDimitry Andric         if (s == "full" || s == "ghash")
16355f757f3fSDimitry Andric           config->debugGHashes = true;
16365f757f3fSDimitry Andric         shouldCreatePDB = true;
16375f757f3fSDimitry Andric         doGC = false;
16385f757f3fSDimitry Andric       } else if (s == "dwarf") {
16395f757f3fSDimitry Andric         config->debug = true;
16405f757f3fSDimitry Andric         config->incremental = true;
16415f757f3fSDimitry Andric         config->includeDwarfChunks = true;
16425f757f3fSDimitry Andric         config->writeSymtab = true;
16435f757f3fSDimitry Andric         config->warnLongSectionNames = false;
16445f757f3fSDimitry Andric         doGC = false;
16455f757f3fSDimitry Andric       } else if (s == "nodwarf") {
16465f757f3fSDimitry Andric         config->includeDwarfChunks = false;
16475f757f3fSDimitry Andric       } else if (s == "symtab") {
16485f757f3fSDimitry Andric         config->writeSymtab = true;
16495f757f3fSDimitry Andric         doGC = false;
16505f757f3fSDimitry Andric       } else if (s == "nosymtab") {
16515f757f3fSDimitry Andric         config->writeSymtab = false;
16525f757f3fSDimitry Andric       } else {
16535f757f3fSDimitry Andric         error("/debug: unknown option: " + s);
16545f757f3fSDimitry Andric       }
16555f757f3fSDimitry Andric     }
16560b57cec5SDimitry Andric   }
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric   // Handle /demangle
165981ad6265SDimitry Andric   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true);
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   // Handle /debugtype
16620b57cec5SDimitry Andric   config->debugTypes = parseDebugTypes(args);
16630b57cec5SDimitry Andric 
1664480093f4SDimitry Andric   // Handle /driver[:uponly|:wdm].
1665480093f4SDimitry Andric   config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1666480093f4SDimitry Andric                          args.hasArg(OPT_driver_uponly_wdm) ||
1667480093f4SDimitry Andric                          args.hasArg(OPT_driver_wdm_uponly);
1668480093f4SDimitry Andric   config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1669480093f4SDimitry Andric                       args.hasArg(OPT_driver_uponly_wdm) ||
1670480093f4SDimitry Andric                       args.hasArg(OPT_driver_wdm_uponly);
1671480093f4SDimitry Andric   config->driver =
1672480093f4SDimitry Andric       config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1673480093f4SDimitry Andric 
16740b57cec5SDimitry Andric   // Handle /pdb
16750b57cec5SDimitry Andric   if (shouldCreatePDB) {
16760b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdb))
16770b57cec5SDimitry Andric       config->pdbPath = arg->getValue();
16780b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdbaltpath))
16790b57cec5SDimitry Andric       config->pdbAltPath = arg->getValue();
1680349cc55cSDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdbpagesize))
1681349cc55cSDimitry Andric       parsePDBPageSize(arg->getValue());
16820b57cec5SDimitry Andric     if (args.hasArg(OPT_natvis))
16830b57cec5SDimitry Andric       config->natvisFiles = args.getAllArgValues(OPT_natvis);
16845ffd83dbSDimitry Andric     if (args.hasArg(OPT_pdbstream)) {
16855ffd83dbSDimitry Andric       for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
16865ffd83dbSDimitry Andric         const std::pair<StringRef, StringRef> nameFile = value.split("=");
16875ffd83dbSDimitry Andric         const StringRef name = nameFile.first;
16885ffd83dbSDimitry Andric         const std::string file = nameFile.second.str();
16895ffd83dbSDimitry Andric         config->namedStreams[name] = file;
16905ffd83dbSDimitry Andric       }
16915ffd83dbSDimitry Andric     }
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdb_source_path))
16940b57cec5SDimitry Andric       config->pdbSourcePath = arg->getValue();
16950b57cec5SDimitry Andric   }
16960b57cec5SDimitry Andric 
16975ffd83dbSDimitry Andric   // Handle /pdbstripped
16985ffd83dbSDimitry Andric   if (args.hasArg(OPT_pdbstripped))
16995ffd83dbSDimitry Andric     warn("ignoring /pdbstripped flag, it is not yet supported");
17005ffd83dbSDimitry Andric 
17010b57cec5SDimitry Andric   // Handle /noentry
17020b57cec5SDimitry Andric   if (args.hasArg(OPT_noentry)) {
17030b57cec5SDimitry Andric     if (args.hasArg(OPT_dll))
17040b57cec5SDimitry Andric       config->noEntry = true;
17050b57cec5SDimitry Andric     else
17060b57cec5SDimitry Andric       error("/noentry must be specified with /dll");
17070b57cec5SDimitry Andric   }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   // Handle /dll
17100b57cec5SDimitry Andric   if (args.hasArg(OPT_dll)) {
17110b57cec5SDimitry Andric     config->dll = true;
17120b57cec5SDimitry Andric     config->manifestID = 2;
17130b57cec5SDimitry Andric   }
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
17160b57cec5SDimitry Andric   // because we need to explicitly check whether that option or its inverse was
17170b57cec5SDimitry Andric   // present in the argument list in order to handle /fixed.
17180b57cec5SDimitry Andric   auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
17190b57cec5SDimitry Andric   if (dynamicBaseArg &&
17200b57cec5SDimitry Andric       dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
17210b57cec5SDimitry Andric     config->dynamicBase = false;
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
17240b57cec5SDimitry Andric   // default setting for any other project type.", but link.exe defaults to
17250b57cec5SDimitry Andric   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
17260b57cec5SDimitry Andric   bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
17270b57cec5SDimitry Andric   if (fixed) {
17280b57cec5SDimitry Andric     if (dynamicBaseArg &&
17290b57cec5SDimitry Andric         dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
17300b57cec5SDimitry Andric       error("/fixed must not be specified with /dynamicbase");
17310b57cec5SDimitry Andric     } else {
17320b57cec5SDimitry Andric       config->relocatable = false;
17330b57cec5SDimitry Andric       config->dynamicBase = false;
17340b57cec5SDimitry Andric     }
17350b57cec5SDimitry Andric   }
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric   // Handle /appcontainer
17380b57cec5SDimitry Andric   config->appContainer =
17390b57cec5SDimitry Andric       args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
17400b57cec5SDimitry Andric 
17410b57cec5SDimitry Andric   // Handle /machine
17425f757f3fSDimitry Andric   {
17435f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Machine arg");
17440b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_machine)) {
17450b57cec5SDimitry Andric       config->machine = getMachineType(arg->getValue());
17460b57cec5SDimitry Andric       if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
17470b57cec5SDimitry Andric         fatal(Twine("unknown /machine argument: ") + arg->getValue());
174881ad6265SDimitry Andric       addWinSysRootLibSearchPaths();
17490b57cec5SDimitry Andric     }
17505f757f3fSDimitry Andric   }
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric   // Handle /nodefaultlib:<filename>
17535f757f3fSDimitry Andric   {
17545f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Nodefaultlib");
17550b57cec5SDimitry Andric     for (auto *arg : args.filtered(OPT_nodefaultlib))
175606c3fb27SDimitry Andric       config->noDefaultLibs.insert(findLib(arg->getValue()).lower());
17575f757f3fSDimitry Andric   }
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric   // Handle /nodefaultlib
17600b57cec5SDimitry Andric   if (args.hasArg(OPT_nodefaultlib_all))
17610b57cec5SDimitry Andric     config->noDefaultLibAll = true;
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   // Handle /base
17640b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_base))
17650b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->imageBase);
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   // Handle /filealign
17680b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_filealign)) {
17690b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->fileAlign);
17700b57cec5SDimitry Andric     if (!isPowerOf2_64(config->fileAlign))
17710b57cec5SDimitry Andric       error("/filealign: not a power of two: " + Twine(config->fileAlign));
17720b57cec5SDimitry Andric   }
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   // Handle /stack
17750b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_stack))
17760b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric   // Handle /guard:cf
17790b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_guard))
17800b57cec5SDimitry Andric     parseGuard(arg->getValue());
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   // Handle /heap
17830b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_heap))
17840b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric   // Handle /version
17870b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_version))
17880b57cec5SDimitry Andric     parseVersion(arg->getValue(), &config->majorImageVersion,
17890b57cec5SDimitry Andric                  &config->minorImageVersion);
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric   // Handle /subsystem
17920b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_subsystem))
1793e8d8bef9SDimitry Andric     parseSubsystem(arg->getValue(), &config->subsystem,
1794e8d8bef9SDimitry Andric                    &config->majorSubsystemVersion,
1795e8d8bef9SDimitry Andric                    &config->minorSubsystemVersion);
1796e8d8bef9SDimitry Andric 
1797e8d8bef9SDimitry Andric   // Handle /osversion
1798e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_osversion)) {
1799e8d8bef9SDimitry Andric     parseVersion(arg->getValue(), &config->majorOSVersion,
18000b57cec5SDimitry Andric                  &config->minorOSVersion);
1801e8d8bef9SDimitry Andric   } else {
1802e8d8bef9SDimitry Andric     config->majorOSVersion = config->majorSubsystemVersion;
1803e8d8bef9SDimitry Andric     config->minorOSVersion = config->minorSubsystemVersion;
1804e8d8bef9SDimitry Andric   }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   // Handle /timestamp
18070b57cec5SDimitry Andric   if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
18080b57cec5SDimitry Andric     if (arg->getOption().getID() == OPT_repro) {
18090b57cec5SDimitry Andric       config->timestamp = 0;
18100b57cec5SDimitry Andric       config->repro = true;
18110b57cec5SDimitry Andric     } else {
18120b57cec5SDimitry Andric       config->repro = false;
18130b57cec5SDimitry Andric       StringRef value(arg->getValue());
18140b57cec5SDimitry Andric       if (value.getAsInteger(0, config->timestamp))
18150b57cec5SDimitry Andric         fatal(Twine("invalid timestamp: ") + value +
18160b57cec5SDimitry Andric               ".  Expected 32-bit integer");
18170b57cec5SDimitry Andric     }
18180b57cec5SDimitry Andric   } else {
18190b57cec5SDimitry Andric     config->repro = false;
182074626c16SDimitry Andric     if (std::optional<std::string> epoch =
182174626c16SDimitry Andric             Process::GetEnv("SOURCE_DATE_EPOCH")) {
182274626c16SDimitry Andric       StringRef value(*epoch);
182374626c16SDimitry Andric       if (value.getAsInteger(0, config->timestamp))
182474626c16SDimitry Andric         fatal(Twine("invalid SOURCE_DATE_EPOCH timestamp: ") + value +
182574626c16SDimitry Andric               ".  Expected 32-bit integer");
182674626c16SDimitry Andric     } else {
18270b57cec5SDimitry Andric       config->timestamp = time(nullptr);
18280b57cec5SDimitry Andric     }
182974626c16SDimitry Andric   }
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric   // Handle /alternatename
18320b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_alternatename))
18330b57cec5SDimitry Andric     parseAlternateName(arg->getValue());
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // Handle /include
18360b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_incl))
18370b57cec5SDimitry Andric     addUndefined(arg->getValue());
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   // Handle /implib
18400b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_implib))
18410b57cec5SDimitry Andric     config->implib = arg->getValue();
18420b57cec5SDimitry Andric 
184381ad6265SDimitry Andric   config->noimplib = args.hasArg(OPT_noimplib);
184481ad6265SDimitry Andric 
18455f757f3fSDimitry Andric   if (args.hasArg(OPT_profile))
18465f757f3fSDimitry Andric     doGC = true;
18470b57cec5SDimitry Andric   // Handle /opt.
1848bdd1243dSDimitry Andric   std::optional<ICFLevel> icfLevel;
1849fe6060f1SDimitry Andric   if (args.hasArg(OPT_profile))
1850fe6060f1SDimitry Andric     icfLevel = ICFLevel::None;
18510b57cec5SDimitry Andric   unsigned tailMerge = 1;
1852e8d8bef9SDimitry Andric   bool ltoDebugPM = false;
18530b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_opt)) {
18540b57cec5SDimitry Andric     std::string str = StringRef(arg->getValue()).lower();
18550b57cec5SDimitry Andric     SmallVector<StringRef, 1> vec;
18560b57cec5SDimitry Andric     StringRef(str).split(vec, ',');
18570b57cec5SDimitry Andric     for (StringRef s : vec) {
18580b57cec5SDimitry Andric       if (s == "ref") {
18590b57cec5SDimitry Andric         doGC = true;
18600b57cec5SDimitry Andric       } else if (s == "noref") {
18610b57cec5SDimitry Andric         doGC = false;
186206c3fb27SDimitry Andric       } else if (s == "icf" || s.starts_with("icf=")) {
1863fe6060f1SDimitry Andric         icfLevel = ICFLevel::All;
1864fe6060f1SDimitry Andric       } else if (s == "safeicf") {
1865fe6060f1SDimitry Andric         icfLevel = ICFLevel::Safe;
18660b57cec5SDimitry Andric       } else if (s == "noicf") {
1867fe6060f1SDimitry Andric         icfLevel = ICFLevel::None;
18680b57cec5SDimitry Andric       } else if (s == "lldtailmerge") {
18690b57cec5SDimitry Andric         tailMerge = 2;
18700b57cec5SDimitry Andric       } else if (s == "nolldtailmerge") {
18710b57cec5SDimitry Andric         tailMerge = 0;
1872e8d8bef9SDimitry Andric       } else if (s == "ltodebugpassmanager") {
1873e8d8bef9SDimitry Andric         ltoDebugPM = true;
1874e8d8bef9SDimitry Andric       } else if (s == "noltodebugpassmanager") {
1875e8d8bef9SDimitry Andric         ltoDebugPM = false;
187606c3fb27SDimitry Andric       } else if (s.consume_front("lldlto=")) {
187706c3fb27SDimitry Andric         if (s.getAsInteger(10, config->ltoo) || config->ltoo > 3)
187806c3fb27SDimitry Andric           error("/opt:lldlto: invalid optimization level: " + s);
187906c3fb27SDimitry Andric       } else if (s.consume_front("lldltocgo=")) {
188006c3fb27SDimitry Andric         config->ltoCgo.emplace();
188106c3fb27SDimitry Andric         if (s.getAsInteger(10, *config->ltoCgo) || *config->ltoCgo > 3)
188206c3fb27SDimitry Andric           error("/opt:lldltocgo: invalid codegen optimization level: " + s);
188306c3fb27SDimitry Andric       } else if (s.consume_front("lldltojobs=")) {
188406c3fb27SDimitry Andric         if (!get_threadpool_strategy(s))
188506c3fb27SDimitry Andric           error("/opt:lldltojobs: invalid job count: " + s);
188606c3fb27SDimitry Andric         config->thinLTOJobs = s.str();
188706c3fb27SDimitry Andric       } else if (s.consume_front("lldltopartitions=")) {
188806c3fb27SDimitry Andric         if (s.getAsInteger(10, config->ltoPartitions) ||
18890b57cec5SDimitry Andric             config->ltoPartitions == 0)
189006c3fb27SDimitry Andric           error("/opt:lldltopartitions: invalid partition count: " + s);
18910b57cec5SDimitry Andric       } else if (s != "lbr" && s != "nolbr")
18920b57cec5SDimitry Andric         error("/opt: unknown option: " + s);
18930b57cec5SDimitry Andric     }
18940b57cec5SDimitry Andric   }
18950b57cec5SDimitry Andric 
1896fe6060f1SDimitry Andric   if (!icfLevel)
1897fe6060f1SDimitry Andric     icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
18980b57cec5SDimitry Andric   config->doGC = doGC;
189981ad6265SDimitry Andric   config->doICF = *icfLevel;
1900fe6060f1SDimitry Andric   config->tailMerge =
1901fe6060f1SDimitry Andric       (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
1902e8d8bef9SDimitry Andric   config->ltoDebugPassManager = ltoDebugPM;
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric   // Handle /lldsavetemps
19050b57cec5SDimitry Andric   if (args.hasArg(OPT_lldsavetemps))
19060b57cec5SDimitry Andric     config->saveTemps = true;
19070b57cec5SDimitry Andric 
19085f757f3fSDimitry Andric   // Handle /lldemit
19095f757f3fSDimitry Andric   if (auto *arg = args.getLastArg(OPT_lldemit)) {
19105f757f3fSDimitry Andric     StringRef s = arg->getValue();
19115f757f3fSDimitry Andric     if (s == "obj")
19125f757f3fSDimitry Andric       config->emit = EmitKind::Obj;
19135f757f3fSDimitry Andric     else if (s == "llvm")
19145f757f3fSDimitry Andric       config->emit = EmitKind::LLVM;
19155f757f3fSDimitry Andric     else if (s == "asm")
19165f757f3fSDimitry Andric       config->emit = EmitKind::ASM;
19175f757f3fSDimitry Andric     else
19185f757f3fSDimitry Andric       error("/lldemit: unknown option: " + s);
19195f757f3fSDimitry Andric   }
19205f757f3fSDimitry Andric 
19210b57cec5SDimitry Andric   // Handle /kill-at
19220b57cec5SDimitry Andric   if (args.hasArg(OPT_kill_at))
19230b57cec5SDimitry Andric     config->killAt = true;
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric   // Handle /lldltocache
19260b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_lldltocache))
19270b57cec5SDimitry Andric     config->ltoCache = arg->getValue();
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   // Handle /lldsavecachepolicy
19300b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
19310b57cec5SDimitry Andric     config->ltoCachePolicy = CHECK(
19320b57cec5SDimitry Andric         parseCachePruningPolicy(arg->getValue()),
19330b57cec5SDimitry Andric         Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric   // Handle /failifmismatch
19360b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_failifmismatch))
19370b57cec5SDimitry Andric     checkFailIfMismatch(arg->getValue(), nullptr);
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric   // Handle /merge
19400b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_merge))
19410b57cec5SDimitry Andric     parseMerge(arg->getValue());
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric   // Add default section merging rules after user rules. User rules take
19440b57cec5SDimitry Andric   // precedence, but we will emit a warning if there is a conflict.
19450b57cec5SDimitry Andric   parseMerge(".idata=.rdata");
19460b57cec5SDimitry Andric   parseMerge(".didat=.rdata");
19470b57cec5SDimitry Andric   parseMerge(".edata=.rdata");
19480b57cec5SDimitry Andric   parseMerge(".xdata=.rdata");
19495f757f3fSDimitry Andric   parseMerge(".00cfg=.rdata");
19500b57cec5SDimitry Andric   parseMerge(".bss=.data");
19510b57cec5SDimitry Andric 
1952647cbc5dSDimitry Andric   if (isArm64EC(config->machine))
1953647cbc5dSDimitry Andric     parseMerge(".wowthk=.text");
1954647cbc5dSDimitry Andric 
19550b57cec5SDimitry Andric   if (config->mingw) {
19560b57cec5SDimitry Andric     parseMerge(".ctors=.rdata");
19570b57cec5SDimitry Andric     parseMerge(".dtors=.rdata");
19580b57cec5SDimitry Andric     parseMerge(".CRT=.rdata");
19590b57cec5SDimitry Andric   }
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric   // Handle /section
19620b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_section))
19630b57cec5SDimitry Andric     parseSection(arg->getValue());
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric   // Handle /align
19660b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_align)) {
19670b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->align);
19680b57cec5SDimitry Andric     if (!isPowerOf2_64(config->align))
19690b57cec5SDimitry Andric       error("/align: not a power of two: " + StringRef(arg->getValue()));
1970480093f4SDimitry Andric     if (!args.hasArg(OPT_driver))
1971480093f4SDimitry Andric       warn("/align specified without /driver; image may not run");
19720b57cec5SDimitry Andric   }
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric   // Handle /aligncomm
19750b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_aligncomm))
19760b57cec5SDimitry Andric     parseAligncomm(arg->getValue());
19770b57cec5SDimitry Andric 
1978349cc55cSDimitry Andric   // Handle /manifestdependency.
1979349cc55cSDimitry Andric   for (auto *arg : args.filtered(OPT_manifestdependency))
1980349cc55cSDimitry Andric     config->manifestDependencies.insert(arg->getValue());
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric   // Handle /manifest and /manifest:
19830b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
19840b57cec5SDimitry Andric     if (arg->getOption().getID() == OPT_manifest)
19850b57cec5SDimitry Andric       config->manifest = Configuration::SideBySide;
19860b57cec5SDimitry Andric     else
19870b57cec5SDimitry Andric       parseManifest(arg->getValue());
19880b57cec5SDimitry Andric   }
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric   // Handle /manifestuac
19910b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_manifestuac))
19920b57cec5SDimitry Andric     parseManifestUAC(arg->getValue());
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric   // Handle /manifestfile
19950b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_manifestfile))
19960b57cec5SDimitry Andric     config->manifestFile = arg->getValue();
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric   // Handle /manifestinput
19990b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_manifestinput))
20000b57cec5SDimitry Andric     config->manifestInput.push_back(arg->getValue());
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric   if (!config->manifestInput.empty() &&
20030b57cec5SDimitry Andric       config->manifest != Configuration::Embed) {
20040b57cec5SDimitry Andric     fatal("/manifestinput: requires /manifest:embed");
20050b57cec5SDimitry Andric   }
20060b57cec5SDimitry Andric 
200706c3fb27SDimitry Andric   // Handle /dwodir
200806c3fb27SDimitry Andric   config->dwoDir = args.getLastArgValue(OPT_dwodir);
200906c3fb27SDimitry Andric 
20100b57cec5SDimitry Andric   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
20110b57cec5SDimitry Andric   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
20120b57cec5SDimitry Andric                              args.hasArg(OPT_thinlto_index_only_arg);
20130b57cec5SDimitry Andric   config->thinLTOIndexOnlyArg =
20140b57cec5SDimitry Andric       args.getLastArgValue(OPT_thinlto_index_only_arg);
201506c3fb27SDimitry Andric   std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
201606c3fb27SDimitry Andric            config->thinLTOPrefixReplaceNativeObject) =
201706c3fb27SDimitry Andric       getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace);
20180b57cec5SDimitry Andric   config->thinLTOObjectSuffixReplace =
20190b57cec5SDimitry Andric       getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
202085868e8aSDimitry Andric   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
2021fe6060f1SDimitry Andric   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
2022fe6060f1SDimitry Andric   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
2023*0fca6ea1SDimitry Andric   config->ltoSampleProfileName = args.getLastArgValue(OPT_lto_sample_profile);
20240b57cec5SDimitry Andric   // Handle miscellaneous boolean flags.
2025349cc55cSDimitry Andric   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
2026349cc55cSDimitry Andric                                             OPT_lto_pgo_warn_mismatch_no, true);
20270b57cec5SDimitry Andric   config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
20280b57cec5SDimitry Andric   config->allowIsolation =
20290b57cec5SDimitry Andric       args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
20300b57cec5SDimitry Andric   config->incremental =
20310b57cec5SDimitry Andric       args.hasFlag(OPT_incremental, OPT_incremental_no,
2032fe6060f1SDimitry Andric                    !config->doGC && config->doICF == ICFLevel::None &&
2033fe6060f1SDimitry Andric                        !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
20340b57cec5SDimitry Andric   config->integrityCheck =
20350b57cec5SDimitry Andric       args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
20365ffd83dbSDimitry Andric   config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
20370b57cec5SDimitry Andric   config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
20380b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_swaprun))
20390b57cec5SDimitry Andric     parseSwaprun(arg->getValue());
20400b57cec5SDimitry Andric   config->terminalServerAware =
20410b57cec5SDimitry Andric       !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
20425ffd83dbSDimitry Andric   config->autoImport =
20435ffd83dbSDimitry Andric       args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
20445ffd83dbSDimitry Andric   config->pseudoRelocs = args.hasFlag(
20455ffd83dbSDimitry Andric       OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
2046e8d8bef9SDimitry Andric   config->callGraphProfileSort = args.hasFlag(
2047e8d8bef9SDimitry Andric       OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
2048fe6060f1SDimitry Andric   config->stdcallFixup =
2049fe6060f1SDimitry Andric       args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
2050fe6060f1SDimitry Andric   config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
20515f757f3fSDimitry Andric   config->allowDuplicateWeak =
20525f757f3fSDimitry Andric       args.hasFlag(OPT_lld_allow_duplicate_weak,
20535f757f3fSDimitry Andric                    OPT_lld_allow_duplicate_weak_no, config->mingw);
20540b57cec5SDimitry Andric 
2055cbe9438cSDimitry Andric   if (args.hasFlag(OPT_inferasanlibs, OPT_inferasanlibs_no, false))
2056cbe9438cSDimitry Andric     warn("ignoring '/inferasanlibs', this flag is not supported");
2057cbe9438cSDimitry Andric 
20580b57cec5SDimitry Andric   if (config->incremental && args.hasArg(OPT_profile)) {
20590b57cec5SDimitry Andric     warn("ignoring '/incremental' due to '/profile' specification");
20600b57cec5SDimitry Andric     config->incremental = false;
20610b57cec5SDimitry Andric   }
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric   if (config->incremental && args.hasArg(OPT_order)) {
20640b57cec5SDimitry Andric     warn("ignoring '/incremental' due to '/order' specification");
20650b57cec5SDimitry Andric     config->incremental = false;
20660b57cec5SDimitry Andric   }
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric   if (config->incremental && config->doGC) {
20690b57cec5SDimitry Andric     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
20700b57cec5SDimitry Andric          "disable");
20710b57cec5SDimitry Andric     config->incremental = false;
20720b57cec5SDimitry Andric   }
20730b57cec5SDimitry Andric 
2074fe6060f1SDimitry Andric   if (config->incremental && config->doICF != ICFLevel::None) {
20750b57cec5SDimitry Andric     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
20760b57cec5SDimitry Andric          "disable");
20770b57cec5SDimitry Andric     config->incremental = false;
20780b57cec5SDimitry Andric   }
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric   if (errorCount())
20810b57cec5SDimitry Andric     return;
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric   std::set<sys::fs::UniqueID> wholeArchives;
20840b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wholearchive_file))
208506c3fb27SDimitry Andric     if (std::optional<StringRef> path = findFile(arg->getValue()))
2086bdd1243dSDimitry Andric       if (std::optional<sys::fs::UniqueID> id = getUniqueID(*path))
20870b57cec5SDimitry Andric         wholeArchives.insert(*id);
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   // A predicate returning true if a given path is an argument for
20900b57cec5SDimitry Andric   // /wholearchive:, or /wholearchive is enabled globally.
20910b57cec5SDimitry Andric   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
20920b57cec5SDimitry Andric   // needs to be handled as "/wholearchive:foo.obj foo.obj".
20930b57cec5SDimitry Andric   auto isWholeArchive = [&](StringRef path) -> bool {
20940b57cec5SDimitry Andric     if (args.hasArg(OPT_wholearchive_flag))
20950b57cec5SDimitry Andric       return true;
2096bdd1243dSDimitry Andric     if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
20970b57cec5SDimitry Andric       return wholeArchives.count(*id);
20980b57cec5SDimitry Andric     return false;
20990b57cec5SDimitry Andric   };
21000b57cec5SDimitry Andric 
210185868e8aSDimitry Andric   // Create a list of input files. These can be given as OPT_INPUT options
210285868e8aSDimitry Andric   // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
210385868e8aSDimitry Andric   // and OPT_end_lib.
21045f757f3fSDimitry Andric   {
21055f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Parse & queue inputs");
210685868e8aSDimitry Andric     bool inLib = false;
210785868e8aSDimitry Andric     for (auto *arg : args) {
210885868e8aSDimitry Andric       switch (arg->getOption().getID()) {
210985868e8aSDimitry Andric       case OPT_end_lib:
211085868e8aSDimitry Andric         if (!inLib)
211185868e8aSDimitry Andric           error("stray " + arg->getSpelling());
211285868e8aSDimitry Andric         inLib = false;
211385868e8aSDimitry Andric         break;
211485868e8aSDimitry Andric       case OPT_start_lib:
211585868e8aSDimitry Andric         if (inLib)
211685868e8aSDimitry Andric           error("nested " + arg->getSpelling());
211785868e8aSDimitry Andric         inLib = true;
211885868e8aSDimitry Andric         break;
211985868e8aSDimitry Andric       case OPT_wholearchive_file:
212006c3fb27SDimitry Andric         if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
212185868e8aSDimitry Andric           enqueuePath(*path, true, inLib);
212285868e8aSDimitry Andric         break;
212385868e8aSDimitry Andric       case OPT_INPUT:
212406c3fb27SDimitry Andric         if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
212585868e8aSDimitry Andric           enqueuePath(*path, isWholeArchive(*path), inLib);
212685868e8aSDimitry Andric         break;
212785868e8aSDimitry Andric       default:
212885868e8aSDimitry Andric         // Ignore other options.
212985868e8aSDimitry Andric         break;
213085868e8aSDimitry Andric       }
213185868e8aSDimitry Andric     }
21325f757f3fSDimitry Andric   }
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   // Read all input files given via the command line.
21350b57cec5SDimitry Andric   run();
21360b57cec5SDimitry Andric   if (errorCount())
21370b57cec5SDimitry Andric     return;
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric   // We should have inferred a machine type by now from the input files, but if
21400b57cec5SDimitry Andric   // not we assume x64.
21410b57cec5SDimitry Andric   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
21420b57cec5SDimitry Andric     warn("/machine is not specified. x64 is assumed");
21430b57cec5SDimitry Andric     config->machine = AMD64;
214481ad6265SDimitry Andric     addWinSysRootLibSearchPaths();
21450b57cec5SDimitry Andric   }
21460b57cec5SDimitry Andric   config->wordsize = config->is64() ? 8 : 4;
21470b57cec5SDimitry Andric 
214806c3fb27SDimitry Andric   if (config->printSearchPaths) {
214906c3fb27SDimitry Andric     SmallString<256> buffer;
215006c3fb27SDimitry Andric     raw_svector_ostream stream(buffer);
215106c3fb27SDimitry Andric     stream << "Library search paths:\n";
215206c3fb27SDimitry Andric 
21533bd749dbSDimitry Andric     for (StringRef path : searchPaths) {
21543bd749dbSDimitry Andric       if (path == "")
21553bd749dbSDimitry Andric         path = "(cwd)";
215606c3fb27SDimitry Andric       stream << "  " << path << "\n";
21573bd749dbSDimitry Andric     }
215806c3fb27SDimitry Andric 
215906c3fb27SDimitry Andric     message(buffer);
216006c3fb27SDimitry Andric   }
216106c3fb27SDimitry Andric 
216281ad6265SDimitry Andric   // Process files specified as /defaultlib. These must be processed after
216381ad6265SDimitry Andric   // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
216481ad6265SDimitry Andric   for (auto *arg : args.filtered(OPT_defaultlib))
216506c3fb27SDimitry Andric     if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
216681ad6265SDimitry Andric       enqueuePath(*path, false, false);
216781ad6265SDimitry Andric   run();
216881ad6265SDimitry Andric   if (errorCount())
216981ad6265SDimitry Andric     return;
217081ad6265SDimitry Andric 
2171bdd1243dSDimitry Andric   // Handle /RELEASE
2172bdd1243dSDimitry Andric   if (args.hasArg(OPT_release))
2173bdd1243dSDimitry Andric     config->writeCheckSum = true;
2174bdd1243dSDimitry Andric 
21750b57cec5SDimitry Andric   // Handle /safeseh, x86 only, on by default, except for mingw.
2176979e22ffSDimitry Andric   if (config->machine == I386) {
2177979e22ffSDimitry Andric     config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
2178979e22ffSDimitry Andric     config->noSEH = args.hasArg(OPT_noseh);
2179979e22ffSDimitry Andric   }
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric   // Handle /functionpadmin
21820b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
2183bdd1243dSDimitry Andric     parseFunctionPadMin(arg);
21840b57cec5SDimitry Andric 
21855f757f3fSDimitry Andric   // Handle /dependentloadflag
21865f757f3fSDimitry Andric   for (auto *arg :
21875f757f3fSDimitry Andric        args.filtered(OPT_dependentloadflag, OPT_dependentloadflag_opt))
21885f757f3fSDimitry Andric     parseDependentLoadFlags(arg);
21895f757f3fSDimitry Andric 
219081ad6265SDimitry Andric   if (tar) {
21915f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Reproducer: response file");
21920b57cec5SDimitry Andric     tar->append("response.txt",
21930b57cec5SDimitry Andric                 createResponseFile(args, filePaths,
21940b57cec5SDimitry Andric                                    ArrayRef<StringRef>(searchPaths).slice(1)));
219581ad6265SDimitry Andric   }
21960b57cec5SDimitry Andric 
21970b57cec5SDimitry Andric   // Handle /largeaddressaware
21980b57cec5SDimitry Andric   config->largeAddressAware = args.hasFlag(
21990b57cec5SDimitry Andric       OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric   // Handle /highentropyva
22020b57cec5SDimitry Andric   config->highEntropyVA =
22030b57cec5SDimitry Andric       config->is64() &&
22040b57cec5SDimitry Andric       args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric   if (!config->dynamicBase &&
22075f757f3fSDimitry Andric       (config->machine == ARMNT || isAnyArm64(config->machine)))
22080b57cec5SDimitry Andric     error("/dynamicbase:no is not compatible with " +
22090b57cec5SDimitry Andric           machineToStr(config->machine));
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric   // Handle /export
22125f757f3fSDimitry Andric   {
22135f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Parse /export");
22140b57cec5SDimitry Andric     for (auto *arg : args.filtered(OPT_export)) {
22150b57cec5SDimitry Andric       Export e = parseExport(arg->getValue());
22160b57cec5SDimitry Andric       if (config->machine == I386) {
22170b57cec5SDimitry Andric         if (!isDecorated(e.name))
221804eeddc0SDimitry Andric           e.name = saver().save("_" + e.name);
22190b57cec5SDimitry Andric         if (!e.extName.empty() && !isDecorated(e.extName))
222004eeddc0SDimitry Andric           e.extName = saver().save("_" + e.extName);
22210b57cec5SDimitry Andric       }
22220b57cec5SDimitry Andric       config->exports.push_back(e);
22230b57cec5SDimitry Andric     }
22245f757f3fSDimitry Andric   }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric   // Handle /def
22270b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_deffile)) {
22280b57cec5SDimitry Andric     // parseModuleDefs mutates Config object.
22290b57cec5SDimitry Andric     parseModuleDefs(arg->getValue());
22300b57cec5SDimitry Andric   }
22310b57cec5SDimitry Andric 
22320b57cec5SDimitry Andric   // Handle generation of import library from a def file.
2233480093f4SDimitry Andric   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
22340b57cec5SDimitry Andric     fixupExports();
223581ad6265SDimitry Andric     if (!config->noimplib)
22360b57cec5SDimitry Andric       createImportLibrary(/*asLib=*/true);
22370b57cec5SDimitry Andric     return;
22380b57cec5SDimitry Andric   }
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric   // Windows specific -- if no /subsystem is given, we need to infer
22410b57cec5SDimitry Andric   // that from entry point name.  Must happen before /entry handling,
22420b57cec5SDimitry Andric   // and after the early return when just writing an import library.
22430b57cec5SDimitry Andric   if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
22445f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Infer subsystem");
22450b57cec5SDimitry Andric     config->subsystem = inferSubsystem();
22460b57cec5SDimitry Andric     if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
22470b57cec5SDimitry Andric       fatal("subsystem must be defined");
22480b57cec5SDimitry Andric   }
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric   // Handle /entry and /dll
22515f757f3fSDimitry Andric   {
22525f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Entry point");
22530b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_entry)) {
2254*0fca6ea1SDimitry Andric       if (!arg->getValue()[0])
2255*0fca6ea1SDimitry Andric         fatal("missing entry point symbol name");
22560b57cec5SDimitry Andric       config->entry = addUndefined(mangle(arg->getValue()));
22570b57cec5SDimitry Andric     } else if (!config->entry && !config->noEntry) {
22580b57cec5SDimitry Andric       if (args.hasArg(OPT_dll)) {
22590b57cec5SDimitry Andric         StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
22600b57cec5SDimitry Andric                                                 : "_DllMainCRTStartup";
22610b57cec5SDimitry Andric         config->entry = addUndefined(s);
2262480093f4SDimitry Andric       } else if (config->driverWdm) {
2263480093f4SDimitry Andric         // /driver:wdm implies /entry:_NtProcessStartup
2264480093f4SDimitry Andric         config->entry = addUndefined(mangle("_NtProcessStartup"));
22650b57cec5SDimitry Andric       } else {
22660b57cec5SDimitry Andric         // Windows specific -- If entry point name is not given, we need to
22670b57cec5SDimitry Andric         // infer that from user-defined entry name.
22680b57cec5SDimitry Andric         StringRef s = findDefaultEntry();
22690b57cec5SDimitry Andric         if (s.empty())
22700b57cec5SDimitry Andric           fatal("entry point must be defined");
22710b57cec5SDimitry Andric         config->entry = addUndefined(s);
22720b57cec5SDimitry Andric         log("Entry name inferred: " + s);
22730b57cec5SDimitry Andric       }
22740b57cec5SDimitry Andric     }
22755f757f3fSDimitry Andric   }
22760b57cec5SDimitry Andric 
22770b57cec5SDimitry Andric   // Handle /delayload
22785f757f3fSDimitry Andric   {
22795f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Delay load");
22800b57cec5SDimitry Andric     for (auto *arg : args.filtered(OPT_delayload)) {
22810b57cec5SDimitry Andric       config->delayLoads.insert(StringRef(arg->getValue()).lower());
22820b57cec5SDimitry Andric       if (config->machine == I386) {
22830b57cec5SDimitry Andric         config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
22840b57cec5SDimitry Andric       } else {
22850b57cec5SDimitry Andric         config->delayLoadHelper = addUndefined("__delayLoadHelper2");
22860b57cec5SDimitry Andric       }
22870b57cec5SDimitry Andric     }
22885f757f3fSDimitry Andric   }
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric   // Set default image name if neither /out or /def set it.
22910b57cec5SDimitry Andric   if (config->outputFile.empty()) {
2292480093f4SDimitry Andric     config->outputFile = getOutputPath(
2293bdd1243dSDimitry Andric         (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue(),
2294bdd1243dSDimitry Andric         config->dll, config->driver);
22950b57cec5SDimitry Andric   }
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   // Fail early if an output file is not writable.
22980b57cec5SDimitry Andric   if (auto e = tryCreateFile(config->outputFile)) {
22990b57cec5SDimitry Andric     error("cannot open output file " + config->outputFile + ": " + e.message());
23000b57cec5SDimitry Andric     return;
23010b57cec5SDimitry Andric   }
23020b57cec5SDimitry Andric 
2303bdd1243dSDimitry Andric   config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
2304bdd1243dSDimitry Andric   config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
2305bdd1243dSDimitry Andric 
2306bdd1243dSDimitry Andric   if (config->mapFile != "" && args.hasArg(OPT_map_info)) {
2307bdd1243dSDimitry Andric     for (auto *arg : args.filtered(OPT_map_info)) {
2308bdd1243dSDimitry Andric       std::string s = StringRef(arg->getValue()).lower();
2309bdd1243dSDimitry Andric       if (s == "exports")
2310bdd1243dSDimitry Andric         config->mapInfo = true;
2311bdd1243dSDimitry Andric       else
2312bdd1243dSDimitry Andric         error("unknown option: /mapinfo:" + s);
2313bdd1243dSDimitry Andric     }
2314bdd1243dSDimitry Andric   }
2315bdd1243dSDimitry Andric 
2316bdd1243dSDimitry Andric   if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
2317bdd1243dSDimitry Andric     warn("/lldmap and /map have the same output file '" + config->mapFile +
2318bdd1243dSDimitry Andric          "'.\n>>> ignoring /lldmap");
2319bdd1243dSDimitry Andric     config->lldmapFile.clear();
2320bdd1243dSDimitry Andric   }
2321bdd1243dSDimitry Andric 
23225f757f3fSDimitry Andric   // If should create PDB, use the hash of PDB content for build id. Otherwise,
23235f757f3fSDimitry Andric   // generate using the hash of executable content.
23245f757f3fSDimitry Andric   if (args.hasFlag(OPT_build_id, OPT_build_id_no, false))
23255f757f3fSDimitry Andric     config->buildIDHash = BuildIDHash::Binary;
23265f757f3fSDimitry Andric 
23270b57cec5SDimitry Andric   if (shouldCreatePDB) {
23280b57cec5SDimitry Andric     // Put the PDB next to the image if no /pdb flag was passed.
23290b57cec5SDimitry Andric     if (config->pdbPath.empty()) {
23300b57cec5SDimitry Andric       config->pdbPath = config->outputFile;
23310b57cec5SDimitry Andric       sys::path::replace_extension(config->pdbPath, ".pdb");
23320b57cec5SDimitry Andric     }
23330b57cec5SDimitry Andric 
23340b57cec5SDimitry Andric     // The embedded PDB path should be the absolute path to the PDB if no
23350b57cec5SDimitry Andric     // /pdbaltpath flag was passed.
23360b57cec5SDimitry Andric     if (config->pdbAltPath.empty()) {
23370b57cec5SDimitry Andric       config->pdbAltPath = config->pdbPath;
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric       // It's important to make the path absolute and remove dots.  This path
23400b57cec5SDimitry Andric       // will eventually be written into the PE header, and certain Microsoft
23410b57cec5SDimitry Andric       // tools won't work correctly if these assumptions are not held.
23420b57cec5SDimitry Andric       sys::fs::make_absolute(config->pdbAltPath);
23430b57cec5SDimitry Andric       sys::path::remove_dots(config->pdbAltPath);
23440b57cec5SDimitry Andric     } else {
2345bdd1243dSDimitry Andric       // Don't do this earlier, so that ctx.OutputFile is ready.
2346bdd1243dSDimitry Andric       parsePDBAltPath();
23470b57cec5SDimitry Andric     }
23485f757f3fSDimitry Andric     config->buildIDHash = BuildIDHash::PDB;
23490b57cec5SDimitry Andric   }
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric   // Set default image base if /base is not given.
23520b57cec5SDimitry Andric   if (config->imageBase == uint64_t(-1))
23530b57cec5SDimitry Andric     config->imageBase = getDefaultImageBase();
23540b57cec5SDimitry Andric 
2355349cc55cSDimitry Andric   ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr);
23560b57cec5SDimitry Andric   if (config->machine == I386) {
2357349cc55cSDimitry Andric     ctx.symtab.addAbsolute("___safe_se_handler_table", 0);
2358349cc55cSDimitry Andric     ctx.symtab.addAbsolute("___safe_se_handler_count", 0);
23590b57cec5SDimitry Andric   }
23600b57cec5SDimitry Andric 
2361349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0);
2362349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0);
2363349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_flags"), 0);
2364349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0);
2365349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0);
2366349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
2367349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
23680b57cec5SDimitry Andric   // Needed for MSVC 2017 15.5 CRT.
2369349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__enclave_config"), 0);
2370fe6060f1SDimitry Andric   // Needed for MSVC 2019 16.8 CRT.
2371349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2372349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0);
23730b57cec5SDimitry Andric 
23745f757f3fSDimitry Andric   if (isArm64EC(config->machine)) {
23755f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__arm64x_extra_rfe_table", 0);
23765f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__arm64x_extra_rfe_table_size", 0);
23775f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__hybrid_code_map", 0);
23785f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__hybrid_code_map_count", 0);
23795f757f3fSDimitry Andric   }
23805f757f3fSDimitry Andric 
23815ffd83dbSDimitry Andric   if (config->pseudoRelocs) {
2382349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2383349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
23845ffd83dbSDimitry Andric   }
23855ffd83dbSDimitry Andric   if (config->mingw) {
2386349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0);
2387349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0);
23880b57cec5SDimitry Andric   }
23895f757f3fSDimitry Andric   if (config->debug || config->buildIDHash != BuildIDHash::None)
23905f757f3fSDimitry Andric     if (ctx.symtab.findUnderscore("__buildid"))
23915f757f3fSDimitry Andric       ctx.symtab.addUndefined(mangle("__buildid"));
23920b57cec5SDimitry Andric 
23930b57cec5SDimitry Andric   // This code may add new undefined symbols to the link, which may enqueue more
23940b57cec5SDimitry Andric   // symbol resolution tasks, so we need to continue executing tasks until we
23950b57cec5SDimitry Andric   // converge.
23965f757f3fSDimitry Andric   {
23975f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Add unresolved symbols");
23980b57cec5SDimitry Andric     do {
23990b57cec5SDimitry Andric       // Windows specific -- if entry point is not found,
24000b57cec5SDimitry Andric       // search for its mangled names.
24010b57cec5SDimitry Andric       if (config->entry)
24020b57cec5SDimitry Andric         mangleMaybe(config->entry);
24030b57cec5SDimitry Andric 
24040b57cec5SDimitry Andric       // Windows specific -- Make sure we resolve all dllexported symbols.
24050b57cec5SDimitry Andric       for (Export &e : config->exports) {
24060b57cec5SDimitry Andric         if (!e.forwardTo.empty())
24070b57cec5SDimitry Andric           continue;
24080b57cec5SDimitry Andric         e.sym = addUndefined(e.name);
240906c3fb27SDimitry Andric         if (e.source != ExportSource::Directives)
24100b57cec5SDimitry Andric           e.symbolName = mangleMaybe(e.sym);
24110b57cec5SDimitry Andric       }
24120b57cec5SDimitry Andric 
24130b57cec5SDimitry Andric       // Add weak aliases. Weak aliases is a mechanism to give remaining
24140b57cec5SDimitry Andric       // undefined symbols final chance to be resolved successfully.
24150b57cec5SDimitry Andric       for (auto pair : config->alternateNames) {
24160b57cec5SDimitry Andric         StringRef from = pair.first;
24170b57cec5SDimitry Andric         StringRef to = pair.second;
2418349cc55cSDimitry Andric         Symbol *sym = ctx.symtab.find(from);
24190b57cec5SDimitry Andric         if (!sym)
24200b57cec5SDimitry Andric           continue;
24210b57cec5SDimitry Andric         if (auto *u = dyn_cast<Undefined>(sym))
24220b57cec5SDimitry Andric           if (!u->weakAlias)
2423349cc55cSDimitry Andric             u->weakAlias = ctx.symtab.addUndefined(to);
24240b57cec5SDimitry Andric       }
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric       // If any inputs are bitcode files, the LTO code generator may create
24270b57cec5SDimitry Andric       // references to library functions that are not explicit in the bitcode
24280b57cec5SDimitry Andric       // file's symbol table. If any of those library functions are defined in a
24290b57cec5SDimitry Andric       // bitcode file in an archive member, we need to arrange to use LTO to
24300b57cec5SDimitry Andric       // compile those archive members by adding them to the link beforehand.
2431*0fca6ea1SDimitry Andric       if (!ctx.bitcodeFileInstances.empty()) {
2432*0fca6ea1SDimitry Andric         llvm::Triple TT(
2433*0fca6ea1SDimitry Andric             ctx.bitcodeFileInstances.front()->obj->getTargetTriple());
2434*0fca6ea1SDimitry Andric         for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT))
2435349cc55cSDimitry Andric           ctx.symtab.addLibcall(s);
2436*0fca6ea1SDimitry Andric       }
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric       // Windows specific -- if __load_config_used can be resolved, resolve it.
2439349cc55cSDimitry Andric       if (ctx.symtab.findUnderscore("_load_config_used"))
24400b57cec5SDimitry Andric         addUndefined(mangle("_load_config_used"));
24410b57cec5SDimitry Andric 
24420b57cec5SDimitry Andric       if (args.hasArg(OPT_include_optional)) {
24430b57cec5SDimitry Andric         // Handle /includeoptional
24440b57cec5SDimitry Andric         for (auto *arg : args.filtered(OPT_include_optional))
24450eae32dcSDimitry Andric           if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue())))
24460b57cec5SDimitry Andric             addUndefined(arg->getValue());
24470b57cec5SDimitry Andric       }
2448a4a491e2SDimitry Andric     } while (run());
24495f757f3fSDimitry Andric   }
24500b57cec5SDimitry Andric 
2451e8d8bef9SDimitry Andric   // Create wrapped symbols for -wrap option.
2452349cc55cSDimitry Andric   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2453e8d8bef9SDimitry Andric   // Load more object files that might be needed for wrapped symbols.
2454e8d8bef9SDimitry Andric   if (!wrapped.empty())
24553bd749dbSDimitry Andric     while (run())
24563bd749dbSDimitry Andric       ;
2457e8d8bef9SDimitry Andric 
2458fe6060f1SDimitry Andric   if (config->autoImport || config->stdcallFixup) {
24595ffd83dbSDimitry Andric     // MinGW specific.
24600b57cec5SDimitry Andric     // Load any further object files that might be needed for doing automatic
2461fe6060f1SDimitry Andric     // imports, and do stdcall fixups.
24620b57cec5SDimitry Andric     //
24630b57cec5SDimitry Andric     // For cases with no automatically imported symbols, this iterates once
24640b57cec5SDimitry Andric     // over the symbol table and doesn't do anything.
24650b57cec5SDimitry Andric     //
24660b57cec5SDimitry Andric     // For the normal case with a few automatically imported symbols, this
24670b57cec5SDimitry Andric     // should only need to be run once, since each new object file imported
24680b57cec5SDimitry Andric     // is an import library and wouldn't add any new undefined references,
24690b57cec5SDimitry Andric     // but there's nothing stopping the __imp_ symbols from coming from a
24700b57cec5SDimitry Andric     // normal object file as well (although that won't be used for the
24710b57cec5SDimitry Andric     // actual autoimport later on). If this pass adds new undefined references,
24720b57cec5SDimitry Andric     // we won't iterate further to resolve them.
2473fe6060f1SDimitry Andric     //
2474fe6060f1SDimitry Andric     // If stdcall fixups only are needed for loading import entries from
2475fe6060f1SDimitry Andric     // a DLL without import library, this also just needs running once.
2476fe6060f1SDimitry Andric     // If it ends up pulling in more object files from static libraries,
2477fe6060f1SDimitry Andric     // (and maybe doing more stdcall fixups along the way), this would need
2478fe6060f1SDimitry Andric     // to loop these two calls.
2479349cc55cSDimitry Andric     ctx.symtab.loadMinGWSymbols();
24800b57cec5SDimitry Andric     run();
24810b57cec5SDimitry Andric   }
24820b57cec5SDimitry Andric 
248385868e8aSDimitry Andric   // At this point, we should not have any symbols that cannot be resolved.
248485868e8aSDimitry Andric   // If we are going to do codegen for link-time optimization, check for
248585868e8aSDimitry Andric   // unresolvable symbols first, so we don't spend time generating code that
248685868e8aSDimitry Andric   // will fail to link anyway.
2487349cc55cSDimitry Andric   if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved)
2488349cc55cSDimitry Andric     ctx.symtab.reportUnresolvable();
24890b57cec5SDimitry Andric   if (errorCount())
24900b57cec5SDimitry Andric     return;
24910b57cec5SDimitry Andric 
2492fe6060f1SDimitry Andric   config->hadExplicitExports = !config->exports.empty();
2493fe6060f1SDimitry Andric   if (config->mingw) {
2494fe6060f1SDimitry Andric     // In MinGW, all symbols are automatically exported if no symbols
2495fe6060f1SDimitry Andric     // are chosen to be exported.
2496fe6060f1SDimitry Andric     maybeExportMinGWSymbols(args);
2497fe6060f1SDimitry Andric   }
2498fe6060f1SDimitry Andric 
249985868e8aSDimitry Andric   // Do LTO by compiling bitcode input files to a set of native COFF files then
250085868e8aSDimitry Andric   // link those files (unless -thinlto-index-only was given, in which case we
250185868e8aSDimitry Andric   // resolve symbols and write indices, but don't generate native code or link).
2502349cc55cSDimitry Andric   ctx.symtab.compileBitcodeFiles();
250385868e8aSDimitry Andric 
25045f757f3fSDimitry Andric   if (Defined *d =
25055f757f3fSDimitry Andric           dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore("_tls_used")))
25065f757f3fSDimitry Andric     config->gcroot.push_back(d);
25075f757f3fSDimitry Andric 
250885868e8aSDimitry Andric   // If -thinlto-index-only is given, we should create only "index
250985868e8aSDimitry Andric   // files" and not object files. Index file creation is already done
2510bdd1243dSDimitry Andric   // in addCombinedLTOObject, so we are done if that's the case.
25115f757f3fSDimitry Andric   // Likewise, don't emit object files for other /lldemit options.
25125f757f3fSDimitry Andric   if (config->emit != EmitKind::Obj || config->thinLTOIndexOnly)
251385868e8aSDimitry Andric     return;
251485868e8aSDimitry Andric 
251585868e8aSDimitry Andric   // If we generated native object files from bitcode files, this resolves
251685868e8aSDimitry Andric   // references to the symbols we use from them.
251785868e8aSDimitry Andric   run();
251885868e8aSDimitry Andric 
2519e8d8bef9SDimitry Andric   // Apply symbol renames for -wrap.
2520e8d8bef9SDimitry Andric   if (!wrapped.empty())
2521349cc55cSDimitry Andric     wrapSymbols(ctx, wrapped);
2522e8d8bef9SDimitry Andric 
252385868e8aSDimitry Andric   // Resolve remaining undefined symbols and warn about imported locals.
2524349cc55cSDimitry Andric   ctx.symtab.resolveRemainingUndefines();
252585868e8aSDimitry Andric   if (errorCount())
252685868e8aSDimitry Andric     return;
252785868e8aSDimitry Andric 
25280b57cec5SDimitry Andric   if (config->mingw) {
25290b57cec5SDimitry Andric     // Make sure the crtend.o object is the last object file. This object
25300b57cec5SDimitry Andric     // file can contain terminating section chunks that need to be placed
25310b57cec5SDimitry Andric     // last. GNU ld processes files and static libraries explicitly in the
25320b57cec5SDimitry Andric     // order provided on the command line, while lld will pull in needed
25330b57cec5SDimitry Andric     // files from static libraries only after the last object file on the
25340b57cec5SDimitry Andric     // command line.
2535349cc55cSDimitry Andric     for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end();
25360b57cec5SDimitry Andric          i != e; i++) {
25370b57cec5SDimitry Andric       ObjFile *file = *i;
25380b57cec5SDimitry Andric       if (isCrtend(file->getName())) {
2539349cc55cSDimitry Andric         ctx.objFileInstances.erase(i);
2540349cc55cSDimitry Andric         ctx.objFileInstances.push_back(file);
25410b57cec5SDimitry Andric         break;
25420b57cec5SDimitry Andric       }
25430b57cec5SDimitry Andric     }
25440b57cec5SDimitry Andric   }
25450b57cec5SDimitry Andric 
25460b57cec5SDimitry Andric   // Windows specific -- when we are creating a .dll file, we also
254785868e8aSDimitry Andric   // need to create a .lib file. In MinGW mode, we only do that when the
254885868e8aSDimitry Andric   // -implib option is given explicitly, for compatibility with GNU ld.
25490b57cec5SDimitry Andric   if (!config->exports.empty() || config->dll) {
25505f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Create .lib exports");
25510b57cec5SDimitry Andric     fixupExports();
255281ad6265SDimitry Andric     if (!config->noimplib && (!config->mingw || !config->implib.empty()))
25530b57cec5SDimitry Andric       createImportLibrary(/*asLib=*/false);
25540b57cec5SDimitry Andric     assignExportOrdinals();
25550b57cec5SDimitry Andric   }
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric   // Handle /output-def (MinGW specific).
25580b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_output_def))
2559bdd1243dSDimitry Andric     writeDefFile(arg->getValue(), config->exports);
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric   // Set extra alignment for .comm symbols
25620b57cec5SDimitry Andric   for (auto pair : config->alignComm) {
25630b57cec5SDimitry Andric     StringRef name = pair.first;
25640b57cec5SDimitry Andric     uint32_t alignment = pair.second;
25650b57cec5SDimitry Andric 
2566349cc55cSDimitry Andric     Symbol *sym = ctx.symtab.find(name);
25670b57cec5SDimitry Andric     if (!sym) {
25680b57cec5SDimitry Andric       warn("/aligncomm symbol " + name + " not found");
25690b57cec5SDimitry Andric       continue;
25700b57cec5SDimitry Andric     }
25710b57cec5SDimitry Andric 
25720b57cec5SDimitry Andric     // If the symbol isn't common, it must have been replaced with a regular
25730b57cec5SDimitry Andric     // symbol, which will carry its own alignment.
25740b57cec5SDimitry Andric     auto *dc = dyn_cast<DefinedCommon>(sym);
25750b57cec5SDimitry Andric     if (!dc)
25760b57cec5SDimitry Andric       continue;
25770b57cec5SDimitry Andric 
25780b57cec5SDimitry Andric     CommonChunk *c = dc->getChunk();
25790b57cec5SDimitry Andric     c->setAlignment(std::max(c->getAlignment(), alignment));
25800b57cec5SDimitry Andric   }
25810b57cec5SDimitry Andric 
2582349cc55cSDimitry Andric   // Windows specific -- Create an embedded or side-by-side manifest.
2583349cc55cSDimitry Andric   // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2584349cc55cSDimitry Andric   // also passed.
2585349cc55cSDimitry Andric   if (config->manifest == Configuration::Embed)
2586349cc55cSDimitry Andric     addBuffer(createManifestRes(), false, false);
2587349cc55cSDimitry Andric   else if (config->manifest == Configuration::SideBySide ||
2588349cc55cSDimitry Andric            (config->manifest == Configuration::Default &&
2589349cc55cSDimitry Andric             !config->manifestDependencies.empty()))
25900b57cec5SDimitry Andric     createSideBySideManifest();
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric   // Handle /order. We want to do this at this moment because we
25930b57cec5SDimitry Andric   // need a complete list of comdat sections to warn on nonexistent
25940b57cec5SDimitry Andric   // functions.
2595e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_order)) {
2596e8d8bef9SDimitry Andric     if (args.hasArg(OPT_call_graph_ordering_file))
2597e8d8bef9SDimitry Andric       error("/order and /call-graph-order-file may not be used together");
2598bdd1243dSDimitry Andric     parseOrderFile(arg->getValue());
2599e8d8bef9SDimitry Andric     config->callGraphProfileSort = false;
2600e8d8bef9SDimitry Andric   }
2601e8d8bef9SDimitry Andric 
2602e8d8bef9SDimitry Andric   // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2603e8d8bef9SDimitry Andric   if (config->callGraphProfileSort) {
26045f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Call graph");
2605e8d8bef9SDimitry Andric     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2606bdd1243dSDimitry Andric       parseCallGraphFile(arg->getValue());
2607e8d8bef9SDimitry Andric     }
2608349cc55cSDimitry Andric     readCallGraphsFromObjectFiles(ctx);
2609e8d8bef9SDimitry Andric   }
2610e8d8bef9SDimitry Andric 
2611e8d8bef9SDimitry Andric   // Handle /print-symbol-order.
2612e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2613e8d8bef9SDimitry Andric     config->printSymbolOrder = arg->getValue();
26140b57cec5SDimitry Andric 
2615*0fca6ea1SDimitry Andric   ctx.symtab.initializeEntryThunks();
2616*0fca6ea1SDimitry Andric 
26170b57cec5SDimitry Andric   // Identify unreferenced COMDAT sections.
2618fe6060f1SDimitry Andric   if (config->doGC) {
2619fe6060f1SDimitry Andric     if (config->mingw) {
2620fe6060f1SDimitry Andric       // markLive doesn't traverse .eh_frame, but the personality function is
2621fe6060f1SDimitry Andric       // only reached that way. The proper solution would be to parse and
2622fe6060f1SDimitry Andric       // traverse the .eh_frame section, like the ELF linker does.
2623fe6060f1SDimitry Andric       // For now, just manually try to retain the known possible personality
2624fe6060f1SDimitry Andric       // functions. This doesn't bring in more object files, but only marks
2625fe6060f1SDimitry Andric       // functions that already have been included to be retained.
2626bdd1243dSDimitry Andric       for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0",
2627bdd1243dSDimitry Andric                             "rust_eh_personality"}) {
2628349cc55cSDimitry Andric         Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n));
2629fe6060f1SDimitry Andric         if (d && !d->isGCRoot) {
2630fe6060f1SDimitry Andric           d->isGCRoot = true;
2631fe6060f1SDimitry Andric           config->gcroot.push_back(d);
2632fe6060f1SDimitry Andric         }
2633fe6060f1SDimitry Andric       }
2634fe6060f1SDimitry Andric     }
2635fe6060f1SDimitry Andric 
2636349cc55cSDimitry Andric     markLive(ctx);
2637fe6060f1SDimitry Andric   }
26380b57cec5SDimitry Andric 
26390b57cec5SDimitry Andric   // Needs to happen after the last call to addFile().
264085868e8aSDimitry Andric   convertResources();
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   // Identify identical COMDAT sections to merge them.
2643fe6060f1SDimitry Andric   if (config->doICF != ICFLevel::None) {
2644349cc55cSDimitry Andric     findKeepUniqueSections(ctx);
2645bdd1243dSDimitry Andric     doICF(ctx);
26460b57cec5SDimitry Andric   }
26470b57cec5SDimitry Andric 
26480b57cec5SDimitry Andric   // Write the result.
2649349cc55cSDimitry Andric   writeResult(ctx);
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric   // Stop early so we can print the results.
26525ffd83dbSDimitry Andric   rootTimer.stop();
26530b57cec5SDimitry Andric   if (config->showTiming)
2654349cc55cSDimitry Andric     ctx.rootTimer.print();
26555f757f3fSDimitry Andric 
26565f757f3fSDimitry Andric   if (config->timeTraceEnabled) {
26575f757f3fSDimitry Andric     // Manually stop the topmost "COFF link" scope, since we're shutting down.
26585f757f3fSDimitry Andric     timeTraceProfilerEnd();
26595f757f3fSDimitry Andric 
26605f757f3fSDimitry Andric     checkError(timeTraceProfilerWrite(
26615f757f3fSDimitry Andric         args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
26625f757f3fSDimitry Andric     timeTraceProfilerCleanup();
26635f757f3fSDimitry Andric   }
26640b57cec5SDimitry Andric }
26650b57cec5SDimitry Andric 
2666bdd1243dSDimitry Andric } // namespace lld::coff
2667