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