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