| 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" |
| 12 | #include "clang/Driver/CommonArgs.h" |
| 13 | #include "clang/Driver/Compilation.h" |
| 14 | #include "clang/Driver/Driver.h" |
| 15 | #include "clang/Driver/SanitizerArgs.h" |
| 16 | #include "clang/Options/Options.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 | |
| 37 | using namespace clang::driver; |
| 38 | using namespace clang::driver::toolchains; |
| 39 | using namespace clang::driver::tools; |
| 40 | using namespace clang; |
| 41 | using namespace llvm::opt; |
| 42 | |
| 43 | static 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. |
| 54 | static 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(Type: llvm::SubDirectoryType::Bin)); |
| 59 | llvm::sys::path::append(path&: FilePath, a: Exe); |
| 60 | return std::string(canExecute(VFS&: TC.getVFS(), Path: FilePath) ? FilePath.str() : Exe); |
| 61 | } |
| 62 | |
| 63 | void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA, |
| 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 | Elt: Args.MakeArgString(Str: std::string("-out:" ) + Output.getFilename())); |
| 76 | |
| 77 | if (Args.hasArg(Ids: options::OPT_marm64x)) |
| 78 | CmdArgs.push_back(Elt: "-machine:arm64x" ); |
| 79 | else if (TC.getTriple().isWindowsArm64EC()) |
| 80 | CmdArgs.push_back(Elt: "-machine:arm64ec" ); |
| 81 | |
| 82 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) { |
| 83 | StringRef V = A->getValue(); |
| 84 | if (V == "ArmPL" ) |
| 85 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--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(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false) && |
| 92 | !Args.hasArg(Ids: options::OPT_nolibsycl) && |
| 93 | !Args.hasArg(Ids: options::OPT_nostdlib, Ids: 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(Ids: 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(Ids: options::OPT__SLASH_M_Group)) { |
| 106 | if (A->getOption().matches(ID: options::OPT__SLASH_MT) || |
| 107 | A->getOption().matches(ID: options::OPT__SLASH_MTd)) |
| 108 | HasStaticCRT = true; |
| 109 | } |
| 110 | |
| 111 | if (HasStaticCRT) { |
| 112 | TC.getDriver().Diag(DiagID: 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(path&: LibPath, a: ".." , b: "lib" ); |
| 117 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-libpath:" ) + LibPath)); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles) && |
| 122 | !C.getDriver().IsCLMode() && !C.getDriver().IsFlangMode()) { |
| 123 | CmdArgs.push_back(Elt: "-defaultlib:libcmt" ); |
| 124 | CmdArgs.push_back(Elt: "-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(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false) && |
| 129 | !Args.hasArg(Ids: options::OPT_nolibsycl)) { |
| 130 | bool IsDebugBuild = false; |
| 131 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) { |
| 132 | StringRef RuntimeVal = A->getValue(); |
| 133 | if (RuntimeVal == "dll_dbg" ) |
| 134 | IsDebugBuild = true; |
| 135 | } |
| 136 | CmdArgs.push_back(Elt: 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(Ids: options::OPT__SLASH_diasdkdir, |
| 147 | Ids: 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(path&: DIAPath, a: "DIA SDK" ); |
| 154 | |
| 155 | // The DIA SDK always uses the legacy vc arch, even in new MSVC versions. |
| 156 | llvm::sys::path::append(path&: DIAPath, a: "lib" , |
| 157 | b: llvm::archToLegacyVCArch(Arch: TC.getArch())); |
| 158 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-libpath:" ) + DIAPath)); |
| 159 | } |
| 160 | if (!llvm::sys::Process::GetEnv(name: "LIB" ) || |
| 161 | Args.hasArg(Ids: options::OPT__SLASH_vctoolsdir, |
| 162 | Ids: options::OPT__SLASH_vctoolsversion, |
| 163 | Ids: options::OPT__SLASH_winsysroot)) { |
| 164 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 165 | Str: Twine("-libpath:" ) + |
| 166 | TC.getSubDirectoryPath(Type: llvm::SubDirectoryType::Lib))); |
| 167 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 168 | Str: Twine("-libpath:" ) + |
| 169 | TC.getSubDirectoryPath(Type: llvm::SubDirectoryType::Lib, SubdirParent: "atlmfc" ))); |
| 170 | } |
| 171 | if (!llvm::sys::Process::GetEnv(name: "LIB" ) || |
| 172 | Args.hasArg(Ids: options::OPT__SLASH_winsdkdir, |
| 173 | Ids: options::OPT__SLASH_winsdkversion, |
| 174 | Ids: options::OPT__SLASH_winsysroot)) { |
| 175 | if (TC.useUniversalCRT()) { |
| 176 | std::string UniversalCRTLibPath; |
| 177 | if (TC.getUniversalCRTLibraryPath(Args, path&: UniversalCRTLibPath)) |
| 178 | CmdArgs.push_back( |
| 179 | Elt: Args.MakeArgString(Str: Twine("-libpath:" ) + UniversalCRTLibPath)); |
| 180 | } |
| 181 | std::string WindowsSdkLibPath; |
| 182 | if (TC.getWindowsSDKLibraryPath(Args, path&: WindowsSdkLibPath)) |
| 183 | CmdArgs.push_back( |
| 184 | Elt: Args.MakeArgString(Str: std::string("-libpath:" ) + WindowsSdkLibPath)); |
| 185 | } |
| 186 | |
| 187 | if (!C.getDriver().IsCLMode() && Args.hasArg(Ids: options::OPT_L)) |
| 188 | for (const auto &LibPath : Args.getAllArgValues(Id: options::OPT_L)) |
| 189 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-libpath:" + LibPath)); |
| 190 | |
| 191 | if (C.getDriver().IsFlangMode() && |
| 192 | !Args.hasArg(Ids: options::OPT_nostdlib, Ids: 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(Elt: "/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(Path: LibPath)) |
| 206 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-libpath:" + LibPath)); |
| 207 | } |
| 208 | for (const auto &LibPath : TC.getFilePaths()) { |
| 209 | if (LibPath.length() > 0) |
| 210 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-libpath:" + LibPath)); |
| 211 | } |
| 212 | auto CRTPath = TC.getCompilerRTPath(); |
| 213 | if (TC.getVFS().exists(Path: CRTPath)) |
| 214 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-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(Pos: options::OPT_fsycl, Neg: options::OPT_fno_sycl, Default: false)) |
| 220 | CmdArgs.push_back(Elt: "/IGNORE:4078" ); |
| 221 | |
| 222 | CmdArgs.push_back(Elt: "-nologo" ); |
| 223 | |
| 224 | if (Args.hasArg(Ids: options::OPT_g_Group, Ids: options::OPT__SLASH_Z7)) |
| 225 | CmdArgs.push_back(Elt: "-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(Ids: options::OPT_fms_hotpatch, Ids: options::OPT__SLASH_hotpatch)) |
| 230 | CmdArgs.push_back(Elt: "-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(Pos: options::OPT_mincremental_linker_compatible, |
| 237 | Neg: options::OPT_mno_incremental_linker_compatible, |
| 238 | Default: DefaultIncrementalLinkerCompatible)) |
| 239 | CmdArgs.push_back(Elt: "-Brepro" ); |
| 240 | |
| 241 | bool DLL = Args.hasArg(Ids: options::OPT__SLASH_LD, Ids: options::OPT__SLASH_LDd, |
| 242 | Ids: options::OPT_shared); |
| 243 | if (DLL) { |
| 244 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-dll" )); |
| 245 | |
| 246 | SmallString<128> ImplibName(Output.getFilename()); |
| 247 | llvm::sys::path::replace_extension(path&: ImplibName, extension: "lib" ); |
| 248 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string("-implib:" ) + ImplibName)); |
| 249 | } |
| 250 | |
| 251 | if (TC.getSanitizerArgs(JobArgs: Args).needsFuzzer()) { |
| 252 | if (!Args.hasArg(Ids: options::OPT_shared)) |
| 253 | CmdArgs.push_back( |
| 254 | Elt: Args.MakeArgString(Str: std::string("-wholearchive:" ) + |
| 255 | TC.getCompilerRTArgString(Args, Component: "fuzzer" ))); |
| 256 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-debug" )); |
| 257 | // Prevent the linker from padding sections we use for instrumentation |
| 258 | // arrays. |
| 259 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-incremental:no" )); |
| 260 | } |
| 261 | |
| 262 | if (TC.getSanitizerArgs(JobArgs: Args).needsAsanRt()) { |
| 263 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-debug" )); |
| 264 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-incremental:no" )); |
| 265 | CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "asan_dynamic" )); |
| 266 | auto defines = Args.getAllArgValues(Id: options::OPT_D); |
| 267 | if (Args.hasArg(Ids: options::OPT__SLASH_MD, Ids: options::OPT__SLASH_MDd) || |
| 268 | llvm::is_contained(Range&: defines, Element: "_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(Elt: Args.MakeArgString( |
| 272 | Str: 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(Elt: Args.MakeArgString( |
| 278 | Str: std::string("-wholearchive:" ) + |
| 279 | TC.getCompilerRT(Args, Component: "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(Elt: Args.MakeArgString( |
| 284 | Str: std::string("-wholearchive:" ) + |
| 285 | TC.getCompilerRT(Args, Component: "asan_static_runtime_thunk" ))); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | if (TC.isUsingLTO(Args)) { |
| 290 | if (Arg *A = tools::getLastProfileSampleUseArg(Args)) |
| 291 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string("-lto-sample-profile:" ) + |
| 292 | A->getValue())); |
| 293 | } |
| 294 | Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT__SLASH_link); |
| 295 | |
| 296 | // Control Flow Guard checks |
| 297 | for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) { |
| 298 | StringRef GuardArgs = A->getValue(); |
| 299 | if (GuardArgs.equals_insensitive(RHS: "cf" ) || |
| 300 | GuardArgs.equals_insensitive(RHS: "cf,nochecks" )) { |
| 301 | // MSVC doesn't yet support the "nochecks" modifier. |
| 302 | CmdArgs.push_back(Elt: "-guard:cf" ); |
| 303 | } else if (GuardArgs.equals_insensitive(RHS: "cf-" )) { |
| 304 | CmdArgs.push_back(Elt: "-guard:cf-" ); |
| 305 | } else if (GuardArgs.equals_insensitive(RHS: "ehcont" )) { |
| 306 | CmdArgs.push_back(Elt: "-guard:ehcont" ); |
| 307 | } else if (GuardArgs.equals_insensitive(RHS: "ehcont-" )) { |
| 308 | CmdArgs.push_back(Elt: "-guard:ehcont-" ); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ, |
| 313 | Neg: options::OPT_fno_openmp, Default: false)) { |
| 314 | CmdArgs.push_back(Elt: "-nodefaultlib:vcomp.lib" ); |
| 315 | CmdArgs.push_back(Elt: "-nodefaultlib:vcompd.lib" ); |
| 316 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string("-libpath:" ) + |
| 317 | TC.getDriver().Dir + "/../lib" )); |
| 318 | switch (TC.getDriver().getOpenMPRuntime(Args)) { |
| 319 | case Driver::OMPRT_OMP: |
| 320 | CmdArgs.push_back(Elt: "-defaultlib:libomp.lib" ); |
| 321 | break; |
| 322 | case Driver::OMPRT_IOMP5: |
| 323 | CmdArgs.push_back(Elt: "-defaultlib:libiomp5md.lib" ); |
| 324 | break; |
| 325 | case Driver::OMPRT_GOMP: |
| 326 | break; |
| 327 | case Driver::OMPRT_Unknown: |
| 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(Ids: options::OPT_nostdlib)) { |
| 336 | AddRunTimeLibs(TC, D: TC.getDriver(), CmdArgs, Args); |
| 337 | } |
| 338 | |
| 339 | const Arg *A = Args.getLastArg(Ids: 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(Ids: options::OPT_gdwarf, Ids: options::OPT_gdwarf_2, |
| 348 | Ids: options::OPT_gdwarf_3, Ids: options::OPT_gdwarf_4, |
| 349 | Ids: options::OPT_gdwarf_5, Ids: 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(RHS: "lld" )) |
| 357 | Linker = "lld-link" ; |
| 358 | |
| 359 | if (Linker == "lld-link" ) { |
| 360 | for (Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) |
| 361 | CmdArgs.push_back( |
| 362 | Elt: Args.MakeArgString(Str: std::string("/vfsoverlay:" ) + A->getValue())); |
| 363 | |
| 364 | if (TC.isUsingLTO(Args) && |
| 365 | Args.hasFlag(Pos: options::OPT_gsplit_dwarf, Neg: options::OPT_gno_split_dwarf, |
| 366 | Default: false)) |
| 367 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: 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(Elt: 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(ID: options::OPT_l)) { |
| 382 | StringRef Lib = A.getValue(); |
| 383 | const char *LinkLibArg; |
| 384 | if (Lib.ends_with(Suffix: ".lib" )) |
| 385 | LinkLibArg = Args.MakeArgString(Str: Lib); |
| 386 | else |
| 387 | LinkLibArg = Args.MakeArgString(Str: Lib + ".lib" ); |
| 388 | CmdArgs.push_back(Elt: 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, Output&: CmdArgs); |
| 395 | } |
| 396 | |
| 397 | TC.addOffloadRTLibs(ActiveKinds: 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(RHS: "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, Exe: "link.exe" ); |
| 411 | |
| 412 | if (!TC.FoundMSVCInstall() && !canExecute(VFS&: TC.getVFS(), Path: linkPath)) { |
| 413 | llvm::SmallString<128> ClPath; |
| 414 | ClPath = TC.GetProgramPath(Name: "cl.exe" ); |
| 415 | if (canExecute(VFS&: TC.getVFS(), Path: ClPath)) { |
| 416 | linkPath = llvm::sys::path::parent_path(path: ClPath); |
| 417 | llvm::sys::path::append(path&: linkPath, a: "link.exe" ); |
| 418 | if (!canExecute(VFS&: TC.getVFS(), Path: linkPath)) |
| 419 | C.getDriver().Diag(DiagID: clang::diag::warn_drv_msvc_not_found); |
| 420 | } else { |
| 421 | C.getDriver().Diag(DiagID: 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(JobArgs: Args).needsAsanRt()) |
| 428 | CmdArgs.push_back(Elt: "/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(Name: Linker.str().c_str()); |
| 491 | } |
| 492 | |
| 493 | auto LinkCmd = std::make_unique<Command>( |
| 494 | args: JA, args: *this, args: ResponseFileSupport::AtFileUTF16(), |
| 495 | args: Args.MakeArgString(Str: linkPath), args&: CmdArgs, args: Inputs, args: Output); |
| 496 | if (!Environment.empty()) |
| 497 | LinkCmd->setEnvironment(Environment); |
| 498 | C.addCommand(Cmd: std::move(LinkCmd)); |
| 499 | } |
| 500 | |
| 501 | MSVCToolChain::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(Elt: getDriver().Dir); |
| 506 | |
| 507 | std::optional<llvm::StringRef> VCToolsDir, VCToolsVersion; |
| 508 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vctoolsdir)) |
| 509 | VCToolsDir = A->getValue(); |
| 510 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vctoolsversion)) |
| 511 | VCToolsVersion = A->getValue(); |
| 512 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_winsdkdir)) |
| 513 | WinSdkDir = A->getValue(); |
| 514 | if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_winsdkversion)) |
| 515 | WinSdkVersion = A->getValue(); |
| 516 | if (Arg *A = Args.getLastArg(Ids: 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(VFS&: getVFS(), VCToolsDir, VCToolsVersion, |
| 524 | WinSysRoot, Path&: VCToolChainPath, VSLayout) || |
| 525 | llvm::findVCToolChainViaEnvironment(VFS&: getVFS(), Path&: VCToolChainPath, |
| 526 | VSLayout) || |
| 527 | llvm::findVCToolChainViaSetupConfig(VFS&: getVFS(), VCToolsVersion, |
| 528 | Path&: VCToolChainPath, VSLayout) || |
| 529 | llvm::findVCToolChainViaRegistry(Path&: VCToolChainPath, VSLayout); |
| 530 | |
| 531 | loadMultilibsFromYAML(Args, D); |
| 532 | } |
| 533 | |
| 534 | Tool *MSVCToolChain::buildLinker() const { |
| 535 | return new tools::visualstudio::Linker(*this); |
| 536 | } |
| 537 | |
| 538 | Tool *MSVCToolChain::buildAssembler() const { |
| 539 | if (getTriple().isOSBinFormatMachO()) |
| 540 | return new tools::darwin::Assembler(*this); |
| 541 | getDriver().Diag(DiagID: clang::diag::err_no_external_assembler); |
| 542 | return nullptr; |
| 543 | } |
| 544 | |
| 545 | ToolChain::UnwindTableLevel |
| 546 | MSVCToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const { |
| 547 | // Don't emit unwind tables by default for MachO targets. |
| 548 | if (getTriple().isOSBinFormatMachO()) |
| 549 | return UnwindTableLevel::None; |
| 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) |
| 556 | return UnwindTableLevel::Asynchronous; |
| 557 | |
| 558 | return UnwindTableLevel::None; |
| 559 | } |
| 560 | |
| 561 | bool MSVCToolChain::isPICDefault() const { |
| 562 | return getArch() == llvm::Triple::x86_64 || |
| 563 | getArch() == llvm::Triple::aarch64; |
| 564 | } |
| 565 | |
| 566 | bool MSVCToolChain::isPIEDefault(const llvm::opt::ArgList &Args) const { |
| 567 | return false; |
| 568 | } |
| 569 | |
| 570 | bool MSVCToolChain::isPICDefaultForced() const { |
| 571 | return getArch() == llvm::Triple::x86_64 || |
| 572 | getArch() == llvm::Triple::aarch64; |
| 573 | } |
| 574 | |
| 575 | void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, |
| 576 | ArgStringList &CC1Args) const { |
| 577 | CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args); |
| 578 | } |
| 579 | |
| 580 | void MSVCToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs, |
| 581 | ArgStringList &CC1Args) const { |
| 582 | RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args); |
| 583 | } |
| 584 | |
| 585 | void MSVCToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs, |
| 586 | ArgStringList &CC1Args) const { |
| 587 | SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args); |
| 588 | } |
| 589 | |
| 590 | void MSVCToolChain::addOffloadRTLibs(unsigned ActiveKinds, const ArgList &Args, |
| 591 | ArgStringList &CmdArgs) const { |
| 592 | if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, |
| 593 | Default: true) || |
| 594 | Args.hasArg(Ids: options::OPT_no_hip_rt) || Args.hasArg(Ids: options::OPT_r)) |
| 595 | return; |
| 596 | |
| 597 | if (ActiveKinds & Action::OFK_HIP) { |
| 598 | CmdArgs.append(IL: {Args.MakeArgString(Str: 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(Path: getCompilerRT(Args, Component: "profile_rocm" , Type: FT_Static))) { |
| 607 | CmdArgs.push_back(Elt: getCompilerRTArgString(Args, Component: "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 | Elt: "-include:__llvm_profile_offload_register_dynamic_module" ); |
| 613 | } |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const { |
| 618 | CudaInstallation->print(OS); |
| 619 | RocmInstallation->print(OS); |
| 620 | } |
| 621 | |
| 622 | std::string |
| 623 | MSVCToolChain::getSubDirectoryPath(llvm::SubDirectoryType Type, |
| 624 | llvm::StringRef SubdirParent) const { |
| 625 | return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, TargetArch: getArch(), |
| 626 | SubdirParent); |
| 627 | } |
| 628 | |
| 629 | std::string |
| 630 | MSVCToolChain::getSubDirectoryPath(llvm::SubDirectoryType Type, |
| 631 | llvm::Triple::ArchType TargetArch) const { |
| 632 | return llvm::getSubDirectoryPath(Type, VSLayout, VCToolChainPath, TargetArch, |
| 633 | SubdirParent: "" ); |
| 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. |
| 641 | bool MSVCToolChain::getWindowsSDKLibraryPath(const ArgList &Args, |
| 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(VFS&: getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot, |
| 650 | Path&: sdkPath, Major&: sdkMajor, WindowsSDKIncludeVersion&: windowsSDKIncludeVersion, |
| 651 | WindowsSDKLibVersion&: windowsSDKLibVersion)) |
| 652 | return false; |
| 653 | |
| 654 | llvm::SmallString<128> libPath(sdkPath); |
| 655 | llvm::sys::path::append(path&: libPath, a: "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(path&: libPath, a: windowsSDKLibVersion, b: "um" ); |
| 662 | return llvm::appendArchToWindowsSDKLibPath(SDKMajor: sdkMajor, LibPath: libPath, Arch: getArch(), |
| 663 | path); |
| 664 | } |
| 665 | |
| 666 | bool MSVCToolChain::useUniversalCRT() const { |
| 667 | return llvm::useUniversalCRT(VSLayout, VCToolChainPath, TargetArch: getArch(), VFS&: getVFS()); |
| 668 | } |
| 669 | |
| 670 | bool MSVCToolChain::getUniversalCRTLibraryPath(const ArgList &Args, |
| 671 | std::string &Path) const { |
| 672 | std::string UniversalCRTSdkPath; |
| 673 | std::string UCRTVersion; |
| 674 | |
| 675 | Path.clear(); |
| 676 | if (!llvm::getUniversalCRTSdkDir(VFS&: getVFS(), WinSdkDir, WinSdkVersion, |
| 677 | WinSysRoot, Path&: 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(Arch: getArch()); |
| 686 | if (ArchName.empty()) |
| 687 | return false; |
| 688 | |
| 689 | llvm::SmallString<128> LibPath(UniversalCRTSdkPath); |
| 690 | llvm::sys::path::append(path&: LibPath, a: "Lib" , b: UCRTVersion, c: "ucrt" , d: ArchName); |
| 691 | |
| 692 | Path = std::string(LibPath); |
| 693 | return true; |
| 694 | } |
| 695 | |
| 696 | static 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 | |
| 732 | void MSVCToolChain::AddSystemIncludeWithSubfolder( |
| 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, a: subfolder1, b: subfolder2, c: subfolder3); |
| 738 | addSystemInclude(DriverArgs, CC1Args, Path: path); |
| 739 | } |
| 740 | |
| 741 | void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, |
| 742 | ArgStringList &CC1Args) const { |
| 743 | if (DriverArgs.hasArg(Ids: options::OPT_nostdinc)) |
| 744 | return; |
| 745 | |
| 746 | if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc)) { |
| 747 | AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, folder: getDriver().ResourceDir, |
| 748 | subfolder1: "include" ); |
| 749 | } |
| 750 | |
| 751 | // Add %INCLUDE%-like directories from the -imsvc flag. |
| 752 | for (const auto &Path : DriverArgs.getAllArgValues(Id: options::OPT__SLASH_imsvc)) |
| 753 | addSystemInclude(DriverArgs, CC1Args, Path); |
| 754 | |
| 755 | auto AddSystemIncludesFromEnv = [&](StringRef Var) -> bool { |
| 756 | if (auto Val = llvm::sys::Process::GetEnv(name: Var)) { |
| 757 | SmallVector<StringRef, 8> Dirs; |
| 758 | StringRef(*Val).split(A&: Dirs, Separator: ";" , /*MaxSplit=*/-1, /*KeepEmpty=*/false); |
| 759 | if (!Dirs.empty()) { |
| 760 | addSystemIncludes(DriverArgs, CC1Args, Paths: 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(Id: options::OPT__SLASH_external_env)) { |
| 770 | AddSystemIncludesFromEnv(Var); |
| 771 | } |
| 772 | |
| 773 | // Add DIA SDK include if requested. |
| 774 | if (const Arg *A = DriverArgs.getLastArg(Ids: options::OPT__SLASH_diasdkdir, |
| 775 | Ids: 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(path&: DIASDKPath, a: "DIA SDK" ); |
| 782 | AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, folder: std::string(DIASDKPath), |
| 783 | subfolder1: "include" ); |
| 784 | } |
| 785 | |
| 786 | if (DriverArgs.hasArg(Ids: 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(path&: Dir, a: M.includeSuffix()); |
| 796 | if (getDriver().getVFS().exists(Path: Dir)) |
| 797 | addSystemInclude(DriverArgs, CC1Args, Path: 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 | Ids: options::OPT__SLASH_vctoolsdir, Ids: options::OPT__SLASH_vctoolsversion, |
| 806 | Ids: options::OPT__SLASH_winsysroot, Ids: options::OPT__SLASH_winsdkdir, |
| 807 | Ids: 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 | Path: getSubDirectoryPath(Type: llvm::SubDirectoryType::Include)); |
| 819 | addSystemInclude( |
| 820 | DriverArgs, CC1Args, |
| 821 | Path: getSubDirectoryPath(Type: llvm::SubDirectoryType::Include, SubdirParent: "atlmfc" )); |
| 822 | |
| 823 | if (useUniversalCRT()) { |
| 824 | std::string UniversalCRTSdkPath; |
| 825 | std::string UCRTVersion; |
| 826 | if (llvm::getUniversalCRTSdkDir(VFS&: getVFS(), WinSdkDir, WinSdkVersion, |
| 827 | WinSysRoot, Path&: UniversalCRTSdkPath, |
| 828 | UCRTVersion)) { |
| 829 | if (!(WinSdkDir.has_value() || WinSysRoot.has_value()) && |
| 830 | WinSdkVersion.has_value()) |
| 831 | UCRTVersion = *WinSdkVersion; |
| 832 | AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, folder: UniversalCRTSdkPath, |
| 833 | subfolder1: "Include" , subfolder2: UCRTVersion, subfolder3: "ucrt" ); |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | std::string WindowsSDKDir; |
| 838 | int major = 0; |
| 839 | std::string windowsSDKIncludeVersion; |
| 840 | std::string windowsSDKLibVersion; |
| 841 | if (llvm::getWindowsSDKDir(VFS&: getVFS(), WinSdkDir, WinSdkVersion, WinSysRoot, |
| 842 | Path&: WindowsSDKDir, Major&: major, WindowsSDKIncludeVersion&: windowsSDKIncludeVersion, |
| 843 | WindowsSDKLibVersion&: 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, folder: WindowsSDKDir, |
| 852 | subfolder1: "Include" , subfolder2: windowsSDKIncludeVersion, |
| 853 | subfolder3: "shared" ); |
| 854 | AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, folder: WindowsSDKDir, |
| 855 | subfolder1: "Include" , subfolder2: windowsSDKIncludeVersion, |
| 856 | subfolder3: "um" ); |
| 857 | AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, folder: WindowsSDKDir, |
| 858 | subfolder1: "Include" , subfolder2: windowsSDKIncludeVersion, |
| 859 | subfolder3: "winrt" ); |
| 860 | if (major >= 10) { |
| 861 | llvm::VersionTuple Tuple; |
| 862 | if (!Tuple.tryParse(string: windowsSDKIncludeVersion) && |
| 863 | Tuple.getSubminor().value_or(u: 0) >= 17134) { |
| 864 | AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, folder: WindowsSDKDir, |
| 865 | subfolder1: "Include" , subfolder2: windowsSDKIncludeVersion, |
| 866 | subfolder3: "cppwinrt" ); |
| 867 | } |
| 868 | } |
| 869 | } else { |
| 870 | AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, folder: WindowsSDKDir, |
| 871 | subfolder1: "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 | |
| 892 | void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, |
| 893 | ArgStringList &CC1Args) const { |
| 894 | // FIXME: There should probably be logic here to find libc++ on Windows. |
| 895 | } |
| 896 | |
| 897 | VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D, |
| 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(BinDir: getSubDirectoryPath(Type: llvm::SubDirectoryType::Bin)); |
| 906 | if (MSVT.empty() && |
| 907 | Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions, |
| 908 | Default: 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 | |
| 918 | std::string |
| 919 | MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args, BoundArch BA, |
| 920 | types::ID InputType) const { |
| 921 | // The MSVC version doesn't care about the architecture, even though it |
| 922 | // may look at the triple internally. |
| 923 | VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args); |
| 924 | MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().value_or(u: 0), |
| 925 | MSVT.getSubminor().value_or(u: 0)); |
| 926 | |
| 927 | // For the rest of the triple, however, a computed architecture name may |
| 928 | // be needed. |
| 929 | llvm::Triple Triple( |
| 930 | ToolChain::ComputeEffectiveClangTriple(Args, BA, InputType)); |
| 931 | if (Triple.getEnvironment() == llvm::Triple::MSVC) { |
| 932 | StringRef ObjFmt = Triple.getEnvironmentName().split(Separator: '-').second; |
| 933 | if (ObjFmt.empty()) |
| 934 | Triple.setEnvironmentName((Twine("msvc" ) + MSVT.getAsString()).str()); |
| 935 | else |
| 936 | Triple.setEnvironmentName( |
| 937 | (Twine("msvc" ) + MSVT.getAsString() + Twine('-') + ObjFmt).str()); |
| 938 | } |
| 939 | return Triple.getTriple(); |
| 940 | } |
| 941 | |
| 942 | SanitizerMask MSVCToolChain::getSupportedSanitizers( |
| 943 | BoundArch BA, Action::OffloadKind DeviceOffloadKind) const { |
| 944 | SanitizerMask Res = ToolChain::getSupportedSanitizers(BA, 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 | |
| 954 | static 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(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_O0)); |
| 977 | } else { |
| 978 | if (OptChar == '1') { |
| 979 | DAL.AddJoinedArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_O), Value: "s" ); |
| 980 | } else if (OptChar == '2' || OptChar == 'x') { |
| 981 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fbuiltin)); |
| 982 | DAL.AddJoinedArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_O), Value: "3" ); |
| 983 | } |
| 984 | if (SupportsForcingFramePointer && |
| 985 | !DAL.hasArgNoClaim(Ids: options::OPT_fno_omit_frame_pointer)) |
| 986 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fomit_frame_pointer)); |
| 987 | if (OptChar == '1' || OptChar == '2') |
| 988 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: 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(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fno_inline)); |
| 996 | break; |
| 997 | case '1': |
| 998 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_finline_hint_functions)); |
| 999 | break; |
| 1000 | case '2': |
| 1001 | case '3': |
| 1002 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: 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(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fno_builtin)); |
| 1015 | } else { |
| 1016 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fbuiltin)); |
| 1017 | } |
| 1018 | break; |
| 1019 | case 's': |
| 1020 | DAL.AddJoinedArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_O), Value: "s" ); |
| 1021 | break; |
| 1022 | case 't': |
| 1023 | DAL.AddJoinedArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_O), Value: "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(BaseArg: A, |
| 1034 | Opt: Opts.getOption(Opt: options::OPT_fomit_frame_pointer)); |
| 1035 | else |
| 1036 | DAL.AddFlagArg( |
| 1037 | BaseArg: A, Opt: Opts.getOption(Opt: 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 | |
| 1051 | static 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(C: '#'); |
| 1057 | if (Hash == StringRef::npos || Hash > Val.find(C: '=')) { |
| 1058 | DAL.append(A); |
| 1059 | return; |
| 1060 | } |
| 1061 | |
| 1062 | std::string NewVal = std::string(Val); |
| 1063 | NewVal[Hash] = '='; |
| 1064 | DAL.AddJoinedArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_D), Value: NewVal); |
| 1065 | } |
| 1066 | |
| 1067 | static void TranslatePermissive(Arg *A, llvm::opt::DerivedArgList &DAL, |
| 1068 | const OptTable &Opts) { |
| 1069 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT__SLASH_Zc_twoPhase_)); |
| 1070 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fno_operator_names)); |
| 1071 | } |
| 1072 | |
| 1073 | static void TranslatePermissiveMinus(Arg *A, llvm::opt::DerivedArgList &DAL, |
| 1074 | const OptTable &Opts) { |
| 1075 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT__SLASH_Zc_twoPhase)); |
| 1076 | DAL.AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_foperator_names)); |
| 1077 | } |
| 1078 | |
| 1079 | llvm::opt::DerivedArgList * |
| 1080 | MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args, |
| 1081 | BoundArch BA, Action::OffloadKind OFK) const { |
| 1082 | DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); |
| 1083 | const OptTable &Opts = getDriver().getOpts(); |
| 1084 | |
| 1085 | // /Oy and /Oy- don't have an effect on X86-64 |
| 1086 | bool SupportsForcingFramePointer = getArch() != llvm::Triple::x86_64; |
| 1087 | |
| 1088 | // The -O[12xd] flag actually expands to several flags. We must desugar the |
| 1089 | // flags so that options embedded can be negated. For example, the '-O2' flag |
| 1090 | // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to |
| 1091 | // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single |
| 1092 | // aspect of '-O2'. |
| 1093 | // |
| 1094 | // Note that this expansion logic only applies to the *last* of '[12xd]'. |
| 1095 | |
| 1096 | // First step is to search for the character we'd like to expand. |
| 1097 | const char *ExpandChar = nullptr; |
| 1098 | for (Arg *A : Args.filtered(Ids: options::OPT__SLASH_O)) { |
| 1099 | StringRef OptStr = A->getValue(); |
| 1100 | for (size_t I = 0, E = OptStr.size(); I != E; ++I) { |
| 1101 | char OptChar = OptStr[I]; |
| 1102 | char PrevChar = I > 0 ? OptStr[I - 1] : '0'; |
| 1103 | if (PrevChar == 'b') { |
| 1104 | // OptChar does not expand; it's an argument to the previous char. |
| 1105 | continue; |
| 1106 | } |
| 1107 | if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd') |
| 1108 | ExpandChar = OptStr.data() + I; |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | for (Arg *A : Args) { |
| 1113 | if (A->getOption().matches(ID: options::OPT__SLASH_O)) { |
| 1114 | // The -O flag actually takes an amalgam of other options. For example, |
| 1115 | // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'. |
| 1116 | TranslateOptArg(A, DAL&: *DAL, SupportsForcingFramePointer, ExpandChar, Opts); |
| 1117 | } else if (A->getOption().matches(ID: options::OPT_D)) { |
| 1118 | // Translate -Dfoo#bar into -Dfoo=bar. |
| 1119 | TranslateDArg(A, DAL&: *DAL, Opts); |
| 1120 | } else if (A->getOption().matches(ID: options::OPT__SLASH_permissive)) { |
| 1121 | // Expand /permissive |
| 1122 | TranslatePermissive(A, DAL&: *DAL, Opts); |
| 1123 | } else if (A->getOption().matches(ID: options::OPT__SLASH_permissive_)) { |
| 1124 | // Expand /permissive- |
| 1125 | TranslatePermissiveMinus(A, DAL&: *DAL, Opts); |
| 1126 | } else if (OFK != Action::OFK_HIP) { |
| 1127 | // HIP Toolchain translates input args by itself. |
| 1128 | DAL->append(A); |
| 1129 | } |
| 1130 | } |
| 1131 | |
| 1132 | return DAL; |
| 1133 | } |
| 1134 | |
| 1135 | void MSVCToolChain::addClangTargetOptions( |
| 1136 | const ArgList &DriverArgs, ArgStringList &CC1Args, BoundArch BA, |
| 1137 | Action::OffloadKind DeviceOffloadKind) const { |
| 1138 | // MSVC STL kindly allows removing all usages of typeid by defining |
| 1139 | // _HAS_STATIC_RTTI to 0. Do so, when compiling with -fno-rtti |
| 1140 | if (DriverArgs.hasFlag(Pos: options::OPT_fno_rtti, Neg: options::OPT_frtti, |
| 1141 | /*Default=*/false)) |
| 1142 | CC1Args.push_back(Elt: "-D_HAS_STATIC_RTTI=0" ); |
| 1143 | |
| 1144 | if (Arg *A = DriverArgs.getLastArgNoClaim(Ids: options::OPT_marm64x)) |
| 1145 | A->ignoreTargetSpecific(); |
| 1146 | } |
| 1147 | |