1 //===-- MSVC.cpp - MSVC ToolChain Implementations -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MSVC.h"
10 #include "CommonArgs.h"
11 #include "Darwin.h"
12 #include "clang/Basic/CharInfo.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Support/ConvertUTF.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Host.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Process.h"
31 #include "llvm/Support/VirtualFileSystem.h"
32 #include <cstdio>
33 
34 #ifdef _WIN32
35   #define WIN32_LEAN_AND_MEAN
36   #define NOGDI
37   #ifndef NOMINMAX
38     #define NOMINMAX
39   #endif
40   #include <windows.h>
41 #endif
42 
43 using namespace clang::driver;
44 using namespace clang::driver::toolchains;
45 using namespace clang::driver::tools;
46 using namespace clang;
47 using namespace llvm::opt;
48 
49 static bool canExecute(llvm::vfs::FileSystem &VFS, StringRef Path) {
50   auto Status = VFS.status(Path);
51   if (!Status)
52     return false;
53   return (Status->getPermissions() & llvm::sys::fs::perms::all_exe) != 0;
54 }
55 
56 // Try to find Exe from a Visual Studio distribution.  This first tries to find
57 // an installed copy of Visual Studio and, failing that, looks in the PATH,
58 // making sure that whatever executable that's found is not a same-named exe
59 // from clang itself to prevent clang from falling back to itself.
60 static std::string FindVisualStudioExecutable(const ToolChain &TC,
61                                               const char *Exe) {
62   const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
63   SmallString<128> FilePath(
64       MSVC.getSubDirectoryPath(llvm::SubDirectoryType::Bin));
65   llvm::sys::path::append(FilePath, Exe);
66   return std::string(canExecute(TC.getVFS(), FilePath) ? FilePath.str() : Exe);
67 }
68 
69 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
70                                         const InputInfo &Output,
71                                         const InputInfoList &Inputs,
72                                         const ArgList &Args,
73                                         const char *LinkingOutput) const {
74   ArgStringList CmdArgs;
75 
76   auto &TC = static_cast<const toolchains::MSVCToolChain &>(getToolChain());
77 
78   assert((Output.isFilename() || Output.isNothing()) && "invalid output");
79   if (Output.isFilename())
80     CmdArgs.push_back(
81         Args.MakeArgString(std::string("-out:") + Output.getFilename()));
82 
83   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
84       !C.getDriver().IsCLMode()) {
85     CmdArgs.push_back("-defaultlib:libcmt");
86     CmdArgs.push_back("-defaultlib:oldnames");
87   }
88 
89   // If the VC environment hasn't been configured (perhaps because the user
90   // did not run vcvarsall), try to build a consistent link environment.  If
91   // the environment variable is set however, assume the user knows what
92   // they're doing. If the user passes /vctoolsdir or /winsdkdir, trust that
93   // over env vars.
94   if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diasdkdir,
95                                      options::OPT__SLASH_winsysroot)) {
96     // cl.exe doesn't find the DIA SDK automatically, so this too requires
97     // explicit flags and doesn't automatically look in "DIA SDK" relative
98     // to the path we found for VCToolChainPath.
99     llvm::SmallString<128> DIAPath(A->getValue());
100     if (A->getOption().getID() == options::OPT__SLASH_winsysroot)
101       llvm::sys::path::append(DIAPath, "DIA SDK");
102 
103     // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
104     llvm::sys::path::append(DIAPath, "lib",
105                             llvm::archToLegacyVCArch(TC.getArch()));
106     CmdArgs.push_back(Args.MakeArgString(Twine("-libpath:") + DIAPath));
107   }
108   if (!llvm::sys::Process::GetEnv("LIB") ||
109       Args.getLastArg(options::OPT__SLASH_vctoolsdir,
110                       options::OPT__SLASH_winsysroot)) {
111     CmdArgs.push_back(Args.MakeArgString(
112         Twine("-libpath:") +
113         TC.getSubDirectoryPath(llvm::SubDirectoryType::Lib)));
114     CmdArgs.push_back(Args.MakeArgString(
115         Twine("-libpath:") +
116         TC.getSubDirectoryPath(llvm::SubDirectoryType::Lib, "atlmfc")));
117   }
118   if (!llvm::sys::Process::GetEnv("LIB") ||
119       Args.getLastArg(options::OPT__SLASH_winsdkdir,
120                       options::OPT__SLASH_winsysroot)) {
121     if (TC.useUniversalCRT()) {
122       std::string UniversalCRTLibPath;
123       if (TC.getUniversalCRTLibraryPath(Args, UniversalCRTLibPath))
124         CmdArgs.push_back(
125             Args.MakeArgString(Twine("-libpath:") + UniversalCRTLibPath));
126     }
127     std::string WindowsSdkLibPath;
128     if (TC.getWindowsSDKLibraryPath(Args, WindowsSdkLibPath))
129       CmdArgs.push_back(
130           Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath));
131   }
132 
133   // Add the compiler-rt library directories to libpath if they exist to help
134   // the linker find the various sanitizer, builtin, and profiling runtimes.
135   for (const auto &LibPath : TC.getLibraryPaths()) {
136     if (TC.getVFS().exists(LibPath))
137       CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
138   }
139   auto CRTPath = TC.getCompilerRTPath();
140   if (TC.getVFS().exists(CRTPath))
141     CmdArgs.push_back(Args.MakeArgString("-libpath:" + CRTPath));
142 
143   if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L))
144     for (const auto &LibPath : Args.getAllArgValues(options::OPT_L))
145       CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath));
146 
147   CmdArgs.push_back("-nologo");
148 
149   if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
150     CmdArgs.push_back("-debug");
151 
152   // If we specify /hotpatch, let the linker add padding in front of each
153   // function, like MSVC does.
154   if (Args.hasArg(options::OPT_fms_hotpatch, options::OPT__SLASH_hotpatch))
155     CmdArgs.push_back("-functionpadmin");
156 
157   // Pass on /Brepro if it was passed to the compiler.
158   // Note that /Brepro maps to -mno-incremental-linker-compatible.
159   bool DefaultIncrementalLinkerCompatible =
160       C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
161   if (!Args.hasFlag(options::OPT_mincremental_linker_compatible,
162                     options::OPT_mno_incremental_linker_compatible,
163                     DefaultIncrementalLinkerCompatible))
164     CmdArgs.push_back("-Brepro");
165 
166   bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
167                          options::OPT_shared);
168   if (DLL) {
169     CmdArgs.push_back(Args.MakeArgString("-dll"));
170 
171     SmallString<128> ImplibName(Output.getFilename());
172     llvm::sys::path::replace_extension(ImplibName, "lib");
173     CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
174   }
175 
176   if (TC.getSanitizerArgs(Args).needsFuzzer()) {
177     if (!Args.hasArg(options::OPT_shared))
178       CmdArgs.push_back(
179           Args.MakeArgString(std::string("-wholearchive:") +
180                              TC.getCompilerRTArgString(Args, "fuzzer")));
181     CmdArgs.push_back(Args.MakeArgString("-debug"));
182     // Prevent the linker from padding sections we use for instrumentation
183     // arrays.
184     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
185   }
186 
187   if (TC.getSanitizerArgs(Args).needsAsanRt()) {
188     CmdArgs.push_back(Args.MakeArgString("-debug"));
189     CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
190     if (TC.getSanitizerArgs(Args).needsSharedRt() ||
191         Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
192       for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
193         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
194       // Make sure the dynamic runtime thunk is not optimized out at link time
195       // to ensure proper SEH handling.
196       CmdArgs.push_back(Args.MakeArgString(
197           TC.getArch() == llvm::Triple::x86
198               ? "-include:___asan_seh_interceptor"
199               : "-include:__asan_seh_interceptor"));
200       // Make sure the linker consider all object files from the dynamic runtime
201       // thunk.
202       CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
203           TC.getCompilerRT(Args, "asan_dynamic_runtime_thunk")));
204     } else if (DLL) {
205       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
206     } else {
207       for (const auto &Lib : {"asan", "asan_cxx"}) {
208         CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
209         // Make sure the linker consider all object files from the static lib.
210         // This is necessary because instrumented dlls need access to all the
211         // interface exported by the static lib in the main executable.
212         CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") +
213             TC.getCompilerRT(Args, Lib)));
214       }
215     }
216   }
217 
218   Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
219 
220   // Control Flow Guard checks
221   if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
222     StringRef GuardArgs = A->getValue();
223     if (GuardArgs.equals_insensitive("cf") ||
224         GuardArgs.equals_insensitive("cf,nochecks")) {
225       // MSVC doesn't yet support the "nochecks" modifier.
226       CmdArgs.push_back("-guard:cf");
227     } else if (GuardArgs.equals_insensitive("cf-")) {
228       CmdArgs.push_back("-guard:cf-");
229     } else if (GuardArgs.equals_insensitive("ehcont")) {
230       CmdArgs.push_back("-guard:ehcont");
231     } else if (GuardArgs.equals_insensitive("ehcont-")) {
232       CmdArgs.push_back("-guard:ehcont-");
233     }
234   }
235 
236   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
237                    options::OPT_fno_openmp, false)) {
238     CmdArgs.push_back("-nodefaultlib:vcomp.lib");
239     CmdArgs.push_back("-nodefaultlib:vcompd.lib");
240     CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
241                                          TC.getDriver().Dir + "/../lib"));
242     switch (TC.getDriver().getOpenMPRuntime(Args)) {
243     case Driver::OMPRT_OMP:
244       CmdArgs.push_back("-defaultlib:libomp.lib");
245       break;
246     case Driver::OMPRT_IOMP5:
247       CmdArgs.push_back("-defaultlib:libiomp5md.lib");
248       break;
249     case Driver::OMPRT_GOMP:
250       break;
251     case Driver::OMPRT_Unknown:
252       // Already diagnosed.
253       break;
254     }
255   }
256 
257   // Add compiler-rt lib in case if it was explicitly
258   // specified as an argument for --rtlib option.
259   if (!Args.hasArg(options::OPT_nostdlib)) {
260     AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
261   }
262 
263   // Add filenames, libraries, and other linker inputs.
264   for (const auto &Input : Inputs) {
265     if (Input.isFilename()) {
266       CmdArgs.push_back(Input.getFilename());
267       continue;
268     }
269 
270     const Arg &A = Input.getInputArg();
271 
272     // Render -l options differently for the MSVC linker.
273     if (A.getOption().matches(options::OPT_l)) {
274       StringRef Lib = A.getValue();
275       const char *LinkLibArg;
276       if (Lib.endswith(".lib"))
277         LinkLibArg = Args.MakeArgString(Lib);
278       else
279         LinkLibArg = Args.MakeArgString(Lib + ".lib");
280       CmdArgs.push_back(LinkLibArg);
281       continue;
282     }
283 
284     // Otherwise, this is some other kind of linker input option like -Wl, -z,
285     // or -L. Render it, even if MSVC doesn't understand it.
286     A.renderAsInput(Args, CmdArgs);
287   }
288 
289   TC.addProfileRTLibs(Args, CmdArgs);
290 
291   std::vector<const char *> Environment;
292 
293   // We need to special case some linker paths.  In the case of lld, we need to
294   // translate 'lld' into 'lld-link', and in the case of the regular msvc
295   // linker, we need to use a special search algorithm.
296   llvm::SmallString<128> linkPath;
297   StringRef Linker
298     = Args.getLastArgValue(options::OPT_fuse_ld_EQ, CLANG_DEFAULT_LINKER);
299   if (Linker.empty())
300     Linker = "link";
301   if (Linker.equals_insensitive("lld"))
302     Linker = "lld-link";
303 
304   if (Linker.equals_insensitive("link")) {
305     // If we're using the MSVC linker, it's not sufficient to just use link
306     // from the program PATH, because other environments like GnuWin32 install
307     // their own link.exe which may come first.
308     linkPath = FindVisualStudioExecutable(TC, "link.exe");
309 
310     if (!TC.FoundMSVCInstall() && !canExecute(TC.getVFS(), linkPath)) {
311       llvm::SmallString<128> ClPath;
312       ClPath = TC.GetProgramPath("cl.exe");
313       if (canExecute(TC.getVFS(), ClPath)) {
314         linkPath = llvm::sys::path::parent_path(ClPath);
315         llvm::sys::path::append(linkPath, "link.exe");
316         if (!canExecute(TC.getVFS(), linkPath))
317           C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
318       } else {
319         C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
320       }
321     }
322 
323 #ifdef _WIN32
324     // When cross-compiling with VS2017 or newer, link.exe expects to have
325     // its containing bin directory at the top of PATH, followed by the
326     // native target bin directory.
327     // e.g. when compiling for x86 on an x64 host, PATH should start with:
328     // /bin/Hostx64/x86;/bin/Hostx64/x64
329     // This doesn't attempt to handle llvm::ToolsetLayout::DevDivInternal.
330     if (TC.getIsVS2017OrNewer() &&
331         llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) {
332       auto HostArch = llvm::Triple(llvm::sys::getProcessTriple()).getArch();
333 
334       auto EnvBlockWide =
335           std::unique_ptr<wchar_t[], decltype(&FreeEnvironmentStringsW)>(
336               GetEnvironmentStringsW(), FreeEnvironmentStringsW);
337       if (!EnvBlockWide)
338         goto SkipSettingEnvironment;
339 
340       size_t EnvCount = 0;
341       size_t EnvBlockLen = 0;
342       while (EnvBlockWide[EnvBlockLen] != L'\0') {
343         ++EnvCount;
344         EnvBlockLen += std::wcslen(&EnvBlockWide[EnvBlockLen]) +
345                        1 /*string null-terminator*/;
346       }
347       ++EnvBlockLen; // add the block null-terminator
348 
349       std::string EnvBlock;
350       if (!llvm::convertUTF16ToUTF8String(
351               llvm::ArrayRef<char>(reinterpret_cast<char *>(EnvBlockWide.get()),
352                                    EnvBlockLen * sizeof(EnvBlockWide[0])),
353               EnvBlock))
354         goto SkipSettingEnvironment;
355 
356       Environment.reserve(EnvCount);
357 
358       // Now loop over each string in the block and copy them into the
359       // environment vector, adjusting the PATH variable as needed when we
360       // find it.
361       for (const char *Cursor = EnvBlock.data(); *Cursor != '\0';) {
362         llvm::StringRef EnvVar(Cursor);
363         if (EnvVar.startswith_insensitive("path=")) {
364           constexpr size_t PrefixLen = 5; // strlen("path=")
365           Environment.push_back(Args.MakeArgString(
366               EnvVar.substr(0, PrefixLen) +
367               TC.getSubDirectoryPath(llvm::SubDirectoryType::Bin) +
368               llvm::Twine(llvm::sys::EnvPathSeparator) +
369               TC.getSubDirectoryPath(llvm::SubDirectoryType::Bin, HostArch) +
370               (EnvVar.size() > PrefixLen
371                    ? llvm::Twine(llvm::sys::EnvPathSeparator) +
372                          EnvVar.substr(PrefixLen)
373                    : "")));
374         } else {
375           Environment.push_back(Args.MakeArgString(EnvVar));
376         }
377         Cursor += EnvVar.size() + 1 /*null-terminator*/;
378       }
379     }
380   SkipSettingEnvironment:;
381 #endif
382   } else {
383     linkPath = TC.GetProgramPath(Linker.str().c_str());
384   }
385 
386   auto LinkCmd = std::make_unique<Command>(
387       JA, *this, ResponseFileSupport::AtFileUTF16(),
388       Args.MakeArgString(linkPath), CmdArgs, Inputs, Output);
389   if (!Environment.empty())
390     LinkCmd->setEnvironment(Environment);
391   C.addCommand(std::move(LinkCmd));
392 }
393 
394 MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
395                              const ArgList &Args)
396     : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
397       RocmInstallation(D, Triple, Args) {
398   getProgramPaths().push_back(getDriver().getInstalledDir());
399   if (getDriver().getInstalledDir() != getDriver().Dir)
400     getProgramPaths().push_back(getDriver().Dir);
401 
402   Optional<llvm::StringRef> VCToolsDir, VCToolsVersion;
403   if (Arg *A = Args.getLastArg(options::OPT__SLASH_vctoolsdir))
404     VCToolsDir = A->getValue();
405   if (Arg *A = Args.getLastArg(options::OPT__SLASH_vctoolsversion))
406     VCToolsVersion = A->getValue();
407   if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkdir))
408     WinSdkDir = A->getValue();
409   if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkversion))
410     WinSdkVersion = A->getValue();
411   if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsysroot))
412     WinSysRoot = A->getValue();
413 
414   // Check the command line first, that's the user explicitly telling us what to
415   // use. Check the environment next, in case we're being invoked from a VS
416   // command prompt. Failing that, just try to find the newest Visual Studio
417   // version we can and use its default VC toolchain.
418   llvm::findVCToolChainViaCommandLine(getVFS(), VCToolsDir, VCToolsVersion,
419                                       WinSysRoot, VCToolChainPath, VSLayout) ||
420       llvm::findVCToolChainViaEnvironment(getVFS(), VCToolChainPath,
421                                           VSLayout) ||
422       llvm::findVCToolChainViaSetupConfig(getVFS(), VCToolChainPath,
423                                           VSLayout) ||
424       llvm::findVCToolChainViaRegistry(VCToolChainPath, VSLayout);
425 }
426 
427 Tool *MSVCToolChain::buildLinker() const {
428   return new tools::visualstudio::Linker(*this);
429 }
430 
431 Tool *MSVCToolChain::buildAssembler() const {
432   if (getTriple().isOSBinFormatMachO())
433     return new tools::darwin::Assembler(*this);
434   getDriver().Diag(clang::diag::err_no_external_assembler);
435   return nullptr;
436 }
437 
438 bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
439   return true;
440 }
441 
442 bool MSVCToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
443   // Don't emit unwind tables by default for MachO targets.
444   if (getTriple().isOSBinFormatMachO())
445     return false;
446 
447   // All non-x86_32 Windows targets require unwind tables. However, LLVM
448   // doesn't know how to generate them for all targets, so only enable
449   // the ones that are actually implemented.
450   return getArch() == llvm::Triple::x86_64 ||
451          getArch() == llvm::Triple::aarch64;
452 }
453 
454 bool MSVCToolChain::isPICDefault() const {
455   return getArch() == llvm::Triple::x86_64 ||
456          getArch() == llvm::Triple::aarch64;
457 }
458 
459 bool MSVCToolChain::isPIEDefault(const llvm::opt::ArgList &Args) const {
460   return false;
461 }
462 
463 bool MSVCToolChain::isPICDefaultForced() const {
464   return getArch() == llvm::Triple::x86_64 ||
465          getArch() == llvm::Triple::aarch64;
466 }
467 
468 void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
469                                        ArgStringList &CC1Args) const {
470   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
471 }
472 
473 void MSVCToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
474                                       ArgStringList &CC1Args) const {
475   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
476 }
477 
478 void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
479   CudaInstallation.print(OS);
480   RocmInstallation.print(OS);
481 }
482 
483 std::string
484 MSVCToolChain::getSubDirectoryPath(llvm::SubDirectoryType Type,
485                                    llvm::StringRef SubdirParent) const {
486   return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, getArch(),
487                                    SubdirParent);
488 }
489 
490 std::string
491 MSVCToolChain::getSubDirectoryPath(llvm::SubDirectoryType Type,
492                                    llvm::Triple::ArchType TargetArch) const {
493   return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, TargetArch,
494                                    "");
495 }
496 
497 // Find the most recent version of Universal CRT or Windows 10 SDK.
498 // vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
499 // directory by name and uses the last one of the list.
500 // So we compare entry names lexicographically to find the greatest one.
501 // Gets the library path required to link against the Windows SDK.
502 bool MSVCToolChain::getWindowsSDKLibraryPath(const ArgList &Args,
503                                              std::string &path) const {
504   std::string sdkPath;
505   int sdkMajor = 0;
506   std::string windowsSDKIncludeVersion;
507   std::string windowsSDKLibVersion;
508 
509   path.clear();
510   if (!llvm::getWindowsSDKDir(getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot,
511                               sdkPath, sdkMajor, windowsSDKIncludeVersion,
512                               windowsSDKLibVersion))
513     return false;
514 
515   llvm::SmallString<128> libPath(sdkPath);
516   llvm::sys::path::append(libPath, "Lib");
517   if (sdkMajor >= 8)
518     llvm::sys::path::append(libPath, windowsSDKLibVersion, "um");
519   return llvm::appendArchToWindowsSDKLibPath(sdkMajor, libPath, getArch(),
520                                              path);
521 }
522 
523 bool MSVCToolChain::useUniversalCRT() const {
524   return llvm::useUniversalCRT(VSLayout, VCToolChainPath, getArch(), getVFS());
525 }
526 
527 bool MSVCToolChain::getUniversalCRTLibraryPath(const ArgList &Args,
528                                                std::string &Path) const {
529   std::string UniversalCRTSdkPath;
530   std::string UCRTVersion;
531 
532   Path.clear();
533   if (!llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir, WinSdkVersion,
534                                    WinSysRoot, UniversalCRTSdkPath,
535                                    UCRTVersion))
536     return false;
537 
538   StringRef ArchName = llvm::archToWindowsSDKArch(getArch());
539   if (ArchName.empty())
540     return false;
541 
542   llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
543   llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
544 
545   Path = std::string(LibPath.str());
546   return true;
547 }
548 
549 static VersionTuple getMSVCVersionFromExe(const std::string &BinDir) {
550   VersionTuple Version;
551 #ifdef _WIN32
552   SmallString<128> ClExe(BinDir);
553   llvm::sys::path::append(ClExe, "cl.exe");
554 
555   std::wstring ClExeWide;
556   if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
557     return Version;
558 
559   const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
560                                                       nullptr);
561   if (VersionSize == 0)
562     return Version;
563 
564   SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
565   if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
566                              VersionBlock.data()))
567     return Version;
568 
569   VS_FIXEDFILEINFO *FileInfo = nullptr;
570   UINT FileInfoSize = 0;
571   if (!::VerQueryValueW(VersionBlock.data(), L"\\",
572                         reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
573       FileInfoSize < sizeof(*FileInfo))
574     return Version;
575 
576   const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
577   const unsigned Minor = (FileInfo->dwFileVersionMS      ) & 0xFFFF;
578   const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
579 
580   Version = VersionTuple(Major, Minor, Micro);
581 #endif
582   return Version;
583 }
584 
585 void MSVCToolChain::AddSystemIncludeWithSubfolder(
586     const ArgList &DriverArgs, ArgStringList &CC1Args,
587     const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
588     const Twine &subfolder3) const {
589   llvm::SmallString<128> path(folder);
590   llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
591   addSystemInclude(DriverArgs, CC1Args, path);
592 }
593 
594 void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
595                                               ArgStringList &CC1Args) const {
596   if (DriverArgs.hasArg(options::OPT_nostdinc))
597     return;
598 
599   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
600     AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
601                                   "include");
602   }
603 
604   // Add %INCLUDE%-like directories from the -imsvc flag.
605   for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
606     addSystemInclude(DriverArgs, CC1Args, Path);
607 
608   auto AddSystemIncludesFromEnv = [&](StringRef Var) -> bool {
609     if (auto Val = llvm::sys::Process::GetEnv(Var)) {
610       SmallVector<StringRef, 8> Dirs;
611       StringRef(*Val).split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
612       if (!Dirs.empty()) {
613         addSystemIncludes(DriverArgs, CC1Args, Dirs);
614         return true;
615       }
616     }
617     return false;
618   };
619 
620   // Add %INCLUDE%-like dirs via /external:env: flags.
621   for (const auto &Var :
622        DriverArgs.getAllArgValues(options::OPT__SLASH_external_env)) {
623     AddSystemIncludesFromEnv(Var);
624   }
625 
626   // Add DIA SDK include if requested.
627   if (const Arg *A = DriverArgs.getLastArg(options::OPT__SLASH_diasdkdir,
628                                            options::OPT__SLASH_winsysroot)) {
629     // cl.exe doesn't find the DIA SDK automatically, so this too requires
630     // explicit flags and doesn't automatically look in "DIA SDK" relative
631     // to the path we found for VCToolChainPath.
632     llvm::SmallString<128> DIASDKPath(A->getValue());
633     if (A->getOption().getID() == options::OPT__SLASH_winsysroot)
634       llvm::sys::path::append(DIASDKPath, "DIA SDK");
635     AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, std::string(DIASDKPath),
636                                   "include");
637   }
638 
639   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
640     return;
641 
642   // Honor %INCLUDE% and %EXTERNAL_INCLUDE%. It should have essential search
643   // paths set by vcvarsall.bat. Skip if the user expressly set a vctoolsdir.
644   if (!DriverArgs.getLastArg(options::OPT__SLASH_vctoolsdir,
645                              options::OPT__SLASH_winsysroot)) {
646     bool Found = AddSystemIncludesFromEnv("INCLUDE");
647     Found |= AddSystemIncludesFromEnv("EXTERNAL_INCLUDE");
648     if (Found)
649       return;
650   }
651 
652   // When built with access to the proper Windows APIs, try to actually find
653   // the correct include paths first.
654   if (!VCToolChainPath.empty()) {
655     addSystemInclude(DriverArgs, CC1Args,
656                      getSubDirectoryPath(llvm::SubDirectoryType::Include));
657     addSystemInclude(
658         DriverArgs, CC1Args,
659         getSubDirectoryPath(llvm::SubDirectoryType::Include, "atlmfc"));
660 
661     if (useUniversalCRT()) {
662       std::string UniversalCRTSdkPath;
663       std::string UCRTVersion;
664       if (llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir, WinSdkVersion,
665                                       WinSysRoot, UniversalCRTSdkPath,
666                                       UCRTVersion)) {
667         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
668                                       "Include", UCRTVersion, "ucrt");
669       }
670     }
671 
672     std::string WindowsSDKDir;
673     int major = 0;
674     std::string windowsSDKIncludeVersion;
675     std::string windowsSDKLibVersion;
676     if (llvm::getWindowsSDKDir(getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot,
677                                WindowsSDKDir, major, windowsSDKIncludeVersion,
678                                windowsSDKLibVersion)) {
679       if (major >= 8) {
680         // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
681         // Anyway, llvm::sys::path::append is able to manage it.
682         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
683                                       "Include", windowsSDKIncludeVersion,
684                                       "shared");
685         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
686                                       "Include", windowsSDKIncludeVersion,
687                                       "um");
688         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
689                                       "Include", windowsSDKIncludeVersion,
690                                       "winrt");
691         if (major >= 10) {
692           llvm::VersionTuple Tuple;
693           if (!Tuple.tryParse(windowsSDKIncludeVersion) &&
694               Tuple.getSubminor().getValueOr(0) >= 17134) {
695             AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
696                                           "Include", windowsSDKIncludeVersion,
697                                           "cppwinrt");
698           }
699         }
700       } else {
701         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
702                                       "Include");
703       }
704     }
705 
706     return;
707   }
708 
709 #if defined(_WIN32)
710   // As a fallback, select default install paths.
711   // FIXME: Don't guess drives and paths like this on Windows.
712   const StringRef Paths[] = {
713     "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
714     "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
715     "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
716     "C:/Program Files/Microsoft Visual Studio 8/VC/include",
717     "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
718   };
719   addSystemIncludes(DriverArgs, CC1Args, Paths);
720 #endif
721 }
722 
723 void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
724                                                  ArgStringList &CC1Args) const {
725   // FIXME: There should probably be logic here to find libc++ on Windows.
726 }
727 
728 VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D,
729                                                const ArgList &Args) const {
730   bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
731   VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
732   if (MSVT.empty())
733     MSVT = getTriple().getEnvironmentVersion();
734   if (MSVT.empty() && IsWindowsMSVC)
735     MSVT =
736         getMSVCVersionFromExe(getSubDirectoryPath(llvm::SubDirectoryType::Bin));
737   if (MSVT.empty() &&
738       Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
739                    IsWindowsMSVC)) {
740     // -fms-compatibility-version=19.20 is default, aka 2019, 16.x
741     MSVT = VersionTuple(19, 20);
742   }
743   return MSVT;
744 }
745 
746 std::string
747 MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
748                                            types::ID InputType) const {
749   // The MSVC version doesn't care about the architecture, even though it
750   // may look at the triple internally.
751   VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
752   MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
753                       MSVT.getSubminor().getValueOr(0));
754 
755   // For the rest of the triple, however, a computed architecture name may
756   // be needed.
757   llvm::Triple Triple(ToolChain::ComputeEffectiveClangTriple(Args, InputType));
758   if (Triple.getEnvironment() == llvm::Triple::MSVC) {
759     StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
760     if (ObjFmt.empty())
761       Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
762     else
763       Triple.setEnvironmentName(
764           (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
765   }
766   return Triple.getTriple();
767 }
768 
769 SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
770   SanitizerMask Res = ToolChain::getSupportedSanitizers();
771   Res |= SanitizerKind::Address;
772   Res |= SanitizerKind::PointerCompare;
773   Res |= SanitizerKind::PointerSubtract;
774   Res |= SanitizerKind::Fuzzer;
775   Res |= SanitizerKind::FuzzerNoLink;
776   Res &= ~SanitizerKind::CFIMFCall;
777   return Res;
778 }
779 
780 static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
781                             bool SupportsForcingFramePointer,
782                             const char *ExpandChar, const OptTable &Opts) {
783   assert(A->getOption().matches(options::OPT__SLASH_O));
784 
785   StringRef OptStr = A->getValue();
786   for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
787     const char &OptChar = *(OptStr.data() + I);
788     switch (OptChar) {
789     default:
790       break;
791     case '1':
792     case '2':
793     case 'x':
794     case 'd':
795       // Ignore /O[12xd] flags that aren't the last one on the command line.
796       // Only the last one gets expanded.
797       if (&OptChar != ExpandChar) {
798         A->claim();
799         break;
800       }
801       if (OptChar == 'd') {
802         DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
803       } else {
804         if (OptChar == '1') {
805           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
806         } else if (OptChar == '2' || OptChar == 'x') {
807           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
808           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
809         }
810         if (SupportsForcingFramePointer &&
811             !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
812           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fomit_frame_pointer));
813         if (OptChar == '1' || OptChar == '2')
814           DAL.AddFlagArg(A, Opts.getOption(options::OPT_ffunction_sections));
815       }
816       break;
817     case 'b':
818       if (I + 1 != E && isdigit(OptStr[I + 1])) {
819         switch (OptStr[I + 1]) {
820         case '0':
821           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
822           break;
823         case '1':
824           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
825           break;
826         case '2':
827           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
828           break;
829         }
830         ++I;
831       }
832       break;
833     case 'g':
834       A->claim();
835       break;
836     case 'i':
837       if (I + 1 != E && OptStr[I + 1] == '-') {
838         ++I;
839         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
840       } else {
841         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
842       }
843       break;
844     case 's':
845       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
846       break;
847     case 't':
848       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
849       break;
850     case 'y': {
851       bool OmitFramePointer = true;
852       if (I + 1 != E && OptStr[I + 1] == '-') {
853         OmitFramePointer = false;
854         ++I;
855       }
856       if (SupportsForcingFramePointer) {
857         if (OmitFramePointer)
858           DAL.AddFlagArg(A,
859                          Opts.getOption(options::OPT_fomit_frame_pointer));
860         else
861           DAL.AddFlagArg(
862               A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
863       } else {
864         // Don't warn about /Oy- in x86-64 builds (where
865         // SupportsForcingFramePointer is false).  The flag having no effect
866         // there is a compiler-internal optimization, and people shouldn't have
867         // to special-case their build files for x86-64 clang-cl.
868         A->claim();
869       }
870       break;
871     }
872     }
873   }
874 }
875 
876 static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
877                           const OptTable &Opts) {
878   assert(A->getOption().matches(options::OPT_D));
879 
880   StringRef Val = A->getValue();
881   size_t Hash = Val.find('#');
882   if (Hash == StringRef::npos || Hash > Val.find('=')) {
883     DAL.append(A);
884     return;
885   }
886 
887   std::string NewVal = std::string(Val);
888   NewVal[Hash] = '=';
889   DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
890 }
891 
892 static void TranslatePermissive(Arg *A, llvm::opt::DerivedArgList &DAL,
893                                 const OptTable &Opts) {
894   DAL.AddFlagArg(A, Opts.getOption(options::OPT__SLASH_Zc_twoPhase_));
895   DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_operator_names));
896 }
897 
898 static void TranslatePermissiveMinus(Arg *A, llvm::opt::DerivedArgList &DAL,
899                                      const OptTable &Opts) {
900   DAL.AddFlagArg(A, Opts.getOption(options::OPT__SLASH_Zc_twoPhase));
901   DAL.AddFlagArg(A, Opts.getOption(options::OPT_foperator_names));
902 }
903 
904 llvm::opt::DerivedArgList *
905 MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
906                              StringRef BoundArch,
907                              Action::OffloadKind OFK) const {
908   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
909   const OptTable &Opts = getDriver().getOpts();
910 
911   // /Oy and /Oy- don't have an effect on X86-64
912   bool SupportsForcingFramePointer = getArch() != llvm::Triple::x86_64;
913 
914   // The -O[12xd] flag actually expands to several flags.  We must desugar the
915   // flags so that options embedded can be negated.  For example, the '-O2' flag
916   // enables '-Oy'.  Expanding '-O2' into its constituent flags allows us to
917   // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
918   // aspect of '-O2'.
919   //
920   // Note that this expansion logic only applies to the *last* of '[12xd]'.
921 
922   // First step is to search for the character we'd like to expand.
923   const char *ExpandChar = nullptr;
924   for (Arg *A : Args.filtered(options::OPT__SLASH_O)) {
925     StringRef OptStr = A->getValue();
926     for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
927       char OptChar = OptStr[I];
928       char PrevChar = I > 0 ? OptStr[I - 1] : '0';
929       if (PrevChar == 'b') {
930         // OptChar does not expand; it's an argument to the previous char.
931         continue;
932       }
933       if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
934         ExpandChar = OptStr.data() + I;
935     }
936   }
937 
938   for (Arg *A : Args) {
939     if (A->getOption().matches(options::OPT__SLASH_O)) {
940       // The -O flag actually takes an amalgam of other options.  For example,
941       // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
942       TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
943     } else if (A->getOption().matches(options::OPT_D)) {
944       // Translate -Dfoo#bar into -Dfoo=bar.
945       TranslateDArg(A, *DAL, Opts);
946     } else if (A->getOption().matches(options::OPT__SLASH_permissive)) {
947       // Expand /permissive
948       TranslatePermissive(A, *DAL, Opts);
949     } else if (A->getOption().matches(options::OPT__SLASH_permissive_)) {
950       // Expand /permissive-
951       TranslatePermissiveMinus(A, *DAL, Opts);
952     } else if (OFK != Action::OFK_HIP) {
953       // HIP Toolchain translates input args by itself.
954       DAL->append(A);
955     }
956   }
957 
958   return DAL;
959 }
960 
961 void MSVCToolChain::addClangTargetOptions(
962     const ArgList &DriverArgs, ArgStringList &CC1Args,
963     Action::OffloadKind DeviceOffloadKind) const {
964   // MSVC STL kindly allows removing all usages of typeid by defining
965   // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
966   if (DriverArgs.hasArg(options::OPT_fno_rtti, options::OPT_frtti,
967                         /*Default=*/false))
968     CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
969 }
970