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