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