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 "CommonArgs.h" 11 #include "Darwin.h" 12 #include "clang/Basic/CharInfo.h" 13 #include "clang/Basic/Version.h" 14 #include "clang/Driver/Compilation.h" 15 #include "clang/Driver/Driver.h" 16 #include "clang/Driver/DriverDiagnostic.h" 17 #include "clang/Driver/Options.h" 18 #include "clang/Driver/SanitizerArgs.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/Option/Arg.h" 22 #include "llvm/Option/ArgList.h" 23 #include "llvm/Support/ConvertUTF.h" 24 #include "llvm/Support/ErrorHandling.h" 25 #include "llvm/Support/FileSystem.h" 26 #include "llvm/Support/Host.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/Process.h" 30 #include <cstdio> 31 32 #ifdef _WIN32 33 #define WIN32_LEAN_AND_MEAN 34 #define NOGDI 35 #ifndef NOMINMAX 36 #define NOMINMAX 37 #endif 38 #include <windows.h> 39 #endif 40 41 #ifdef _MSC_VER 42 // Don't support SetupApi on MinGW. 43 #define USE_MSVC_SETUP_API 44 45 // Make sure this comes before MSVCSetupApi.h 46 #include <comdef.h> 47 48 #include "MSVCSetupApi.h" 49 #include "llvm/Support/COM.h" 50 _COM_SMARTPTR_TYPEDEF(ISetupConfiguration, __uuidof(ISetupConfiguration)); 51 _COM_SMARTPTR_TYPEDEF(ISetupConfiguration2, __uuidof(ISetupConfiguration2)); 52 _COM_SMARTPTR_TYPEDEF(ISetupHelper, __uuidof(ISetupHelper)); 53 _COM_SMARTPTR_TYPEDEF(IEnumSetupInstances, __uuidof(IEnumSetupInstances)); 54 _COM_SMARTPTR_TYPEDEF(ISetupInstance, __uuidof(ISetupInstance)); 55 _COM_SMARTPTR_TYPEDEF(ISetupInstance2, __uuidof(ISetupInstance2)); 56 #endif 57 58 using namespace clang::driver; 59 using namespace clang::driver::toolchains; 60 using namespace clang::driver::tools; 61 using namespace clang; 62 using namespace llvm::opt; 63 64 // Defined below. 65 // Forward declare this so there aren't too many things above the constructor. 66 static bool getSystemRegistryString(const char *keyPath, const char *valueName, 67 std::string &value, std::string *phValue); 68 69 // Check various environment variables to try and find a toolchain. 70 static bool findVCToolChainViaEnvironment(std::string &Path, 71 MSVCToolChain::ToolsetLayout &VSLayout) { 72 // These variables are typically set by vcvarsall.bat 73 // when launching a developer command prompt. 74 if (llvm::Optional<std::string> VCToolsInstallDir = 75 llvm::sys::Process::GetEnv("VCToolsInstallDir")) { 76 // This is only set by newer Visual Studios, and it leads straight to 77 // the toolchain directory. 78 Path = std::move(*VCToolsInstallDir); 79 VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer; 80 return true; 81 } 82 if (llvm::Optional<std::string> VCInstallDir = 83 llvm::sys::Process::GetEnv("VCINSTALLDIR")) { 84 // If the previous variable isn't set but this one is, then we've found 85 // an older Visual Studio. This variable is set by newer Visual Studios too, 86 // so this check has to appear second. 87 // In older Visual Studios, the VC directory is the toolchain. 88 Path = std::move(*VCInstallDir); 89 VSLayout = MSVCToolChain::ToolsetLayout::OlderVS; 90 return true; 91 } 92 93 // We couldn't find any VC environment variables. Let's walk through PATH and 94 // see if it leads us to a VC toolchain bin directory. If it does, pick the 95 // first one that we find. 96 if (llvm::Optional<std::string> PathEnv = 97 llvm::sys::Process::GetEnv("PATH")) { 98 llvm::SmallVector<llvm::StringRef, 8> PathEntries; 99 llvm::StringRef(*PathEnv).split(PathEntries, llvm::sys::EnvPathSeparator); 100 for (llvm::StringRef PathEntry : PathEntries) { 101 if (PathEntry.empty()) 102 continue; 103 104 llvm::SmallString<256> ExeTestPath; 105 106 // If cl.exe doesn't exist, then this definitely isn't a VC toolchain. 107 ExeTestPath = PathEntry; 108 llvm::sys::path::append(ExeTestPath, "cl.exe"); 109 if (!llvm::sys::fs::exists(ExeTestPath)) 110 continue; 111 112 // cl.exe existing isn't a conclusive test for a VC toolchain; clang also 113 // has a cl.exe. So let's check for link.exe too. 114 ExeTestPath = PathEntry; 115 llvm::sys::path::append(ExeTestPath, "link.exe"); 116 if (!llvm::sys::fs::exists(ExeTestPath)) 117 continue; 118 119 // whatever/VC/bin --> old toolchain, VC dir is toolchain dir. 120 llvm::StringRef TestPath = PathEntry; 121 bool IsBin = llvm::sys::path::filename(TestPath).equals_lower("bin"); 122 if (!IsBin) { 123 // Strip any architecture subdir like "amd64". 124 TestPath = llvm::sys::path::parent_path(TestPath); 125 IsBin = llvm::sys::path::filename(TestPath).equals_lower("bin"); 126 } 127 if (IsBin) { 128 llvm::StringRef ParentPath = llvm::sys::path::parent_path(TestPath); 129 llvm::StringRef ParentFilename = llvm::sys::path::filename(ParentPath); 130 if (ParentFilename == "VC") { 131 Path = std::string(ParentPath); 132 VSLayout = MSVCToolChain::ToolsetLayout::OlderVS; 133 return true; 134 } 135 if (ParentFilename == "x86ret" || ParentFilename == "x86chk" 136 || ParentFilename == "amd64ret" || ParentFilename == "amd64chk") { 137 Path = std::string(ParentPath); 138 VSLayout = MSVCToolChain::ToolsetLayout::DevDivInternal; 139 return true; 140 } 141 142 } else { 143 // This could be a new (>=VS2017) toolchain. If it is, we should find 144 // path components with these prefixes when walking backwards through 145 // the path. 146 // Note: empty strings match anything. 147 llvm::StringRef ExpectedPrefixes[] = {"", "Host", "bin", "", 148 "MSVC", "Tools", "VC"}; 149 150 auto It = llvm::sys::path::rbegin(PathEntry); 151 auto End = llvm::sys::path::rend(PathEntry); 152 for (llvm::StringRef Prefix : ExpectedPrefixes) { 153 if (It == End) 154 goto NotAToolChain; 155 if (!It->startswith(Prefix)) 156 goto NotAToolChain; 157 ++It; 158 } 159 160 // We've found a new toolchain! 161 // Back up 3 times (/bin/Host/arch) to get the root path. 162 llvm::StringRef ToolChainPath(PathEntry); 163 for (int i = 0; i < 3; ++i) 164 ToolChainPath = llvm::sys::path::parent_path(ToolChainPath); 165 166 Path = std::string(ToolChainPath); 167 VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer; 168 return true; 169 } 170 171 NotAToolChain: 172 continue; 173 } 174 } 175 return false; 176 } 177 178 // Query the Setup Config server for installs, then pick the newest version 179 // and find its default VC toolchain. 180 // This is the preferred way to discover new Visual Studios, as they're no 181 // longer listed in the registry. 182 static bool findVCToolChainViaSetupConfig(std::string &Path, 183 MSVCToolChain::ToolsetLayout &VSLayout) { 184 #if !defined(USE_MSVC_SETUP_API) 185 return false; 186 #else 187 // FIXME: This really should be done once in the top-level program's main 188 // function, as it may have already been initialized with a different 189 // threading model otherwise. 190 llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::SingleThreaded); 191 HRESULT HR; 192 193 // _com_ptr_t will throw a _com_error if a COM calls fail. 194 // The LLVM coding standards forbid exception handling, so we'll have to 195 // stop them from being thrown in the first place. 196 // The destructor will put the regular error handler back when we leave 197 // this scope. 198 struct SuppressCOMErrorsRAII { 199 static void __stdcall handler(HRESULT hr, IErrorInfo *perrinfo) {} 200 201 SuppressCOMErrorsRAII() { _set_com_error_handler(handler); } 202 203 ~SuppressCOMErrorsRAII() { _set_com_error_handler(_com_raise_error); } 204 205 } COMErrorSuppressor; 206 207 ISetupConfigurationPtr Query; 208 HR = Query.CreateInstance(__uuidof(SetupConfiguration)); 209 if (FAILED(HR)) 210 return false; 211 212 IEnumSetupInstancesPtr EnumInstances; 213 HR = ISetupConfiguration2Ptr(Query)->EnumAllInstances(&EnumInstances); 214 if (FAILED(HR)) 215 return false; 216 217 ISetupInstancePtr Instance; 218 HR = EnumInstances->Next(1, &Instance, nullptr); 219 if (HR != S_OK) 220 return false; 221 222 ISetupInstancePtr NewestInstance; 223 Optional<uint64_t> NewestVersionNum; 224 do { 225 bstr_t VersionString; 226 uint64_t VersionNum; 227 HR = Instance->GetInstallationVersion(VersionString.GetAddress()); 228 if (FAILED(HR)) 229 continue; 230 HR = ISetupHelperPtr(Query)->ParseVersion(VersionString, &VersionNum); 231 if (FAILED(HR)) 232 continue; 233 if (!NewestVersionNum || (VersionNum > NewestVersionNum)) { 234 NewestInstance = Instance; 235 NewestVersionNum = VersionNum; 236 } 237 } while ((HR = EnumInstances->Next(1, &Instance, nullptr)) == S_OK); 238 239 if (!NewestInstance) 240 return false; 241 242 bstr_t VCPathWide; 243 HR = NewestInstance->ResolvePath(L"VC", VCPathWide.GetAddress()); 244 if (FAILED(HR)) 245 return false; 246 247 std::string VCRootPath; 248 llvm::convertWideToUTF8(std::wstring(VCPathWide), VCRootPath); 249 250 llvm::SmallString<256> ToolsVersionFilePath(VCRootPath); 251 llvm::sys::path::append(ToolsVersionFilePath, "Auxiliary", "Build", 252 "Microsoft.VCToolsVersion.default.txt"); 253 254 auto ToolsVersionFile = llvm::MemoryBuffer::getFile(ToolsVersionFilePath); 255 if (!ToolsVersionFile) 256 return false; 257 258 llvm::SmallString<256> ToolchainPath(VCRootPath); 259 llvm::sys::path::append(ToolchainPath, "Tools", "MSVC", 260 ToolsVersionFile->get()->getBuffer().rtrim()); 261 if (!llvm::sys::fs::is_directory(ToolchainPath)) 262 return false; 263 264 Path = std::string(ToolchainPath.str()); 265 VSLayout = MSVCToolChain::ToolsetLayout::VS2017OrNewer; 266 return true; 267 #endif 268 } 269 270 // Look in the registry for Visual Studio installs, and use that to get 271 // a toolchain path. VS2017 and newer don't get added to the registry. 272 // So if we find something here, we know that it's an older version. 273 static bool findVCToolChainViaRegistry(std::string &Path, 274 MSVCToolChain::ToolsetLayout &VSLayout) { 275 std::string VSInstallPath; 276 if (getSystemRegistryString(R"(SOFTWARE\Microsoft\VisualStudio\$VERSION)", 277 "InstallDir", VSInstallPath, nullptr) || 278 getSystemRegistryString(R"(SOFTWARE\Microsoft\VCExpress\$VERSION)", 279 "InstallDir", VSInstallPath, nullptr)) { 280 if (!VSInstallPath.empty()) { 281 llvm::SmallString<256> VCPath(llvm::StringRef( 282 VSInstallPath.c_str(), VSInstallPath.find(R"(\Common7\IDE)"))); 283 llvm::sys::path::append(VCPath, "VC"); 284 285 Path = std::string(VCPath.str()); 286 VSLayout = MSVCToolChain::ToolsetLayout::OlderVS; 287 return true; 288 } 289 } 290 return false; 291 } 292 293 // Try to find Exe from a Visual Studio distribution. This first tries to find 294 // an installed copy of Visual Studio and, failing that, looks in the PATH, 295 // making sure that whatever executable that's found is not a same-named exe 296 // from clang itself to prevent clang from falling back to itself. 297 static std::string FindVisualStudioExecutable(const ToolChain &TC, 298 const char *Exe) { 299 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC); 300 SmallString<128> FilePath(MSVC.getSubDirectoryPath( 301 toolchains::MSVCToolChain::SubDirectoryType::Bin)); 302 llvm::sys::path::append(FilePath, Exe); 303 return std::string(llvm::sys::fs::can_execute(FilePath) ? FilePath.str() 304 : Exe); 305 } 306 307 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA, 308 const InputInfo &Output, 309 const InputInfoList &Inputs, 310 const ArgList &Args, 311 const char *LinkingOutput) const { 312 ArgStringList CmdArgs; 313 314 auto &TC = static_cast<const toolchains::MSVCToolChain &>(getToolChain()); 315 316 assert((Output.isFilename() || Output.isNothing()) && "invalid output"); 317 if (Output.isFilename()) 318 CmdArgs.push_back( 319 Args.MakeArgString(std::string("-out:") + Output.getFilename())); 320 321 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) && 322 !C.getDriver().IsCLMode()) 323 CmdArgs.push_back("-defaultlib:libcmt"); 324 325 if (!llvm::sys::Process::GetEnv("LIB")) { 326 // If the VC environment hasn't been configured (perhaps because the user 327 // did not run vcvarsall), try to build a consistent link environment. If 328 // the environment variable is set however, assume the user knows what 329 // they're doing. 330 CmdArgs.push_back(Args.MakeArgString( 331 Twine("-libpath:") + 332 TC.getSubDirectoryPath( 333 toolchains::MSVCToolChain::SubDirectoryType::Lib))); 334 335 CmdArgs.push_back(Args.MakeArgString( 336 Twine("-libpath:") + 337 TC.getSubDirectoryPath(toolchains::MSVCToolChain::SubDirectoryType::Lib, 338 "atlmfc"))); 339 340 if (TC.useUniversalCRT()) { 341 std::string UniversalCRTLibPath; 342 if (TC.getUniversalCRTLibraryPath(UniversalCRTLibPath)) 343 CmdArgs.push_back( 344 Args.MakeArgString(Twine("-libpath:") + UniversalCRTLibPath)); 345 } 346 347 std::string WindowsSdkLibPath; 348 if (TC.getWindowsSDKLibraryPath(WindowsSdkLibPath)) 349 CmdArgs.push_back( 350 Args.MakeArgString(std::string("-libpath:") + WindowsSdkLibPath)); 351 } 352 353 // Add the compiler-rt library directories to libpath if they exist to help 354 // the linker find the various sanitizer, builtin, and profiling runtimes. 355 for (const auto &LibPath : TC.getLibraryPaths()) { 356 if (TC.getVFS().exists(LibPath)) 357 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath)); 358 } 359 auto CRTPath = TC.getCompilerRTPath(); 360 if (TC.getVFS().exists(CRTPath)) 361 CmdArgs.push_back(Args.MakeArgString("-libpath:" + CRTPath)); 362 363 if (!C.getDriver().IsCLMode() && Args.hasArg(options::OPT_L)) 364 for (const auto &LibPath : Args.getAllArgValues(options::OPT_L)) 365 CmdArgs.push_back(Args.MakeArgString("-libpath:" + LibPath)); 366 367 CmdArgs.push_back("-nologo"); 368 369 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7, 370 options::OPT__SLASH_Zd)) 371 CmdArgs.push_back("-debug"); 372 373 // Pass on /Brepro if it was passed to the compiler. 374 // Note that /Brepro maps to -mno-incremental-linker-compatible. 375 bool DefaultIncrementalLinkerCompatible = 376 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment(); 377 if (!Args.hasFlag(options::OPT_mincremental_linker_compatible, 378 options::OPT_mno_incremental_linker_compatible, 379 DefaultIncrementalLinkerCompatible)) 380 CmdArgs.push_back("-Brepro"); 381 382 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd, 383 options::OPT_shared); 384 if (DLL) { 385 CmdArgs.push_back(Args.MakeArgString("-dll")); 386 387 SmallString<128> ImplibName(Output.getFilename()); 388 llvm::sys::path::replace_extension(ImplibName, "lib"); 389 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName)); 390 } 391 392 if (TC.getSanitizerArgs().needsFuzzer()) { 393 if (!Args.hasArg(options::OPT_shared)) 394 CmdArgs.push_back( 395 Args.MakeArgString(std::string("-wholearchive:") + 396 TC.getCompilerRTArgString(Args, "fuzzer"))); 397 CmdArgs.push_back(Args.MakeArgString("-debug")); 398 // Prevent the linker from padding sections we use for instrumentation 399 // arrays. 400 CmdArgs.push_back(Args.MakeArgString("-incremental:no")); 401 } 402 403 if (TC.getSanitizerArgs().needsAsanRt()) { 404 CmdArgs.push_back(Args.MakeArgString("-debug")); 405 CmdArgs.push_back(Args.MakeArgString("-incremental:no")); 406 if (TC.getSanitizerArgs().needsSharedRt() || 407 Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) { 408 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"}) 409 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib)); 410 // Make sure the dynamic runtime thunk is not optimized out at link time 411 // to ensure proper SEH handling. 412 CmdArgs.push_back(Args.MakeArgString( 413 TC.getArch() == llvm::Triple::x86 414 ? "-include:___asan_seh_interceptor" 415 : "-include:__asan_seh_interceptor")); 416 // Make sure the linker consider all object files from the dynamic runtime 417 // thunk. 418 CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") + 419 TC.getCompilerRT(Args, "asan_dynamic_runtime_thunk"))); 420 } else if (DLL) { 421 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk")); 422 } else { 423 for (const auto &Lib : {"asan", "asan_cxx"}) { 424 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib)); 425 // Make sure the linker consider all object files from the static lib. 426 // This is necessary because instrumented dlls need access to all the 427 // interface exported by the static lib in the main executable. 428 CmdArgs.push_back(Args.MakeArgString(std::string("-wholearchive:") + 429 TC.getCompilerRT(Args, Lib))); 430 } 431 } 432 } 433 434 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link); 435 436 // Control Flow Guard checks 437 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) { 438 StringRef GuardArgs = A->getValue(); 439 if (GuardArgs.equals_lower("cf") || GuardArgs.equals_lower("cf,nochecks")) { 440 // MSVC doesn't yet support the "nochecks" modifier. 441 CmdArgs.push_back("-guard:cf"); 442 } else if (GuardArgs.equals_lower("cf-")) { 443 CmdArgs.push_back("-guard:cf-"); 444 } 445 } 446 447 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 448 options::OPT_fno_openmp, false)) { 449 CmdArgs.push_back("-nodefaultlib:vcomp.lib"); 450 CmdArgs.push_back("-nodefaultlib:vcompd.lib"); 451 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") + 452 TC.getDriver().Dir + "/../lib")); 453 switch (TC.getDriver().getOpenMPRuntime(Args)) { 454 case Driver::OMPRT_OMP: 455 CmdArgs.push_back("-defaultlib:libomp.lib"); 456 break; 457 case Driver::OMPRT_IOMP5: 458 CmdArgs.push_back("-defaultlib:libiomp5md.lib"); 459 break; 460 case Driver::OMPRT_GOMP: 461 break; 462 case Driver::OMPRT_Unknown: 463 // Already diagnosed. 464 break; 465 } 466 } 467 468 // Add compiler-rt lib in case if it was explicitly 469 // specified as an argument for --rtlib option. 470 if (!Args.hasArg(options::OPT_nostdlib)) { 471 AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args); 472 } 473 474 // Add filenames, libraries, and other linker inputs. 475 for (const auto &Input : Inputs) { 476 if (Input.isFilename()) { 477 CmdArgs.push_back(Input.getFilename()); 478 continue; 479 } 480 481 const Arg &A = Input.getInputArg(); 482 483 // Render -l options differently for the MSVC linker. 484 if (A.getOption().matches(options::OPT_l)) { 485 StringRef Lib = A.getValue(); 486 const char *LinkLibArg; 487 if (Lib.endswith(".lib")) 488 LinkLibArg = Args.MakeArgString(Lib); 489 else 490 LinkLibArg = Args.MakeArgString(Lib + ".lib"); 491 CmdArgs.push_back(LinkLibArg); 492 continue; 493 } 494 495 // Otherwise, this is some other kind of linker input option like -Wl, -z, 496 // or -L. Render it, even if MSVC doesn't understand it. 497 A.renderAsInput(Args, CmdArgs); 498 } 499 500 TC.addProfileRTLibs(Args, CmdArgs); 501 502 std::vector<const char *> Environment; 503 504 // We need to special case some linker paths. In the case of lld, we need to 505 // translate 'lld' into 'lld-link', and in the case of the regular msvc 506 // linker, we need to use a special search algorithm. 507 llvm::SmallString<128> linkPath; 508 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link"); 509 if (Linker.equals_lower("lld")) 510 Linker = "lld-link"; 511 512 if (Linker.equals_lower("link")) { 513 // If we're using the MSVC linker, it's not sufficient to just use link 514 // from the program PATH, because other environments like GnuWin32 install 515 // their own link.exe which may come first. 516 linkPath = FindVisualStudioExecutable(TC, "link.exe"); 517 518 if (!TC.FoundMSVCInstall() && !llvm::sys::fs::can_execute(linkPath)) { 519 llvm::SmallString<128> ClPath; 520 ClPath = TC.GetProgramPath("cl.exe"); 521 if (llvm::sys::fs::can_execute(ClPath)) { 522 linkPath = llvm::sys::path::parent_path(ClPath); 523 llvm::sys::path::append(linkPath, "link.exe"); 524 if (!llvm::sys::fs::can_execute(linkPath)) 525 C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found); 526 } else { 527 C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found); 528 } 529 } 530 531 #ifdef _WIN32 532 // When cross-compiling with VS2017 or newer, link.exe expects to have 533 // its containing bin directory at the top of PATH, followed by the 534 // native target bin directory. 535 // e.g. when compiling for x86 on an x64 host, PATH should start with: 536 // /bin/Hostx64/x86;/bin/Hostx64/x64 537 // This doesn't attempt to handle ToolsetLayout::DevDivInternal. 538 if (TC.getIsVS2017OrNewer() && 539 llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) { 540 auto HostArch = llvm::Triple(llvm::sys::getProcessTriple()).getArch(); 541 542 auto EnvBlockWide = 543 std::unique_ptr<wchar_t[], decltype(&FreeEnvironmentStringsW)>( 544 GetEnvironmentStringsW(), FreeEnvironmentStringsW); 545 if (!EnvBlockWide) 546 goto SkipSettingEnvironment; 547 548 size_t EnvCount = 0; 549 size_t EnvBlockLen = 0; 550 while (EnvBlockWide[EnvBlockLen] != L'\0') { 551 ++EnvCount; 552 EnvBlockLen += std::wcslen(&EnvBlockWide[EnvBlockLen]) + 553 1 /*string null-terminator*/; 554 } 555 ++EnvBlockLen; // add the block null-terminator 556 557 std::string EnvBlock; 558 if (!llvm::convertUTF16ToUTF8String( 559 llvm::ArrayRef<char>(reinterpret_cast<char *>(EnvBlockWide.get()), 560 EnvBlockLen * sizeof(EnvBlockWide[0])), 561 EnvBlock)) 562 goto SkipSettingEnvironment; 563 564 Environment.reserve(EnvCount); 565 566 // Now loop over each string in the block and copy them into the 567 // environment vector, adjusting the PATH variable as needed when we 568 // find it. 569 for (const char *Cursor = EnvBlock.data(); *Cursor != '\0';) { 570 llvm::StringRef EnvVar(Cursor); 571 if (EnvVar.startswith_lower("path=")) { 572 using SubDirectoryType = toolchains::MSVCToolChain::SubDirectoryType; 573 constexpr size_t PrefixLen = 5; // strlen("path=") 574 Environment.push_back(Args.MakeArgString( 575 EnvVar.substr(0, PrefixLen) + 576 TC.getSubDirectoryPath(SubDirectoryType::Bin) + 577 llvm::Twine(llvm::sys::EnvPathSeparator) + 578 TC.getSubDirectoryPath(SubDirectoryType::Bin, "", HostArch) + 579 (EnvVar.size() > PrefixLen 580 ? llvm::Twine(llvm::sys::EnvPathSeparator) + 581 EnvVar.substr(PrefixLen) 582 : ""))); 583 } else { 584 Environment.push_back(Args.MakeArgString(EnvVar)); 585 } 586 Cursor += EnvVar.size() + 1 /*null-terminator*/; 587 } 588 } 589 SkipSettingEnvironment:; 590 #endif 591 } else { 592 linkPath = TC.GetProgramPath(Linker.str().c_str()); 593 } 594 595 auto LinkCmd = std::make_unique<Command>( 596 JA, *this, Args.MakeArgString(linkPath), CmdArgs, Inputs); 597 if (!Environment.empty()) 598 LinkCmd->setEnvironment(Environment); 599 C.addCommand(std::move(LinkCmd)); 600 } 601 602 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA, 603 const InputInfo &Output, 604 const InputInfoList &Inputs, 605 const ArgList &Args, 606 const char *LinkingOutput) const { 607 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput)); 608 } 609 610 std::unique_ptr<Command> visualstudio::Compiler::GetCommand( 611 Compilation &C, const JobAction &JA, const InputInfo &Output, 612 const InputInfoList &Inputs, const ArgList &Args, 613 const char *LinkingOutput) const { 614 ArgStringList CmdArgs; 615 CmdArgs.push_back("/nologo"); 616 CmdArgs.push_back("/c"); // Compile only. 617 CmdArgs.push_back("/W0"); // No warnings. 618 619 // The goal is to be able to invoke this tool correctly based on 620 // any flag accepted by clang-cl. 621 622 // These are spelled the same way in clang and cl.exe,. 623 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I}); 624 625 // Optimization level. 626 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin)) 627 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi" 628 : "/Oi-"); 629 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) { 630 if (A->getOption().getID() == options::OPT_O0) { 631 CmdArgs.push_back("/Od"); 632 } else { 633 CmdArgs.push_back("/Og"); 634 635 StringRef OptLevel = A->getValue(); 636 if (OptLevel == "s" || OptLevel == "z") 637 CmdArgs.push_back("/Os"); 638 else 639 CmdArgs.push_back("/Ot"); 640 641 CmdArgs.push_back("/Ob2"); 642 } 643 } 644 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer, 645 options::OPT_fno_omit_frame_pointer)) 646 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer 647 ? "/Oy" 648 : "/Oy-"); 649 if (!Args.hasArg(options::OPT_fwritable_strings)) 650 CmdArgs.push_back("/GF"); 651 652 // Flags for which clang-cl has an alias. 653 // FIXME: How can we ensure this stays in sync with relevant clang-cl options? 654 655 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR, 656 /*Default=*/false)) 657 CmdArgs.push_back("/GR-"); 658 659 if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS, 660 /*Default=*/false)) 661 CmdArgs.push_back("/GS-"); 662 663 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections, 664 options::OPT_fno_function_sections)) 665 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections 666 ? "/Gy" 667 : "/Gy-"); 668 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections, 669 options::OPT_fno_data_sections)) 670 CmdArgs.push_back( 671 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-"); 672 if (Args.hasArg(options::OPT_fsyntax_only)) 673 CmdArgs.push_back("/Zs"); 674 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only, 675 options::OPT__SLASH_Z7)) 676 CmdArgs.push_back("/Z7"); 677 678 std::vector<std::string> Includes = 679 Args.getAllArgValues(options::OPT_include); 680 for (const auto &Include : Includes) 681 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include)); 682 683 // Flags that can simply be passed through. 684 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD); 685 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd); 686 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX); 687 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_); 688 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH); 689 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl); 690 691 // The order of these flags is relevant, so pick the last one. 692 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd, 693 options::OPT__SLASH_MT, options::OPT__SLASH_MTd)) 694 A->render(Args, CmdArgs); 695 696 // Use MSVC's default threadsafe statics behaviour unless there was a flag. 697 if (Arg *A = Args.getLastArg(options::OPT_fthreadsafe_statics, 698 options::OPT_fno_threadsafe_statics)) { 699 CmdArgs.push_back(A->getOption().getID() == options::OPT_fthreadsafe_statics 700 ? "/Zc:threadSafeInit" 701 : "/Zc:threadSafeInit-"); 702 } 703 704 // Control Flow Guard checks 705 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) { 706 StringRef GuardArgs = A->getValue(); 707 if (GuardArgs.equals_lower("cf") || GuardArgs.equals_lower("cf,nochecks")) { 708 // MSVC doesn't yet support the "nochecks" modifier. 709 CmdArgs.push_back("/guard:cf"); 710 } else if (GuardArgs.equals_lower("cf-")) { 711 CmdArgs.push_back("/guard:cf-"); 712 } 713 } 714 715 // Pass through all unknown arguments so that the fallback command can see 716 // them too. 717 Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN); 718 719 // Input filename. 720 assert(Inputs.size() == 1); 721 const InputInfo &II = Inputs[0]; 722 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX); 723 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp"); 724 if (II.isFilename()) 725 CmdArgs.push_back(II.getFilename()); 726 else 727 II.getInputArg().renderAsInput(Args, CmdArgs); 728 729 // Output filename. 730 assert(Output.getType() == types::TY_Object); 731 const char *Fo = 732 Args.MakeArgString(std::string("/Fo") + Output.getFilename()); 733 CmdArgs.push_back(Fo); 734 735 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe"); 736 return std::make_unique<Command>(JA, *this, Args.MakeArgString(Exec), 737 CmdArgs, Inputs); 738 } 739 740 MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple, 741 const ArgList &Args) 742 : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args) { 743 getProgramPaths().push_back(getDriver().getInstalledDir()); 744 if (getDriver().getInstalledDir() != getDriver().Dir) 745 getProgramPaths().push_back(getDriver().Dir); 746 747 // Check the environment first, since that's probably the user telling us 748 // what they want to use. 749 // Failing that, just try to find the newest Visual Studio version we can 750 // and use its default VC toolchain. 751 findVCToolChainViaEnvironment(VCToolChainPath, VSLayout) || 752 findVCToolChainViaSetupConfig(VCToolChainPath, VSLayout) || 753 findVCToolChainViaRegistry(VCToolChainPath, VSLayout); 754 } 755 756 Tool *MSVCToolChain::buildLinker() const { 757 return new tools::visualstudio::Linker(*this); 758 } 759 760 Tool *MSVCToolChain::buildAssembler() const { 761 if (getTriple().isOSBinFormatMachO()) 762 return new tools::darwin::Assembler(*this); 763 getDriver().Diag(clang::diag::err_no_external_assembler); 764 return nullptr; 765 } 766 767 bool MSVCToolChain::IsIntegratedAssemblerDefault() const { 768 return true; 769 } 770 771 bool MSVCToolChain::IsUnwindTablesDefault(const ArgList &Args) const { 772 // Don't emit unwind tables by default for MachO targets. 773 if (getTriple().isOSBinFormatMachO()) 774 return false; 775 776 // All non-x86_32 Windows targets require unwind tables. However, LLVM 777 // doesn't know how to generate them for all targets, so only enable 778 // the ones that are actually implemented. 779 return getArch() == llvm::Triple::x86_64 || 780 getArch() == llvm::Triple::aarch64; 781 } 782 783 bool MSVCToolChain::isPICDefault() const { 784 return getArch() == llvm::Triple::x86_64; 785 } 786 787 bool MSVCToolChain::isPIEDefault() const { 788 return false; 789 } 790 791 bool MSVCToolChain::isPICDefaultForced() const { 792 return getArch() == llvm::Triple::x86_64; 793 } 794 795 void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs, 796 ArgStringList &CC1Args) const { 797 CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args); 798 } 799 800 void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const { 801 CudaInstallation.print(OS); 802 } 803 804 // Windows SDKs and VC Toolchains group their contents into subdirectories based 805 // on the target architecture. This function converts an llvm::Triple::ArchType 806 // to the corresponding subdirectory name. 807 static const char *llvmArchToWindowsSDKArch(llvm::Triple::ArchType Arch) { 808 using ArchType = llvm::Triple::ArchType; 809 switch (Arch) { 810 case ArchType::x86: 811 return "x86"; 812 case ArchType::x86_64: 813 return "x64"; 814 case ArchType::arm: 815 return "arm"; 816 case ArchType::aarch64: 817 return "arm64"; 818 default: 819 return ""; 820 } 821 } 822 823 // Similar to the above function, but for Visual Studios before VS2017. 824 static const char *llvmArchToLegacyVCArch(llvm::Triple::ArchType Arch) { 825 using ArchType = llvm::Triple::ArchType; 826 switch (Arch) { 827 case ArchType::x86: 828 // x86 is default in legacy VC toolchains. 829 // e.g. x86 libs are directly in /lib as opposed to /lib/x86. 830 return ""; 831 case ArchType::x86_64: 832 return "amd64"; 833 case ArchType::arm: 834 return "arm"; 835 case ArchType::aarch64: 836 return "arm64"; 837 default: 838 return ""; 839 } 840 } 841 842 // Similar to the above function, but for DevDiv internal builds. 843 static const char *llvmArchToDevDivInternalArch(llvm::Triple::ArchType Arch) { 844 using ArchType = llvm::Triple::ArchType; 845 switch (Arch) { 846 case ArchType::x86: 847 return "i386"; 848 case ArchType::x86_64: 849 return "amd64"; 850 case ArchType::arm: 851 return "arm"; 852 case ArchType::aarch64: 853 return "arm64"; 854 default: 855 return ""; 856 } 857 } 858 859 // Get the path to a specific subdirectory in the current toolchain for 860 // a given target architecture. 861 // VS2017 changed the VC toolchain layout, so this should be used instead 862 // of hardcoding paths. 863 std::string 864 MSVCToolChain::getSubDirectoryPath(SubDirectoryType Type, 865 llvm::StringRef SubdirParent, 866 llvm::Triple::ArchType TargetArch) const { 867 const char *SubdirName; 868 const char *IncludeName; 869 switch (VSLayout) { 870 case ToolsetLayout::OlderVS: 871 SubdirName = llvmArchToLegacyVCArch(TargetArch); 872 IncludeName = "include"; 873 break; 874 case ToolsetLayout::VS2017OrNewer: 875 SubdirName = llvmArchToWindowsSDKArch(TargetArch); 876 IncludeName = "include"; 877 break; 878 case ToolsetLayout::DevDivInternal: 879 SubdirName = llvmArchToDevDivInternalArch(TargetArch); 880 IncludeName = "inc"; 881 break; 882 } 883 884 llvm::SmallString<256> Path(VCToolChainPath); 885 if (!SubdirParent.empty()) 886 llvm::sys::path::append(Path, SubdirParent); 887 888 switch (Type) { 889 case SubDirectoryType::Bin: 890 if (VSLayout == ToolsetLayout::VS2017OrNewer) { 891 const bool HostIsX64 = 892 llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit(); 893 const char *const HostName = HostIsX64 ? "Hostx64" : "Hostx86"; 894 llvm::sys::path::append(Path, "bin", HostName, SubdirName); 895 } else { // OlderVS or DevDivInternal 896 llvm::sys::path::append(Path, "bin", SubdirName); 897 } 898 break; 899 case SubDirectoryType::Include: 900 llvm::sys::path::append(Path, IncludeName); 901 break; 902 case SubDirectoryType::Lib: 903 llvm::sys::path::append(Path, "lib", SubdirName); 904 break; 905 } 906 return std::string(Path.str()); 907 } 908 909 #ifdef _WIN32 910 static bool readFullStringValue(HKEY hkey, const char *valueName, 911 std::string &value) { 912 std::wstring WideValueName; 913 if (!llvm::ConvertUTF8toWide(valueName, WideValueName)) 914 return false; 915 916 DWORD result = 0; 917 DWORD valueSize = 0; 918 DWORD type = 0; 919 // First just query for the required size. 920 result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL, 921 &valueSize); 922 if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize) 923 return false; 924 std::vector<BYTE> buffer(valueSize); 925 result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0], 926 &valueSize); 927 if (result == ERROR_SUCCESS) { 928 std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()), 929 valueSize / sizeof(wchar_t)); 930 if (valueSize && WideValue.back() == L'\0') { 931 WideValue.pop_back(); 932 } 933 // The destination buffer must be empty as an invariant of the conversion 934 // function; but this function is sometimes called in a loop that passes in 935 // the same buffer, however. Simply clear it out so we can overwrite it. 936 value.clear(); 937 return llvm::convertWideToUTF8(WideValue, value); 938 } 939 return false; 940 } 941 #endif 942 943 /// Read registry string. 944 /// This also supports a means to look for high-versioned keys by use 945 /// of a $VERSION placeholder in the key path. 946 /// $VERSION in the key path is a placeholder for the version number, 947 /// causing the highest value path to be searched for and used. 948 /// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION". 949 /// There can be additional characters in the component. Only the numeric 950 /// characters are compared. This function only searches HKLM. 951 static bool getSystemRegistryString(const char *keyPath, const char *valueName, 952 std::string &value, std::string *phValue) { 953 #ifndef _WIN32 954 return false; 955 #else 956 HKEY hRootKey = HKEY_LOCAL_MACHINE; 957 HKEY hKey = NULL; 958 long lResult; 959 bool returnValue = false; 960 961 const char *placeHolder = strstr(keyPath, "$VERSION"); 962 std::string bestName; 963 // If we have a $VERSION placeholder, do the highest-version search. 964 if (placeHolder) { 965 const char *keyEnd = placeHolder - 1; 966 const char *nextKey = placeHolder; 967 // Find end of previous key. 968 while ((keyEnd > keyPath) && (*keyEnd != '\\')) 969 keyEnd--; 970 // Find end of key containing $VERSION. 971 while (*nextKey && (*nextKey != '\\')) 972 nextKey++; 973 size_t partialKeyLength = keyEnd - keyPath; 974 char partialKey[256]; 975 if (partialKeyLength >= sizeof(partialKey)) 976 partialKeyLength = sizeof(partialKey) - 1; 977 strncpy(partialKey, keyPath, partialKeyLength); 978 partialKey[partialKeyLength] = '\0'; 979 HKEY hTopKey = NULL; 980 lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY, 981 &hTopKey); 982 if (lResult == ERROR_SUCCESS) { 983 char keyName[256]; 984 double bestValue = 0.0; 985 DWORD index, size = sizeof(keyName) - 1; 986 for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL, 987 NULL, NULL) == ERROR_SUCCESS; 988 index++) { 989 const char *sp = keyName; 990 while (*sp && !isDigit(*sp)) 991 sp++; 992 if (!*sp) 993 continue; 994 const char *ep = sp + 1; 995 while (*ep && (isDigit(*ep) || (*ep == '.'))) 996 ep++; 997 char numBuf[32]; 998 strncpy(numBuf, sp, sizeof(numBuf) - 1); 999 numBuf[sizeof(numBuf) - 1] = '\0'; 1000 double dvalue = strtod(numBuf, NULL); 1001 if (dvalue > bestValue) { 1002 // Test that InstallDir is indeed there before keeping this index. 1003 // Open the chosen key path remainder. 1004 bestName = keyName; 1005 // Append rest of key. 1006 bestName.append(nextKey); 1007 lResult = RegOpenKeyExA(hTopKey, bestName.c_str(), 0, 1008 KEY_READ | KEY_WOW64_32KEY, &hKey); 1009 if (lResult == ERROR_SUCCESS) { 1010 if (readFullStringValue(hKey, valueName, value)) { 1011 bestValue = dvalue; 1012 if (phValue) 1013 *phValue = bestName; 1014 returnValue = true; 1015 } 1016 RegCloseKey(hKey); 1017 } 1018 } 1019 size = sizeof(keyName) - 1; 1020 } 1021 RegCloseKey(hTopKey); 1022 } 1023 } else { 1024 lResult = 1025 RegOpenKeyExA(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey); 1026 if (lResult == ERROR_SUCCESS) { 1027 if (readFullStringValue(hKey, valueName, value)) 1028 returnValue = true; 1029 if (phValue) 1030 phValue->clear(); 1031 RegCloseKey(hKey); 1032 } 1033 } 1034 return returnValue; 1035 #endif // _WIN32 1036 } 1037 1038 // Find the most recent version of Universal CRT or Windows 10 SDK. 1039 // vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include 1040 // directory by name and uses the last one of the list. 1041 // So we compare entry names lexicographically to find the greatest one. 1042 static bool getWindows10SDKVersionFromPath(const std::string &SDKPath, 1043 std::string &SDKVersion) { 1044 SDKVersion.clear(); 1045 1046 std::error_code EC; 1047 llvm::SmallString<128> IncludePath(SDKPath); 1048 llvm::sys::path::append(IncludePath, "Include"); 1049 for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd; 1050 DirIt != DirEnd && !EC; DirIt.increment(EC)) { 1051 if (!llvm::sys::fs::is_directory(DirIt->path())) 1052 continue; 1053 StringRef CandidateName = llvm::sys::path::filename(DirIt->path()); 1054 // If WDK is installed, there could be subfolders like "wdf" in the 1055 // "Include" directory. 1056 // Allow only directories which names start with "10.". 1057 if (!CandidateName.startswith("10.")) 1058 continue; 1059 if (CandidateName > SDKVersion) 1060 SDKVersion = std::string(CandidateName); 1061 } 1062 1063 return !SDKVersion.empty(); 1064 } 1065 1066 /// Get Windows SDK installation directory. 1067 static bool getWindowsSDKDir(std::string &Path, int &Major, 1068 std::string &WindowsSDKIncludeVersion, 1069 std::string &WindowsSDKLibVersion) { 1070 std::string RegistrySDKVersion; 1071 // Try the Windows registry. 1072 if (!getSystemRegistryString( 1073 "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION", 1074 "InstallationFolder", Path, &RegistrySDKVersion)) 1075 return false; 1076 if (Path.empty() || RegistrySDKVersion.empty()) 1077 return false; 1078 1079 WindowsSDKIncludeVersion.clear(); 1080 WindowsSDKLibVersion.clear(); 1081 Major = 0; 1082 std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major); 1083 if (Major <= 7) 1084 return true; 1085 if (Major == 8) { 1086 // Windows SDK 8.x installs libraries in a folder whose names depend on the 1087 // version of the OS you're targeting. By default choose the newest, which 1088 // usually corresponds to the version of the OS you've installed the SDK on. 1089 const char *Tests[] = {"winv6.3", "win8", "win7"}; 1090 for (const char *Test : Tests) { 1091 llvm::SmallString<128> TestPath(Path); 1092 llvm::sys::path::append(TestPath, "Lib", Test); 1093 if (llvm::sys::fs::exists(TestPath.c_str())) { 1094 WindowsSDKLibVersion = Test; 1095 break; 1096 } 1097 } 1098 return !WindowsSDKLibVersion.empty(); 1099 } 1100 if (Major == 10) { 1101 if (!getWindows10SDKVersionFromPath(Path, WindowsSDKIncludeVersion)) 1102 return false; 1103 WindowsSDKLibVersion = WindowsSDKIncludeVersion; 1104 return true; 1105 } 1106 // Unsupported SDK version 1107 return false; 1108 } 1109 1110 // Gets the library path required to link against the Windows SDK. 1111 bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const { 1112 std::string sdkPath; 1113 int sdkMajor = 0; 1114 std::string windowsSDKIncludeVersion; 1115 std::string windowsSDKLibVersion; 1116 1117 path.clear(); 1118 if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion, 1119 windowsSDKLibVersion)) 1120 return false; 1121 1122 llvm::SmallString<128> libPath(sdkPath); 1123 llvm::sys::path::append(libPath, "Lib"); 1124 if (sdkMajor >= 8) { 1125 llvm::sys::path::append(libPath, windowsSDKLibVersion, "um", 1126 llvmArchToWindowsSDKArch(getArch())); 1127 } else { 1128 switch (getArch()) { 1129 // In Windows SDK 7.x, x86 libraries are directly in the Lib folder. 1130 case llvm::Triple::x86: 1131 break; 1132 case llvm::Triple::x86_64: 1133 llvm::sys::path::append(libPath, "x64"); 1134 break; 1135 case llvm::Triple::arm: 1136 // It is not necessary to link against Windows SDK 7.x when targeting ARM. 1137 return false; 1138 default: 1139 return false; 1140 } 1141 } 1142 1143 path = std::string(libPath.str()); 1144 return true; 1145 } 1146 1147 // Check if the Include path of a specified version of Visual Studio contains 1148 // specific header files. If not, they are probably shipped with Universal CRT. 1149 bool MSVCToolChain::useUniversalCRT() const { 1150 llvm::SmallString<128> TestPath( 1151 getSubDirectoryPath(SubDirectoryType::Include)); 1152 llvm::sys::path::append(TestPath, "stdlib.h"); 1153 return !llvm::sys::fs::exists(TestPath); 1154 } 1155 1156 static bool getUniversalCRTSdkDir(std::string &Path, std::string &UCRTVersion) { 1157 // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry 1158 // for the specific key "KitsRoot10". So do we. 1159 if (!getSystemRegistryString( 1160 "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10", 1161 Path, nullptr)) 1162 return false; 1163 1164 return getWindows10SDKVersionFromPath(Path, UCRTVersion); 1165 } 1166 1167 bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const { 1168 std::string UniversalCRTSdkPath; 1169 std::string UCRTVersion; 1170 1171 Path.clear(); 1172 if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) 1173 return false; 1174 1175 StringRef ArchName = llvmArchToWindowsSDKArch(getArch()); 1176 if (ArchName.empty()) 1177 return false; 1178 1179 llvm::SmallString<128> LibPath(UniversalCRTSdkPath); 1180 llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName); 1181 1182 Path = std::string(LibPath.str()); 1183 return true; 1184 } 1185 1186 static VersionTuple getMSVCVersionFromTriple(const llvm::Triple &Triple) { 1187 unsigned Major, Minor, Micro; 1188 Triple.getEnvironmentVersion(Major, Minor, Micro); 1189 if (Major || Minor || Micro) 1190 return VersionTuple(Major, Minor, Micro); 1191 return VersionTuple(); 1192 } 1193 1194 static VersionTuple getMSVCVersionFromExe(const std::string &BinDir) { 1195 VersionTuple Version; 1196 #ifdef _WIN32 1197 SmallString<128> ClExe(BinDir); 1198 llvm::sys::path::append(ClExe, "cl.exe"); 1199 1200 std::wstring ClExeWide; 1201 if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide)) 1202 return Version; 1203 1204 const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(), 1205 nullptr); 1206 if (VersionSize == 0) 1207 return Version; 1208 1209 SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize); 1210 if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize, 1211 VersionBlock.data())) 1212 return Version; 1213 1214 VS_FIXEDFILEINFO *FileInfo = nullptr; 1215 UINT FileInfoSize = 0; 1216 if (!::VerQueryValueW(VersionBlock.data(), L"\\", 1217 reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) || 1218 FileInfoSize < sizeof(*FileInfo)) 1219 return Version; 1220 1221 const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF; 1222 const unsigned Minor = (FileInfo->dwFileVersionMS ) & 0xFFFF; 1223 const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF; 1224 1225 Version = VersionTuple(Major, Minor, Micro); 1226 #endif 1227 return Version; 1228 } 1229 1230 void MSVCToolChain::AddSystemIncludeWithSubfolder( 1231 const ArgList &DriverArgs, ArgStringList &CC1Args, 1232 const std::string &folder, const Twine &subfolder1, const Twine &subfolder2, 1233 const Twine &subfolder3) const { 1234 llvm::SmallString<128> path(folder); 1235 llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3); 1236 addSystemInclude(DriverArgs, CC1Args, path); 1237 } 1238 1239 void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, 1240 ArgStringList &CC1Args) const { 1241 if (DriverArgs.hasArg(options::OPT_nostdinc)) 1242 return; 1243 1244 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { 1245 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir, 1246 "include"); 1247 } 1248 1249 // Add %INCLUDE%-like directories from the -imsvc flag. 1250 for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc)) 1251 addSystemInclude(DriverArgs, CC1Args, Path); 1252 1253 if (DriverArgs.hasArg(options::OPT_nostdlibinc)) 1254 return; 1255 1256 // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat. 1257 if (llvm::Optional<std::string> cl_include_dir = 1258 llvm::sys::Process::GetEnv("INCLUDE")) { 1259 SmallVector<StringRef, 8> Dirs; 1260 StringRef(*cl_include_dir) 1261 .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false); 1262 for (StringRef Dir : Dirs) 1263 addSystemInclude(DriverArgs, CC1Args, Dir); 1264 if (!Dirs.empty()) 1265 return; 1266 } 1267 1268 // When built with access to the proper Windows APIs, try to actually find 1269 // the correct include paths first. 1270 if (!VCToolChainPath.empty()) { 1271 addSystemInclude(DriverArgs, CC1Args, 1272 getSubDirectoryPath(SubDirectoryType::Include)); 1273 addSystemInclude(DriverArgs, CC1Args, 1274 getSubDirectoryPath(SubDirectoryType::Include, "atlmfc")); 1275 1276 if (useUniversalCRT()) { 1277 std::string UniversalCRTSdkPath; 1278 std::string UCRTVersion; 1279 if (getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) { 1280 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath, 1281 "Include", UCRTVersion, "ucrt"); 1282 } 1283 } 1284 1285 std::string WindowsSDKDir; 1286 int major; 1287 std::string windowsSDKIncludeVersion; 1288 std::string windowsSDKLibVersion; 1289 if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion, 1290 windowsSDKLibVersion)) { 1291 if (major >= 8) { 1292 // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10. 1293 // Anyway, llvm::sys::path::append is able to manage it. 1294 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir, 1295 "include", windowsSDKIncludeVersion, 1296 "shared"); 1297 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir, 1298 "include", windowsSDKIncludeVersion, 1299 "um"); 1300 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir, 1301 "include", windowsSDKIncludeVersion, 1302 "winrt"); 1303 } else { 1304 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir, 1305 "include"); 1306 } 1307 } 1308 1309 return; 1310 } 1311 1312 #if defined(_WIN32) 1313 // As a fallback, select default install paths. 1314 // FIXME: Don't guess drives and paths like this on Windows. 1315 const StringRef Paths[] = { 1316 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include", 1317 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include", 1318 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include", 1319 "C:/Program Files/Microsoft Visual Studio 8/VC/include", 1320 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include" 1321 }; 1322 addSystemIncludes(DriverArgs, CC1Args, Paths); 1323 #endif 1324 } 1325 1326 void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 1327 ArgStringList &CC1Args) const { 1328 // FIXME: There should probably be logic here to find libc++ on Windows. 1329 } 1330 1331 VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D, 1332 const ArgList &Args) const { 1333 bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment(); 1334 VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args); 1335 if (MSVT.empty()) 1336 MSVT = getMSVCVersionFromTriple(getTriple()); 1337 if (MSVT.empty() && IsWindowsMSVC) 1338 MSVT = getMSVCVersionFromExe(getSubDirectoryPath(SubDirectoryType::Bin)); 1339 if (MSVT.empty() && 1340 Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions, 1341 IsWindowsMSVC)) { 1342 // -fms-compatibility-version=19.11 is default, aka 2017, 15.3 1343 MSVT = VersionTuple(19, 11); 1344 } 1345 return MSVT; 1346 } 1347 1348 std::string 1349 MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args, 1350 types::ID InputType) const { 1351 // The MSVC version doesn't care about the architecture, even though it 1352 // may look at the triple internally. 1353 VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args); 1354 MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0), 1355 MSVT.getSubminor().getValueOr(0)); 1356 1357 // For the rest of the triple, however, a computed architecture name may 1358 // be needed. 1359 llvm::Triple Triple(ToolChain::ComputeEffectiveClangTriple(Args, InputType)); 1360 if (Triple.getEnvironment() == llvm::Triple::MSVC) { 1361 StringRef ObjFmt = Triple.getEnvironmentName().split('-').second; 1362 if (ObjFmt.empty()) 1363 Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str()); 1364 else 1365 Triple.setEnvironmentName( 1366 (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str()); 1367 } 1368 return Triple.getTriple(); 1369 } 1370 1371 SanitizerMask MSVCToolChain::getSupportedSanitizers() const { 1372 SanitizerMask Res = ToolChain::getSupportedSanitizers(); 1373 Res |= SanitizerKind::Address; 1374 Res |= SanitizerKind::PointerCompare; 1375 Res |= SanitizerKind::PointerSubtract; 1376 Res |= SanitizerKind::Fuzzer; 1377 Res |= SanitizerKind::FuzzerNoLink; 1378 Res &= ~SanitizerKind::CFIMFCall; 1379 return Res; 1380 } 1381 1382 static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL, 1383 bool SupportsForcingFramePointer, 1384 const char *ExpandChar, const OptTable &Opts) { 1385 assert(A->getOption().matches(options::OPT__SLASH_O)); 1386 1387 StringRef OptStr = A->getValue(); 1388 for (size_t I = 0, E = OptStr.size(); I != E; ++I) { 1389 const char &OptChar = *(OptStr.data() + I); 1390 switch (OptChar) { 1391 default: 1392 break; 1393 case '1': 1394 case '2': 1395 case 'x': 1396 case 'd': 1397 // Ignore /O[12xd] flags that aren't the last one on the command line. 1398 // Only the last one gets expanded. 1399 if (&OptChar != ExpandChar) { 1400 A->claim(); 1401 break; 1402 } 1403 if (OptChar == 'd') { 1404 DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0)); 1405 } else { 1406 if (OptChar == '1') { 1407 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s"); 1408 } else if (OptChar == '2' || OptChar == 'x') { 1409 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin)); 1410 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2"); 1411 } 1412 if (SupportsForcingFramePointer && 1413 !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer)) 1414 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fomit_frame_pointer)); 1415 if (OptChar == '1' || OptChar == '2') 1416 DAL.AddFlagArg(A, Opts.getOption(options::OPT_ffunction_sections)); 1417 } 1418 break; 1419 case 'b': 1420 if (I + 1 != E && isdigit(OptStr[I + 1])) { 1421 switch (OptStr[I + 1]) { 1422 case '0': 1423 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline)); 1424 break; 1425 case '1': 1426 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions)); 1427 break; 1428 case '2': 1429 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions)); 1430 break; 1431 } 1432 ++I; 1433 } 1434 break; 1435 case 'g': 1436 A->claim(); 1437 break; 1438 case 'i': 1439 if (I + 1 != E && OptStr[I + 1] == '-') { 1440 ++I; 1441 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin)); 1442 } else { 1443 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin)); 1444 } 1445 break; 1446 case 's': 1447 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s"); 1448 break; 1449 case 't': 1450 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2"); 1451 break; 1452 case 'y': { 1453 bool OmitFramePointer = true; 1454 if (I + 1 != E && OptStr[I + 1] == '-') { 1455 OmitFramePointer = false; 1456 ++I; 1457 } 1458 if (SupportsForcingFramePointer) { 1459 if (OmitFramePointer) 1460 DAL.AddFlagArg(A, 1461 Opts.getOption(options::OPT_fomit_frame_pointer)); 1462 else 1463 DAL.AddFlagArg( 1464 A, Opts.getOption(options::OPT_fno_omit_frame_pointer)); 1465 } else { 1466 // Don't warn about /Oy- in x86-64 builds (where 1467 // SupportsForcingFramePointer is false). The flag having no effect 1468 // there is a compiler-internal optimization, and people shouldn't have 1469 // to special-case their build files for x86-64 clang-cl. 1470 A->claim(); 1471 } 1472 break; 1473 } 1474 } 1475 } 1476 } 1477 1478 static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL, 1479 const OptTable &Opts) { 1480 assert(A->getOption().matches(options::OPT_D)); 1481 1482 StringRef Val = A->getValue(); 1483 size_t Hash = Val.find('#'); 1484 if (Hash == StringRef::npos || Hash > Val.find('=')) { 1485 DAL.append(A); 1486 return; 1487 } 1488 1489 std::string NewVal = std::string(Val); 1490 NewVal[Hash] = '='; 1491 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal); 1492 } 1493 1494 llvm::opt::DerivedArgList * 1495 MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args, 1496 StringRef BoundArch, 1497 Action::OffloadKind OFK) const { 1498 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 1499 const OptTable &Opts = getDriver().getOpts(); 1500 1501 // /Oy and /Oy- don't have an effect on X86-64 1502 bool SupportsForcingFramePointer = getArch() != llvm::Triple::x86_64; 1503 1504 // The -O[12xd] flag actually expands to several flags. We must desugar the 1505 // flags so that options embedded can be negated. For example, the '-O2' flag 1506 // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to 1507 // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single 1508 // aspect of '-O2'. 1509 // 1510 // Note that this expansion logic only applies to the *last* of '[12xd]'. 1511 1512 // First step is to search for the character we'd like to expand. 1513 const char *ExpandChar = nullptr; 1514 for (Arg *A : Args.filtered(options::OPT__SLASH_O)) { 1515 StringRef OptStr = A->getValue(); 1516 for (size_t I = 0, E = OptStr.size(); I != E; ++I) { 1517 char OptChar = OptStr[I]; 1518 char PrevChar = I > 0 ? OptStr[I - 1] : '0'; 1519 if (PrevChar == 'b') { 1520 // OptChar does not expand; it's an argument to the previous char. 1521 continue; 1522 } 1523 if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd') 1524 ExpandChar = OptStr.data() + I; 1525 } 1526 } 1527 1528 for (Arg *A : Args) { 1529 if (A->getOption().matches(options::OPT__SLASH_O)) { 1530 // The -O flag actually takes an amalgam of other options. For example, 1531 // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'. 1532 TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts); 1533 } else if (A->getOption().matches(options::OPT_D)) { 1534 // Translate -Dfoo#bar into -Dfoo=bar. 1535 TranslateDArg(A, *DAL, Opts); 1536 } else if (OFK != Action::OFK_HIP) { 1537 // HIP Toolchain translates input args by itself. 1538 DAL->append(A); 1539 } 1540 } 1541 1542 return DAL; 1543 } 1544