1 //===-- MSVC.cpp - MSVC ToolChain Implementations -------------------------===//
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
7 //===----------------------------------------------------------------------===//
10 #include "CommonArgs.h"
12 #include "clang/Basic/CharInfo.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Option/Arg.h"
22 #include "llvm/Option/ArgList.h"
23 #include "llvm/Support/ConvertUTF.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/Process.h"
30 #include "llvm/Support/VirtualFileSystem.h"
34 #define WIN32_LEAN_AND_MEAN
42 using namespace clang::driver
;
43 using namespace clang::driver::toolchains
;
44 using namespace clang::driver::tools
;
45 using namespace clang
;
46 using namespace llvm::opt
;
48 static bool canExecute(llvm::vfs::FileSystem
&VFS
, StringRef Path
) {
49 auto Status
= VFS
.status(Path
);
52 return (Status
->getPermissions() & llvm::sys::fs::perms::all_exe
) != 0;
55 // Try to find Exe from a Visual Studio distribution. This first tries to find
56 // an installed copy of Visual Studio and, failing that, looks in the PATH,
57 // making sure that whatever executable that's found is not a same-named exe
58 // from clang itself to prevent clang from falling back to itself.
59 static std::string
FindVisualStudioExecutable(const ToolChain
&TC
,
61 const auto &MSVC
= static_cast<const toolchains::MSVCToolChain
&>(TC
);
62 SmallString
<128> FilePath(
63 MSVC
.getSubDirectoryPath(llvm::SubDirectoryType::Bin
));
64 llvm::sys::path::append(FilePath
, Exe
);
65 return std::string(canExecute(TC
.getVFS(), FilePath
) ? FilePath
.str() : Exe
);
68 void visualstudio::Linker::ConstructJob(Compilation
&C
, const JobAction
&JA
,
69 const InputInfo
&Output
,
70 const InputInfoList
&Inputs
,
72 const char *LinkingOutput
) const {
73 ArgStringList CmdArgs
;
75 auto &TC
= static_cast<const toolchains::MSVCToolChain
&>(getToolChain());
77 assert((Output
.isFilename() || Output
.isNothing()) && "invalid output");
78 if (Output
.isFilename())
80 Args
.MakeArgString(std::string("-out:") + Output
.getFilename()));
82 if (!Args
.hasArg(options::OPT_nostdlib
, options::OPT_nostartfiles
) &&
83 !C
.getDriver().IsCLMode() && !C
.getDriver().IsFlangMode()) {
84 CmdArgs
.push_back("-defaultlib:libcmt");
85 CmdArgs
.push_back("-defaultlib:oldnames");
88 // If the VC environment hasn't been configured (perhaps because the user
89 // did not run vcvarsall), try to build a consistent link environment. If
90 // the environment variable is set however, assume the user knows what
91 // they're doing. If the user passes /vctoolsdir or /winsdkdir, trust that
93 if (const Arg
*A
= Args
.getLastArg(options::OPT__SLASH_diasdkdir
,
94 options::OPT__SLASH_winsysroot
)) {
95 // cl.exe doesn't find the DIA SDK automatically, so this too requires
96 // explicit flags and doesn't automatically look in "DIA SDK" relative
97 // to the path we found for VCToolChainPath.
98 llvm::SmallString
<128> DIAPath(A
->getValue());
99 if (A
->getOption().getID() == options::OPT__SLASH_winsysroot
)
100 llvm::sys::path::append(DIAPath
, "DIA SDK");
102 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
103 llvm::sys::path::append(DIAPath
, "lib",
104 llvm::archToLegacyVCArch(TC
.getArch()));
105 CmdArgs
.push_back(Args
.MakeArgString(Twine("-libpath:") + DIAPath
));
107 if (!llvm::sys::Process::GetEnv("LIB") ||
108 Args
.getLastArg(options::OPT__SLASH_vctoolsdir
,
109 options::OPT__SLASH_winsysroot
)) {
110 CmdArgs
.push_back(Args
.MakeArgString(
112 TC
.getSubDirectoryPath(llvm::SubDirectoryType::Lib
)));
113 CmdArgs
.push_back(Args
.MakeArgString(
115 TC
.getSubDirectoryPath(llvm::SubDirectoryType::Lib
, "atlmfc")));
117 if (!llvm::sys::Process::GetEnv("LIB") ||
118 Args
.getLastArg(options::OPT__SLASH_winsdkdir
,
119 options::OPT__SLASH_winsysroot
)) {
120 if (TC
.useUniversalCRT()) {
121 std::string UniversalCRTLibPath
;
122 if (TC
.getUniversalCRTLibraryPath(Args
, UniversalCRTLibPath
))
124 Args
.MakeArgString(Twine("-libpath:") + UniversalCRTLibPath
));
126 std::string WindowsSdkLibPath
;
127 if (TC
.getWindowsSDKLibraryPath(Args
, WindowsSdkLibPath
))
129 Args
.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath
));
132 if (C
.getDriver().IsFlangMode()) {
133 addFortranRuntimeLibraryPath(TC
, Args
, CmdArgs
);
134 addFortranRuntimeLibs(TC
, CmdArgs
);
136 // Inform the MSVC linker that we're generating a console application, i.e.
137 // one with `main` as the "user-defined" entry point. The `main` function is
138 // defined in flang's runtime libraries.
139 CmdArgs
.push_back("/subsystem:console");
142 // Add the compiler-rt library directories to libpath if they exist to help
143 // the linker find the various sanitizer, builtin, and profiling runtimes.
144 for (const auto &LibPath
: TC
.getLibraryPaths()) {
145 if (TC
.getVFS().exists(LibPath
))
146 CmdArgs
.push_back(Args
.MakeArgString("-libpath:" + LibPath
));
148 auto CRTPath
= TC
.getCompilerRTPath();
149 if (TC
.getVFS().exists(CRTPath
))
150 CmdArgs
.push_back(Args
.MakeArgString("-libpath:" + CRTPath
));
152 if (!C
.getDriver().IsCLMode() && Args
.hasArg(options::OPT_L
))
153 for (const auto &LibPath
: Args
.getAllArgValues(options::OPT_L
))
154 CmdArgs
.push_back(Args
.MakeArgString("-libpath:" + LibPath
));
156 CmdArgs
.push_back("-nologo");
158 if (Args
.hasArg(options::OPT_g_Group
, options::OPT__SLASH_Z7
))
159 CmdArgs
.push_back("-debug");
161 // If we specify /hotpatch, let the linker add padding in front of each
162 // function, like MSVC does.
163 if (Args
.hasArg(options::OPT_fms_hotpatch
, options::OPT__SLASH_hotpatch
))
164 CmdArgs
.push_back("-functionpadmin");
166 // Pass on /Brepro if it was passed to the compiler.
167 // Note that /Brepro maps to -mno-incremental-linker-compatible.
168 bool DefaultIncrementalLinkerCompatible
=
169 C
.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
170 if (!Args
.hasFlag(options::OPT_mincremental_linker_compatible
,
171 options::OPT_mno_incremental_linker_compatible
,
172 DefaultIncrementalLinkerCompatible
))
173 CmdArgs
.push_back("-Brepro");
175 bool DLL
= Args
.hasArg(options::OPT__SLASH_LD
, options::OPT__SLASH_LDd
,
176 options::OPT_shared
);
178 CmdArgs
.push_back(Args
.MakeArgString("-dll"));
180 SmallString
<128> ImplibName(Output
.getFilename());
181 llvm::sys::path::replace_extension(ImplibName
, "lib");
182 CmdArgs
.push_back(Args
.MakeArgString(std::string("-implib:") + ImplibName
));
185 if (TC
.getSanitizerArgs(Args
).needsFuzzer()) {
186 if (!Args
.hasArg(options::OPT_shared
))
188 Args
.MakeArgString(std::string("-wholearchive:") +
189 TC
.getCompilerRTArgString(Args
, "fuzzer")));
190 CmdArgs
.push_back(Args
.MakeArgString("-debug"));
191 // Prevent the linker from padding sections we use for instrumentation
193 CmdArgs
.push_back(Args
.MakeArgString("-incremental:no"));
196 if (TC
.getSanitizerArgs(Args
).needsAsanRt()) {
197 CmdArgs
.push_back(Args
.MakeArgString("-debug"));
198 CmdArgs
.push_back(Args
.MakeArgString("-incremental:no"));
199 if (TC
.getSanitizerArgs(Args
).needsSharedRt() ||
200 Args
.hasArg(options::OPT__SLASH_MD
, options::OPT__SLASH_MDd
)) {
201 for (const auto &Lib
: {"asan_dynamic", "asan_dynamic_runtime_thunk"})
202 CmdArgs
.push_back(TC
.getCompilerRTArgString(Args
, Lib
));
203 // Make sure the dynamic runtime thunk is not optimized out at link time
204 // to ensure proper SEH handling.
205 CmdArgs
.push_back(Args
.MakeArgString(
206 TC
.getArch() == llvm::Triple::x86
207 ? "-include:___asan_seh_interceptor"
208 : "-include:__asan_seh_interceptor"));
209 // Make sure the linker consider all object files from the dynamic runtime
211 CmdArgs
.push_back(Args
.MakeArgString(std::string("-wholearchive:") +
212 TC
.getCompilerRT(Args
, "asan_dynamic_runtime_thunk")));
214 CmdArgs
.push_back(TC
.getCompilerRTArgString(Args
, "asan_dll_thunk"));
216 for (const auto &Lib
: {"asan", "asan_cxx"}) {
217 CmdArgs
.push_back(TC
.getCompilerRTArgString(Args
, Lib
));
218 // Make sure the linker consider all object files from the static lib.
219 // This is necessary because instrumented dlls need access to all the
220 // interface exported by the static lib in the main executable.
221 CmdArgs
.push_back(Args
.MakeArgString(std::string("-wholearchive:") +
222 TC
.getCompilerRT(Args
, Lib
)));
227 Args
.AddAllArgValues(CmdArgs
, options::OPT__SLASH_link
);
229 // Control Flow Guard checks
230 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_guard
)) {
231 StringRef GuardArgs
= A
->getValue();
232 if (GuardArgs
.equals_insensitive("cf") ||
233 GuardArgs
.equals_insensitive("cf,nochecks")) {
234 // MSVC doesn't yet support the "nochecks" modifier.
235 CmdArgs
.push_back("-guard:cf");
236 } else if (GuardArgs
.equals_insensitive("cf-")) {
237 CmdArgs
.push_back("-guard:cf-");
238 } else if (GuardArgs
.equals_insensitive("ehcont")) {
239 CmdArgs
.push_back("-guard:ehcont");
240 } else if (GuardArgs
.equals_insensitive("ehcont-")) {
241 CmdArgs
.push_back("-guard:ehcont-");
245 if (Args
.hasFlag(options::OPT_fopenmp
, options::OPT_fopenmp_EQ
,
246 options::OPT_fno_openmp
, false)) {
247 CmdArgs
.push_back("-nodefaultlib:vcomp.lib");
248 CmdArgs
.push_back("-nodefaultlib:vcompd.lib");
249 CmdArgs
.push_back(Args
.MakeArgString(std::string("-libpath:") +
250 TC
.getDriver().Dir
+ "/../lib"));
251 switch (TC
.getDriver().getOpenMPRuntime(Args
)) {
252 case Driver::OMPRT_OMP
:
253 CmdArgs
.push_back("-defaultlib:libomp.lib");
255 case Driver::OMPRT_IOMP5
:
256 CmdArgs
.push_back("-defaultlib:libiomp5md.lib");
258 case Driver::OMPRT_GOMP
:
260 case Driver::OMPRT_Unknown
:
261 // Already diagnosed.
266 // Add compiler-rt lib in case if it was explicitly
267 // specified as an argument for --rtlib option.
268 if (!Args
.hasArg(options::OPT_nostdlib
)) {
269 AddRunTimeLibs(TC
, TC
.getDriver(), CmdArgs
, Args
);
272 // Add filenames, libraries, and other linker inputs.
273 for (const auto &Input
: Inputs
) {
274 if (Input
.isFilename()) {
275 CmdArgs
.push_back(Input
.getFilename());
279 const Arg
&A
= Input
.getInputArg();
281 // Render -l options differently for the MSVC linker.
282 if (A
.getOption().matches(options::OPT_l
)) {
283 StringRef Lib
= A
.getValue();
284 const char *LinkLibArg
;
285 if (Lib
.endswith(".lib"))
286 LinkLibArg
= Args
.MakeArgString(Lib
);
288 LinkLibArg
= Args
.MakeArgString(Lib
+ ".lib");
289 CmdArgs
.push_back(LinkLibArg
);
293 // Otherwise, this is some other kind of linker input option like -Wl, -z,
294 // or -L. Render it, even if MSVC doesn't understand it.
295 A
.renderAsInput(Args
, CmdArgs
);
298 addHIPRuntimeLibArgs(TC
, Args
, CmdArgs
);
300 TC
.addProfileRTLibs(Args
, CmdArgs
);
302 std::vector
<const char *> Environment
;
304 // We need to special case some linker paths. In the case of lld, we need to
305 // translate 'lld' into 'lld-link', and in the case of the regular msvc
306 // linker, we need to use a special search algorithm.
307 llvm::SmallString
<128> linkPath
;
309 = Args
.getLastArgValue(options::OPT_fuse_ld_EQ
, CLANG_DEFAULT_LINKER
);
312 if (Linker
.equals_insensitive("lld"))
315 if (Linker
.equals_insensitive("link")) {
316 // If we're using the MSVC linker, it's not sufficient to just use link
317 // from the program PATH, because other environments like GnuWin32 install
318 // their own link.exe which may come first.
319 linkPath
= FindVisualStudioExecutable(TC
, "link.exe");
321 if (!TC
.FoundMSVCInstall() && !canExecute(TC
.getVFS(), linkPath
)) {
322 llvm::SmallString
<128> ClPath
;
323 ClPath
= TC
.GetProgramPath("cl.exe");
324 if (canExecute(TC
.getVFS(), ClPath
)) {
325 linkPath
= llvm::sys::path::parent_path(ClPath
);
326 llvm::sys::path::append(linkPath
, "link.exe");
327 if (!canExecute(TC
.getVFS(), linkPath
))
328 C
.getDriver().Diag(clang::diag::warn_drv_msvc_not_found
);
330 C
.getDriver().Diag(clang::diag::warn_drv_msvc_not_found
);
335 // When cross-compiling with VS2017 or newer, link.exe expects to have
336 // its containing bin directory at the top of PATH, followed by the
337 // native target bin directory.
338 // e.g. when compiling for x86 on an x64 host, PATH should start with:
339 // /bin/Hostx64/x86;/bin/Hostx64/x64
340 // This doesn't attempt to handle llvm::ToolsetLayout::DevDivInternal.
341 if (TC
.getIsVS2017OrNewer() &&
342 llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC
.getArch()) {
343 auto HostArch
= llvm::Triple(llvm::sys::getProcessTriple()).getArch();
346 std::unique_ptr
<wchar_t[], decltype(&FreeEnvironmentStringsW
)>(
347 GetEnvironmentStringsW(), FreeEnvironmentStringsW
);
349 goto SkipSettingEnvironment
;
352 size_t EnvBlockLen
= 0;
353 while (EnvBlockWide
[EnvBlockLen
] != L
'\0') {
355 EnvBlockLen
+= std::wcslen(&EnvBlockWide
[EnvBlockLen
]) +
356 1 /*string null-terminator*/;
358 ++EnvBlockLen
; // add the block null-terminator
360 std::string EnvBlock
;
361 if (!llvm::convertUTF16ToUTF8String(
362 llvm::ArrayRef
<char>(reinterpret_cast<char *>(EnvBlockWide
.get()),
363 EnvBlockLen
* sizeof(EnvBlockWide
[0])),
365 goto SkipSettingEnvironment
;
367 Environment
.reserve(EnvCount
);
369 // Now loop over each string in the block and copy them into the
370 // environment vector, adjusting the PATH variable as needed when we
372 for (const char *Cursor
= EnvBlock
.data(); *Cursor
!= '\0';) {
373 llvm::StringRef
EnvVar(Cursor
);
374 if (EnvVar
.startswith_insensitive("path=")) {
375 constexpr size_t PrefixLen
= 5; // strlen("path=")
376 Environment
.push_back(Args
.MakeArgString(
377 EnvVar
.substr(0, PrefixLen
) +
378 TC
.getSubDirectoryPath(llvm::SubDirectoryType::Bin
) +
379 llvm::Twine(llvm::sys::EnvPathSeparator
) +
380 TC
.getSubDirectoryPath(llvm::SubDirectoryType::Bin
, HostArch
) +
381 (EnvVar
.size() > PrefixLen
382 ? llvm::Twine(llvm::sys::EnvPathSeparator
) +
383 EnvVar
.substr(PrefixLen
)
386 Environment
.push_back(Args
.MakeArgString(EnvVar
));
388 Cursor
+= EnvVar
.size() + 1 /*null-terminator*/;
391 SkipSettingEnvironment
:;
394 linkPath
= TC
.GetProgramPath(Linker
.str().c_str());
397 auto LinkCmd
= std::make_unique
<Command
>(
398 JA
, *this, ResponseFileSupport::AtFileUTF16(),
399 Args
.MakeArgString(linkPath
), CmdArgs
, Inputs
, Output
);
400 if (!Environment
.empty())
401 LinkCmd
->setEnvironment(Environment
);
402 C
.addCommand(std::move(LinkCmd
));
405 MSVCToolChain::MSVCToolChain(const Driver
&D
, const llvm::Triple
&Triple
,
407 : ToolChain(D
, Triple
, Args
), CudaInstallation(D
, Triple
, Args
),
408 RocmInstallation(D
, Triple
, Args
) {
409 getProgramPaths().push_back(getDriver().getInstalledDir());
410 if (getDriver().getInstalledDir() != getDriver().Dir
)
411 getProgramPaths().push_back(getDriver().Dir
);
413 Optional
<llvm::StringRef
> VCToolsDir
, VCToolsVersion
;
414 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_vctoolsdir
))
415 VCToolsDir
= A
->getValue();
416 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_vctoolsversion
))
417 VCToolsVersion
= A
->getValue();
418 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_winsdkdir
))
419 WinSdkDir
= A
->getValue();
420 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_winsdkversion
))
421 WinSdkVersion
= A
->getValue();
422 if (Arg
*A
= Args
.getLastArg(options::OPT__SLASH_winsysroot
))
423 WinSysRoot
= A
->getValue();
425 // Check the command line first, that's the user explicitly telling us what to
426 // use. Check the environment next, in case we're being invoked from a VS
427 // command prompt. Failing that, just try to find the newest Visual Studio
428 // version we can and use its default VC toolchain.
429 llvm::findVCToolChainViaCommandLine(getVFS(), VCToolsDir
, VCToolsVersion
,
430 WinSysRoot
, VCToolChainPath
, VSLayout
) ||
431 llvm::findVCToolChainViaEnvironment(getVFS(), VCToolChainPath
,
433 llvm::findVCToolChainViaSetupConfig(getVFS(), VCToolChainPath
,
435 llvm::findVCToolChainViaRegistry(VCToolChainPath
, VSLayout
);
438 Tool
*MSVCToolChain::buildLinker() const {
439 return new tools::visualstudio::Linker(*this);
442 Tool
*MSVCToolChain::buildAssembler() const {
443 if (getTriple().isOSBinFormatMachO())
444 return new tools::darwin::Assembler(*this);
445 getDriver().Diag(clang::diag::err_no_external_assembler
);
449 bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
453 bool MSVCToolChain::IsUnwindTablesDefault(const ArgList
&Args
) const {
454 // Don't emit unwind tables by default for MachO targets.
455 if (getTriple().isOSBinFormatMachO())
458 // All non-x86_32 Windows targets require unwind tables. However, LLVM
459 // doesn't know how to generate them for all targets, so only enable
460 // the ones that are actually implemented.
461 return getArch() == llvm::Triple::x86_64
|| getArch() == llvm::Triple::arm
||
462 getArch() == llvm::Triple::thumb
|| getArch() == llvm::Triple::aarch64
;
465 bool MSVCToolChain::isPICDefault() const {
466 return getArch() == llvm::Triple::x86_64
||
467 getArch() == llvm::Triple::aarch64
;
470 bool MSVCToolChain::isPIEDefault(const llvm::opt::ArgList
&Args
) const {
474 bool MSVCToolChain::isPICDefaultForced() const {
475 return getArch() == llvm::Triple::x86_64
||
476 getArch() == llvm::Triple::aarch64
;
479 void MSVCToolChain::AddCudaIncludeArgs(const ArgList
&DriverArgs
,
480 ArgStringList
&CC1Args
) const {
481 CudaInstallation
.AddCudaIncludeArgs(DriverArgs
, CC1Args
);
484 void MSVCToolChain::AddHIPIncludeArgs(const ArgList
&DriverArgs
,
485 ArgStringList
&CC1Args
) const {
486 RocmInstallation
.AddHIPIncludeArgs(DriverArgs
, CC1Args
);
489 void MSVCToolChain::AddHIPRuntimeLibArgs(const ArgList
&Args
,
490 ArgStringList
&CmdArgs
) const {
491 CmdArgs
.append({Args
.MakeArgString(StringRef("-libpath:") +
492 RocmInstallation
.getLibPath()),
496 void MSVCToolChain::printVerboseInfo(raw_ostream
&OS
) const {
497 CudaInstallation
.print(OS
);
498 RocmInstallation
.print(OS
);
502 MSVCToolChain::getSubDirectoryPath(llvm::SubDirectoryType Type
,
503 llvm::StringRef SubdirParent
) const {
504 return llvm::getSubDirectoryPath(Type
, VSLayout
, VCToolChainPath
, getArch(),
509 MSVCToolChain::getSubDirectoryPath(llvm::SubDirectoryType Type
,
510 llvm::Triple::ArchType TargetArch
) const {
511 return llvm::getSubDirectoryPath(Type
, VSLayout
, VCToolChainPath
, TargetArch
,
515 // Find the most recent version of Universal CRT or Windows 10 SDK.
516 // vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
517 // directory by name and uses the last one of the list.
518 // So we compare entry names lexicographically to find the greatest one.
519 // Gets the library path required to link against the Windows SDK.
520 bool MSVCToolChain::getWindowsSDKLibraryPath(const ArgList
&Args
,
521 std::string
&path
) const {
524 std::string windowsSDKIncludeVersion
;
525 std::string windowsSDKLibVersion
;
528 if (!llvm::getWindowsSDKDir(getVFS(), WinSdkDir
, WinSdkVersion
, WinSysRoot
,
529 sdkPath
, sdkMajor
, windowsSDKIncludeVersion
,
530 windowsSDKLibVersion
))
533 llvm::SmallString
<128> libPath(sdkPath
);
534 llvm::sys::path::append(libPath
, "Lib");
536 llvm::sys::path::append(libPath
, windowsSDKLibVersion
, "um");
537 return llvm::appendArchToWindowsSDKLibPath(sdkMajor
, libPath
, getArch(),
541 bool MSVCToolChain::useUniversalCRT() const {
542 return llvm::useUniversalCRT(VSLayout
, VCToolChainPath
, getArch(), getVFS());
545 bool MSVCToolChain::getUniversalCRTLibraryPath(const ArgList
&Args
,
546 std::string
&Path
) const {
547 std::string UniversalCRTSdkPath
;
548 std::string UCRTVersion
;
551 if (!llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir
, WinSdkVersion
,
552 WinSysRoot
, UniversalCRTSdkPath
,
556 StringRef ArchName
= llvm::archToWindowsSDKArch(getArch());
557 if (ArchName
.empty())
560 llvm::SmallString
<128> LibPath(UniversalCRTSdkPath
);
561 llvm::sys::path::append(LibPath
, "Lib", UCRTVersion
, "ucrt", ArchName
);
563 Path
= std::string(LibPath
.str());
567 static VersionTuple
getMSVCVersionFromExe(const std::string
&BinDir
) {
568 VersionTuple Version
;
570 SmallString
<128> ClExe(BinDir
);
571 llvm::sys::path::append(ClExe
, "cl.exe");
573 std::wstring ClExeWide
;
574 if (!llvm::ConvertUTF8toWide(ClExe
.c_str(), ClExeWide
))
577 const DWORD VersionSize
= ::GetFileVersionInfoSizeW(ClExeWide
.c_str(),
579 if (VersionSize
== 0)
582 SmallVector
<uint8_t, 4 * 1024> VersionBlock(VersionSize
);
583 if (!::GetFileVersionInfoW(ClExeWide
.c_str(), 0, VersionSize
,
584 VersionBlock
.data()))
587 VS_FIXEDFILEINFO
*FileInfo
= nullptr;
588 UINT FileInfoSize
= 0;
589 if (!::VerQueryValueW(VersionBlock
.data(), L
"\\",
590 reinterpret_cast<LPVOID
*>(&FileInfo
), &FileInfoSize
) ||
591 FileInfoSize
< sizeof(*FileInfo
))
594 const unsigned Major
= (FileInfo
->dwFileVersionMS
>> 16) & 0xFFFF;
595 const unsigned Minor
= (FileInfo
->dwFileVersionMS
) & 0xFFFF;
596 const unsigned Micro
= (FileInfo
->dwFileVersionLS
>> 16) & 0xFFFF;
598 Version
= VersionTuple(Major
, Minor
, Micro
);
603 void MSVCToolChain::AddSystemIncludeWithSubfolder(
604 const ArgList
&DriverArgs
, ArgStringList
&CC1Args
,
605 const std::string
&folder
, const Twine
&subfolder1
, const Twine
&subfolder2
,
606 const Twine
&subfolder3
) const {
607 llvm::SmallString
<128> path(folder
);
608 llvm::sys::path::append(path
, subfolder1
, subfolder2
, subfolder3
);
609 addSystemInclude(DriverArgs
, CC1Args
, path
);
612 void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList
&DriverArgs
,
613 ArgStringList
&CC1Args
) const {
614 if (DriverArgs
.hasArg(options::OPT_nostdinc
))
617 if (!DriverArgs
.hasArg(options::OPT_nobuiltininc
)) {
618 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, getDriver().ResourceDir
,
622 // Add %INCLUDE%-like directories from the -imsvc flag.
623 for (const auto &Path
: DriverArgs
.getAllArgValues(options::OPT__SLASH_imsvc
))
624 addSystemInclude(DriverArgs
, CC1Args
, Path
);
626 auto AddSystemIncludesFromEnv
= [&](StringRef Var
) -> bool {
627 if (auto Val
= llvm::sys::Process::GetEnv(Var
)) {
628 SmallVector
<StringRef
, 8> Dirs
;
629 StringRef(*Val
).split(Dirs
, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
631 addSystemIncludes(DriverArgs
, CC1Args
, Dirs
);
638 // Add %INCLUDE%-like dirs via /external:env: flags.
639 for (const auto &Var
:
640 DriverArgs
.getAllArgValues(options::OPT__SLASH_external_env
)) {
641 AddSystemIncludesFromEnv(Var
);
644 // Add DIA SDK include if requested.
645 if (const Arg
*A
= DriverArgs
.getLastArg(options::OPT__SLASH_diasdkdir
,
646 options::OPT__SLASH_winsysroot
)) {
647 // cl.exe doesn't find the DIA SDK automatically, so this too requires
648 // explicit flags and doesn't automatically look in "DIA SDK" relative
649 // to the path we found for VCToolChainPath.
650 llvm::SmallString
<128> DIASDKPath(A
->getValue());
651 if (A
->getOption().getID() == options::OPT__SLASH_winsysroot
)
652 llvm::sys::path::append(DIASDKPath
, "DIA SDK");
653 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, std::string(DIASDKPath
),
657 if (DriverArgs
.hasArg(options::OPT_nostdlibinc
))
660 // Honor %INCLUDE% and %EXTERNAL_INCLUDE%. It should have essential search
661 // paths set by vcvarsall.bat. Skip if the user expressly set a vctoolsdir.
662 if (!DriverArgs
.getLastArg(options::OPT__SLASH_vctoolsdir
,
663 options::OPT__SLASH_winsysroot
)) {
664 bool Found
= AddSystemIncludesFromEnv("INCLUDE");
665 Found
|= AddSystemIncludesFromEnv("EXTERNAL_INCLUDE");
670 // When built with access to the proper Windows APIs, try to actually find
671 // the correct include paths first.
672 if (!VCToolChainPath
.empty()) {
673 addSystemInclude(DriverArgs
, CC1Args
,
674 getSubDirectoryPath(llvm::SubDirectoryType::Include
));
677 getSubDirectoryPath(llvm::SubDirectoryType::Include
, "atlmfc"));
679 if (useUniversalCRT()) {
680 std::string UniversalCRTSdkPath
;
681 std::string UCRTVersion
;
682 if (llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir
, WinSdkVersion
,
683 WinSysRoot
, UniversalCRTSdkPath
,
685 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, UniversalCRTSdkPath
,
686 "Include", UCRTVersion
, "ucrt");
690 std::string WindowsSDKDir
;
692 std::string windowsSDKIncludeVersion
;
693 std::string windowsSDKLibVersion
;
694 if (llvm::getWindowsSDKDir(getVFS(), WinSdkDir
, WinSdkVersion
, WinSysRoot
,
695 WindowsSDKDir
, major
, windowsSDKIncludeVersion
,
696 windowsSDKLibVersion
)) {
698 // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
699 // Anyway, llvm::sys::path::append is able to manage it.
700 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, WindowsSDKDir
,
701 "Include", windowsSDKIncludeVersion
,
703 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, WindowsSDKDir
,
704 "Include", windowsSDKIncludeVersion
,
706 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, WindowsSDKDir
,
707 "Include", windowsSDKIncludeVersion
,
710 llvm::VersionTuple Tuple
;
711 if (!Tuple
.tryParse(windowsSDKIncludeVersion
) &&
712 Tuple
.getSubminor().value_or(0) >= 17134) {
713 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, WindowsSDKDir
,
714 "Include", windowsSDKIncludeVersion
,
719 AddSystemIncludeWithSubfolder(DriverArgs
, CC1Args
, WindowsSDKDir
,
728 // As a fallback, select default install paths.
729 // FIXME: Don't guess drives and paths like this on Windows.
730 const StringRef Paths
[] = {
731 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
732 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
733 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
734 "C:/Program Files/Microsoft Visual Studio 8/VC/include",
735 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
737 addSystemIncludes(DriverArgs
, CC1Args
, Paths
);
741 void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList
&DriverArgs
,
742 ArgStringList
&CC1Args
) const {
743 // FIXME: There should probably be logic here to find libc++ on Windows.
746 VersionTuple
MSVCToolChain::computeMSVCVersion(const Driver
*D
,
747 const ArgList
&Args
) const {
748 bool IsWindowsMSVC
= getTriple().isWindowsMSVCEnvironment();
749 VersionTuple MSVT
= ToolChain::computeMSVCVersion(D
, Args
);
751 MSVT
= getTriple().getEnvironmentVersion();
752 if (MSVT
.empty() && IsWindowsMSVC
)
754 getMSVCVersionFromExe(getSubDirectoryPath(llvm::SubDirectoryType::Bin
));
756 Args
.hasFlag(options::OPT_fms_extensions
, options::OPT_fno_ms_extensions
,
758 // -fms-compatibility-version=19.20 is default, aka 2019, 16.x
759 MSVT
= VersionTuple(19, 20);
765 MSVCToolChain::ComputeEffectiveClangTriple(const ArgList
&Args
,
766 types::ID InputType
) const {
767 // The MSVC version doesn't care about the architecture, even though it
768 // may look at the triple internally.
769 VersionTuple MSVT
= computeMSVCVersion(/*D=*/nullptr, Args
);
770 MSVT
= VersionTuple(MSVT
.getMajor(), MSVT
.getMinor().value_or(0),
771 MSVT
.getSubminor().value_or(0));
773 // For the rest of the triple, however, a computed architecture name may
775 llvm::Triple
Triple(ToolChain::ComputeEffectiveClangTriple(Args
, InputType
));
776 if (Triple
.getEnvironment() == llvm::Triple::MSVC
) {
777 StringRef ObjFmt
= Triple
.getEnvironmentName().split('-').second
;
779 Triple
.setEnvironmentName((Twine("msvc") + MSVT
.getAsString()).str());
781 Triple
.setEnvironmentName(
782 (Twine("msvc") + MSVT
.getAsString() + Twine('-') + ObjFmt
).str());
784 return Triple
.getTriple();
787 SanitizerMask
MSVCToolChain::getSupportedSanitizers() const {
788 SanitizerMask Res
= ToolChain::getSupportedSanitizers();
789 Res
|= SanitizerKind::Address
;
790 Res
|= SanitizerKind::PointerCompare
;
791 Res
|= SanitizerKind::PointerSubtract
;
792 Res
|= SanitizerKind::Fuzzer
;
793 Res
|= SanitizerKind::FuzzerNoLink
;
794 Res
&= ~SanitizerKind::CFIMFCall
;
798 static void TranslateOptArg(Arg
*A
, llvm::opt::DerivedArgList
&DAL
,
799 bool SupportsForcingFramePointer
,
800 const char *ExpandChar
, const OptTable
&Opts
) {
801 assert(A
->getOption().matches(options::OPT__SLASH_O
));
803 StringRef OptStr
= A
->getValue();
804 for (size_t I
= 0, E
= OptStr
.size(); I
!= E
; ++I
) {
805 const char &OptChar
= *(OptStr
.data() + I
);
813 // Ignore /O[12xd] flags that aren't the last one on the command line.
814 // Only the last one gets expanded.
815 if (&OptChar
!= ExpandChar
) {
819 if (OptChar
== 'd') {
820 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_O0
));
822 if (OptChar
== '1') {
823 DAL
.AddJoinedArg(A
, Opts
.getOption(options::OPT_O
), "s");
824 } else if (OptChar
== '2' || OptChar
== 'x') {
825 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_fbuiltin
));
826 DAL
.AddJoinedArg(A
, Opts
.getOption(options::OPT_O
), "2");
828 if (SupportsForcingFramePointer
&&
829 !DAL
.hasArgNoClaim(options::OPT_fno_omit_frame_pointer
))
830 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_fomit_frame_pointer
));
831 if (OptChar
== '1' || OptChar
== '2')
832 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_ffunction_sections
));
836 if (I
+ 1 != E
&& isdigit(OptStr
[I
+ 1])) {
837 switch (OptStr
[I
+ 1]) {
839 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_fno_inline
));
842 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_finline_hint_functions
));
845 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_finline_functions
));
855 if (I
+ 1 != E
&& OptStr
[I
+ 1] == '-') {
857 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_fno_builtin
));
859 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_fbuiltin
));
863 DAL
.AddJoinedArg(A
, Opts
.getOption(options::OPT_O
), "s");
866 DAL
.AddJoinedArg(A
, Opts
.getOption(options::OPT_O
), "2");
869 bool OmitFramePointer
= true;
870 if (I
+ 1 != E
&& OptStr
[I
+ 1] == '-') {
871 OmitFramePointer
= false;
874 if (SupportsForcingFramePointer
) {
875 if (OmitFramePointer
)
877 Opts
.getOption(options::OPT_fomit_frame_pointer
));
880 A
, Opts
.getOption(options::OPT_fno_omit_frame_pointer
));
882 // Don't warn about /Oy- in x86-64 builds (where
883 // SupportsForcingFramePointer is false). The flag having no effect
884 // there is a compiler-internal optimization, and people shouldn't have
885 // to special-case their build files for x86-64 clang-cl.
894 static void TranslateDArg(Arg
*A
, llvm::opt::DerivedArgList
&DAL
,
895 const OptTable
&Opts
) {
896 assert(A
->getOption().matches(options::OPT_D
));
898 StringRef Val
= A
->getValue();
899 size_t Hash
= Val
.find('#');
900 if (Hash
== StringRef::npos
|| Hash
> Val
.find('=')) {
905 std::string NewVal
= std::string(Val
);
907 DAL
.AddJoinedArg(A
, Opts
.getOption(options::OPT_D
), NewVal
);
910 static void TranslatePermissive(Arg
*A
, llvm::opt::DerivedArgList
&DAL
,
911 const OptTable
&Opts
) {
912 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT__SLASH_Zc_twoPhase_
));
913 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_fno_operator_names
));
916 static void TranslatePermissiveMinus(Arg
*A
, llvm::opt::DerivedArgList
&DAL
,
917 const OptTable
&Opts
) {
918 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT__SLASH_Zc_twoPhase
));
919 DAL
.AddFlagArg(A
, Opts
.getOption(options::OPT_foperator_names
));
922 llvm::opt::DerivedArgList
*
923 MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList
&Args
,
925 Action::OffloadKind OFK
) const {
926 DerivedArgList
*DAL
= new DerivedArgList(Args
.getBaseArgs());
927 const OptTable
&Opts
= getDriver().getOpts();
929 // /Oy and /Oy- don't have an effect on X86-64
930 bool SupportsForcingFramePointer
= getArch() != llvm::Triple::x86_64
;
932 // The -O[12xd] flag actually expands to several flags. We must desugar the
933 // flags so that options embedded can be negated. For example, the '-O2' flag
934 // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to
935 // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
938 // Note that this expansion logic only applies to the *last* of '[12xd]'.
940 // First step is to search for the character we'd like to expand.
941 const char *ExpandChar
= nullptr;
942 for (Arg
*A
: Args
.filtered(options::OPT__SLASH_O
)) {
943 StringRef OptStr
= A
->getValue();
944 for (size_t I
= 0, E
= OptStr
.size(); I
!= E
; ++I
) {
945 char OptChar
= OptStr
[I
];
946 char PrevChar
= I
> 0 ? OptStr
[I
- 1] : '0';
947 if (PrevChar
== 'b') {
948 // OptChar does not expand; it's an argument to the previous char.
951 if (OptChar
== '1' || OptChar
== '2' || OptChar
== 'x' || OptChar
== 'd')
952 ExpandChar
= OptStr
.data() + I
;
956 for (Arg
*A
: Args
) {
957 if (A
->getOption().matches(options::OPT__SLASH_O
)) {
958 // The -O flag actually takes an amalgam of other options. For example,
959 // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
960 TranslateOptArg(A
, *DAL
, SupportsForcingFramePointer
, ExpandChar
, Opts
);
961 } else if (A
->getOption().matches(options::OPT_D
)) {
962 // Translate -Dfoo#bar into -Dfoo=bar.
963 TranslateDArg(A
, *DAL
, Opts
);
964 } else if (A
->getOption().matches(options::OPT__SLASH_permissive
)) {
965 // Expand /permissive
966 TranslatePermissive(A
, *DAL
, Opts
);
967 } else if (A
->getOption().matches(options::OPT__SLASH_permissive_
)) {
968 // Expand /permissive-
969 TranslatePermissiveMinus(A
, *DAL
, Opts
);
970 } else if (OFK
!= Action::OFK_HIP
) {
971 // HIP Toolchain translates input args by itself.
979 void MSVCToolChain::addClangTargetOptions(
980 const ArgList
&DriverArgs
, ArgStringList
&CC1Args
,
981 Action::OffloadKind DeviceOffloadKind
) const {
982 // MSVC STL kindly allows removing all usages of typeid by defining
983 // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
984 if (DriverArgs
.hasFlag(options::OPT_fno_rtti
, options::OPT_frtti
,
986 CC1Args
.push_back("-D_HAS_STATIC_RTTI=0");