clang 24.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 // Also 'lld-link' for hybrid object files if -marm64x is requested.
348 if (Args.hasArg(options::OPT_gdwarf, options::OPT_gdwarf_2,
349 options::OPT_gdwarf_3, options::OPT_gdwarf_4,
350 options::OPT_gdwarf_5, options::OPT_gdwarf_6,
351 options::OPT_marm64x))
352 Linker = "lld-link";
353 else
354 Linker = "link";
355 }
356
357 // We need to translate 'lld' into 'lld-link'.
358 if (Linker.equals_insensitive("lld"))
359 Linker = "lld-link";
360
361 if (Linker == "lld-link") {
362 for (Arg *A : Args.filtered(options::OPT_vfsoverlay))
363 CmdArgs.push_back(
364 Args.MakeArgString(std::string("/vfsoverlay:") + A->getValue()));
365
366 if (TC.isUsingLTO(Args) &&
367 Args.hasFlag(options::OPT_gsplit_dwarf, options::OPT_gno_split_dwarf,
368 false))
369 CmdArgs.push_back(Args.MakeArgString(Twine("/dwodir:") +
370 Output.getFilename() + "_dwo"));
371 }
372
373 // Add filenames, libraries, and other linker inputs.
374 for (const auto &Input : Inputs) {
375 if (Input.isFilename()) {
376 CmdArgs.push_back(Input.getFilename());
377 continue;
378 }
379
380 const Arg &A = Input.getInputArg();
381
382 // Render -l options differently for the MSVC linker.
383 if (A.getOption().matches(options::OPT_l)) {
384 StringRef Lib = A.getValue();
385 const char *LinkLibArg;
386 if (Lib.ends_with(".lib"))
387 LinkLibArg = Args.MakeArgString(Lib);
388 else
389 LinkLibArg = Args.MakeArgString(Lib + ".lib");
390 CmdArgs.push_back(LinkLibArg);
391 continue;
392 }
393
394 // Otherwise, this is some other kind of linker input option like -Wl, -z,
395 // or -L. Render it, even if MSVC doesn't understand it.
396 A.renderAsInput(Args, CmdArgs);
397 }
398
399 TC.addOffloadRTLibs(C.getActiveOffloadKinds(), Args, CmdArgs);
400
401 TC.addProfileRTLibs(Args, CmdArgs);
402
403 std::vector<const char *> Environment;
404
405 // We need to special case some linker paths. In the case of the regular msvc
406 // linker, we need to use a special search algorithm.
407 llvm::SmallString<128> linkPath;
408 if (Linker.equals_insensitive("link")) {
409 // If we're using the MSVC linker, it's not sufficient to just use link
410 // from the program PATH, because other environments like GnuWin32 install
411 // their own link.exe which may come first.
412 linkPath = FindVisualStudioExecutable(TC, "link.exe");
413
414 if (!TC.FoundMSVCInstall() && !canExecute(TC.getVFS(), linkPath)) {
416 ClPath = TC.GetProgramPath("cl.exe");
417 if (canExecute(TC.getVFS(), ClPath)) {
418 linkPath = llvm::sys::path::parent_path(ClPath);
419 llvm::sys::path::append(linkPath, "link.exe");
420 if (!canExecute(TC.getVFS(), linkPath))
421 C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
422 } else {
423 C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
424 }
425 }
426
427 // Clang handles passing the proper asan libs to the linker, which goes
428 // against link.exe's /INFERASANLIBS which automatically finds asan libs.
429 if (TC.getSanitizerArgs(Args).needsAsanRt())
430 CmdArgs.push_back("/INFERASANLIBS:NO");
431
432#ifdef _WIN32
433 // When cross-compiling with VS2017 or newer, link.exe expects to have
434 // its containing bin directory at the top of PATH, followed by the
435 // native target bin directory.
436 // e.g. when compiling for x86 on an x64 host, PATH should start with:
437 // /bin/Hostx64/x86;/bin/Hostx64/x64
438 // This doesn't attempt to handle llvm::ToolsetLayout::DevDivInternal.
439 if (TC.getIsVS2017OrNewer() &&
440 llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) {
441 auto HostArch = llvm::Triple(llvm::sys::getProcessTriple()).getArch();
442
443 auto EnvBlockWide =
444 std::unique_ptr<wchar_t[], decltype(&FreeEnvironmentStringsW)>(
445 GetEnvironmentStringsW(), FreeEnvironmentStringsW);
446 if (!EnvBlockWide)
447 goto SkipSettingEnvironment;
448
449 size_t EnvCount = 0;
450 size_t EnvBlockLen = 0;
451 while (EnvBlockWide[EnvBlockLen] != L'\0') {
452 ++EnvCount;
453 EnvBlockLen += std::wcslen(&EnvBlockWide[EnvBlockLen]) +
454 1 /*string null-terminator*/;
455 }
456 ++EnvBlockLen; // add the block null-terminator
457
458 std::string EnvBlock;
459 if (!llvm::convertUTF16ToUTF8String(
460 llvm::ArrayRef<char>(reinterpret_cast<char *>(EnvBlockWide.get()),
461 EnvBlockLen * sizeof(EnvBlockWide[0])),
462 EnvBlock))
463 goto SkipSettingEnvironment;
464
465 Environment.reserve(EnvCount);
466
467 // Now loop over each string in the block and copy them into the
468 // environment vector, adjusting the PATH variable as needed when we
469 // find it.
470 for (const char *Cursor = EnvBlock.data(); *Cursor != '\0';) {
471 llvm::StringRef EnvVar(Cursor);
472 if (EnvVar.starts_with_insensitive("path=")) {
473 constexpr size_t PrefixLen = 5; // strlen("path=")
474 Environment.push_back(Args.MakeArgString(
475 EnvVar.substr(0, PrefixLen) +
476 TC.getSubDirectoryPath(llvm::SubDirectoryType::Bin) +
477 llvm::Twine(llvm::sys::EnvPathSeparator) +
478 TC.getSubDirectoryPath(llvm::SubDirectoryType::Bin, HostArch) +
479 (EnvVar.size() > PrefixLen
480 ? llvm::Twine(llvm::sys::EnvPathSeparator) +
481 EnvVar.substr(PrefixLen)
482 : "")));
483 } else {
484 Environment.push_back(Args.MakeArgString(EnvVar));
485 }
486 Cursor += EnvVar.size() + 1 /*null-terminator*/;
487 }
488 }
489 SkipSettingEnvironment:;
490#endif
491 } else {
492 linkPath = TC.GetProgramPath(Linker.str().c_str());
493 }
494
495 auto LinkCmd = std::make_unique<Command>(
497 Args.MakeArgString(linkPath), CmdArgs, Inputs, Output);
498 if (!Environment.empty())
499 LinkCmd->setEnvironment(Environment);
500 C.addCommand(std::move(LinkCmd));
501}
502
504 const InputInfo &Output,
505 const InputInfoList &Inputs,
506 const ArgList &Args,
507 const char *LinkingOutput) const {
508 // Assume llvm-objcopy is only used for hybrid ARM64X object files.
509 if (Inputs.size() != 2)
510 return;
511
512 std::string ObjcopyPath = getToolChain().GetProgramPath("llvm-objcopy");
513 const char *Exec = Args.MakeArgString(ObjcopyPath);
514
515 // Embed the hybrid object in the .obj.arm64ec section.
516 ArgStringList CmdArgs;
517 CmdArgs.push_back(Args.MakeArgString("--add-section=.obj.arm64ec=" +
518 Twine(Inputs[1].getFilename())));
519 // Mark the .obj.arm64ec section as discardable.
520 CmdArgs.push_back("--set-section-flags=.obj.arm64ec=exclude");
521 CmdArgs.push_back(Inputs[0].getFilename());
522 CmdArgs.push_back(Output.getFilename());
523
524 C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
525 Exec, CmdArgs, Inputs, Output));
526}
527
528MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
529 const ArgList &Args)
530 : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
531 RocmInstallation(D, Triple, Args), SYCLInstallation(D, Triple, Args) {
532 getProgramPaths().push_back(getDriver().Dir);
533
534 std::optional<llvm::StringRef> VCToolsDir, VCToolsVersion;
535 if (Arg *A = Args.getLastArg(options::OPT__SLASH_vctoolsdir))
536 VCToolsDir = A->getValue();
537 if (Arg *A = Args.getLastArg(options::OPT__SLASH_vctoolsversion))
538 VCToolsVersion = A->getValue();
539 if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkdir))
540 WinSdkDir = A->getValue();
541 if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsdkversion))
542 WinSdkVersion = A->getValue();
543 if (Arg *A = Args.getLastArg(options::OPT__SLASH_winsysroot))
544 WinSysRoot = A->getValue();
545
546 // Check the command line first, that's the user explicitly telling us what to
547 // use. Check the environment next, in case we're being invoked from a VS
548 // command prompt. Failing that, just try to find the newest Visual Studio
549 // version we can and use its default VC toolchain.
550 llvm::findVCToolChainViaCommandLine(getVFS(), VCToolsDir, VCToolsVersion,
551 WinSysRoot, VCToolChainPath, VSLayout) ||
552 llvm::findVCToolChainViaEnvironment(getVFS(), VCToolChainPath,
553 VSLayout) ||
554 llvm::findVCToolChainViaSetupConfig(getVFS(), VCToolsVersion,
555 VCToolChainPath, VSLayout) ||
556 llvm::findVCToolChainViaRegistry(VCToolChainPath, VSLayout);
557
558 loadMultilibsFromYAML(Args, D);
559}
560
562 switch (AC) {
564 if (!Objcopy)
565 Objcopy.reset(new tools::ARM64XObjcopy(*this));
566 return Objcopy.get();
567 default:
568 return ToolChain::getTool(AC);
569 }
570}
571
573 return new tools::visualstudio::Linker(*this);
574}
575
577 if (getTriple().isOSBinFormatMachO())
578 return new tools::darwin::Assembler(*this);
579 getDriver().Diag(clang::diag::err_no_external_assembler);
580 return nullptr;
581}
582
585 // Don't emit unwind tables by default for MachO targets.
586 if (getTriple().isOSBinFormatMachO())
588
589 // All non-x86_32 Windows targets require unwind tables. However, LLVM
590 // doesn't know how to generate them for all targets, so only enable
591 // the ones that are actually implemented.
592 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::arm ||
593 getArch() == llvm::Triple::thumb || getArch() == llvm::Triple::aarch64)
595
597}
598
600 return getArch() == llvm::Triple::x86_64 ||
601 getArch() == llvm::Triple::aarch64;
602}
603
604bool MSVCToolChain::isPIEDefault(const llvm::opt::ArgList &Args) const {
605 return false;
606}
607
609 return getArch() == llvm::Triple::x86_64 ||
610 getArch() == llvm::Triple::aarch64;
611}
612
613void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
614 ArgStringList &CC1Args) const {
615 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
616}
617
618void MSVCToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
619 ArgStringList &CC1Args) const {
620 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
621}
622
623void MSVCToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs,
624 ArgStringList &CC1Args) const {
625 SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args);
626}
627
628void MSVCToolChain::addOffloadRTLibs(unsigned ActiveKinds, const ArgList &Args,
629 ArgStringList &CmdArgs) const {
630 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib,
631 true) ||
632 Args.hasArg(options::OPT_no_hip_rt) || Args.hasArg(options::OPT_r))
633 return;
634
635 if (ActiveKinds & Action::OFK_HIP) {
636 CmdArgs.append({Args.MakeArgString(StringRef("-libpath:") +
637 RocmInstallation->getLibPath()),
638 "amdhip64.lib"});
639
640 // For HIP device PGO, link clang_rt.profile_rocm when available. It is a
641 // self-contained superset of clang_rt.profile, emitted first so the base
642 // archive stays inert (avoiding a /MD-vs-/MT CRT mix in the host image).
643 if (needsProfileRT(Args) &&
644 getVFS().exists(getCompilerRT(Args, "profile_rocm", FT_Static))) {
645 CmdArgs.push_back(getCompilerRTArgString(Args, "profile_rocm"));
646 // Force the linker to retain the constructor-only hipModuleLoad*
647 // interceptor object from clang_rt.profile_rocm (see Linux.cpp). The
648 // constructor self-skips for programs that do not use hipModuleLoad.
649 CmdArgs.push_back(
650 "-include:__llvm_profile_offload_register_dynamic_module");
651 }
652 }
653}
654
655void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
656 CudaInstallation->print(OS);
657 RocmInstallation->print(OS);
658}
659
660std::string
662 llvm::StringRef SubdirParent) const {
663 return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, getArch(),
664 SubdirParent);
665}
666
667std::string
669 llvm::Triple::ArchType TargetArch) const {
670 return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, TargetArch,
671 "");
672}
673
674// Find the most recent version of Universal CRT or Windows 10 SDK.
675// vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
676// directory by name and uses the last one of the list.
677// So we compare entry names lexicographically to find the greatest one.
678// Gets the library path required to link against the Windows SDK.
680 std::string &path) const {
681 std::string sdkPath;
682 int sdkMajor = 0;
683 std::string windowsSDKIncludeVersion;
684 std::string windowsSDKLibVersion;
685
686 path.clear();
687 if (!llvm::getWindowsSDKDir(getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot,
688 sdkPath, sdkMajor, windowsSDKIncludeVersion,
689 windowsSDKLibVersion))
690 return false;
691
692 llvm::SmallString<128> libPath(sdkPath);
693 llvm::sys::path::append(libPath, "Lib");
694 if (sdkMajor >= 10)
695 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
696 WinSdkVersion.has_value())
697 windowsSDKLibVersion = *WinSdkVersion;
698 if (sdkMajor >= 8)
699 llvm::sys::path::append(libPath, windowsSDKLibVersion, "um");
700 return llvm::appendArchToWindowsSDKLibPath(sdkMajor, libPath, getArch(),
701 path);
702}
703
705 return llvm::useUniversalCRT(VSLayout, VCToolChainPath, getArch(), getVFS());
706}
707
709 std::string &Path) const {
710 std::string UniversalCRTSdkPath;
711 std::string UCRTVersion;
712
713 Path.clear();
714 if (!llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir, WinSdkVersion,
715 WinSysRoot, UniversalCRTSdkPath,
716 UCRTVersion))
717 return false;
718
719 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
720 WinSdkVersion.has_value())
721 UCRTVersion = *WinSdkVersion;
722
723 StringRef ArchName = llvm::archToWindowsSDKArch(getArch());
724 if (ArchName.empty())
725 return false;
726
727 llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
728 llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
729
730 Path = std::string(LibPath);
731 return true;
732}
733
734static VersionTuple getMSVCVersionFromExe(const std::string &BinDir) {
735 VersionTuple Version;
736#ifdef _WIN32
737 SmallString<128> ClExe(BinDir);
738 llvm::sys::path::append(ClExe, "cl.exe");
739
740 std::wstring ClExeWide;
741 if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
742 return Version;
743
744 const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
745 nullptr);
746 if (VersionSize == 0)
747 return Version;
748
749 SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
750 if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
751 VersionBlock.data()))
752 return Version;
753
754 VS_FIXEDFILEINFO *FileInfo = nullptr;
755 UINT FileInfoSize = 0;
756 if (!::VerQueryValueW(VersionBlock.data(), L"\\",
757 reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
758 FileInfoSize < sizeof(*FileInfo))
759 return Version;
760
761 const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
762 const unsigned Minor = (FileInfo->dwFileVersionMS ) & 0xFFFF;
763 const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
764
765 Version = VersionTuple(Major, Minor, Micro);
766#endif
767 return Version;
768}
769
771 const ArgList &DriverArgs, ArgStringList &CC1Args,
772 const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
773 const Twine &subfolder3) const {
774 llvm::SmallString<128> path(folder);
775 llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
776 addSystemInclude(DriverArgs, CC1Args, path);
777}
778
780 const ArgList &DriverArgs, ArgStringList &CC1Args,
781 bool HonorNostdincxx) const {
782 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc) ||
783 (HonorNostdincxx && DriverArgs.hasArg(options::OPT_nostdincxx)))
784 return;
785
786 // Add multilib variant include paths in priority order.
787 for (const Multilib &M : getOrderedMultilibs()) {
788 if (M.isDefault())
789 continue;
790 if (std::optional<std::string> StdlibIncDir = getStdlibIncludePath()) {
791 SmallString<128> Dir(*StdlibIncDir);
792 llvm::sys::path::append(Dir, M.includeSuffix());
793 if (getDriver().getVFS().exists(Dir))
794 addSystemInclude(DriverArgs, CC1Args, Dir);
795 }
796 }
797}
798
799void MSVCToolChain::AddMSVCStdlibIncludeArgs(const ArgList &DriverArgs,
800 ArgStringList &CC1Args) const {
801 AddMSVCStdlibMultilibIncludeArgs(DriverArgs, CC1Args,
802 /*HonorNostdincxx=*/true);
803
804 if (!DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc) &&
805 !DriverArgs.hasArg(options::OPT_nostdincxx) && !VCToolChainPath.empty())
806 addSystemInclude(DriverArgs, CC1Args,
807 getSubDirectoryPath(llvm::SubDirectoryType::Include));
808}
809
810void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
811 ArgStringList &CC1Args) const {
812 if (DriverArgs.hasArg(options::OPT_nostdinc))
813 return;
814
815 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
816 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
817 "include");
818 }
819
820 // Add %INCLUDE%-like directories from the -imsvc flag.
821 for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
822 addSystemInclude(DriverArgs, CC1Args, Path);
823
824 auto AddSystemIncludesFromEnv = [&](StringRef Var) -> bool {
825 if (auto Val = llvm::sys::Process::GetEnv(Var)) {
827 StringRef(*Val).split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
828 if (!Dirs.empty()) {
829 addSystemIncludes(DriverArgs, CC1Args, Dirs);
830 return true;
831 }
832 }
833 return false;
834 };
835
836 // Add %INCLUDE%-like dirs via /external:env: flags.
837 for (const auto &Var :
838 DriverArgs.getAllArgValues(options::OPT__SLASH_external_env)) {
839 AddSystemIncludesFromEnv(Var);
840 }
841
842 // Add DIA SDK include if requested.
843 if (const Arg *A = DriverArgs.getLastArg(options::OPT__SLASH_diasdkdir,
844 options::OPT__SLASH_winsysroot)) {
845 // cl.exe doesn't find the DIA SDK automatically, so this too requires
846 // explicit flags and doesn't automatically look in "DIA SDK" relative
847 // to the path we found for VCToolChainPath.
848 llvm::SmallString<128> DIASDKPath(A->getValue());
849 if (A->getOption().getID() == options::OPT__SLASH_winsysroot)
850 llvm::sys::path::append(DIASDKPath, "DIA SDK");
851 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, std::string(DIASDKPath),
852 "include");
853 }
854
855 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
856 return;
857
858 AddMSVCStdlibMultilibIncludeArgs(DriverArgs, CC1Args,
859 /*HonorNostdincxx=*/false);
860
861 // Honor %INCLUDE% and %EXTERNAL_INCLUDE%. It should have essential search
862 // paths set by vcvarsall.bat. Skip if the user expressly set any of the
863 // Windows SDK or VC Tools options.
864 if (!DriverArgs.hasArg(
865 options::OPT__SLASH_vctoolsdir, options::OPT__SLASH_vctoolsversion,
866 options::OPT__SLASH_winsysroot, options::OPT__SLASH_winsdkdir,
867 options::OPT__SLASH_winsdkversion)) {
868 bool Found = AddSystemIncludesFromEnv("INCLUDE");
869 Found |= AddSystemIncludesFromEnv("EXTERNAL_INCLUDE");
870 if (Found)
871 return;
872 }
873
874 // When built with access to the proper Windows APIs, try to actually find
875 // the correct include paths first.
876 if (!VCToolChainPath.empty()) {
877 addSystemInclude(DriverArgs, CC1Args,
878 getSubDirectoryPath(llvm::SubDirectoryType::Include));
880 DriverArgs, CC1Args,
881 getSubDirectoryPath(llvm::SubDirectoryType::Include, "atlmfc"));
882
883 if (useUniversalCRT()) {
884 std::string UniversalCRTSdkPath;
885 std::string UCRTVersion;
886 if (llvm::getUniversalCRTSdkDir(getVFS(), WinSdkDir, WinSdkVersion,
887 WinSysRoot, UniversalCRTSdkPath,
888 UCRTVersion)) {
889 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
890 WinSdkVersion.has_value())
891 UCRTVersion = *WinSdkVersion;
892 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
893 "Include", UCRTVersion, "ucrt");
894 }
895 }
896
897 std::string WindowsSDKDir;
898 int major = 0;
899 std::string windowsSDKIncludeVersion;
900 std::string windowsSDKLibVersion;
901 if (llvm::getWindowsSDKDir(getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot,
902 WindowsSDKDir, major, windowsSDKIncludeVersion,
903 windowsSDKLibVersion)) {
904 if (major >= 10)
905 if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) &&
906 WinSdkVersion.has_value())
907 windowsSDKIncludeVersion = windowsSDKLibVersion = *WinSdkVersion;
908 if (major >= 8) {
909 // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
910 // Anyway, llvm::sys::path::append is able to manage it.
911 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
912 "Include", windowsSDKIncludeVersion,
913 "shared");
914 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
915 "Include", windowsSDKIncludeVersion,
916 "um");
917 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
918 "Include", windowsSDKIncludeVersion,
919 "winrt");
920 if (major >= 10) {
921 llvm::VersionTuple Tuple;
922 if (!Tuple.tryParse(windowsSDKIncludeVersion) &&
923 Tuple.getSubminor().value_or(0) >= 17134) {
924 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
925 "Include", windowsSDKIncludeVersion,
926 "cppwinrt");
927 }
928 }
929 } else {
930 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
931 "Include");
932 }
933 }
934
935 return;
936 }
937
938#if defined(_WIN32)
939 // As a fallback, select default install paths.
940 // FIXME: Don't guess drives and paths like this on Windows.
941 const StringRef Paths[] = {
942 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
943 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
944 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
945 "C:/Program Files/Microsoft Visual Studio 8/VC/include",
946 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
947 };
948 addSystemIncludes(DriverArgs, CC1Args, Paths);
949#endif
950}
951
952void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
953 ArgStringList &CC1Args) const {
954 // MSVC STL paths are added from AddClangSystemIncludeArgs during normal
955 // compilation to preserve clang-cl header search order.
956 if (DriverArgs.hasArg(options::OPT_print_cxx_stdlib_include_dirs) &&
957 !DriverArgs.hasArg(options::OPT_stdlib_EQ))
958 AddMSVCStdlibIncludeArgs(DriverArgs, CC1Args);
959}
960
961StringRef MSVCToolChain::GetCXXStdlibName(const ArgList &DriverArgs) const {
962 if (!DriverArgs.hasArg(options::OPT_stdlib_EQ))
963 return "msvcstl";
964 return ToolChain::GetCXXStdlibName(DriverArgs);
965}
966
968 const ArgList &Args) const {
969 bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
970 VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
971 if (MSVT.empty())
972 MSVT = getTriple().getEnvironmentVersion();
973 if (MSVT.empty() && IsWindowsMSVC)
974 MSVT =
975 getMSVCVersionFromExe(getSubDirectoryPath(llvm::SubDirectoryType::Bin));
976 if (MSVT.empty() &&
977 Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
978 IsWindowsMSVC)) {
979 // -fms-compatibility-version=19.33 is default, aka 2022, 17.3
980 // NOTE: when changing this value, also update
981 // clang/docs/CommandGuide/clang.rst and clang/docs/UsersManual.md
982 // accordingly.
983 MSVT = VersionTuple(19, 33);
984 }
985 return MSVT;
986}
987
988std::string
990 types::ID InputType) const {
991 // The MSVC version doesn't care about the architecture, even though it
992 // may look at the triple internally.
993 VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
994 MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().value_or(0),
995 MSVT.getSubminor().value_or(0));
996
997 // For the rest of the triple, however, a computed architecture name may
998 // be needed.
999 llvm::Triple Triple(
1000 ToolChain::ComputeEffectiveClangTriple(Args, BA, InputType));
1001 if (Triple.getEnvironment() == llvm::Triple::MSVC) {
1002 StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
1003 if (ObjFmt.empty())
1004 Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
1005 else
1006 Triple.setEnvironmentName(
1007 (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
1008 }
1009 return Triple.getTriple();
1010}
1011
1013 BoundArch BA, Action::OffloadKind DeviceOffloadKind) const {
1014 SanitizerMask Res = ToolChain::getSupportedSanitizers(BA, DeviceOffloadKind);
1015 Res |= SanitizerKind::Address;
1016 Res |= SanitizerKind::PointerCompare;
1017 Res |= SanitizerKind::PointerSubtract;
1018 Res |= SanitizerKind::Fuzzer;
1019 Res |= SanitizerKind::FuzzerNoLink;
1020 Res &= ~SanitizerKind::CFIMFCall;
1021 return Res;
1022}
1023
1024static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1025 bool SupportsForcingFramePointer,
1026 const char *ExpandChar, const OptTable &Opts) {
1027 assert(A->getOption().matches(options::OPT__SLASH_O));
1028
1029 StringRef OptStr = A->getValue();
1030 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1031 const char &OptChar = *(OptStr.data() + I);
1032 switch (OptChar) {
1033 default:
1034 break;
1035 case '1':
1036 case '2':
1037 case 'x':
1038 case 'd':
1039 // Ignore /O[12xd] flags that aren't the last one on the command line.
1040 // Only the last one gets expanded.
1041 if (&OptChar != ExpandChar) {
1042 A->claim();
1043 break;
1044 }
1045 if (OptChar == 'd') {
1046 DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
1047 } else {
1048 if (OptChar == '1') {
1049 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1050 } else if (OptChar == '2' || OptChar == 'x') {
1051 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1052 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "3");
1053 }
1054 if (SupportsForcingFramePointer &&
1055 !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
1056 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fomit_frame_pointer));
1057 if (OptChar == '1' || OptChar == '2')
1058 DAL.AddFlagArg(A, Opts.getOption(options::OPT_ffunction_sections));
1059 }
1060 break;
1061 case 'b':
1062 if (I + 1 != E && isdigit(OptStr[I + 1])) {
1063 switch (OptStr[I + 1]) {
1064 case '0':
1065 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
1066 break;
1067 case '1':
1068 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
1069 break;
1070 case '2':
1071 case '3':
1072 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
1073 break;
1074 }
1075 ++I;
1076 }
1077 break;
1078 case 'g':
1079 A->claim();
1080 break;
1081 case 'i':
1082 if (I + 1 != E && OptStr[I + 1] == '-') {
1083 ++I;
1084 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
1085 } else {
1086 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1087 }
1088 break;
1089 case 's':
1090 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1091 break;
1092 case 't':
1093 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "3");
1094 break;
1095 case 'y': {
1096 bool OmitFramePointer = true;
1097 if (I + 1 != E && OptStr[I + 1] == '-') {
1098 OmitFramePointer = false;
1099 ++I;
1100 }
1101 if (SupportsForcingFramePointer) {
1102 if (OmitFramePointer)
1103 DAL.AddFlagArg(A,
1104 Opts.getOption(options::OPT_fomit_frame_pointer));
1105 else
1106 DAL.AddFlagArg(
1107 A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
1108 } else {
1109 // Don't warn about /Oy- in x86-64 builds (where
1110 // SupportsForcingFramePointer is false). The flag having no effect
1111 // there is a compiler-internal optimization, and people shouldn't have
1112 // to special-case their build files for x86-64 clang-cl.
1113 A->claim();
1114 }
1115 break;
1116 }
1117 }
1118 }
1119}
1120
1121static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1122 const OptTable &Opts) {
1123 assert(A->getOption().matches(options::OPT_D));
1124
1125 StringRef Val = A->getValue();
1126 size_t Hash = Val.find('#');
1127 if (Hash == StringRef::npos || Hash > Val.find('=')) {
1128 DAL.append(A);
1129 return;
1130 }
1131
1132 std::string NewVal = std::string(Val);
1133 NewVal[Hash] = '=';
1134 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
1135}
1136
1137static void TranslatePermissive(Arg *A, llvm::opt::DerivedArgList &DAL,
1138 const OptTable &Opts) {
1139 DAL.AddFlagArg(A, Opts.getOption(options::OPT__SLASH_Zc_twoPhase_));
1140 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_operator_names));
1141}
1142
1143static void TranslatePermissiveMinus(Arg *A, llvm::opt::DerivedArgList &DAL,
1144 const OptTable &Opts) {
1145 DAL.AddFlagArg(A, Opts.getOption(options::OPT__SLASH_Zc_twoPhase));
1146 DAL.AddFlagArg(A, Opts.getOption(options::OPT_foperator_names));
1147}
1148
1149llvm::opt::DerivedArgList *
1150MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
1151 BoundArch BA, Action::OffloadKind OFK) const {
1152 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1153 const OptTable &Opts = getDriver().getOpts();
1154
1155 // /Oy and /Oy- don't have an effect on X86-64
1156 bool SupportsForcingFramePointer = getArch() != llvm::Triple::x86_64;
1157
1158 // The -O[12xd] flag actually expands to several flags. We must desugar the
1159 // flags so that options embedded can be negated. For example, the '-O2' flag
1160 // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to
1161 // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
1162 // aspect of '-O2'.
1163 //
1164 // Note that this expansion logic only applies to the *last* of '[12xd]'.
1165
1166 // First step is to search for the character we'd like to expand.
1167 const char *ExpandChar = nullptr;
1168 for (Arg *A : Args.filtered(options::OPT__SLASH_O)) {
1169 StringRef OptStr = A->getValue();
1170 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1171 char OptChar = OptStr[I];
1172 char PrevChar = I > 0 ? OptStr[I - 1] : '0';
1173 if (PrevChar == 'b') {
1174 // OptChar does not expand; it's an argument to the previous char.
1175 continue;
1176 }
1177 if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
1178 ExpandChar = OptStr.data() + I;
1179 }
1180 }
1181
1182 for (Arg *A : Args) {
1183 if (A->getOption().matches(options::OPT__SLASH_O)) {
1184 // The -O flag actually takes an amalgam of other options. For example,
1185 // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
1186 TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
1187 } else if (A->getOption().matches(options::OPT_D)) {
1188 // Translate -Dfoo#bar into -Dfoo=bar.
1189 TranslateDArg(A, *DAL, Opts);
1190 } else if (A->getOption().matches(options::OPT__SLASH_permissive)) {
1191 // Expand /permissive
1192 TranslatePermissive(A, *DAL, Opts);
1193 } else if (A->getOption().matches(options::OPT__SLASH_permissive_)) {
1194 // Expand /permissive-
1195 TranslatePermissiveMinus(A, *DAL, Opts);
1196 } else if (OFK != Action::OFK_HIP) {
1197 // HIP Toolchain translates input args by itself.
1198 DAL->append(A);
1199 }
1200 }
1201
1202 return DAL;
1203}
1204
1206 const ArgList &DriverArgs, ArgStringList &CC1Args, BoundArch BA,
1207 Action::OffloadKind DeviceOffloadKind) const {
1208 // MSVC STL kindly allows removing all usages of typeid by defining
1209 // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti
1210 if (DriverArgs.hasFlag(options::OPT_fno_rtti, options::OPT_frtti,
1211 /*Default=*/false))
1212 CC1Args.push_back("-D_HAS_STATIC_RTTI=0");
1213
1214 if (Arg *A = DriverArgs.getLastArgNoClaim(options::OPT_marm64x))
1215 A->ignoreTargetSpecific();
1216}
#define V(N, I)
static void TranslatePermissiveMinus(Arg *A, llvm::opt::DerivedArgList &DAL, const OptTable &Opts)
Definition MSVC.cpp:1143
static VersionTuple getMSVCVersionFromExe(const std::string &BinDir)
Definition MSVC.cpp:734
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:1121
static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL, bool SupportsForcingFramePointer, const char *ExpandChar, const OptTable &Opts)
Definition MSVC.cpp:1024
static void TranslatePermissive(Arg *A, llvm::opt::DerivedArgList &DAL, const OptTable &Opts)
Definition MSVC.cpp:1137
The base class of the type hierarchy.
Definition TypeBase.h:1876
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:95
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:159
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:407
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:155
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:145
@ OMPRT_Unknown
An unknown OpenMP runtime.
Definition Driver.h:141
@ OMPRT_GOMP
The GNU OpenMP runtime.
Definition Driver.h:150
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:96
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.
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual SanitizerMask getSupportedSanitizers(BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:302
const Driver & getDriver() const
Definition ToolChain.h:286
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:329
const llvm::Triple & getTriple() const
Definition ToolChain.h:288
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 StringRef GetCXXStdlibName(const llvm::opt::ArgList &Args) const
virtual Tool * getTool(Action::ActionClass AC) const
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
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition MSVC.cpp:1150
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition MSVC.cpp:613
Tool * buildLinker() const override
Definition MSVC.cpp:572
bool getUniversalCRTLibraryPath(const llvm::opt::ArgList &Args, std::string &path) const
Definition MSVC.cpp:708
UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override
How detailed should the unwind tables be by default.
Definition MSVC.cpp:584
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:628
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition MSVC.cpp:599
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition MSVC.cpp:608
VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const override
On Windows, returns the MSVC compatibility version.
Definition MSVC.cpp:967
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:810
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:952
MSVCToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition MSVC.cpp:528
std::string getSubDirectoryPath(llvm::SubDirectoryType Type, llvm::StringRef SubdirParent="") const
Definition MSVC.cpp:661
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition MSVC.cpp:655
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition MSVC.cpp:604
SanitizerMask getSupportedSanitizers(BoundArch BA, Action::OffloadKind DeviceOffloadKind) const override
Return sanitizers which are available in this toolchain.
Definition MSVC.cpp:1012
void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific SYCL includes.
Definition MSVC.cpp:623
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA, types::ID InputType) const override
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
Definition MSVC.cpp:989
void AddMSVCStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition MSVC.cpp:799
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition MSVC.cpp:618
Tool * buildAssembler() const override
Definition MSVC.cpp:576
Tool * getTool(Action::ActionClass AC) const override
Definition MSVC.cpp:561
void AddMSVCStdlibMultilibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, bool HonorNostdincxx) const
Definition MSVC.cpp:779
bool getWindowsSDKLibraryPath(const llvm::opt::ArgList &Args, std::string &path) const
Definition MSVC.cpp:679
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:770
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition MSVC.cpp:1205
llvm::StringRef GetCXXStdlibName(const llvm::opt::ArgList &DriverArgs) const override
Definition MSVC.cpp:961
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:503
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:51
The JSON file list parser is used to communicate input to InstallAPI.
Represents a bound architecture for offload / multiple architecture compilation.
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:79
static constexpr ResponseFileSupport AtFileUTF16()
Definition Job.h:100