xref: /freebsd/contrib/llvm-project/lld/COFF/Driver.cpp (revision 7a6dacaca14b62ca4b74406814becb87a3fefac0)
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/Object/WindowsMachineFlag.h"
350b57cec5SDimitry Andric #include "llvm/Option/Arg.h"
360b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
370b57cec5SDimitry Andric #include "llvm/Option/Option.h"
38e8d8bef9SDimitry Andric #include "llvm/Support/BinaryStreamReader.h"
39480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
400b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
410b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
420b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
435ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
440b57cec5SDimitry Andric #include "llvm/Support/Path.h"
450b57cec5SDimitry Andric #include "llvm/Support/Process.h"
460b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
470b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.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 
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".
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>
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".
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$/.
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.
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.
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 
159bdd1243dSDimitry Andric llvm::Triple::ArchType LinkerDriver::getArch() {
160bdd1243dSDimitry Andric   switch (ctx.config.machine) {
16181ad6265SDimitry Andric   case I386:
16281ad6265SDimitry Andric     return llvm::Triple::ArchType::x86;
16381ad6265SDimitry Andric   case AMD64:
16481ad6265SDimitry Andric     return llvm::Triple::ArchType::x86_64;
16581ad6265SDimitry Andric   case ARMNT:
16681ad6265SDimitry Andric     return llvm::Triple::ArchType::arm;
16781ad6265SDimitry Andric   case ARM64:
16881ad6265SDimitry Andric     return llvm::Triple::ArchType::aarch64;
16981ad6265SDimitry Andric   default:
17081ad6265SDimitry Andric     return llvm::Triple::ArchType::UnknownArch;
17181ad6265SDimitry Andric   }
17281ad6265SDimitry Andric }
17381ad6265SDimitry Andric 
174349cc55cSDimitry Andric bool LinkerDriver::findUnderscoreMangle(StringRef sym) {
175349cc55cSDimitry Andric   Symbol *s = ctx.symtab.findMangle(mangle(sym));
1760b57cec5SDimitry Andric   return s && !isa<Undefined>(s);
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
1800b57cec5SDimitry Andric   MemoryBufferRef mbref = *mb;
1810b57cec5SDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
1820b57cec5SDimitry Andric 
183bdd1243dSDimitry Andric   if (ctx.driver.tar)
184bdd1243dSDimitry Andric     ctx.driver.tar->append(relativeToRoot(mbref.getBufferIdentifier()),
1850b57cec5SDimitry Andric                            mbref.getBuffer());
1860b57cec5SDimitry Andric   return mbref;
1870b57cec5SDimitry Andric }
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
19085868e8aSDimitry Andric                              bool wholeArchive, bool lazy) {
1910b57cec5SDimitry Andric   StringRef filename = mb->getBufferIdentifier();
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   MemoryBufferRef mbref = takeBuffer(std::move(mb));
1940b57cec5SDimitry Andric   filePaths.push_back(filename);
1950b57cec5SDimitry Andric 
1960b57cec5SDimitry Andric   // File type is detected by contents, not by file extension.
1970b57cec5SDimitry Andric   switch (identify_magic(mbref.getBuffer())) {
1980b57cec5SDimitry Andric   case file_magic::windows_resource:
1990b57cec5SDimitry Andric     resources.push_back(mbref);
2000b57cec5SDimitry Andric     break;
2010b57cec5SDimitry Andric   case file_magic::archive:
2020b57cec5SDimitry Andric     if (wholeArchive) {
2030b57cec5SDimitry Andric       std::unique_ptr<Archive> file =
2040b57cec5SDimitry Andric           CHECK(Archive::create(mbref), filename + ": failed to parse archive");
2050b57cec5SDimitry Andric       Archive *archive = file.get();
2060b57cec5SDimitry Andric       make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
2070b57cec5SDimitry Andric 
20885868e8aSDimitry Andric       int memberIndex = 0;
2090b57cec5SDimitry Andric       for (MemoryBufferRef m : getArchiveMembers(archive))
21085868e8aSDimitry Andric         addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
2110b57cec5SDimitry Andric       return;
2120b57cec5SDimitry Andric     }
213349cc55cSDimitry Andric     ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref));
2140b57cec5SDimitry Andric     break;
2150b57cec5SDimitry Andric   case file_magic::bitcode:
21604eeddc0SDimitry Andric     ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy));
2170b57cec5SDimitry Andric     break;
2180b57cec5SDimitry Andric   case file_magic::coff_object:
2190b57cec5SDimitry Andric   case file_magic::coff_import_library:
22004eeddc0SDimitry Andric     ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy));
2210b57cec5SDimitry Andric     break;
2220b57cec5SDimitry Andric   case file_magic::pdb:
223349cc55cSDimitry Andric     ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref));
2240b57cec5SDimitry Andric     break;
2250b57cec5SDimitry Andric   case file_magic::coff_cl_gl_object:
2260b57cec5SDimitry Andric     error(filename + ": is not a native COFF file. Recompile without /GL");
2270b57cec5SDimitry Andric     break;
2280b57cec5SDimitry Andric   case file_magic::pecoff_executable:
229bdd1243dSDimitry Andric     if (ctx.config.mingw) {
230349cc55cSDimitry Andric       ctx.symtab.addFile(make<DLLFile>(ctx, mbref));
231fe6060f1SDimitry Andric       break;
232fe6060f1SDimitry Andric     }
23306c3fb27SDimitry Andric     if (filename.ends_with_insensitive(".dll")) {
2340b57cec5SDimitry Andric       error(filename + ": bad file type. Did you specify a DLL instead of an "
2350b57cec5SDimitry Andric                        "import library?");
2360b57cec5SDimitry Andric       break;
2370b57cec5SDimitry Andric     }
238bdd1243dSDimitry Andric     [[fallthrough]];
2390b57cec5SDimitry Andric   default:
2400b57cec5SDimitry Andric     error(mbref.getBufferIdentifier() + ": unknown file type");
2410b57cec5SDimitry Andric     break;
2420b57cec5SDimitry Andric   }
2430b57cec5SDimitry Andric }
2440b57cec5SDimitry Andric 
24585868e8aSDimitry Andric void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
2465ffd83dbSDimitry Andric   auto future = std::make_shared<std::future<MBErrPair>>(
2475ffd83dbSDimitry Andric       createFutureForFile(std::string(path)));
2485ffd83dbSDimitry Andric   std::string pathStr = std::string(path);
2490b57cec5SDimitry Andric   enqueueTask([=]() {
2505f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("File: ", path);
25106c3fb27SDimitry Andric     auto [mb, ec] = future->get();
25206c3fb27SDimitry Andric     if (ec) {
25306c3fb27SDimitry Andric       // Retry reading the file (synchronously) now that we may have added
25406c3fb27SDimitry Andric       // winsysroot search paths from SymbolTable::addFile().
25506c3fb27SDimitry Andric       // Retrying synchronously is important for keeping the order of inputs
25606c3fb27SDimitry Andric       // consistent.
25706c3fb27SDimitry Andric       // This makes it so that if the user passes something in the winsysroot
25806c3fb27SDimitry Andric       // before something we can find with an architecture, we won't find the
25906c3fb27SDimitry Andric       // winsysroot file.
26006c3fb27SDimitry Andric       if (std::optional<StringRef> retryPath = findFileIfNew(pathStr)) {
26106c3fb27SDimitry Andric         auto retryMb = MemoryBuffer::getFile(*retryPath, /*IsText=*/false,
26206c3fb27SDimitry Andric                                              /*RequiresNullTerminator=*/false);
26306c3fb27SDimitry Andric         ec = retryMb.getError();
26406c3fb27SDimitry Andric         if (!ec)
26506c3fb27SDimitry Andric           mb = std::move(*retryMb);
26606c3fb27SDimitry Andric       } else {
26706c3fb27SDimitry Andric         // We've already handled this file.
26806c3fb27SDimitry Andric         return;
26906c3fb27SDimitry Andric       }
27006c3fb27SDimitry Andric     }
27106c3fb27SDimitry Andric     if (ec) {
27206c3fb27SDimitry Andric       std::string msg = "could not open '" + pathStr + "': " + ec.message();
2730b57cec5SDimitry Andric       // Check if the filename is a typo for an option flag. OptTable thinks
2740b57cec5SDimitry Andric       // that all args that are not known options and that start with / are
2750b57cec5SDimitry Andric       // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
2760b57cec5SDimitry Andric       // the option `/nodefaultlib` than a reference to a file in the root
2770b57cec5SDimitry Andric       // directory.
2780b57cec5SDimitry Andric       std::string nearest;
279bdd1243dSDimitry Andric       if (ctx.optTable.findNearest(pathStr, nearest) > 1)
2800b57cec5SDimitry Andric         error(msg);
2810b57cec5SDimitry Andric       else
2820b57cec5SDimitry Andric         error(msg + "; did you mean '" + nearest + "'");
2830b57cec5SDimitry Andric     } else
28406c3fb27SDimitry Andric       ctx.driver.addBuffer(std::move(mb), wholeArchive, lazy);
2850b57cec5SDimitry Andric   });
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
2890b57cec5SDimitry Andric                                     StringRef parentName,
2900b57cec5SDimitry Andric                                     uint64_t offsetInArchive) {
2910b57cec5SDimitry Andric   file_magic magic = identify_magic(mb.getBuffer());
2920b57cec5SDimitry Andric   if (magic == file_magic::coff_import_library) {
293349cc55cSDimitry Andric     InputFile *imp = make<ImportFile>(ctx, mb);
2940b57cec5SDimitry Andric     imp->parentName = parentName;
295349cc55cSDimitry Andric     ctx.symtab.addFile(imp);
2960b57cec5SDimitry Andric     return;
2970b57cec5SDimitry Andric   }
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   InputFile *obj;
3000b57cec5SDimitry Andric   if (magic == file_magic::coff_object) {
301349cc55cSDimitry Andric     obj = make<ObjFile>(ctx, mb);
3020b57cec5SDimitry Andric   } else if (magic == file_magic::bitcode) {
30304eeddc0SDimitry Andric     obj =
30404eeddc0SDimitry Andric         make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false);
305bdd1243dSDimitry Andric   } else if (magic == file_magic::coff_cl_gl_object) {
306bdd1243dSDimitry Andric     error(mb.getBufferIdentifier() +
307bdd1243dSDimitry Andric           ": is not a native COFF file. Recompile without /GL?");
308bdd1243dSDimitry Andric     return;
3090b57cec5SDimitry Andric   } else {
3100b57cec5SDimitry Andric     error("unknown file type: " + mb.getBufferIdentifier());
3110b57cec5SDimitry Andric     return;
3120b57cec5SDimitry Andric   }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric   obj->parentName = parentName;
315349cc55cSDimitry Andric   ctx.symtab.addFile(obj);
3160b57cec5SDimitry Andric   log("Loaded " + toString(obj) + " for " + symName);
3170b57cec5SDimitry Andric }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
3200b57cec5SDimitry Andric                                         const Archive::Symbol &sym,
3210b57cec5SDimitry Andric                                         StringRef parentName) {
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   auto reportBufferError = [=](Error &&e, StringRef childName) {
3240b57cec5SDimitry Andric     fatal("could not get the buffer for the member defining symbol " +
325bdd1243dSDimitry Andric           toCOFFString(ctx, sym) + ": " + parentName + "(" + childName +
326bdd1243dSDimitry Andric           "): " + toString(std::move(e)));
3270b57cec5SDimitry Andric   };
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   if (!c.getParent()->isThin()) {
3300b57cec5SDimitry Andric     uint64_t offsetInArchive = c.getChildOffset();
3310b57cec5SDimitry Andric     Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
3320b57cec5SDimitry Andric     if (!mbOrErr)
3330b57cec5SDimitry Andric       reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
3340b57cec5SDimitry Andric     MemoryBufferRef mb = mbOrErr.get();
3350b57cec5SDimitry Andric     enqueueTask([=]() {
3365f757f3fSDimitry Andric       llvm::TimeTraceScope timeScope("Archive: ", mb.getBufferIdentifier());
337bdd1243dSDimitry Andric       ctx.driver.addArchiveBuffer(mb, toCOFFString(ctx, sym), parentName,
3380b57cec5SDimitry Andric                                   offsetInArchive);
3390b57cec5SDimitry Andric     });
3400b57cec5SDimitry Andric     return;
3410b57cec5SDimitry Andric   }
3420b57cec5SDimitry Andric 
343bdd1243dSDimitry Andric   std::string childName =
344bdd1243dSDimitry Andric       CHECK(c.getFullName(),
3450b57cec5SDimitry Andric             "could not get the filename for the member defining symbol " +
346bdd1243dSDimitry Andric                 toCOFFString(ctx, sym));
3473bd749dbSDimitry Andric   auto future =
3483bd749dbSDimitry Andric       std::make_shared<std::future<MBErrPair>>(createFutureForFile(childName));
3490b57cec5SDimitry Andric   enqueueTask([=]() {
3500b57cec5SDimitry Andric     auto mbOrErr = future->get();
3510b57cec5SDimitry Andric     if (mbOrErr.second)
3520b57cec5SDimitry Andric       reportBufferError(errorCodeToError(mbOrErr.second), childName);
3535f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Archive: ",
3545f757f3fSDimitry Andric                                    mbOrErr.first->getBufferIdentifier());
35585868e8aSDimitry Andric     // Pass empty string as archive name so that the original filename is
35685868e8aSDimitry Andric     // used as the buffer identifier.
357bdd1243dSDimitry Andric     ctx.driver.addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
358bdd1243dSDimitry Andric                                 toCOFFString(ctx, sym), "",
359bdd1243dSDimitry Andric                                 /*OffsetInArchive=*/0);
3600b57cec5SDimitry Andric   });
3610b57cec5SDimitry Andric }
3620b57cec5SDimitry Andric 
363bdd1243dSDimitry Andric bool LinkerDriver::isDecorated(StringRef sym) {
36406c3fb27SDimitry Andric   return sym.starts_with("@") || sym.contains("@@") || sym.starts_with("?") ||
365bdd1243dSDimitry Andric          (!ctx.config.mingw && sym.contains('@'));
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric // Parses .drectve section contents and returns a list of files
3690b57cec5SDimitry Andric // specified by /defaultlib.
3700b57cec5SDimitry Andric void LinkerDriver::parseDirectives(InputFile *file) {
3710b57cec5SDimitry Andric   StringRef s = file->getDirectives();
3720b57cec5SDimitry Andric   if (s.empty())
3730b57cec5SDimitry Andric     return;
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric   log("Directives: " + toString(file) + ": " + s);
3760b57cec5SDimitry Andric 
377bdd1243dSDimitry Andric   ArgParser parser(ctx);
3780b57cec5SDimitry Andric   // .drectve is always tokenized using Windows shell rules.
3790b57cec5SDimitry Andric   // /EXPORT: option can appear too many times, processing in fastpath.
3805ffd83dbSDimitry Andric   ParsedDirectives directives = parser.parseDirectives(s);
3810b57cec5SDimitry Andric 
3825ffd83dbSDimitry Andric   for (StringRef e : directives.exports) {
3830b57cec5SDimitry Andric     // If a common header file contains dllexported function
3840b57cec5SDimitry Andric     // declarations, many object files may end up with having the
3850b57cec5SDimitry Andric     // same /EXPORT options. In order to save cost of parsing them,
3860b57cec5SDimitry Andric     // we dedup them first.
3870b57cec5SDimitry Andric     if (!directivesExports.insert(e).second)
3880b57cec5SDimitry Andric       continue;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     Export exp = parseExport(e);
391bdd1243dSDimitry Andric     if (ctx.config.machine == I386 && ctx.config.mingw) {
3920b57cec5SDimitry Andric       if (!isDecorated(exp.name))
39304eeddc0SDimitry Andric         exp.name = saver().save("_" + exp.name);
3940b57cec5SDimitry Andric       if (!exp.extName.empty() && !isDecorated(exp.extName))
39504eeddc0SDimitry Andric         exp.extName = saver().save("_" + exp.extName);
3960b57cec5SDimitry Andric     }
39706c3fb27SDimitry Andric     exp.source = ExportSource::Directives;
398bdd1243dSDimitry Andric     ctx.config.exports.push_back(exp);
3990b57cec5SDimitry Andric   }
4000b57cec5SDimitry Andric 
4015ffd83dbSDimitry Andric   // Handle /include: in bulk.
4025ffd83dbSDimitry Andric   for (StringRef inc : directives.includes)
4035ffd83dbSDimitry Andric     addUndefined(inc);
4045ffd83dbSDimitry Andric 
40561cfbce3SDimitry Andric   // Handle /exclude-symbols: in bulk.
40661cfbce3SDimitry Andric   for (StringRef e : directives.excludes) {
40761cfbce3SDimitry Andric     SmallVector<StringRef, 2> vec;
40861cfbce3SDimitry Andric     e.split(vec, ',');
40961cfbce3SDimitry Andric     for (StringRef sym : vec)
41061cfbce3SDimitry Andric       excludedSymbols.insert(mangle(sym));
41161cfbce3SDimitry Andric   }
41261cfbce3SDimitry Andric 
413349cc55cSDimitry Andric   // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
4145ffd83dbSDimitry Andric   for (auto *arg : directives.args) {
4150b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
4160b57cec5SDimitry Andric     case OPT_aligncomm:
4170b57cec5SDimitry Andric       parseAligncomm(arg->getValue());
4180b57cec5SDimitry Andric       break;
4190b57cec5SDimitry Andric     case OPT_alternatename:
4200b57cec5SDimitry Andric       parseAlternateName(arg->getValue());
4210b57cec5SDimitry Andric       break;
4220b57cec5SDimitry Andric     case OPT_defaultlib:
42306c3fb27SDimitry Andric       if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
42485868e8aSDimitry Andric         enqueuePath(*path, false, false);
4250b57cec5SDimitry Andric       break;
4260b57cec5SDimitry Andric     case OPT_entry:
427bdd1243dSDimitry Andric       ctx.config.entry = addUndefined(mangle(arg->getValue()));
4280b57cec5SDimitry Andric       break;
4290b57cec5SDimitry Andric     case OPT_failifmismatch:
4300b57cec5SDimitry Andric       checkFailIfMismatch(arg->getValue(), file);
4310b57cec5SDimitry Andric       break;
4320b57cec5SDimitry Andric     case OPT_incl:
4330b57cec5SDimitry Andric       addUndefined(arg->getValue());
4340b57cec5SDimitry Andric       break;
435349cc55cSDimitry Andric     case OPT_manifestdependency:
436bdd1243dSDimitry Andric       ctx.config.manifestDependencies.insert(arg->getValue());
437349cc55cSDimitry Andric       break;
4380b57cec5SDimitry Andric     case OPT_merge:
4390b57cec5SDimitry Andric       parseMerge(arg->getValue());
4400b57cec5SDimitry Andric       break;
4410b57cec5SDimitry Andric     case OPT_nodefaultlib:
44206c3fb27SDimitry Andric       ctx.config.noDefaultLibs.insert(findLib(arg->getValue()).lower());
443bdd1243dSDimitry Andric       break;
444bdd1243dSDimitry Andric     case OPT_release:
445bdd1243dSDimitry Andric       ctx.config.writeCheckSum = true;
4460b57cec5SDimitry Andric       break;
4470b57cec5SDimitry Andric     case OPT_section:
4480b57cec5SDimitry Andric       parseSection(arg->getValue());
4490b57cec5SDimitry Andric       break;
450fe6060f1SDimitry Andric     case OPT_stack:
451bdd1243dSDimitry Andric       parseNumbers(arg->getValue(), &ctx.config.stackReserve,
452bdd1243dSDimitry Andric                    &ctx.config.stackCommit);
453fe6060f1SDimitry Andric       break;
454e8d8bef9SDimitry Andric     case OPT_subsystem: {
455e8d8bef9SDimitry Andric       bool gotVersion = false;
456bdd1243dSDimitry Andric       parseSubsystem(arg->getValue(), &ctx.config.subsystem,
457bdd1243dSDimitry Andric                      &ctx.config.majorSubsystemVersion,
458bdd1243dSDimitry Andric                      &ctx.config.minorSubsystemVersion, &gotVersion);
459e8d8bef9SDimitry Andric       if (gotVersion) {
460bdd1243dSDimitry Andric         ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion;
461bdd1243dSDimitry Andric         ctx.config.minorOSVersion = ctx.config.minorSubsystemVersion;
462e8d8bef9SDimitry Andric       }
4630b57cec5SDimitry Andric       break;
464e8d8bef9SDimitry Andric     }
4650b57cec5SDimitry Andric     // Only add flags here that link.exe accepts in
4660b57cec5SDimitry Andric     // `#pragma comment(linker, "/flag")`-generated sections.
4670b57cec5SDimitry Andric     case OPT_editandcontinue:
4680b57cec5SDimitry Andric     case OPT_guardsym:
4690b57cec5SDimitry Andric     case OPT_throwingnew:
470cbe9438cSDimitry Andric     case OPT_inferasanlibs:
471cbe9438cSDimitry Andric     case OPT_inferasanlibs_no:
4720b57cec5SDimitry Andric       break;
4730b57cec5SDimitry Andric     default:
474cbe9438cSDimitry Andric       error(arg->getSpelling() + " is not allowed in .drectve (" +
475cbe9438cSDimitry Andric             toString(file) + ")");
4760b57cec5SDimitry Andric     }
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes
4810b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist.
48206c3fb27SDimitry Andric StringRef LinkerDriver::findFile(StringRef filename) {
483bdd1243dSDimitry Andric   auto getFilename = [this](StringRef filename) -> StringRef {
484bdd1243dSDimitry Andric     if (ctx.config.vfs)
485bdd1243dSDimitry Andric       if (auto statOrErr = ctx.config.vfs->status(filename))
486753f127fSDimitry Andric         return saver().save(statOrErr->getName());
487753f127fSDimitry Andric     return filename;
488753f127fSDimitry Andric   };
489753f127fSDimitry Andric 
49006c3fb27SDimitry Andric   if (sys::path::is_absolute(filename))
491753f127fSDimitry Andric     return getFilename(filename);
4920b57cec5SDimitry Andric   bool hasExt = filename.contains('.');
4930b57cec5SDimitry Andric   for (StringRef dir : searchPaths) {
4940b57cec5SDimitry Andric     SmallString<128> path = dir;
4950b57cec5SDimitry Andric     sys::path::append(path, filename);
496753f127fSDimitry Andric     path = SmallString<128>{getFilename(path.str())};
4970b57cec5SDimitry Andric     if (sys::fs::exists(path.str()))
49804eeddc0SDimitry Andric       return saver().save(path.str());
4990b57cec5SDimitry Andric     if (!hasExt) {
5000b57cec5SDimitry Andric       path.append(".obj");
501753f127fSDimitry Andric       path = SmallString<128>{getFilename(path.str())};
5020b57cec5SDimitry Andric       if (sys::fs::exists(path.str()))
50304eeddc0SDimitry Andric         return saver().save(path.str());
5040b57cec5SDimitry Andric     }
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric   return filename;
5070b57cec5SDimitry Andric }
5080b57cec5SDimitry Andric 
509bdd1243dSDimitry Andric static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
5100b57cec5SDimitry Andric   sys::fs::UniqueID ret;
5110b57cec5SDimitry Andric   if (sys::fs::getUniqueID(path, ret))
512bdd1243dSDimitry Andric     return std::nullopt;
5130b57cec5SDimitry Andric   return ret;
5140b57cec5SDimitry Andric }
5150b57cec5SDimitry Andric 
5160b57cec5SDimitry Andric // Resolves a file path. This never returns the same path
517bdd1243dSDimitry Andric // (in that case, it returns std::nullopt).
51806c3fb27SDimitry Andric std::optional<StringRef> LinkerDriver::findFileIfNew(StringRef filename) {
51906c3fb27SDimitry Andric   StringRef path = findFile(filename);
5200b57cec5SDimitry Andric 
521bdd1243dSDimitry Andric   if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) {
5220b57cec5SDimitry Andric     bool seen = !visitedFiles.insert(*id).second;
5230b57cec5SDimitry Andric     if (seen)
524bdd1243dSDimitry Andric       return std::nullopt;
5250b57cec5SDimitry Andric   }
5260b57cec5SDimitry Andric 
52706c3fb27SDimitry Andric   if (path.ends_with_insensitive(".lib"))
52881ad6265SDimitry Andric     visitedLibs.insert(std::string(sys::path::filename(path).lower()));
5290b57cec5SDimitry Andric   return path;
5300b57cec5SDimitry Andric }
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to
5330b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead.
53406c3fb27SDimitry Andric StringRef LinkerDriver::findLibMinGW(StringRef filename) {
5350b57cec5SDimitry Andric   if (filename.contains('/') || filename.contains('\\'))
5360b57cec5SDimitry Andric     return filename;
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric   SmallString<128> s = filename;
5390b57cec5SDimitry Andric   sys::path::replace_extension(s, ".a");
54004eeddc0SDimitry Andric   StringRef libName = saver().save("lib" + s.str());
54106c3fb27SDimitry Andric   return findFile(libName);
5420b57cec5SDimitry Andric }
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric // Find library file from search path.
54506c3fb27SDimitry Andric StringRef LinkerDriver::findLib(StringRef filename) {
5460b57cec5SDimitry Andric   // Add ".lib" to Filename if that has no file extension.
5470b57cec5SDimitry Andric   bool hasExt = filename.contains('.');
5480b57cec5SDimitry Andric   if (!hasExt)
54904eeddc0SDimitry Andric     filename = saver().save(filename + ".lib");
55006c3fb27SDimitry Andric   StringRef ret = findFile(filename);
5510b57cec5SDimitry Andric   // For MinGW, if the find above didn't turn up anything, try
5520b57cec5SDimitry Andric   // looking for a MinGW formatted library name.
553bdd1243dSDimitry Andric   if (ctx.config.mingw && ret == filename)
55406c3fb27SDimitry Andric     return findLibMinGW(filename);
5550b57cec5SDimitry Andric   return ret;
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into
5590b57cec5SDimitry Andric // consideration. This never returns the same path (in that case,
560bdd1243dSDimitry Andric // it returns std::nullopt).
56106c3fb27SDimitry Andric std::optional<StringRef> LinkerDriver::findLibIfNew(StringRef filename) {
562bdd1243dSDimitry Andric   if (ctx.config.noDefaultLibAll)
563bdd1243dSDimitry Andric     return std::nullopt;
5640b57cec5SDimitry Andric   if (!visitedLibs.insert(filename.lower()).second)
565bdd1243dSDimitry Andric     return std::nullopt;
5660b57cec5SDimitry Andric 
56706c3fb27SDimitry Andric   StringRef path = findLib(filename);
568bdd1243dSDimitry Andric   if (ctx.config.noDefaultLibs.count(path.lower()))
569bdd1243dSDimitry Andric     return std::nullopt;
5700b57cec5SDimitry Andric 
571bdd1243dSDimitry Andric   if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
5720b57cec5SDimitry Andric     if (!visitedFiles.insert(*id).second)
573bdd1243dSDimitry Andric       return std::nullopt;
5740b57cec5SDimitry Andric   return path;
5750b57cec5SDimitry Andric }
5760b57cec5SDimitry Andric 
57781ad6265SDimitry Andric void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
57881ad6265SDimitry Andric   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
57981ad6265SDimitry Andric 
58081ad6265SDimitry Andric   // Check the command line first, that's the user explicitly telling us what to
58181ad6265SDimitry Andric   // use. Check the environment next, in case we're being invoked from a VS
58281ad6265SDimitry Andric   // command prompt. Failing that, just try to find the newest Visual Studio
58381ad6265SDimitry Andric   // version we can and use its default VC toolchain.
584bdd1243dSDimitry Andric   std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
58581ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_vctoolsdir))
58681ad6265SDimitry Andric     VCToolsDir = A->getValue();
58781ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_vctoolsversion))
58881ad6265SDimitry Andric     VCToolsVersion = A->getValue();
58981ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_winsysroot))
59081ad6265SDimitry Andric     WinSysRoot = A->getValue();
59181ad6265SDimitry Andric   if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
59281ad6265SDimitry Andric                                      WinSysRoot, vcToolChainPath, vsLayout) &&
59381ad6265SDimitry Andric       (Args.hasArg(OPT_lldignoreenv) ||
59481ad6265SDimitry Andric        !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
59506c3fb27SDimitry Andric       !findVCToolChainViaSetupConfig(*VFS, {}, vcToolChainPath, vsLayout) &&
59681ad6265SDimitry Andric       !findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
59781ad6265SDimitry Andric     return;
59881ad6265SDimitry Andric 
59981ad6265SDimitry Andric   // If the VC environment hasn't been configured (perhaps because the user did
60081ad6265SDimitry Andric   // not run vcvarsall), try to build a consistent link environment.  If the
60181ad6265SDimitry Andric   // environment variable is set however, assume the user knows what they're
60281ad6265SDimitry Andric   // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
60381ad6265SDimitry Andric   // vars.
60481ad6265SDimitry Andric   if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
60581ad6265SDimitry Andric     diaPath = A->getValue();
60681ad6265SDimitry Andric     if (A->getOption().getID() == OPT_winsysroot)
60781ad6265SDimitry Andric       path::append(diaPath, "DIA SDK");
60881ad6265SDimitry Andric   }
60981ad6265SDimitry Andric   useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
61081ad6265SDimitry Andric                          !Process::GetEnv("LIB") ||
61181ad6265SDimitry Andric                          Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
61281ad6265SDimitry Andric   if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
61381ad6265SDimitry Andric       Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
614bdd1243dSDimitry Andric     std::optional<StringRef> WinSdkDir, WinSdkVersion;
61581ad6265SDimitry Andric     if (auto *A = Args.getLastArg(OPT_winsdkdir))
61681ad6265SDimitry Andric       WinSdkDir = A->getValue();
61781ad6265SDimitry Andric     if (auto *A = Args.getLastArg(OPT_winsdkversion))
61881ad6265SDimitry Andric       WinSdkVersion = A->getValue();
61981ad6265SDimitry Andric 
62081ad6265SDimitry Andric     if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
62181ad6265SDimitry Andric       std::string UniversalCRTSdkPath;
62281ad6265SDimitry Andric       std::string UCRTVersion;
62381ad6265SDimitry Andric       if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
62481ad6265SDimitry Andric                                 UniversalCRTSdkPath, UCRTVersion)) {
62581ad6265SDimitry Andric         universalCRTLibPath = UniversalCRTSdkPath;
62681ad6265SDimitry Andric         path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
62781ad6265SDimitry Andric       }
62881ad6265SDimitry Andric     }
62981ad6265SDimitry Andric 
63081ad6265SDimitry Andric     std::string sdkPath;
63181ad6265SDimitry Andric     std::string windowsSDKIncludeVersion;
63281ad6265SDimitry Andric     std::string windowsSDKLibVersion;
63381ad6265SDimitry Andric     if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
63481ad6265SDimitry Andric                          sdkMajor, windowsSDKIncludeVersion,
63581ad6265SDimitry Andric                          windowsSDKLibVersion)) {
63681ad6265SDimitry Andric       windowsSdkLibPath = sdkPath;
63781ad6265SDimitry Andric       path::append(windowsSdkLibPath, "Lib");
63881ad6265SDimitry Andric       if (sdkMajor >= 8)
63981ad6265SDimitry Andric         path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
64081ad6265SDimitry Andric     }
64181ad6265SDimitry Andric   }
64281ad6265SDimitry Andric }
64381ad6265SDimitry Andric 
64406c3fb27SDimitry Andric void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
64506c3fb27SDimitry Andric   std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
64606c3fb27SDimitry Andric   SmallString<128> binDir(lldBinary);
64706c3fb27SDimitry Andric   sys::path::remove_filename(binDir);                 // remove lld-link.exe
64806c3fb27SDimitry Andric   StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
64906c3fb27SDimitry Andric 
65006c3fb27SDimitry Andric   SmallString<128> libDir(rootDir);
65106c3fb27SDimitry Andric   sys::path::append(libDir, "lib");
65206c3fb27SDimitry Andric 
65306c3fb27SDimitry Andric   // Add the resource dir library path
65406c3fb27SDimitry Andric   SmallString<128> runtimeLibDir(rootDir);
6553bd749dbSDimitry Andric   sys::path::append(runtimeLibDir, "lib", "clang",
6563bd749dbSDimitry Andric                     std::to_string(LLVM_VERSION_MAJOR), "lib");
65706c3fb27SDimitry Andric   // Resource dir + osname, which is hardcoded to windows since we are in the
65806c3fb27SDimitry Andric   // COFF driver.
65906c3fb27SDimitry Andric   SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
66006c3fb27SDimitry Andric   sys::path::append(runtimeLibDirWithOS, "windows");
66106c3fb27SDimitry Andric 
6623bd749dbSDimitry Andric   searchPaths.push_back(saver().save(runtimeLibDirWithOS.str()));
6633bd749dbSDimitry Andric   searchPaths.push_back(saver().save(runtimeLibDir.str()));
6643bd749dbSDimitry Andric   searchPaths.push_back(saver().save(libDir.str()));
66506c3fb27SDimitry Andric }
66606c3fb27SDimitry Andric 
66781ad6265SDimitry Andric void LinkerDriver::addWinSysRootLibSearchPaths() {
66881ad6265SDimitry Andric   if (!diaPath.empty()) {
66981ad6265SDimitry Andric     // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
67081ad6265SDimitry Andric     path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
67181ad6265SDimitry Andric     searchPaths.push_back(saver().save(diaPath.str()));
67281ad6265SDimitry Andric   }
67381ad6265SDimitry Andric   if (useWinSysRootLibPath) {
67481ad6265SDimitry Andric     searchPaths.push_back(saver().save(getSubDirectoryPath(
67581ad6265SDimitry Andric         SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
67681ad6265SDimitry Andric     searchPaths.push_back(saver().save(
67781ad6265SDimitry Andric         getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
67881ad6265SDimitry Andric                             getArch(), "atlmfc")));
67981ad6265SDimitry Andric   }
68081ad6265SDimitry Andric   if (!universalCRTLibPath.empty()) {
68181ad6265SDimitry Andric     StringRef ArchName = archToWindowsSDKArch(getArch());
68281ad6265SDimitry Andric     if (!ArchName.empty()) {
68381ad6265SDimitry Andric       path::append(universalCRTLibPath, ArchName);
68481ad6265SDimitry Andric       searchPaths.push_back(saver().save(universalCRTLibPath.str()));
68581ad6265SDimitry Andric     }
68681ad6265SDimitry Andric   }
68781ad6265SDimitry Andric   if (!windowsSdkLibPath.empty()) {
68881ad6265SDimitry Andric     std::string path;
68981ad6265SDimitry Andric     if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
69081ad6265SDimitry Andric                                       path))
69181ad6265SDimitry Andric       searchPaths.push_back(saver().save(path));
69281ad6265SDimitry Andric   }
69381ad6265SDimitry Andric }
69481ad6265SDimitry Andric 
6950b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths.
6960b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() {
697bdd1243dSDimitry Andric   std::optional<std::string> envOpt = Process::GetEnv("LIB");
69881ad6265SDimitry Andric   if (!envOpt)
6990b57cec5SDimitry Andric     return;
70004eeddc0SDimitry Andric   StringRef env = saver().save(*envOpt);
7010b57cec5SDimitry Andric   while (!env.empty()) {
7020b57cec5SDimitry Andric     StringRef path;
7030b57cec5SDimitry Andric     std::tie(path, env) = env.split(';');
7040b57cec5SDimitry Andric     searchPaths.push_back(path);
7050b57cec5SDimitry Andric   }
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) {
709349cc55cSDimitry Andric   Symbol *b = ctx.symtab.addUndefined(name);
7100b57cec5SDimitry Andric   if (!b->isGCRoot) {
7110b57cec5SDimitry Andric     b->isGCRoot = true;
712bdd1243dSDimitry Andric     ctx.config.gcroot.push_back(b);
7130b57cec5SDimitry Andric   }
7140b57cec5SDimitry Andric   return b;
7150b57cec5SDimitry Andric }
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) {
7180b57cec5SDimitry Andric   // If the plain symbol name has already been resolved, do nothing.
7190b57cec5SDimitry Andric   Undefined *unmangled = dyn_cast<Undefined>(s);
7200b57cec5SDimitry Andric   if (!unmangled)
7210b57cec5SDimitry Andric     return "";
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   // Otherwise, see if a similar, mangled symbol exists in the symbol table.
724349cc55cSDimitry Andric   Symbol *mangled = ctx.symtab.findMangle(unmangled->getName());
7250b57cec5SDimitry Andric   if (!mangled)
7260b57cec5SDimitry Andric     return "";
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   // If we find a similar mangled symbol, make this an alias to it and return
7290b57cec5SDimitry Andric   // its name.
7300b57cec5SDimitry Andric   log(unmangled->getName() + " aliased to " + mangled->getName());
731349cc55cSDimitry Andric   unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName());
7320b57cec5SDimitry Andric   return mangled->getName();
7330b57cec5SDimitry Andric }
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric // Windows specific -- find default entry point name.
7360b57cec5SDimitry Andric //
7370b57cec5SDimitry Andric // There are four different entry point functions for Windows executables,
7380b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function
7390b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function.
7400b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() {
741bdd1243dSDimitry Andric   assert(ctx.config.subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
7420b57cec5SDimitry Andric          "must handle /subsystem before calling this");
7430b57cec5SDimitry Andric 
744bdd1243dSDimitry Andric   if (ctx.config.mingw)
745bdd1243dSDimitry Andric     return mangle(ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
7460b57cec5SDimitry Andric                       ? "WinMainCRTStartup"
7470b57cec5SDimitry Andric                       : "mainCRTStartup");
7480b57cec5SDimitry Andric 
749bdd1243dSDimitry Andric   if (ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
7500b57cec5SDimitry Andric     if (findUnderscoreMangle("wWinMain")) {
7510b57cec5SDimitry Andric       if (!findUnderscoreMangle("WinMain"))
7520b57cec5SDimitry Andric         return mangle("wWinMainCRTStartup");
7530b57cec5SDimitry Andric       warn("found both wWinMain and WinMain; using latter");
7540b57cec5SDimitry Andric     }
7550b57cec5SDimitry Andric     return mangle("WinMainCRTStartup");
7560b57cec5SDimitry Andric   }
7570b57cec5SDimitry Andric   if (findUnderscoreMangle("wmain")) {
7580b57cec5SDimitry Andric     if (!findUnderscoreMangle("main"))
7590b57cec5SDimitry Andric       return mangle("wmainCRTStartup");
7600b57cec5SDimitry Andric     warn("found both wmain and main; using latter");
7610b57cec5SDimitry Andric   }
7620b57cec5SDimitry Andric   return mangle("mainCRTStartup");
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() {
766bdd1243dSDimitry Andric   if (ctx.config.dll)
7670b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
768bdd1243dSDimitry Andric   if (ctx.config.mingw)
7690b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
7700b57cec5SDimitry Andric   // Note that link.exe infers the subsystem from the presence of these
7710b57cec5SDimitry Andric   // functions even if /entry: or /nodefaultlib are passed which causes them
7720b57cec5SDimitry Andric   // to not be called.
7730b57cec5SDimitry Andric   bool haveMain = findUnderscoreMangle("main");
7740b57cec5SDimitry Andric   bool haveWMain = findUnderscoreMangle("wmain");
7750b57cec5SDimitry Andric   bool haveWinMain = findUnderscoreMangle("WinMain");
7760b57cec5SDimitry Andric   bool haveWWinMain = findUnderscoreMangle("wWinMain");
7770b57cec5SDimitry Andric   if (haveMain || haveWMain) {
7780b57cec5SDimitry Andric     if (haveWinMain || haveWWinMain) {
7790b57cec5SDimitry Andric       warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
7800b57cec5SDimitry Andric            (haveWinMain ? "WinMain" : "wWinMain") +
7810b57cec5SDimitry Andric            "; defaulting to /subsystem:console");
7820b57cec5SDimitry Andric     }
7830b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
7840b57cec5SDimitry Andric   }
7850b57cec5SDimitry Andric   if (haveWinMain || haveWWinMain)
7860b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
7870b57cec5SDimitry Andric   return IMAGE_SUBSYSTEM_UNKNOWN;
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
790bdd1243dSDimitry Andric uint64_t LinkerDriver::getDefaultImageBase() {
791bdd1243dSDimitry Andric   if (ctx.config.is64())
792bdd1243dSDimitry Andric     return ctx.config.dll ? 0x180000000 : 0x140000000;
793bdd1243dSDimitry Andric   return ctx.config.dll ? 0x10000000 : 0x400000;
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
796fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) {
797fe6060f1SDimitry Andric   if (fs::exists(s))
798fe6060f1SDimitry Andric     return relativeToRoot(s);
799fe6060f1SDimitry Andric   return std::string(s);
800fe6060f1SDimitry Andric }
801fe6060f1SDimitry Andric 
802fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run
803fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce.
8040b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args,
8050b57cec5SDimitry Andric                                       ArrayRef<StringRef> filePaths,
8060b57cec5SDimitry Andric                                       ArrayRef<StringRef> searchPaths) {
8070b57cec5SDimitry Andric   SmallString<0> data;
8080b57cec5SDimitry Andric   raw_svector_ostream os(data);
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   for (auto *arg : args) {
8110b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
8120b57cec5SDimitry Andric     case OPT_linkrepro:
81385868e8aSDimitry Andric     case OPT_reproduce:
8140b57cec5SDimitry Andric     case OPT_INPUT:
8150b57cec5SDimitry Andric     case OPT_defaultlib:
8160b57cec5SDimitry Andric     case OPT_libpath:
81781ad6265SDimitry Andric     case OPT_winsysroot:
8180b57cec5SDimitry Andric       break;
819fe6060f1SDimitry Andric     case OPT_call_graph_ordering_file:
820fe6060f1SDimitry Andric     case OPT_deffile:
821349cc55cSDimitry Andric     case OPT_manifestinput:
822fe6060f1SDimitry Andric     case OPT_natvis:
823fe6060f1SDimitry Andric       os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
824fe6060f1SDimitry Andric       break;
825fe6060f1SDimitry Andric     case OPT_order: {
826fe6060f1SDimitry Andric       StringRef orderFile = arg->getValue();
827fe6060f1SDimitry Andric       orderFile.consume_front("@");
828fe6060f1SDimitry Andric       os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
829fe6060f1SDimitry Andric       break;
830fe6060f1SDimitry Andric     }
831fe6060f1SDimitry Andric     case OPT_pdbstream: {
832fe6060f1SDimitry Andric       const std::pair<StringRef, StringRef> nameFile =
833fe6060f1SDimitry Andric           StringRef(arg->getValue()).split("=");
834fe6060f1SDimitry Andric       os << arg->getSpelling() << nameFile.first << '='
835fe6060f1SDimitry Andric          << quote(rewritePath(nameFile.second)) << '\n';
836fe6060f1SDimitry Andric       break;
837fe6060f1SDimitry Andric     }
8380b57cec5SDimitry Andric     case OPT_implib:
839349cc55cSDimitry Andric     case OPT_manifestfile:
8400b57cec5SDimitry Andric     case OPT_pdb:
8415ffd83dbSDimitry Andric     case OPT_pdbstripped:
8420b57cec5SDimitry Andric     case OPT_out:
8430b57cec5SDimitry Andric       os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
8440b57cec5SDimitry Andric       break;
8450b57cec5SDimitry Andric     default:
8460b57cec5SDimitry Andric       os << toString(*arg) << "\n";
8470b57cec5SDimitry Andric     }
8480b57cec5SDimitry Andric   }
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   for (StringRef path : searchPaths) {
8510b57cec5SDimitry Andric     std::string relPath = relativeToRoot(path);
8520b57cec5SDimitry Andric     os << "/libpath:" << quote(relPath) << "\n";
8530b57cec5SDimitry Andric   }
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric   for (StringRef path : filePaths)
8560b57cec5SDimitry Andric     os << quote(relativeToRoot(path)) << "\n";
8570b57cec5SDimitry Andric 
858*7a6dacacSDimitry Andric   return std::string(data);
8590b57cec5SDimitry Andric }
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) {
8620b57cec5SDimitry Andric   unsigned debugTypes = static_cast<unsigned>(DebugType::None);
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric   if (auto *a = args.getLastArg(OPT_debugtype)) {
8650b57cec5SDimitry Andric     SmallVector<StringRef, 3> types;
8660b57cec5SDimitry Andric     StringRef(a->getValue())
8670b57cec5SDimitry Andric         .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric     for (StringRef type : types) {
8700b57cec5SDimitry Andric       unsigned v = StringSwitch<unsigned>(type.lower())
8710b57cec5SDimitry Andric                        .Case("cv", static_cast<unsigned>(DebugType::CV))
8720b57cec5SDimitry Andric                        .Case("pdata", static_cast<unsigned>(DebugType::PData))
8730b57cec5SDimitry Andric                        .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
8740b57cec5SDimitry Andric                        .Default(0);
8750b57cec5SDimitry Andric       if (v == 0) {
8760b57cec5SDimitry Andric         warn("/debugtype: unknown option '" + type + "'");
8770b57cec5SDimitry Andric         continue;
8780b57cec5SDimitry Andric       }
8790b57cec5SDimitry Andric       debugTypes |= v;
8800b57cec5SDimitry Andric     }
8810b57cec5SDimitry Andric     return debugTypes;
8820b57cec5SDimitry Andric   }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   // Default debug types
8850b57cec5SDimitry Andric   debugTypes = static_cast<unsigned>(DebugType::CV);
8860b57cec5SDimitry Andric   if (args.hasArg(OPT_driver))
8870b57cec5SDimitry Andric     debugTypes |= static_cast<unsigned>(DebugType::PData);
8880b57cec5SDimitry Andric   if (args.hasArg(OPT_profile))
8890b57cec5SDimitry Andric     debugTypes |= static_cast<unsigned>(DebugType::Fixup);
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric   return debugTypes;
8920b57cec5SDimitry Andric }
8930b57cec5SDimitry Andric 
894bdd1243dSDimitry Andric std::string LinkerDriver::getMapFile(const opt::InputArgList &args,
895bdd1243dSDimitry Andric                                      opt::OptSpecifier os,
896bdd1243dSDimitry Andric                                      opt::OptSpecifier osFile) {
8975ffd83dbSDimitry Andric   auto *arg = args.getLastArg(os, osFile);
8980b57cec5SDimitry Andric   if (!arg)
8990b57cec5SDimitry Andric     return "";
9005ffd83dbSDimitry Andric   if (arg->getOption().getID() == osFile.getID())
9010b57cec5SDimitry Andric     return arg->getValue();
9020b57cec5SDimitry Andric 
9035ffd83dbSDimitry Andric   assert(arg->getOption().getID() == os.getID());
904bdd1243dSDimitry Andric   StringRef outFile = ctx.config.outputFile;
9050b57cec5SDimitry Andric   return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
9060b57cec5SDimitry Andric }
9070b57cec5SDimitry Andric 
908bdd1243dSDimitry Andric std::string LinkerDriver::getImplibPath() {
909bdd1243dSDimitry Andric   if (!ctx.config.implib.empty())
910bdd1243dSDimitry Andric     return std::string(ctx.config.implib);
911bdd1243dSDimitry Andric   SmallString<128> out = StringRef(ctx.config.outputFile);
9120b57cec5SDimitry Andric   sys::path::replace_extension(out, ".lib");
913*7a6dacacSDimitry Andric   return std::string(out);
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric 
91685868e8aSDimitry Andric // The import name is calculated as follows:
9170b57cec5SDimitry Andric //
9180b57cec5SDimitry Andric //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
9190b57cec5SDimitry Andric //   -----+----------------+---------------------+------------------
9200b57cec5SDimitry Andric //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
9210b57cec5SDimitry Andric //    LIB | {value}        | {value}.dll         | {output name}.dll
9220b57cec5SDimitry Andric //
923bdd1243dSDimitry Andric std::string LinkerDriver::getImportName(bool asLib) {
9240b57cec5SDimitry Andric   SmallString<128> out;
9250b57cec5SDimitry Andric 
926bdd1243dSDimitry Andric   if (ctx.config.importName.empty()) {
927bdd1243dSDimitry Andric     out.assign(sys::path::filename(ctx.config.outputFile));
9280b57cec5SDimitry Andric     if (asLib)
9290b57cec5SDimitry Andric       sys::path::replace_extension(out, ".dll");
9300b57cec5SDimitry Andric   } else {
931bdd1243dSDimitry Andric     out.assign(ctx.config.importName);
9320b57cec5SDimitry Andric     if (!sys::path::has_extension(out))
9330b57cec5SDimitry Andric       sys::path::replace_extension(out,
934bdd1243dSDimitry Andric                                    (ctx.config.dll || asLib) ? ".dll" : ".exe");
9350b57cec5SDimitry Andric   }
9360b57cec5SDimitry Andric 
937*7a6dacacSDimitry Andric   return std::string(out);
9380b57cec5SDimitry Andric }
9390b57cec5SDimitry Andric 
940bdd1243dSDimitry Andric void LinkerDriver::createImportLibrary(bool asLib) {
9415f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Create import library");
9420b57cec5SDimitry Andric   std::vector<COFFShortExport> exports;
943bdd1243dSDimitry Andric   for (Export &e1 : ctx.config.exports) {
9440b57cec5SDimitry Andric     COFFShortExport e2;
9455ffd83dbSDimitry Andric     e2.Name = std::string(e1.name);
9465ffd83dbSDimitry Andric     e2.SymbolName = std::string(e1.symbolName);
9475ffd83dbSDimitry Andric     e2.ExtName = std::string(e1.extName);
94804eeddc0SDimitry Andric     e2.AliasTarget = std::string(e1.aliasTarget);
9490b57cec5SDimitry Andric     e2.Ordinal = e1.ordinal;
9500b57cec5SDimitry Andric     e2.Noname = e1.noname;
9510b57cec5SDimitry Andric     e2.Data = e1.data;
9520b57cec5SDimitry Andric     e2.Private = e1.isPrivate;
9530b57cec5SDimitry Andric     e2.Constant = e1.constant;
9540b57cec5SDimitry Andric     exports.push_back(e2);
9550b57cec5SDimitry Andric   }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric   std::string libName = getImportName(asLib);
9580b57cec5SDimitry Andric   std::string path = getImplibPath();
9590b57cec5SDimitry Andric 
960bdd1243dSDimitry Andric   if (!ctx.config.incremental) {
961bdd1243dSDimitry Andric     checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
962bdd1243dSDimitry Andric                                   ctx.config.mingw));
9630b57cec5SDimitry Andric     return;
9640b57cec5SDimitry Andric   }
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric   // If the import library already exists, replace it only if the contents
9670b57cec5SDimitry Andric   // have changed.
9680b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
969fe6060f1SDimitry Andric       path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
9700b57cec5SDimitry Andric   if (!oldBuf) {
971bdd1243dSDimitry Andric     checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
972bdd1243dSDimitry Andric                                   ctx.config.mingw));
9730b57cec5SDimitry Andric     return;
9740b57cec5SDimitry Andric   }
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   SmallString<128> tmpName;
9770b57cec5SDimitry Andric   if (std::error_code ec =
9780b57cec5SDimitry Andric           sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
9790b57cec5SDimitry Andric     fatal("cannot create temporary file for import library " + path + ": " +
9800b57cec5SDimitry Andric           ec.message());
9810b57cec5SDimitry Andric 
982bdd1243dSDimitry Andric   if (Error e = writeImportLibrary(libName, tmpName, exports,
983bdd1243dSDimitry Andric                                    ctx.config.machine, ctx.config.mingw)) {
984349cc55cSDimitry Andric     checkError(std::move(e));
9850b57cec5SDimitry Andric     return;
9860b57cec5SDimitry Andric   }
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
989fe6060f1SDimitry Andric       tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
9900b57cec5SDimitry Andric   if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
9910b57cec5SDimitry Andric     oldBuf->reset();
992349cc55cSDimitry Andric     checkError(errorCodeToError(sys::fs::rename(tmpName, path)));
9930b57cec5SDimitry Andric   } else {
9940b57cec5SDimitry Andric     sys::fs::remove(tmpName);
9950b57cec5SDimitry Andric   }
9960b57cec5SDimitry Andric }
9970b57cec5SDimitry Andric 
998bdd1243dSDimitry Andric void LinkerDriver::parseModuleDefs(StringRef path) {
9995f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Parse def file");
1000fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
1001fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1002fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
1003fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
1004fe6060f1SDimitry Andric             "could not open " + path);
10050b57cec5SDimitry Andric   COFFModuleDefinition m = check(parseCOFFModuleDefinition(
1006bdd1243dSDimitry Andric       mb->getMemBufferRef(), ctx.config.machine, ctx.config.mingw));
10070b57cec5SDimitry Andric 
1008fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1009bdd1243dSDimitry Andric   ctx.driver.takeBuffer(std::move(mb));
1010fe6060f1SDimitry Andric 
1011bdd1243dSDimitry Andric   if (ctx.config.outputFile.empty())
1012bdd1243dSDimitry Andric     ctx.config.outputFile = std::string(saver().save(m.OutputFile));
1013bdd1243dSDimitry Andric   ctx.config.importName = std::string(saver().save(m.ImportName));
10140b57cec5SDimitry Andric   if (m.ImageBase)
1015bdd1243dSDimitry Andric     ctx.config.imageBase = m.ImageBase;
10160b57cec5SDimitry Andric   if (m.StackReserve)
1017bdd1243dSDimitry Andric     ctx.config.stackReserve = m.StackReserve;
10180b57cec5SDimitry Andric   if (m.StackCommit)
1019bdd1243dSDimitry Andric     ctx.config.stackCommit = m.StackCommit;
10200b57cec5SDimitry Andric   if (m.HeapReserve)
1021bdd1243dSDimitry Andric     ctx.config.heapReserve = m.HeapReserve;
10220b57cec5SDimitry Andric   if (m.HeapCommit)
1023bdd1243dSDimitry Andric     ctx.config.heapCommit = m.HeapCommit;
10240b57cec5SDimitry Andric   if (m.MajorImageVersion)
1025bdd1243dSDimitry Andric     ctx.config.majorImageVersion = m.MajorImageVersion;
10260b57cec5SDimitry Andric   if (m.MinorImageVersion)
1027bdd1243dSDimitry Andric     ctx.config.minorImageVersion = m.MinorImageVersion;
10280b57cec5SDimitry Andric   if (m.MajorOSVersion)
1029bdd1243dSDimitry Andric     ctx.config.majorOSVersion = m.MajorOSVersion;
10300b57cec5SDimitry Andric   if (m.MinorOSVersion)
1031bdd1243dSDimitry Andric     ctx.config.minorOSVersion = m.MinorOSVersion;
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   for (COFFShortExport e1 : m.Exports) {
10340b57cec5SDimitry Andric     Export e2;
10350b57cec5SDimitry Andric     // In simple cases, only Name is set. Renamed exports are parsed
10360b57cec5SDimitry Andric     // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
10370b57cec5SDimitry Andric     // it shouldn't be a normal exported function but a forward to another
10380b57cec5SDimitry Andric     // DLL instead. This is supported by both MS and GNU linkers.
10395ffd83dbSDimitry Andric     if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
10405ffd83dbSDimitry Andric         StringRef(e1.Name).contains('.')) {
104104eeddc0SDimitry Andric       e2.name = saver().save(e1.ExtName);
104204eeddc0SDimitry Andric       e2.forwardTo = saver().save(e1.Name);
1043bdd1243dSDimitry Andric       ctx.config.exports.push_back(e2);
10440b57cec5SDimitry Andric       continue;
10450b57cec5SDimitry Andric     }
104604eeddc0SDimitry Andric     e2.name = saver().save(e1.Name);
104704eeddc0SDimitry Andric     e2.extName = saver().save(e1.ExtName);
104804eeddc0SDimitry Andric     e2.aliasTarget = saver().save(e1.AliasTarget);
10490b57cec5SDimitry Andric     e2.ordinal = e1.Ordinal;
10500b57cec5SDimitry Andric     e2.noname = e1.Noname;
10510b57cec5SDimitry Andric     e2.data = e1.Data;
10520b57cec5SDimitry Andric     e2.isPrivate = e1.Private;
10530b57cec5SDimitry Andric     e2.constant = e1.Constant;
105406c3fb27SDimitry Andric     e2.source = ExportSource::ModuleDefinition;
1055bdd1243dSDimitry Andric     ctx.config.exports.push_back(e2);
10560b57cec5SDimitry Andric   }
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) {
10600b57cec5SDimitry Andric   taskQueue.push_back(std::move(task));
10610b57cec5SDimitry Andric }
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric bool LinkerDriver::run() {
10645f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Read input files");
1065349cc55cSDimitry Andric   ScopedTimer t(ctx.inputFileTimer);
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   bool didWork = !taskQueue.empty();
10680b57cec5SDimitry Andric   while (!taskQueue.empty()) {
10690b57cec5SDimitry Andric     taskQueue.front()();
10700b57cec5SDimitry Andric     taskQueue.pop_front();
10710b57cec5SDimitry Andric   }
10720b57cec5SDimitry Andric   return didWork;
10730b57cec5SDimitry Andric }
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places
10760b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the
10770b57cec5SDimitry Andric // given file.
1078bdd1243dSDimitry Andric void LinkerDriver::parseOrderFile(StringRef arg) {
10790b57cec5SDimitry Andric   // For some reason, the MSVC linker requires a filename to be
10800b57cec5SDimitry Andric   // preceded by "@".
108106c3fb27SDimitry Andric   if (!arg.starts_with("@")) {
10820b57cec5SDimitry Andric     error("malformed /order option: '@' missing");
10830b57cec5SDimitry Andric     return;
10840b57cec5SDimitry Andric   }
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   // Get a list of all comdat sections for error checking.
10870b57cec5SDimitry Andric   DenseSet<StringRef> set;
1088349cc55cSDimitry Andric   for (Chunk *c : ctx.symtab.getChunks())
10890b57cec5SDimitry Andric     if (auto *sec = dyn_cast<SectionChunk>(c))
10900b57cec5SDimitry Andric       if (sec->sym)
10910b57cec5SDimitry Andric         set.insert(sec->sym->getName());
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric   // Open a file.
10940b57cec5SDimitry Andric   StringRef path = arg.substr(1);
1095fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
1096fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1097fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
1098fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
1099fe6060f1SDimitry Andric             "could not open " + path);
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   // Parse a file. An order file contains one symbol per line.
11020b57cec5SDimitry Andric   // All symbols that were not present in a given order file are
11030b57cec5SDimitry Andric   // considered to have the lowest priority 0 and are placed at
11040b57cec5SDimitry Andric   // end of an output section.
11055ffd83dbSDimitry Andric   for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
11065ffd83dbSDimitry Andric     std::string s(arg);
1107bdd1243dSDimitry Andric     if (ctx.config.machine == I386 && !isDecorated(s))
11080b57cec5SDimitry Andric       s = "_" + s;
11090b57cec5SDimitry Andric 
11100b57cec5SDimitry Andric     if (set.count(s) == 0) {
1111bdd1243dSDimitry Andric       if (ctx.config.warnMissingOrderSymbol)
11120b57cec5SDimitry Andric         warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
11133bd749dbSDimitry Andric     } else
1114bdd1243dSDimitry Andric       ctx.config.order[s] = INT_MIN + ctx.config.order.size();
11150b57cec5SDimitry Andric   }
1116fe6060f1SDimitry Andric 
1117fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1118bdd1243dSDimitry Andric   ctx.driver.takeBuffer(std::move(mb));
11190b57cec5SDimitry Andric }
11200b57cec5SDimitry Andric 
1121bdd1243dSDimitry Andric void LinkerDriver::parseCallGraphFile(StringRef path) {
1122fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
1123fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1124fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
1125fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
1126fe6060f1SDimitry Andric             "could not open " + path);
1127e8d8bef9SDimitry Andric 
1128e8d8bef9SDimitry Andric   // Build a map from symbol name to section.
1129e8d8bef9SDimitry Andric   DenseMap<StringRef, Symbol *> map;
1130349cc55cSDimitry Andric   for (ObjFile *file : ctx.objFileInstances)
1131e8d8bef9SDimitry Andric     for (Symbol *sym : file->getSymbols())
1132e8d8bef9SDimitry Andric       if (sym)
1133e8d8bef9SDimitry Andric         map[sym->getName()] = sym;
1134e8d8bef9SDimitry Andric 
1135e8d8bef9SDimitry Andric   auto findSection = [&](StringRef name) -> SectionChunk * {
1136e8d8bef9SDimitry Andric     Symbol *sym = map.lookup(name);
1137e8d8bef9SDimitry Andric     if (!sym) {
1138bdd1243dSDimitry Andric       if (ctx.config.warnMissingOrderSymbol)
1139e8d8bef9SDimitry Andric         warn(path + ": no such symbol: " + name);
1140e8d8bef9SDimitry Andric       return nullptr;
1141e8d8bef9SDimitry Andric     }
1142e8d8bef9SDimitry Andric 
1143e8d8bef9SDimitry Andric     if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1144e8d8bef9SDimitry Andric       return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1145e8d8bef9SDimitry Andric     return nullptr;
1146e8d8bef9SDimitry Andric   };
1147e8d8bef9SDimitry Andric 
1148e8d8bef9SDimitry Andric   for (StringRef line : args::getLines(*mb)) {
1149e8d8bef9SDimitry Andric     SmallVector<StringRef, 3> fields;
1150e8d8bef9SDimitry Andric     line.split(fields, ' ');
1151e8d8bef9SDimitry Andric     uint64_t count;
1152e8d8bef9SDimitry Andric 
1153e8d8bef9SDimitry Andric     if (fields.size() != 3 || !to_integer(fields[2], count)) {
1154e8d8bef9SDimitry Andric       error(path + ": parse error");
1155e8d8bef9SDimitry Andric       return;
1156e8d8bef9SDimitry Andric     }
1157e8d8bef9SDimitry Andric 
1158e8d8bef9SDimitry Andric     if (SectionChunk *from = findSection(fields[0]))
1159e8d8bef9SDimitry Andric       if (SectionChunk *to = findSection(fields[1]))
1160bdd1243dSDimitry Andric         ctx.config.callGraphProfile[{from, to}] += count;
1161e8d8bef9SDimitry Andric   }
1162fe6060f1SDimitry Andric 
1163fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1164bdd1243dSDimitry Andric   ctx.driver.takeBuffer(std::move(mb));
1165e8d8bef9SDimitry Andric }
1166e8d8bef9SDimitry Andric 
1167349cc55cSDimitry Andric static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) {
1168349cc55cSDimitry Andric   for (ObjFile *obj : ctx.objFileInstances) {
1169e8d8bef9SDimitry Andric     if (obj->callgraphSec) {
1170e8d8bef9SDimitry Andric       ArrayRef<uint8_t> contents;
1171e8d8bef9SDimitry Andric       cantFail(
1172e8d8bef9SDimitry Andric           obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
11735f757f3fSDimitry Andric       BinaryStreamReader reader(contents, llvm::endianness::little);
1174e8d8bef9SDimitry Andric       while (!reader.empty()) {
1175e8d8bef9SDimitry Andric         uint32_t fromIndex, toIndex;
1176e8d8bef9SDimitry Andric         uint64_t count;
1177e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(fromIndex))
1178e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 32-bit integer");
1179e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(toIndex))
1180e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 32-bit integer");
1181e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(count))
1182e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 64-bit integer");
1183e8d8bef9SDimitry Andric         auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1184e8d8bef9SDimitry Andric         auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1185e8d8bef9SDimitry Andric         if (!fromSym || !toSym)
1186e8d8bef9SDimitry Andric           continue;
1187e8d8bef9SDimitry Andric         auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1188e8d8bef9SDimitry Andric         auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1189e8d8bef9SDimitry Andric         if (from && to)
1190bdd1243dSDimitry Andric           ctx.config.callGraphProfile[{from, to}] += count;
1191e8d8bef9SDimitry Andric       }
1192e8d8bef9SDimitry Andric     }
1193e8d8bef9SDimitry Andric   }
1194e8d8bef9SDimitry Andric }
1195e8d8bef9SDimitry Andric 
11960b57cec5SDimitry Andric static void markAddrsig(Symbol *s) {
11970b57cec5SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
11980b57cec5SDimitry Andric     if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
11990b57cec5SDimitry Andric       c->keepUnique = true;
12000b57cec5SDimitry Andric }
12010b57cec5SDimitry Andric 
1202349cc55cSDimitry Andric static void findKeepUniqueSections(COFFLinkerContext &ctx) {
12035f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Find keep unique sections");
12045f757f3fSDimitry Andric 
12050b57cec5SDimitry Andric   // Exported symbols could be address-significant in other executables or DSOs,
12060b57cec5SDimitry Andric   // so we conservatively mark them as address-significant.
1207bdd1243dSDimitry Andric   for (Export &r : ctx.config.exports)
12080b57cec5SDimitry Andric     markAddrsig(r.sym);
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric   // Visit the address-significance table in each object file and mark each
12110b57cec5SDimitry Andric   // referenced symbol as address-significant.
1212349cc55cSDimitry Andric   for (ObjFile *obj : ctx.objFileInstances) {
12130b57cec5SDimitry Andric     ArrayRef<Symbol *> syms = obj->getSymbols();
12140b57cec5SDimitry Andric     if (obj->addrsigSec) {
12150b57cec5SDimitry Andric       ArrayRef<uint8_t> contents;
12160b57cec5SDimitry Andric       cantFail(
12170b57cec5SDimitry Andric           obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
12180b57cec5SDimitry Andric       const uint8_t *cur = contents.begin();
12190b57cec5SDimitry Andric       while (cur != contents.end()) {
12200b57cec5SDimitry Andric         unsigned size;
12215f757f3fSDimitry Andric         const char *err = nullptr;
12220b57cec5SDimitry Andric         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
12230b57cec5SDimitry Andric         if (err)
12240b57cec5SDimitry Andric           fatal(toString(obj) + ": could not decode addrsig section: " + err);
12250b57cec5SDimitry Andric         if (symIndex >= syms.size())
12260b57cec5SDimitry Andric           fatal(toString(obj) + ": invalid symbol index in addrsig section");
12270b57cec5SDimitry Andric         markAddrsig(syms[symIndex]);
12280b57cec5SDimitry Andric         cur += size;
12290b57cec5SDimitry Andric       }
12300b57cec5SDimitry Andric     } else {
12310b57cec5SDimitry Andric       // If an object file does not have an address-significance table,
12320b57cec5SDimitry Andric       // conservatively mark all of its symbols as address-significant.
12330b57cec5SDimitry Andric       for (Symbol *s : syms)
12340b57cec5SDimitry Andric         markAddrsig(s);
12350b57cec5SDimitry Andric     }
12360b57cec5SDimitry Andric   }
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment
12400b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename
12410b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output
12420b57cec5SDimitry Andric // binary).
12430b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env
12440b57cec5SDimitry Andric // vars.
1245bdd1243dSDimitry Andric void LinkerDriver::parsePDBAltPath() {
12460b57cec5SDimitry Andric   SmallString<128> buf;
12470b57cec5SDimitry Andric   StringRef pdbBasename =
1248bdd1243dSDimitry Andric       sys::path::filename(ctx.config.pdbPath, sys::path::Style::windows);
12490b57cec5SDimitry Andric   StringRef binaryExtension =
1250bdd1243dSDimitry Andric       sys::path::extension(ctx.config.outputFile, sys::path::Style::windows);
12510b57cec5SDimitry Andric   if (!binaryExtension.empty())
12520b57cec5SDimitry Andric     binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric   // Invariant:
12550b57cec5SDimitry Andric   //   +--------- cursor ('a...' might be the empty string).
12560b57cec5SDimitry Andric   //   |   +----- firstMark
12570b57cec5SDimitry Andric   //   |   |   +- secondMark
12580b57cec5SDimitry Andric   //   v   v   v
12590b57cec5SDimitry Andric   //   a...%...%...
12600b57cec5SDimitry Andric   size_t cursor = 0;
1261bdd1243dSDimitry Andric   while (cursor < ctx.config.pdbAltPath.size()) {
12620b57cec5SDimitry Andric     size_t firstMark, secondMark;
1263bdd1243dSDimitry Andric     if ((firstMark = ctx.config.pdbAltPath.find('%', cursor)) ==
1264bdd1243dSDimitry Andric             StringRef::npos ||
1265bdd1243dSDimitry Andric         (secondMark = ctx.config.pdbAltPath.find('%', firstMark + 1)) ==
1266bdd1243dSDimitry Andric             StringRef::npos) {
12670b57cec5SDimitry Andric       // Didn't find another full fragment, treat rest of string as literal.
1268bdd1243dSDimitry Andric       buf.append(ctx.config.pdbAltPath.substr(cursor));
12690b57cec5SDimitry Andric       break;
12700b57cec5SDimitry Andric     }
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric     // Found a full fragment. Append text in front of first %, and interpret
12730b57cec5SDimitry Andric     // text between first and second % as variable name.
1274bdd1243dSDimitry Andric     buf.append(ctx.config.pdbAltPath.substr(cursor, firstMark - cursor));
1275bdd1243dSDimitry Andric     StringRef var =
1276bdd1243dSDimitry Andric         ctx.config.pdbAltPath.substr(firstMark, secondMark - firstMark + 1);
1277fe6060f1SDimitry Andric     if (var.equals_insensitive("%_pdb%"))
12780b57cec5SDimitry Andric       buf.append(pdbBasename);
1279fe6060f1SDimitry Andric     else if (var.equals_insensitive("%_ext%"))
12800b57cec5SDimitry Andric       buf.append(binaryExtension);
12810b57cec5SDimitry Andric     else {
12823bd749dbSDimitry Andric       warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + var +
12833bd749dbSDimitry Andric            " as literal");
12840b57cec5SDimitry Andric       buf.append(var);
12850b57cec5SDimitry Andric     }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric     cursor = secondMark + 1;
12880b57cec5SDimitry Andric   }
12890b57cec5SDimitry Andric 
1290bdd1243dSDimitry Andric   ctx.config.pdbAltPath = buf;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
129385868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object
129485868e8aSDimitry Andric /// trees into one resource tree.
12950b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete.
129685868e8aSDimitry Andric void LinkerDriver::convertResources() {
12975f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("Convert resources");
129885868e8aSDimitry Andric   std::vector<ObjFile *> resourceObjFiles;
129985868e8aSDimitry Andric 
1300349cc55cSDimitry Andric   for (ObjFile *f : ctx.objFileInstances) {
130185868e8aSDimitry Andric     if (f->isResourceObjFile())
130285868e8aSDimitry Andric       resourceObjFiles.push_back(f);
13030b57cec5SDimitry Andric   }
13040b57cec5SDimitry Andric 
1305bdd1243dSDimitry Andric   if (!ctx.config.mingw &&
130685868e8aSDimitry Andric       (resourceObjFiles.size() > 1 ||
130785868e8aSDimitry Andric        (resourceObjFiles.size() == 1 && !resources.empty()))) {
130885868e8aSDimitry Andric     error((!resources.empty() ? "internal .obj file created from .res files"
130985868e8aSDimitry Andric                               : toString(resourceObjFiles[1])) +
13100b57cec5SDimitry Andric           ": more than one resource obj file not allowed, already got " +
131185868e8aSDimitry Andric           toString(resourceObjFiles.front()));
131285868e8aSDimitry Andric     return;
13130b57cec5SDimitry Andric   }
131485868e8aSDimitry Andric 
131585868e8aSDimitry Andric   if (resources.empty() && resourceObjFiles.size() <= 1) {
131685868e8aSDimitry Andric     // No resources to convert, and max one resource object file in
131785868e8aSDimitry Andric     // the input. Keep that preconverted resource section as is.
131885868e8aSDimitry Andric     for (ObjFile *f : resourceObjFiles)
131985868e8aSDimitry Andric       f->includeResourceChunks();
132085868e8aSDimitry Andric     return;
132185868e8aSDimitry Andric   }
1322349cc55cSDimitry Andric   ObjFile *f =
1323349cc55cSDimitry Andric       make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles));
1324349cc55cSDimitry Andric   ctx.symtab.addFile(f);
132585868e8aSDimitry Andric   f->includeResourceChunks();
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are
13290b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the
13300b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are
13310b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the
13320b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
13330b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported.
13340b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1335fe6060f1SDimitry Andric   if (!args.hasArg(OPT_export_all_symbols)) {
1336bdd1243dSDimitry Andric     if (!ctx.config.dll)
13370b57cec5SDimitry Andric       return;
13380b57cec5SDimitry Andric 
1339bdd1243dSDimitry Andric     if (!ctx.config.exports.empty())
13400b57cec5SDimitry Andric       return;
13410b57cec5SDimitry Andric     if (args.hasArg(OPT_exclude_all_symbols))
13420b57cec5SDimitry Andric       return;
13430b57cec5SDimitry Andric   }
13440b57cec5SDimitry Andric 
1345bdd1243dSDimitry Andric   AutoExporter exporter(ctx, excludedSymbols);
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wholearchive_file))
134806c3fb27SDimitry Andric     if (std::optional<StringRef> path = findFile(arg->getValue()))
13490b57cec5SDimitry Andric       exporter.addWholeArchive(*path);
13500b57cec5SDimitry Andric 
135161cfbce3SDimitry Andric   for (auto *arg : args.filtered(OPT_exclude_symbols)) {
135261cfbce3SDimitry Andric     SmallVector<StringRef, 2> vec;
135361cfbce3SDimitry Andric     StringRef(arg->getValue()).split(vec, ',');
135461cfbce3SDimitry Andric     for (StringRef sym : vec)
135561cfbce3SDimitry Andric       exporter.addExcludedSymbol(mangle(sym));
135661cfbce3SDimitry Andric   }
135761cfbce3SDimitry Andric 
1358349cc55cSDimitry Andric   ctx.symtab.forEachSymbol([&](Symbol *s) {
13590b57cec5SDimitry Andric     auto *def = dyn_cast<Defined>(s);
1360bdd1243dSDimitry Andric     if (!exporter.shouldExport(def))
13610b57cec5SDimitry Andric       return;
13620b57cec5SDimitry Andric 
1363fe6060f1SDimitry Andric     if (!def->isGCRoot) {
1364fe6060f1SDimitry Andric       def->isGCRoot = true;
1365bdd1243dSDimitry Andric       ctx.config.gcroot.push_back(def);
1366fe6060f1SDimitry Andric     }
1367fe6060f1SDimitry Andric 
13680b57cec5SDimitry Andric     Export e;
13690b57cec5SDimitry Andric     e.name = def->getName();
13700b57cec5SDimitry Andric     e.sym = def;
13710b57cec5SDimitry Andric     if (Chunk *c = def->getChunk())
13720b57cec5SDimitry Andric       if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
13730b57cec5SDimitry Andric         e.data = true;
1374fe6060f1SDimitry Andric     s->isUsedInRegularObj = true;
1375bdd1243dSDimitry Andric     ctx.config.exports.push_back(e);
13760b57cec5SDimitry Andric   });
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric 
137985868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as
138085868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly
138185868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce.
138285868e8aSDimitry Andric //
138385868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
138485868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility
138585868e8aSDimitry Andric // with Microsoft link.exe.
1386bdd1243dSDimitry Andric std::optional<std::string> getReproduceFile(const opt::InputArgList &args) {
138785868e8aSDimitry Andric   if (auto *arg = args.getLastArg(OPT_reproduce))
138885868e8aSDimitry Andric     return std::string(arg->getValue());
138985868e8aSDimitry Andric 
139085868e8aSDimitry Andric   if (auto *arg = args.getLastArg(OPT_linkrepro)) {
139185868e8aSDimitry Andric     SmallString<64> path = StringRef(arg->getValue());
139285868e8aSDimitry Andric     sys::path::append(path, "repro.tar");
13935ffd83dbSDimitry Andric     return std::string(path);
139485868e8aSDimitry Andric   }
139585868e8aSDimitry Andric 
1396e8d8bef9SDimitry Andric   // This is intentionally not guarded by OPT_lldignoreenv since writing
1397e8d8bef9SDimitry Andric   // a repro tar file doesn't affect the main output.
1398e8d8bef9SDimitry Andric   if (auto *path = getenv("LLD_REPRODUCE"))
1399e8d8bef9SDimitry Andric     return std::string(path);
1400e8d8bef9SDimitry Andric 
1401bdd1243dSDimitry Andric   return std::nullopt;
140285868e8aSDimitry Andric }
14030b57cec5SDimitry Andric 
1404753f127fSDimitry Andric static std::unique_ptr<llvm::vfs::FileSystem>
1405753f127fSDimitry Andric getVFS(const opt::InputArgList &args) {
1406753f127fSDimitry Andric   using namespace llvm::vfs;
1407753f127fSDimitry Andric 
1408753f127fSDimitry Andric   const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay);
1409753f127fSDimitry Andric   if (!arg)
1410753f127fSDimitry Andric     return nullptr;
1411753f127fSDimitry Andric 
1412753f127fSDimitry Andric   auto bufOrErr = llvm::MemoryBuffer::getFile(arg->getValue());
1413753f127fSDimitry Andric   if (!bufOrErr) {
1414753f127fSDimitry Andric     checkError(errorCodeToError(bufOrErr.getError()));
1415753f127fSDimitry Andric     return nullptr;
1416753f127fSDimitry Andric   }
1417753f127fSDimitry Andric 
14183bd749dbSDimitry Andric   if (auto ret = vfs::getVFSFromYAML(std::move(*bufOrErr),
14193bd749dbSDimitry Andric                                      /*DiagHandler*/ nullptr, arg->getValue()))
1420753f127fSDimitry Andric     return ret;
1421753f127fSDimitry Andric 
1422753f127fSDimitry Andric   error("Invalid vfs overlay");
1423753f127fSDimitry Andric   return nullptr;
1424753f127fSDimitry Andric }
1425753f127fSDimitry Andric 
1426e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1427349cc55cSDimitry Andric   ScopedTimer rootTimer(ctx.rootTimer);
1428bdd1243dSDimitry Andric   Configuration *config = &ctx.config;
14295ffd83dbSDimitry Andric 
14300b57cec5SDimitry Andric   // Needed for LTO.
14310b57cec5SDimitry Andric   InitializeAllTargetInfos();
14320b57cec5SDimitry Andric   InitializeAllTargets();
14330b57cec5SDimitry Andric   InitializeAllTargetMCs();
14340b57cec5SDimitry Andric   InitializeAllAsmParsers();
14350b57cec5SDimitry Andric   InitializeAllAsmPrinters();
14360b57cec5SDimitry Andric 
14370b57cec5SDimitry Andric   // If the first command line argument is "/lib", link.exe acts like lib.exe.
14380b57cec5SDimitry Andric   // We call our own implementation of lib.exe that understands bitcode files.
1439fe6060f1SDimitry Andric   if (argsArr.size() > 1 &&
1440fe6060f1SDimitry Andric       (StringRef(argsArr[1]).equals_insensitive("/lib") ||
1441fe6060f1SDimitry Andric        StringRef(argsArr[1]).equals_insensitive("-lib"))) {
14420b57cec5SDimitry Andric     if (llvm::libDriverMain(argsArr.slice(1)) != 0)
14430b57cec5SDimitry Andric       fatal("lib failed");
14440b57cec5SDimitry Andric     return;
14450b57cec5SDimitry Andric   }
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric   // Parse command line options.
1448bdd1243dSDimitry Andric   ArgParser parser(ctx);
144985868e8aSDimitry Andric   opt::InputArgList args = parser.parse(argsArr);
14500b57cec5SDimitry Andric 
14515f757f3fSDimitry Andric   // Initialize time trace profiler.
14525f757f3fSDimitry Andric   config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
14535f757f3fSDimitry Andric   config->timeTraceGranularity =
14545f757f3fSDimitry Andric       args::getInteger(args, OPT_time_trace_granularity_eq, 500);
14555f757f3fSDimitry Andric 
14565f757f3fSDimitry Andric   if (config->timeTraceEnabled)
14575f757f3fSDimitry Andric     timeTraceProfilerInitialize(config->timeTraceGranularity, argsArr[0]);
14585f757f3fSDimitry Andric 
14595f757f3fSDimitry Andric   llvm::TimeTraceScope timeScope("COFF link");
14605f757f3fSDimitry Andric 
14610b57cec5SDimitry Andric   // Parse and evaluate -mllvm options.
14620b57cec5SDimitry Andric   std::vector<const char *> v;
14630b57cec5SDimitry Andric   v.push_back("lld-link (LLVM option parsing)");
1464bdd1243dSDimitry Andric   for (const auto *arg : args.filtered(OPT_mllvm)) {
14650b57cec5SDimitry Andric     v.push_back(arg->getValue());
1466bdd1243dSDimitry Andric     config->mllvmOpts.emplace_back(arg->getValue());
1467bdd1243dSDimitry Andric   }
14685f757f3fSDimitry Andric   {
14695f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Parse cl::opt");
1470e8d8bef9SDimitry Andric     cl::ResetAllOptionOccurrences();
14710b57cec5SDimitry Andric     cl::ParseCommandLineOptions(v.size(), v.data());
14725f757f3fSDimitry Andric   }
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   // Handle /errorlimit early, because error() depends on it.
14750b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_errorlimit)) {
14760b57cec5SDimitry Andric     int n = 20;
14770b57cec5SDimitry Andric     StringRef s = arg->getValue();
14780b57cec5SDimitry Andric     if (s.getAsInteger(10, n))
14790b57cec5SDimitry Andric       error(arg->getSpelling() + " number expected, but got " + s);
14800b57cec5SDimitry Andric     errorHandler().errorLimit = n;
14810b57cec5SDimitry Andric   }
14820b57cec5SDimitry Andric 
1483753f127fSDimitry Andric   config->vfs = getVFS(args);
1484753f127fSDimitry Andric 
14850b57cec5SDimitry Andric   // Handle /help
14860b57cec5SDimitry Andric   if (args.hasArg(OPT_help)) {
14870b57cec5SDimitry Andric     printHelp(argsArr[0]);
14880b57cec5SDimitry Andric     return;
14890b57cec5SDimitry Andric   }
14900b57cec5SDimitry Andric 
14915ffd83dbSDimitry Andric   // /threads: takes a positive integer and provides the default value for
14925ffd83dbSDimitry Andric   // /opt:lldltojobs=.
14935ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_threads)) {
14945ffd83dbSDimitry Andric     StringRef v(arg->getValue());
14955ffd83dbSDimitry Andric     unsigned threads = 0;
14965ffd83dbSDimitry Andric     if (!llvm::to_integer(v, threads, 0) || threads == 0)
14975ffd83dbSDimitry Andric       error(arg->getSpelling() + ": expected a positive integer, but got '" +
14985ffd83dbSDimitry Andric             arg->getValue() + "'");
14995ffd83dbSDimitry Andric     parallel::strategy = hardware_concurrency(threads);
15005ffd83dbSDimitry Andric     config->thinLTOJobs = v.str();
15015ffd83dbSDimitry Andric   }
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   if (args.hasArg(OPT_show_timing))
15040b57cec5SDimitry Andric     config->showTiming = true;
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric   config->showSummary = args.hasArg(OPT_summary);
150706c3fb27SDimitry Andric   config->printSearchPaths = args.hasArg(OPT_print_search_paths);
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   // Handle --version, which is an lld extension. This option is a bit odd
15100b57cec5SDimitry Andric   // because it doesn't start with "/", but we deliberately chose "--" to
15110b57cec5SDimitry Andric   // avoid conflict with /version and for compatibility with clang-cl.
15120b57cec5SDimitry Andric   if (args.hasArg(OPT_dash_dash_version)) {
1513e8d8bef9SDimitry Andric     message(getLLDVersion());
15140b57cec5SDimitry Andric     return;
15150b57cec5SDimitry Andric   }
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric   // Handle /lldmingw early, since it can potentially affect how other
15180b57cec5SDimitry Andric   // options are handled.
15190b57cec5SDimitry Andric   config->mingw = args.hasArg(OPT_lldmingw);
1520bdd1243dSDimitry Andric   if (config->mingw)
1521bdd1243dSDimitry Andric     ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now"
1522bdd1243dSDimitry Andric                                   " (use --error-limit=0 to see all errors)";
15230b57cec5SDimitry Andric 
152485868e8aSDimitry Andric   // Handle /linkrepro and /reproduce.
15255f757f3fSDimitry Andric   {
15265f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Reproducer");
1527bdd1243dSDimitry Andric     if (std::optional<std::string> path = getReproduceFile(args)) {
15280b57cec5SDimitry Andric       Expected<std::unique_ptr<TarWriter>> errOrWriter =
152985868e8aSDimitry Andric           TarWriter::create(*path, sys::path::stem(*path));
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric       if (errOrWriter) {
15320b57cec5SDimitry Andric         tar = std::move(*errOrWriter);
15330b57cec5SDimitry Andric       } else {
153485868e8aSDimitry Andric         error("/linkrepro: failed to open " + *path + ": " +
15350b57cec5SDimitry Andric               toString(errOrWriter.takeError()));
15360b57cec5SDimitry Andric       }
15370b57cec5SDimitry Andric     }
15385f757f3fSDimitry Andric   }
15390b57cec5SDimitry Andric 
1540480093f4SDimitry Andric   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
15410b57cec5SDimitry Andric     if (args.hasArg(OPT_deffile))
15420b57cec5SDimitry Andric       config->noEntry = true;
15430b57cec5SDimitry Andric     else
15440b57cec5SDimitry Andric       fatal("no input files");
15450b57cec5SDimitry Andric   }
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric   // Construct search path list.
15485f757f3fSDimitry Andric   {
15495f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Search paths");
155006c3fb27SDimitry Andric     searchPaths.emplace_back("");
1551*7a6dacacSDimitry Andric     for (auto *arg : args.filtered(OPT_libpath))
1552*7a6dacacSDimitry Andric       searchPaths.push_back(arg->getValue());
15535f757f3fSDimitry Andric     if (!config->mingw) {
15543bd749dbSDimitry Andric       // Prefer the Clang provided builtins over the ones bundled with MSVC.
15555f757f3fSDimitry Andric       // In MinGW mode, the compiler driver passes the necessary libpath
15565f757f3fSDimitry Andric       // options explicitly.
15573bd749dbSDimitry Andric       addClangLibSearchPaths(argsArr[0]);
15585f757f3fSDimitry Andric       // Don't automatically deduce the lib path from the environment or MSVC
15595f757f3fSDimitry Andric       // installations when operating in mingw mode. (This also makes LLD ignore
15605f757f3fSDimitry Andric       // winsysroot and vctoolsdir arguments.)
156181ad6265SDimitry Andric       detectWinSysRoot(args);
156281ad6265SDimitry Andric       if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
15630b57cec5SDimitry Andric         addLibSearchPaths();
15645f757f3fSDimitry Andric     } else {
15655f757f3fSDimitry Andric       if (args.hasArg(OPT_vctoolsdir, OPT_winsysroot))
15665f757f3fSDimitry Andric         warn("ignoring /vctoolsdir or /winsysroot flags in MinGW mode");
15675f757f3fSDimitry Andric     }
15685f757f3fSDimitry Andric   }
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   // Handle /ignore
15710b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_ignore)) {
15720b57cec5SDimitry Andric     SmallVector<StringRef, 8> vec;
15730b57cec5SDimitry Andric     StringRef(arg->getValue()).split(vec, ',');
15740b57cec5SDimitry Andric     for (StringRef s : vec) {
15750b57cec5SDimitry Andric       if (s == "4037")
15760b57cec5SDimitry Andric         config->warnMissingOrderSymbol = false;
15770b57cec5SDimitry Andric       else if (s == "4099")
15780b57cec5SDimitry Andric         config->warnDebugInfoUnusable = false;
15790b57cec5SDimitry Andric       else if (s == "4217")
15800b57cec5SDimitry Andric         config->warnLocallyDefinedImported = false;
1581480093f4SDimitry Andric       else if (s == "longsections")
1582480093f4SDimitry Andric         config->warnLongSectionNames = false;
15830b57cec5SDimitry Andric       // Other warning numbers are ignored.
15840b57cec5SDimitry Andric     }
15850b57cec5SDimitry Andric   }
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric   // Handle /out
15880b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_out))
15890b57cec5SDimitry Andric     config->outputFile = arg->getValue();
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric   // Handle /verbose
15920b57cec5SDimitry Andric   if (args.hasArg(OPT_verbose))
15930b57cec5SDimitry Andric     config->verbose = true;
15940b57cec5SDimitry Andric   errorHandler().verbose = config->verbose;
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric   // Handle /force or /force:unresolved
15970b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_unresolved))
15980b57cec5SDimitry Andric     config->forceUnresolved = true;
15990b57cec5SDimitry Andric 
16000b57cec5SDimitry Andric   // Handle /force or /force:multiple
16010b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_multiple))
16020b57cec5SDimitry Andric     config->forceMultiple = true;
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric   // Handle /force or /force:multipleres
16050b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_multipleres))
16060b57cec5SDimitry Andric     config->forceMultipleRes = true;
16070b57cec5SDimitry Andric 
16085f757f3fSDimitry Andric   // Don't warn about long section names, such as .debug_info, for mingw (or
16095f757f3fSDimitry Andric   // when -debug:dwarf is requested, handled below).
16105f757f3fSDimitry Andric   if (config->mingw)
16115f757f3fSDimitry Andric     config->warnLongSectionNames = false;
16125f757f3fSDimitry Andric 
16135f757f3fSDimitry Andric   bool doGC = true;
16145f757f3fSDimitry Andric 
16150b57cec5SDimitry Andric   // Handle /debug
16165f757f3fSDimitry Andric   bool shouldCreatePDB = false;
16175f757f3fSDimitry Andric   for (auto *arg : args.filtered(OPT_debug, OPT_debug_opt)) {
16185f757f3fSDimitry Andric     std::string str;
16195f757f3fSDimitry Andric     if (arg->getOption().getID() == OPT_debug)
16205f757f3fSDimitry Andric       str = "full";
16215f757f3fSDimitry Andric     else
16225f757f3fSDimitry Andric       str = StringRef(arg->getValue()).lower();
16235f757f3fSDimitry Andric     SmallVector<StringRef, 1> vec;
16245f757f3fSDimitry Andric     StringRef(str).split(vec, ',');
16255f757f3fSDimitry Andric     for (StringRef s : vec) {
16265f757f3fSDimitry Andric       if (s == "fastlink") {
16275f757f3fSDimitry Andric         warn("/debug:fastlink unsupported; using /debug:full");
16285f757f3fSDimitry Andric         s = "full";
16295f757f3fSDimitry Andric       }
16305f757f3fSDimitry Andric       if (s == "none") {
16315f757f3fSDimitry Andric         config->debug = false;
16325f757f3fSDimitry Andric         config->incremental = false;
16335f757f3fSDimitry Andric         config->includeDwarfChunks = false;
16345f757f3fSDimitry Andric         config->debugGHashes = false;
16355f757f3fSDimitry Andric         config->writeSymtab = false;
16365f757f3fSDimitry Andric         shouldCreatePDB = false;
16375f757f3fSDimitry Andric         doGC = true;
16385f757f3fSDimitry Andric       } else if (s == "full" || s == "ghash" || s == "noghash") {
16390b57cec5SDimitry Andric         config->debug = true;
16400b57cec5SDimitry Andric         config->incremental = true;
16415f757f3fSDimitry Andric         config->includeDwarfChunks = true;
16425f757f3fSDimitry Andric         if (s == "full" || s == "ghash")
16435f757f3fSDimitry Andric           config->debugGHashes = true;
16445f757f3fSDimitry Andric         shouldCreatePDB = true;
16455f757f3fSDimitry Andric         doGC = false;
16465f757f3fSDimitry Andric       } else if (s == "dwarf") {
16475f757f3fSDimitry Andric         config->debug = true;
16485f757f3fSDimitry Andric         config->incremental = true;
16495f757f3fSDimitry Andric         config->includeDwarfChunks = true;
16505f757f3fSDimitry Andric         config->writeSymtab = true;
16515f757f3fSDimitry Andric         config->warnLongSectionNames = false;
16525f757f3fSDimitry Andric         doGC = false;
16535f757f3fSDimitry Andric       } else if (s == "nodwarf") {
16545f757f3fSDimitry Andric         config->includeDwarfChunks = false;
16555f757f3fSDimitry Andric       } else if (s == "symtab") {
16565f757f3fSDimitry Andric         config->writeSymtab = true;
16575f757f3fSDimitry Andric         doGC = false;
16585f757f3fSDimitry Andric       } else if (s == "nosymtab") {
16595f757f3fSDimitry Andric         config->writeSymtab = false;
16605f757f3fSDimitry Andric       } else {
16615f757f3fSDimitry Andric         error("/debug: unknown option: " + s);
16625f757f3fSDimitry Andric       }
16635f757f3fSDimitry Andric     }
16640b57cec5SDimitry Andric   }
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric   // Handle /demangle
166781ad6265SDimitry Andric   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true);
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric   // Handle /debugtype
16700b57cec5SDimitry Andric   config->debugTypes = parseDebugTypes(args);
16710b57cec5SDimitry Andric 
1672480093f4SDimitry Andric   // Handle /driver[:uponly|:wdm].
1673480093f4SDimitry Andric   config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1674480093f4SDimitry Andric                          args.hasArg(OPT_driver_uponly_wdm) ||
1675480093f4SDimitry Andric                          args.hasArg(OPT_driver_wdm_uponly);
1676480093f4SDimitry Andric   config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1677480093f4SDimitry Andric                       args.hasArg(OPT_driver_uponly_wdm) ||
1678480093f4SDimitry Andric                       args.hasArg(OPT_driver_wdm_uponly);
1679480093f4SDimitry Andric   config->driver =
1680480093f4SDimitry Andric       config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1681480093f4SDimitry Andric 
16820b57cec5SDimitry Andric   // Handle /pdb
16830b57cec5SDimitry Andric   if (shouldCreatePDB) {
16840b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdb))
16850b57cec5SDimitry Andric       config->pdbPath = arg->getValue();
16860b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdbaltpath))
16870b57cec5SDimitry Andric       config->pdbAltPath = arg->getValue();
1688349cc55cSDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdbpagesize))
1689349cc55cSDimitry Andric       parsePDBPageSize(arg->getValue());
16900b57cec5SDimitry Andric     if (args.hasArg(OPT_natvis))
16910b57cec5SDimitry Andric       config->natvisFiles = args.getAllArgValues(OPT_natvis);
16925ffd83dbSDimitry Andric     if (args.hasArg(OPT_pdbstream)) {
16935ffd83dbSDimitry Andric       for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
16945ffd83dbSDimitry Andric         const std::pair<StringRef, StringRef> nameFile = value.split("=");
16955ffd83dbSDimitry Andric         const StringRef name = nameFile.first;
16965ffd83dbSDimitry Andric         const std::string file = nameFile.second.str();
16975ffd83dbSDimitry Andric         config->namedStreams[name] = file;
16985ffd83dbSDimitry Andric       }
16995ffd83dbSDimitry Andric     }
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdb_source_path))
17020b57cec5SDimitry Andric       config->pdbSourcePath = arg->getValue();
17030b57cec5SDimitry Andric   }
17040b57cec5SDimitry Andric 
17055ffd83dbSDimitry Andric   // Handle /pdbstripped
17065ffd83dbSDimitry Andric   if (args.hasArg(OPT_pdbstripped))
17075ffd83dbSDimitry Andric     warn("ignoring /pdbstripped flag, it is not yet supported");
17085ffd83dbSDimitry Andric 
17090b57cec5SDimitry Andric   // Handle /noentry
17100b57cec5SDimitry Andric   if (args.hasArg(OPT_noentry)) {
17110b57cec5SDimitry Andric     if (args.hasArg(OPT_dll))
17120b57cec5SDimitry Andric       config->noEntry = true;
17130b57cec5SDimitry Andric     else
17140b57cec5SDimitry Andric       error("/noentry must be specified with /dll");
17150b57cec5SDimitry Andric   }
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   // Handle /dll
17180b57cec5SDimitry Andric   if (args.hasArg(OPT_dll)) {
17190b57cec5SDimitry Andric     config->dll = true;
17200b57cec5SDimitry Andric     config->manifestID = 2;
17210b57cec5SDimitry Andric   }
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
17240b57cec5SDimitry Andric   // because we need to explicitly check whether that option or its inverse was
17250b57cec5SDimitry Andric   // present in the argument list in order to handle /fixed.
17260b57cec5SDimitry Andric   auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
17270b57cec5SDimitry Andric   if (dynamicBaseArg &&
17280b57cec5SDimitry Andric       dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
17290b57cec5SDimitry Andric     config->dynamicBase = false;
17300b57cec5SDimitry Andric 
17310b57cec5SDimitry Andric   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
17320b57cec5SDimitry Andric   // default setting for any other project type.", but link.exe defaults to
17330b57cec5SDimitry Andric   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
17340b57cec5SDimitry Andric   bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
17350b57cec5SDimitry Andric   if (fixed) {
17360b57cec5SDimitry Andric     if (dynamicBaseArg &&
17370b57cec5SDimitry Andric         dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
17380b57cec5SDimitry Andric       error("/fixed must not be specified with /dynamicbase");
17390b57cec5SDimitry Andric     } else {
17400b57cec5SDimitry Andric       config->relocatable = false;
17410b57cec5SDimitry Andric       config->dynamicBase = false;
17420b57cec5SDimitry Andric     }
17430b57cec5SDimitry Andric   }
17440b57cec5SDimitry Andric 
17450b57cec5SDimitry Andric   // Handle /appcontainer
17460b57cec5SDimitry Andric   config->appContainer =
17470b57cec5SDimitry Andric       args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric   // Handle /machine
17505f757f3fSDimitry Andric   {
17515f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Machine arg");
17520b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_machine)) {
17530b57cec5SDimitry Andric       config->machine = getMachineType(arg->getValue());
17540b57cec5SDimitry Andric       if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
17550b57cec5SDimitry Andric         fatal(Twine("unknown /machine argument: ") + arg->getValue());
175681ad6265SDimitry Andric       addWinSysRootLibSearchPaths();
17570b57cec5SDimitry Andric     }
17585f757f3fSDimitry Andric   }
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric   // Handle /nodefaultlib:<filename>
17615f757f3fSDimitry Andric   {
17625f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Nodefaultlib");
17630b57cec5SDimitry Andric     for (auto *arg : args.filtered(OPT_nodefaultlib))
176406c3fb27SDimitry Andric       config->noDefaultLibs.insert(findLib(arg->getValue()).lower());
17655f757f3fSDimitry Andric   }
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   // Handle /nodefaultlib
17680b57cec5SDimitry Andric   if (args.hasArg(OPT_nodefaultlib_all))
17690b57cec5SDimitry Andric     config->noDefaultLibAll = true;
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric   // Handle /base
17720b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_base))
17730b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->imageBase);
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric   // Handle /filealign
17760b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_filealign)) {
17770b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->fileAlign);
17780b57cec5SDimitry Andric     if (!isPowerOf2_64(config->fileAlign))
17790b57cec5SDimitry Andric       error("/filealign: not a power of two: " + Twine(config->fileAlign));
17800b57cec5SDimitry Andric   }
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   // Handle /stack
17830b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_stack))
17840b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric   // Handle /guard:cf
17870b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_guard))
17880b57cec5SDimitry Andric     parseGuard(arg->getValue());
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric   // Handle /heap
17910b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_heap))
17920b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
17930b57cec5SDimitry Andric 
17940b57cec5SDimitry Andric   // Handle /version
17950b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_version))
17960b57cec5SDimitry Andric     parseVersion(arg->getValue(), &config->majorImageVersion,
17970b57cec5SDimitry Andric                  &config->minorImageVersion);
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric   // Handle /subsystem
18000b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_subsystem))
1801e8d8bef9SDimitry Andric     parseSubsystem(arg->getValue(), &config->subsystem,
1802e8d8bef9SDimitry Andric                    &config->majorSubsystemVersion,
1803e8d8bef9SDimitry Andric                    &config->minorSubsystemVersion);
1804e8d8bef9SDimitry Andric 
1805e8d8bef9SDimitry Andric   // Handle /osversion
1806e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_osversion)) {
1807e8d8bef9SDimitry Andric     parseVersion(arg->getValue(), &config->majorOSVersion,
18080b57cec5SDimitry Andric                  &config->minorOSVersion);
1809e8d8bef9SDimitry Andric   } else {
1810e8d8bef9SDimitry Andric     config->majorOSVersion = config->majorSubsystemVersion;
1811e8d8bef9SDimitry Andric     config->minorOSVersion = config->minorSubsystemVersion;
1812e8d8bef9SDimitry Andric   }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   // Handle /timestamp
18150b57cec5SDimitry Andric   if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
18160b57cec5SDimitry Andric     if (arg->getOption().getID() == OPT_repro) {
18170b57cec5SDimitry Andric       config->timestamp = 0;
18180b57cec5SDimitry Andric       config->repro = true;
18190b57cec5SDimitry Andric     } else {
18200b57cec5SDimitry Andric       config->repro = false;
18210b57cec5SDimitry Andric       StringRef value(arg->getValue());
18220b57cec5SDimitry Andric       if (value.getAsInteger(0, config->timestamp))
18230b57cec5SDimitry Andric         fatal(Twine("invalid timestamp: ") + value +
18240b57cec5SDimitry Andric               ".  Expected 32-bit integer");
18250b57cec5SDimitry Andric     }
18260b57cec5SDimitry Andric   } else {
18270b57cec5SDimitry Andric     config->repro = false;
18280b57cec5SDimitry Andric     config->timestamp = time(nullptr);
18290b57cec5SDimitry 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);
20230b57cec5SDimitry Andric   // Handle miscellaneous boolean flags.
2024349cc55cSDimitry Andric   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
2025349cc55cSDimitry Andric                                             OPT_lto_pgo_warn_mismatch_no, true);
20260b57cec5SDimitry Andric   config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
20270b57cec5SDimitry Andric   config->allowIsolation =
20280b57cec5SDimitry Andric       args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
20290b57cec5SDimitry Andric   config->incremental =
20300b57cec5SDimitry Andric       args.hasFlag(OPT_incremental, OPT_incremental_no,
2031fe6060f1SDimitry Andric                    !config->doGC && config->doICF == ICFLevel::None &&
2032fe6060f1SDimitry Andric                        !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
20330b57cec5SDimitry Andric   config->integrityCheck =
20340b57cec5SDimitry Andric       args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
20355ffd83dbSDimitry Andric   config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
20360b57cec5SDimitry Andric   config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
20370b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_swaprun))
20380b57cec5SDimitry Andric     parseSwaprun(arg->getValue());
20390b57cec5SDimitry Andric   config->terminalServerAware =
20400b57cec5SDimitry Andric       !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
20415ffd83dbSDimitry Andric   config->autoImport =
20425ffd83dbSDimitry Andric       args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
20435ffd83dbSDimitry Andric   config->pseudoRelocs = args.hasFlag(
20445ffd83dbSDimitry Andric       OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
2045e8d8bef9SDimitry Andric   config->callGraphProfileSort = args.hasFlag(
2046e8d8bef9SDimitry Andric       OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
2047fe6060f1SDimitry Andric   config->stdcallFixup =
2048fe6060f1SDimitry Andric       args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
2049fe6060f1SDimitry Andric   config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
20505f757f3fSDimitry Andric   config->allowDuplicateWeak =
20515f757f3fSDimitry Andric       args.hasFlag(OPT_lld_allow_duplicate_weak,
20525f757f3fSDimitry Andric                    OPT_lld_allow_duplicate_weak_no, config->mingw);
20530b57cec5SDimitry Andric 
2054cbe9438cSDimitry Andric   if (args.hasFlag(OPT_inferasanlibs, OPT_inferasanlibs_no, false))
2055cbe9438cSDimitry Andric     warn("ignoring '/inferasanlibs', this flag is not supported");
2056cbe9438cSDimitry Andric 
20570b57cec5SDimitry Andric   if (config->incremental && args.hasArg(OPT_profile)) {
20580b57cec5SDimitry Andric     warn("ignoring '/incremental' due to '/profile' specification");
20590b57cec5SDimitry Andric     config->incremental = false;
20600b57cec5SDimitry Andric   }
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric   if (config->incremental && args.hasArg(OPT_order)) {
20630b57cec5SDimitry Andric     warn("ignoring '/incremental' due to '/order' specification");
20640b57cec5SDimitry Andric     config->incremental = false;
20650b57cec5SDimitry Andric   }
20660b57cec5SDimitry Andric 
20670b57cec5SDimitry Andric   if (config->incremental && config->doGC) {
20680b57cec5SDimitry Andric     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
20690b57cec5SDimitry Andric          "disable");
20700b57cec5SDimitry Andric     config->incremental = false;
20710b57cec5SDimitry Andric   }
20720b57cec5SDimitry Andric 
2073fe6060f1SDimitry Andric   if (config->incremental && config->doICF != ICFLevel::None) {
20740b57cec5SDimitry Andric     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
20750b57cec5SDimitry Andric          "disable");
20760b57cec5SDimitry Andric     config->incremental = false;
20770b57cec5SDimitry Andric   }
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric   if (errorCount())
20800b57cec5SDimitry Andric     return;
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric   std::set<sys::fs::UniqueID> wholeArchives;
20830b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wholearchive_file))
208406c3fb27SDimitry Andric     if (std::optional<StringRef> path = findFile(arg->getValue()))
2085bdd1243dSDimitry Andric       if (std::optional<sys::fs::UniqueID> id = getUniqueID(*path))
20860b57cec5SDimitry Andric         wholeArchives.insert(*id);
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric   // A predicate returning true if a given path is an argument for
20890b57cec5SDimitry Andric   // /wholearchive:, or /wholearchive is enabled globally.
20900b57cec5SDimitry Andric   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
20910b57cec5SDimitry Andric   // needs to be handled as "/wholearchive:foo.obj foo.obj".
20920b57cec5SDimitry Andric   auto isWholeArchive = [&](StringRef path) -> bool {
20930b57cec5SDimitry Andric     if (args.hasArg(OPT_wholearchive_flag))
20940b57cec5SDimitry Andric       return true;
2095bdd1243dSDimitry Andric     if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
20960b57cec5SDimitry Andric       return wholeArchives.count(*id);
20970b57cec5SDimitry Andric     return false;
20980b57cec5SDimitry Andric   };
20990b57cec5SDimitry Andric 
210085868e8aSDimitry Andric   // Create a list of input files. These can be given as OPT_INPUT options
210185868e8aSDimitry Andric   // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
210285868e8aSDimitry Andric   // and OPT_end_lib.
21035f757f3fSDimitry Andric   {
21045f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope2("Parse & queue inputs");
210585868e8aSDimitry Andric     bool inLib = false;
210685868e8aSDimitry Andric     for (auto *arg : args) {
210785868e8aSDimitry Andric       switch (arg->getOption().getID()) {
210885868e8aSDimitry Andric       case OPT_end_lib:
210985868e8aSDimitry Andric         if (!inLib)
211085868e8aSDimitry Andric           error("stray " + arg->getSpelling());
211185868e8aSDimitry Andric         inLib = false;
211285868e8aSDimitry Andric         break;
211385868e8aSDimitry Andric       case OPT_start_lib:
211485868e8aSDimitry Andric         if (inLib)
211585868e8aSDimitry Andric           error("nested " + arg->getSpelling());
211685868e8aSDimitry Andric         inLib = true;
211785868e8aSDimitry Andric         break;
211885868e8aSDimitry Andric       case OPT_wholearchive_file:
211906c3fb27SDimitry Andric         if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
212085868e8aSDimitry Andric           enqueuePath(*path, true, inLib);
212185868e8aSDimitry Andric         break;
212285868e8aSDimitry Andric       case OPT_INPUT:
212306c3fb27SDimitry Andric         if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
212485868e8aSDimitry Andric           enqueuePath(*path, isWholeArchive(*path), inLib);
212585868e8aSDimitry Andric         break;
212685868e8aSDimitry Andric       default:
212785868e8aSDimitry Andric         // Ignore other options.
212885868e8aSDimitry Andric         break;
212985868e8aSDimitry Andric       }
213085868e8aSDimitry Andric     }
21315f757f3fSDimitry Andric   }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric   // Read all input files given via the command line.
21340b57cec5SDimitry Andric   run();
21350b57cec5SDimitry Andric   if (errorCount())
21360b57cec5SDimitry Andric     return;
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric   // We should have inferred a machine type by now from the input files, but if
21390b57cec5SDimitry Andric   // not we assume x64.
21400b57cec5SDimitry Andric   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
21410b57cec5SDimitry Andric     warn("/machine is not specified. x64 is assumed");
21420b57cec5SDimitry Andric     config->machine = AMD64;
214381ad6265SDimitry Andric     addWinSysRootLibSearchPaths();
21440b57cec5SDimitry Andric   }
21450b57cec5SDimitry Andric   config->wordsize = config->is64() ? 8 : 4;
21460b57cec5SDimitry Andric 
214706c3fb27SDimitry Andric   if (config->printSearchPaths) {
214806c3fb27SDimitry Andric     SmallString<256> buffer;
214906c3fb27SDimitry Andric     raw_svector_ostream stream(buffer);
215006c3fb27SDimitry Andric     stream << "Library search paths:\n";
215106c3fb27SDimitry Andric 
21523bd749dbSDimitry Andric     for (StringRef path : searchPaths) {
21533bd749dbSDimitry Andric       if (path == "")
21543bd749dbSDimitry Andric         path = "(cwd)";
215506c3fb27SDimitry Andric       stream << "  " << path << "\n";
21563bd749dbSDimitry Andric     }
215706c3fb27SDimitry Andric 
215806c3fb27SDimitry Andric     message(buffer);
215906c3fb27SDimitry Andric   }
216006c3fb27SDimitry Andric 
216181ad6265SDimitry Andric   // Process files specified as /defaultlib. These must be processed after
216281ad6265SDimitry Andric   // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
216381ad6265SDimitry Andric   for (auto *arg : args.filtered(OPT_defaultlib))
216406c3fb27SDimitry Andric     if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
216581ad6265SDimitry Andric       enqueuePath(*path, false, false);
216681ad6265SDimitry Andric   run();
216781ad6265SDimitry Andric   if (errorCount())
216881ad6265SDimitry Andric     return;
216981ad6265SDimitry Andric 
2170bdd1243dSDimitry Andric   // Handle /RELEASE
2171bdd1243dSDimitry Andric   if (args.hasArg(OPT_release))
2172bdd1243dSDimitry Andric     config->writeCheckSum = true;
2173bdd1243dSDimitry Andric 
21740b57cec5SDimitry Andric   // Handle /safeseh, x86 only, on by default, except for mingw.
2175979e22ffSDimitry Andric   if (config->machine == I386) {
2176979e22ffSDimitry Andric     config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
2177979e22ffSDimitry Andric     config->noSEH = args.hasArg(OPT_noseh);
2178979e22ffSDimitry Andric   }
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric   // Handle /functionpadmin
21810b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
2182bdd1243dSDimitry Andric     parseFunctionPadMin(arg);
21830b57cec5SDimitry Andric 
21845f757f3fSDimitry Andric   // Handle /dependentloadflag
21855f757f3fSDimitry Andric   for (auto *arg :
21865f757f3fSDimitry Andric        args.filtered(OPT_dependentloadflag, OPT_dependentloadflag_opt))
21875f757f3fSDimitry Andric     parseDependentLoadFlags(arg);
21885f757f3fSDimitry Andric 
218981ad6265SDimitry Andric   if (tar) {
21905f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Reproducer: response file");
21910b57cec5SDimitry Andric     tar->append("response.txt",
21920b57cec5SDimitry Andric                 createResponseFile(args, filePaths,
21930b57cec5SDimitry Andric                                    ArrayRef<StringRef>(searchPaths).slice(1)));
219481ad6265SDimitry Andric   }
21950b57cec5SDimitry Andric 
21960b57cec5SDimitry Andric   // Handle /largeaddressaware
21970b57cec5SDimitry Andric   config->largeAddressAware = args.hasFlag(
21980b57cec5SDimitry Andric       OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
21990b57cec5SDimitry Andric 
22000b57cec5SDimitry Andric   // Handle /highentropyva
22010b57cec5SDimitry Andric   config->highEntropyVA =
22020b57cec5SDimitry Andric       config->is64() &&
22030b57cec5SDimitry Andric       args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric   if (!config->dynamicBase &&
22065f757f3fSDimitry Andric       (config->machine == ARMNT || isAnyArm64(config->machine)))
22070b57cec5SDimitry Andric     error("/dynamicbase:no is not compatible with " +
22080b57cec5SDimitry Andric           machineToStr(config->machine));
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric   // Handle /export
22115f757f3fSDimitry Andric   {
22125f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Parse /export");
22130b57cec5SDimitry Andric     for (auto *arg : args.filtered(OPT_export)) {
22140b57cec5SDimitry Andric       Export e = parseExport(arg->getValue());
22150b57cec5SDimitry Andric       if (config->machine == I386) {
22160b57cec5SDimitry Andric         if (!isDecorated(e.name))
221704eeddc0SDimitry Andric           e.name = saver().save("_" + e.name);
22180b57cec5SDimitry Andric         if (!e.extName.empty() && !isDecorated(e.extName))
221904eeddc0SDimitry Andric           e.extName = saver().save("_" + e.extName);
22200b57cec5SDimitry Andric       }
22210b57cec5SDimitry Andric       config->exports.push_back(e);
22220b57cec5SDimitry Andric     }
22235f757f3fSDimitry Andric   }
22240b57cec5SDimitry Andric 
22250b57cec5SDimitry Andric   // Handle /def
22260b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_deffile)) {
22270b57cec5SDimitry Andric     // parseModuleDefs mutates Config object.
22280b57cec5SDimitry Andric     parseModuleDefs(arg->getValue());
22290b57cec5SDimitry Andric   }
22300b57cec5SDimitry Andric 
22310b57cec5SDimitry Andric   // Handle generation of import library from a def file.
2232480093f4SDimitry Andric   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
22330b57cec5SDimitry Andric     fixupExports();
223481ad6265SDimitry Andric     if (!config->noimplib)
22350b57cec5SDimitry Andric       createImportLibrary(/*asLib=*/true);
22360b57cec5SDimitry Andric     return;
22370b57cec5SDimitry Andric   }
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric   // Windows specific -- if no /subsystem is given, we need to infer
22400b57cec5SDimitry Andric   // that from entry point name.  Must happen before /entry handling,
22410b57cec5SDimitry Andric   // and after the early return when just writing an import library.
22420b57cec5SDimitry Andric   if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
22435f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Infer subsystem");
22440b57cec5SDimitry Andric     config->subsystem = inferSubsystem();
22450b57cec5SDimitry Andric     if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
22460b57cec5SDimitry Andric       fatal("subsystem must be defined");
22470b57cec5SDimitry Andric   }
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   // Handle /entry and /dll
22505f757f3fSDimitry Andric   {
22515f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Entry point");
22520b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_entry)) {
22530b57cec5SDimitry Andric       config->entry = addUndefined(mangle(arg->getValue()));
22540b57cec5SDimitry Andric     } else if (!config->entry && !config->noEntry) {
22550b57cec5SDimitry Andric       if (args.hasArg(OPT_dll)) {
22560b57cec5SDimitry Andric         StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
22570b57cec5SDimitry Andric                                                 : "_DllMainCRTStartup";
22580b57cec5SDimitry Andric         config->entry = addUndefined(s);
2259480093f4SDimitry Andric       } else if (config->driverWdm) {
2260480093f4SDimitry Andric         // /driver:wdm implies /entry:_NtProcessStartup
2261480093f4SDimitry Andric         config->entry = addUndefined(mangle("_NtProcessStartup"));
22620b57cec5SDimitry Andric       } else {
22630b57cec5SDimitry Andric         // Windows specific -- If entry point name is not given, we need to
22640b57cec5SDimitry Andric         // infer that from user-defined entry name.
22650b57cec5SDimitry Andric         StringRef s = findDefaultEntry();
22660b57cec5SDimitry Andric         if (s.empty())
22670b57cec5SDimitry Andric           fatal("entry point must be defined");
22680b57cec5SDimitry Andric         config->entry = addUndefined(s);
22690b57cec5SDimitry Andric         log("Entry name inferred: " + s);
22700b57cec5SDimitry Andric       }
22710b57cec5SDimitry Andric     }
22725f757f3fSDimitry Andric   }
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric   // Handle /delayload
22755f757f3fSDimitry Andric   {
22765f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Delay load");
22770b57cec5SDimitry Andric     for (auto *arg : args.filtered(OPT_delayload)) {
22780b57cec5SDimitry Andric       config->delayLoads.insert(StringRef(arg->getValue()).lower());
22790b57cec5SDimitry Andric       if (config->machine == I386) {
22800b57cec5SDimitry Andric         config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
22810b57cec5SDimitry Andric       } else {
22820b57cec5SDimitry Andric         config->delayLoadHelper = addUndefined("__delayLoadHelper2");
22830b57cec5SDimitry Andric       }
22840b57cec5SDimitry Andric     }
22855f757f3fSDimitry Andric   }
22860b57cec5SDimitry Andric 
22870b57cec5SDimitry Andric   // Set default image name if neither /out or /def set it.
22880b57cec5SDimitry Andric   if (config->outputFile.empty()) {
2289480093f4SDimitry Andric     config->outputFile = getOutputPath(
2290bdd1243dSDimitry Andric         (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue(),
2291bdd1243dSDimitry Andric         config->dll, config->driver);
22920b57cec5SDimitry Andric   }
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric   // Fail early if an output file is not writable.
22950b57cec5SDimitry Andric   if (auto e = tryCreateFile(config->outputFile)) {
22960b57cec5SDimitry Andric     error("cannot open output file " + config->outputFile + ": " + e.message());
22970b57cec5SDimitry Andric     return;
22980b57cec5SDimitry Andric   }
22990b57cec5SDimitry Andric 
2300bdd1243dSDimitry Andric   config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
2301bdd1243dSDimitry Andric   config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
2302bdd1243dSDimitry Andric 
2303bdd1243dSDimitry Andric   if (config->mapFile != "" && args.hasArg(OPT_map_info)) {
2304bdd1243dSDimitry Andric     for (auto *arg : args.filtered(OPT_map_info)) {
2305bdd1243dSDimitry Andric       std::string s = StringRef(arg->getValue()).lower();
2306bdd1243dSDimitry Andric       if (s == "exports")
2307bdd1243dSDimitry Andric         config->mapInfo = true;
2308bdd1243dSDimitry Andric       else
2309bdd1243dSDimitry Andric         error("unknown option: /mapinfo:" + s);
2310bdd1243dSDimitry Andric     }
2311bdd1243dSDimitry Andric   }
2312bdd1243dSDimitry Andric 
2313bdd1243dSDimitry Andric   if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
2314bdd1243dSDimitry Andric     warn("/lldmap and /map have the same output file '" + config->mapFile +
2315bdd1243dSDimitry Andric          "'.\n>>> ignoring /lldmap");
2316bdd1243dSDimitry Andric     config->lldmapFile.clear();
2317bdd1243dSDimitry Andric   }
2318bdd1243dSDimitry Andric 
23195f757f3fSDimitry Andric   // If should create PDB, use the hash of PDB content for build id. Otherwise,
23205f757f3fSDimitry Andric   // generate using the hash of executable content.
23215f757f3fSDimitry Andric   if (args.hasFlag(OPT_build_id, OPT_build_id_no, false))
23225f757f3fSDimitry Andric     config->buildIDHash = BuildIDHash::Binary;
23235f757f3fSDimitry Andric 
23240b57cec5SDimitry Andric   if (shouldCreatePDB) {
23250b57cec5SDimitry Andric     // Put the PDB next to the image if no /pdb flag was passed.
23260b57cec5SDimitry Andric     if (config->pdbPath.empty()) {
23270b57cec5SDimitry Andric       config->pdbPath = config->outputFile;
23280b57cec5SDimitry Andric       sys::path::replace_extension(config->pdbPath, ".pdb");
23290b57cec5SDimitry Andric     }
23300b57cec5SDimitry Andric 
23310b57cec5SDimitry Andric     // The embedded PDB path should be the absolute path to the PDB if no
23320b57cec5SDimitry Andric     // /pdbaltpath flag was passed.
23330b57cec5SDimitry Andric     if (config->pdbAltPath.empty()) {
23340b57cec5SDimitry Andric       config->pdbAltPath = config->pdbPath;
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric       // It's important to make the path absolute and remove dots.  This path
23370b57cec5SDimitry Andric       // will eventually be written into the PE header, and certain Microsoft
23380b57cec5SDimitry Andric       // tools won't work correctly if these assumptions are not held.
23390b57cec5SDimitry Andric       sys::fs::make_absolute(config->pdbAltPath);
23400b57cec5SDimitry Andric       sys::path::remove_dots(config->pdbAltPath);
23410b57cec5SDimitry Andric     } else {
2342bdd1243dSDimitry Andric       // Don't do this earlier, so that ctx.OutputFile is ready.
2343bdd1243dSDimitry Andric       parsePDBAltPath();
23440b57cec5SDimitry Andric     }
23455f757f3fSDimitry Andric     config->buildIDHash = BuildIDHash::PDB;
23460b57cec5SDimitry Andric   }
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric   // Set default image base if /base is not given.
23490b57cec5SDimitry Andric   if (config->imageBase == uint64_t(-1))
23500b57cec5SDimitry Andric     config->imageBase = getDefaultImageBase();
23510b57cec5SDimitry Andric 
2352349cc55cSDimitry Andric   ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr);
23530b57cec5SDimitry Andric   if (config->machine == I386) {
2354349cc55cSDimitry Andric     ctx.symtab.addAbsolute("___safe_se_handler_table", 0);
2355349cc55cSDimitry Andric     ctx.symtab.addAbsolute("___safe_se_handler_count", 0);
23560b57cec5SDimitry Andric   }
23570b57cec5SDimitry Andric 
2358349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0);
2359349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0);
2360349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_flags"), 0);
2361349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0);
2362349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0);
2363349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
2364349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
23650b57cec5SDimitry Andric   // Needed for MSVC 2017 15.5 CRT.
2366349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__enclave_config"), 0);
2367fe6060f1SDimitry Andric   // Needed for MSVC 2019 16.8 CRT.
2368349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2369349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0);
23700b57cec5SDimitry Andric 
23715f757f3fSDimitry Andric   if (isArm64EC(config->machine)) {
23725f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__arm64x_extra_rfe_table", 0);
23735f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__arm64x_extra_rfe_table_size", 0);
23745f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__hybrid_code_map", 0);
23755f757f3fSDimitry Andric     ctx.symtab.addAbsolute("__hybrid_code_map_count", 0);
23765f757f3fSDimitry Andric   }
23775f757f3fSDimitry Andric 
23785ffd83dbSDimitry Andric   if (config->pseudoRelocs) {
2379349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2380349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
23815ffd83dbSDimitry Andric   }
23825ffd83dbSDimitry Andric   if (config->mingw) {
2383349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0);
2384349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0);
23850b57cec5SDimitry Andric   }
23865f757f3fSDimitry Andric   if (config->debug || config->buildIDHash != BuildIDHash::None)
23875f757f3fSDimitry Andric     if (ctx.symtab.findUnderscore("__buildid"))
23885f757f3fSDimitry Andric       ctx.symtab.addUndefined(mangle("__buildid"));
23890b57cec5SDimitry Andric 
23900b57cec5SDimitry Andric   // This code may add new undefined symbols to the link, which may enqueue more
23910b57cec5SDimitry Andric   // symbol resolution tasks, so we need to continue executing tasks until we
23920b57cec5SDimitry Andric   // converge.
23935f757f3fSDimitry Andric   {
23945f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Add unresolved symbols");
23950b57cec5SDimitry Andric     do {
23960b57cec5SDimitry Andric       // Windows specific -- if entry point is not found,
23970b57cec5SDimitry Andric       // search for its mangled names.
23980b57cec5SDimitry Andric       if (config->entry)
23990b57cec5SDimitry Andric         mangleMaybe(config->entry);
24000b57cec5SDimitry Andric 
24010b57cec5SDimitry Andric       // Windows specific -- Make sure we resolve all dllexported symbols.
24020b57cec5SDimitry Andric       for (Export &e : config->exports) {
24030b57cec5SDimitry Andric         if (!e.forwardTo.empty())
24040b57cec5SDimitry Andric           continue;
24050b57cec5SDimitry Andric         e.sym = addUndefined(e.name);
240606c3fb27SDimitry Andric         if (e.source != ExportSource::Directives)
24070b57cec5SDimitry Andric           e.symbolName = mangleMaybe(e.sym);
24080b57cec5SDimitry Andric       }
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric       // Add weak aliases. Weak aliases is a mechanism to give remaining
24110b57cec5SDimitry Andric       // undefined symbols final chance to be resolved successfully.
24120b57cec5SDimitry Andric       for (auto pair : config->alternateNames) {
24130b57cec5SDimitry Andric         StringRef from = pair.first;
24140b57cec5SDimitry Andric         StringRef to = pair.second;
2415349cc55cSDimitry Andric         Symbol *sym = ctx.symtab.find(from);
24160b57cec5SDimitry Andric         if (!sym)
24170b57cec5SDimitry Andric           continue;
24180b57cec5SDimitry Andric         if (auto *u = dyn_cast<Undefined>(sym))
24190b57cec5SDimitry Andric           if (!u->weakAlias)
2420349cc55cSDimitry Andric             u->weakAlias = ctx.symtab.addUndefined(to);
24210b57cec5SDimitry Andric       }
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric       // If any inputs are bitcode files, the LTO code generator may create
24240b57cec5SDimitry Andric       // references to library functions that are not explicit in the bitcode
24250b57cec5SDimitry Andric       // file's symbol table. If any of those library functions are defined in a
24260b57cec5SDimitry Andric       // bitcode file in an archive member, we need to arrange to use LTO to
24270b57cec5SDimitry Andric       // compile those archive members by adding them to the link beforehand.
2428349cc55cSDimitry Andric       if (!ctx.bitcodeFileInstances.empty())
242985868e8aSDimitry Andric         for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2430349cc55cSDimitry Andric           ctx.symtab.addLibcall(s);
24310b57cec5SDimitry Andric 
24320b57cec5SDimitry Andric       // Windows specific -- if __load_config_used can be resolved, resolve it.
2433349cc55cSDimitry Andric       if (ctx.symtab.findUnderscore("_load_config_used"))
24340b57cec5SDimitry Andric         addUndefined(mangle("_load_config_used"));
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric       if (args.hasArg(OPT_include_optional)) {
24370b57cec5SDimitry Andric         // Handle /includeoptional
24380b57cec5SDimitry Andric         for (auto *arg : args.filtered(OPT_include_optional))
24390eae32dcSDimitry Andric           if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue())))
24400b57cec5SDimitry Andric             addUndefined(arg->getValue());
24410b57cec5SDimitry Andric       }
2442a4a491e2SDimitry Andric     } while (run());
24435f757f3fSDimitry Andric   }
24440b57cec5SDimitry Andric 
2445e8d8bef9SDimitry Andric   // Create wrapped symbols for -wrap option.
2446349cc55cSDimitry Andric   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2447e8d8bef9SDimitry Andric   // Load more object files that might be needed for wrapped symbols.
2448e8d8bef9SDimitry Andric   if (!wrapped.empty())
24493bd749dbSDimitry Andric     while (run())
24503bd749dbSDimitry Andric       ;
2451e8d8bef9SDimitry Andric 
2452fe6060f1SDimitry Andric   if (config->autoImport || config->stdcallFixup) {
24535ffd83dbSDimitry Andric     // MinGW specific.
24540b57cec5SDimitry Andric     // Load any further object files that might be needed for doing automatic
2455fe6060f1SDimitry Andric     // imports, and do stdcall fixups.
24560b57cec5SDimitry Andric     //
24570b57cec5SDimitry Andric     // For cases with no automatically imported symbols, this iterates once
24580b57cec5SDimitry Andric     // over the symbol table and doesn't do anything.
24590b57cec5SDimitry Andric     //
24600b57cec5SDimitry Andric     // For the normal case with a few automatically imported symbols, this
24610b57cec5SDimitry Andric     // should only need to be run once, since each new object file imported
24620b57cec5SDimitry Andric     // is an import library and wouldn't add any new undefined references,
24630b57cec5SDimitry Andric     // but there's nothing stopping the __imp_ symbols from coming from a
24640b57cec5SDimitry Andric     // normal object file as well (although that won't be used for the
24650b57cec5SDimitry Andric     // actual autoimport later on). If this pass adds new undefined references,
24660b57cec5SDimitry Andric     // we won't iterate further to resolve them.
2467fe6060f1SDimitry Andric     //
2468fe6060f1SDimitry Andric     // If stdcall fixups only are needed for loading import entries from
2469fe6060f1SDimitry Andric     // a DLL without import library, this also just needs running once.
2470fe6060f1SDimitry Andric     // If it ends up pulling in more object files from static libraries,
2471fe6060f1SDimitry Andric     // (and maybe doing more stdcall fixups along the way), this would need
2472fe6060f1SDimitry Andric     // to loop these two calls.
2473349cc55cSDimitry Andric     ctx.symtab.loadMinGWSymbols();
24740b57cec5SDimitry Andric     run();
24750b57cec5SDimitry Andric   }
24760b57cec5SDimitry Andric 
247785868e8aSDimitry Andric   // At this point, we should not have any symbols that cannot be resolved.
247885868e8aSDimitry Andric   // If we are going to do codegen for link-time optimization, check for
247985868e8aSDimitry Andric   // unresolvable symbols first, so we don't spend time generating code that
248085868e8aSDimitry Andric   // will fail to link anyway.
2481349cc55cSDimitry Andric   if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved)
2482349cc55cSDimitry Andric     ctx.symtab.reportUnresolvable();
24830b57cec5SDimitry Andric   if (errorCount())
24840b57cec5SDimitry Andric     return;
24850b57cec5SDimitry Andric 
2486fe6060f1SDimitry Andric   config->hadExplicitExports = !config->exports.empty();
2487fe6060f1SDimitry Andric   if (config->mingw) {
2488fe6060f1SDimitry Andric     // In MinGW, all symbols are automatically exported if no symbols
2489fe6060f1SDimitry Andric     // are chosen to be exported.
2490fe6060f1SDimitry Andric     maybeExportMinGWSymbols(args);
2491fe6060f1SDimitry Andric   }
2492fe6060f1SDimitry Andric 
249385868e8aSDimitry Andric   // Do LTO by compiling bitcode input files to a set of native COFF files then
249485868e8aSDimitry Andric   // link those files (unless -thinlto-index-only was given, in which case we
249585868e8aSDimitry Andric   // resolve symbols and write indices, but don't generate native code or link).
2496349cc55cSDimitry Andric   ctx.symtab.compileBitcodeFiles();
249785868e8aSDimitry Andric 
24985f757f3fSDimitry Andric   if (Defined *d =
24995f757f3fSDimitry Andric           dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore("_tls_used")))
25005f757f3fSDimitry Andric     config->gcroot.push_back(d);
25015f757f3fSDimitry Andric 
250285868e8aSDimitry Andric   // If -thinlto-index-only is given, we should create only "index
250385868e8aSDimitry Andric   // files" and not object files. Index file creation is already done
2504bdd1243dSDimitry Andric   // in addCombinedLTOObject, so we are done if that's the case.
25055f757f3fSDimitry Andric   // Likewise, don't emit object files for other /lldemit options.
25065f757f3fSDimitry Andric   if (config->emit != EmitKind::Obj || config->thinLTOIndexOnly)
250785868e8aSDimitry Andric     return;
250885868e8aSDimitry Andric 
250985868e8aSDimitry Andric   // If we generated native object files from bitcode files, this resolves
251085868e8aSDimitry Andric   // references to the symbols we use from them.
251185868e8aSDimitry Andric   run();
251285868e8aSDimitry Andric 
2513e8d8bef9SDimitry Andric   // Apply symbol renames for -wrap.
2514e8d8bef9SDimitry Andric   if (!wrapped.empty())
2515349cc55cSDimitry Andric     wrapSymbols(ctx, wrapped);
2516e8d8bef9SDimitry Andric 
251785868e8aSDimitry Andric   // Resolve remaining undefined symbols and warn about imported locals.
2518349cc55cSDimitry Andric   ctx.symtab.resolveRemainingUndefines();
251985868e8aSDimitry Andric   if (errorCount())
252085868e8aSDimitry Andric     return;
252185868e8aSDimitry Andric 
25220b57cec5SDimitry Andric   if (config->mingw) {
25230b57cec5SDimitry Andric     // Make sure the crtend.o object is the last object file. This object
25240b57cec5SDimitry Andric     // file can contain terminating section chunks that need to be placed
25250b57cec5SDimitry Andric     // last. GNU ld processes files and static libraries explicitly in the
25260b57cec5SDimitry Andric     // order provided on the command line, while lld will pull in needed
25270b57cec5SDimitry Andric     // files from static libraries only after the last object file on the
25280b57cec5SDimitry Andric     // command line.
2529349cc55cSDimitry Andric     for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end();
25300b57cec5SDimitry Andric          i != e; i++) {
25310b57cec5SDimitry Andric       ObjFile *file = *i;
25320b57cec5SDimitry Andric       if (isCrtend(file->getName())) {
2533349cc55cSDimitry Andric         ctx.objFileInstances.erase(i);
2534349cc55cSDimitry Andric         ctx.objFileInstances.push_back(file);
25350b57cec5SDimitry Andric         break;
25360b57cec5SDimitry Andric       }
25370b57cec5SDimitry Andric     }
25380b57cec5SDimitry Andric   }
25390b57cec5SDimitry Andric 
25400b57cec5SDimitry Andric   // Windows specific -- when we are creating a .dll file, we also
254185868e8aSDimitry Andric   // need to create a .lib file. In MinGW mode, we only do that when the
254285868e8aSDimitry Andric   // -implib option is given explicitly, for compatibility with GNU ld.
25430b57cec5SDimitry Andric   if (!config->exports.empty() || config->dll) {
25445f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Create .lib exports");
25450b57cec5SDimitry Andric     fixupExports();
254681ad6265SDimitry Andric     if (!config->noimplib && (!config->mingw || !config->implib.empty()))
25470b57cec5SDimitry Andric       createImportLibrary(/*asLib=*/false);
25480b57cec5SDimitry Andric     assignExportOrdinals();
25490b57cec5SDimitry Andric   }
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric   // Handle /output-def (MinGW specific).
25520b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_output_def))
2553bdd1243dSDimitry Andric     writeDefFile(arg->getValue(), config->exports);
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric   // Set extra alignment for .comm symbols
25560b57cec5SDimitry Andric   for (auto pair : config->alignComm) {
25570b57cec5SDimitry Andric     StringRef name = pair.first;
25580b57cec5SDimitry Andric     uint32_t alignment = pair.second;
25590b57cec5SDimitry Andric 
2560349cc55cSDimitry Andric     Symbol *sym = ctx.symtab.find(name);
25610b57cec5SDimitry Andric     if (!sym) {
25620b57cec5SDimitry Andric       warn("/aligncomm symbol " + name + " not found");
25630b57cec5SDimitry Andric       continue;
25640b57cec5SDimitry Andric     }
25650b57cec5SDimitry Andric 
25660b57cec5SDimitry Andric     // If the symbol isn't common, it must have been replaced with a regular
25670b57cec5SDimitry Andric     // symbol, which will carry its own alignment.
25680b57cec5SDimitry Andric     auto *dc = dyn_cast<DefinedCommon>(sym);
25690b57cec5SDimitry Andric     if (!dc)
25700b57cec5SDimitry Andric       continue;
25710b57cec5SDimitry Andric 
25720b57cec5SDimitry Andric     CommonChunk *c = dc->getChunk();
25730b57cec5SDimitry Andric     c->setAlignment(std::max(c->getAlignment(), alignment));
25740b57cec5SDimitry Andric   }
25750b57cec5SDimitry Andric 
2576349cc55cSDimitry Andric   // Windows specific -- Create an embedded or side-by-side manifest.
2577349cc55cSDimitry Andric   // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2578349cc55cSDimitry Andric   // also passed.
2579349cc55cSDimitry Andric   if (config->manifest == Configuration::Embed)
2580349cc55cSDimitry Andric     addBuffer(createManifestRes(), false, false);
2581349cc55cSDimitry Andric   else if (config->manifest == Configuration::SideBySide ||
2582349cc55cSDimitry Andric            (config->manifest == Configuration::Default &&
2583349cc55cSDimitry Andric             !config->manifestDependencies.empty()))
25840b57cec5SDimitry Andric     createSideBySideManifest();
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric   // Handle /order. We want to do this at this moment because we
25870b57cec5SDimitry Andric   // need a complete list of comdat sections to warn on nonexistent
25880b57cec5SDimitry Andric   // functions.
2589e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_order)) {
2590e8d8bef9SDimitry Andric     if (args.hasArg(OPT_call_graph_ordering_file))
2591e8d8bef9SDimitry Andric       error("/order and /call-graph-order-file may not be used together");
2592bdd1243dSDimitry Andric     parseOrderFile(arg->getValue());
2593e8d8bef9SDimitry Andric     config->callGraphProfileSort = false;
2594e8d8bef9SDimitry Andric   }
2595e8d8bef9SDimitry Andric 
2596e8d8bef9SDimitry Andric   // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2597e8d8bef9SDimitry Andric   if (config->callGraphProfileSort) {
25985f757f3fSDimitry Andric     llvm::TimeTraceScope timeScope("Call graph");
2599e8d8bef9SDimitry Andric     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2600bdd1243dSDimitry Andric       parseCallGraphFile(arg->getValue());
2601e8d8bef9SDimitry Andric     }
2602349cc55cSDimitry Andric     readCallGraphsFromObjectFiles(ctx);
2603e8d8bef9SDimitry Andric   }
2604e8d8bef9SDimitry Andric 
2605e8d8bef9SDimitry Andric   // Handle /print-symbol-order.
2606e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2607e8d8bef9SDimitry Andric     config->printSymbolOrder = arg->getValue();
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric   // Identify unreferenced COMDAT sections.
2610fe6060f1SDimitry Andric   if (config->doGC) {
2611fe6060f1SDimitry Andric     if (config->mingw) {
2612fe6060f1SDimitry Andric       // markLive doesn't traverse .eh_frame, but the personality function is
2613fe6060f1SDimitry Andric       // only reached that way. The proper solution would be to parse and
2614fe6060f1SDimitry Andric       // traverse the .eh_frame section, like the ELF linker does.
2615fe6060f1SDimitry Andric       // For now, just manually try to retain the known possible personality
2616fe6060f1SDimitry Andric       // functions. This doesn't bring in more object files, but only marks
2617fe6060f1SDimitry Andric       // functions that already have been included to be retained.
2618bdd1243dSDimitry Andric       for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0",
2619bdd1243dSDimitry Andric                             "rust_eh_personality"}) {
2620349cc55cSDimitry Andric         Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n));
2621fe6060f1SDimitry Andric         if (d && !d->isGCRoot) {
2622fe6060f1SDimitry Andric           d->isGCRoot = true;
2623fe6060f1SDimitry Andric           config->gcroot.push_back(d);
2624fe6060f1SDimitry Andric         }
2625fe6060f1SDimitry Andric       }
2626fe6060f1SDimitry Andric     }
2627fe6060f1SDimitry Andric 
2628349cc55cSDimitry Andric     markLive(ctx);
2629fe6060f1SDimitry Andric   }
26300b57cec5SDimitry Andric 
26310b57cec5SDimitry Andric   // Needs to happen after the last call to addFile().
263285868e8aSDimitry Andric   convertResources();
26330b57cec5SDimitry Andric 
26340b57cec5SDimitry Andric   // Identify identical COMDAT sections to merge them.
2635fe6060f1SDimitry Andric   if (config->doICF != ICFLevel::None) {
2636349cc55cSDimitry Andric     findKeepUniqueSections(ctx);
2637bdd1243dSDimitry Andric     doICF(ctx);
26380b57cec5SDimitry Andric   }
26390b57cec5SDimitry Andric 
26400b57cec5SDimitry Andric   // Write the result.
2641349cc55cSDimitry Andric   writeResult(ctx);
26420b57cec5SDimitry Andric 
26430b57cec5SDimitry Andric   // Stop early so we can print the results.
26445ffd83dbSDimitry Andric   rootTimer.stop();
26450b57cec5SDimitry Andric   if (config->showTiming)
2646349cc55cSDimitry Andric     ctx.rootTimer.print();
26475f757f3fSDimitry Andric 
26485f757f3fSDimitry Andric   if (config->timeTraceEnabled) {
26495f757f3fSDimitry Andric     // Manually stop the topmost "COFF link" scope, since we're shutting down.
26505f757f3fSDimitry Andric     timeTraceProfilerEnd();
26515f757f3fSDimitry Andric 
26525f757f3fSDimitry Andric     checkError(timeTraceProfilerWrite(
26535f757f3fSDimitry Andric         args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
26545f757f3fSDimitry Andric     timeTraceProfilerCleanup();
26555f757f3fSDimitry Andric   }
26560b57cec5SDimitry Andric }
26570b57cec5SDimitry Andric 
2658bdd1243dSDimitry Andric } // namespace lld::coff
2659