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.
findVCToolChainViaEnvironment(std::string & Path,MSVCToolChain::ToolsetLayout & VSLayout)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.
findVCToolChainViaSetupConfig(std::string & Path,MSVCToolChain::ToolsetLayout & VSLayout)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.
findVCToolChainViaRegistry(std::string & Path,MSVCToolChain::ToolsetLayout & VSLayout)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.
FindVisualStudioExecutable(const ToolChain & TC,const char * Exe)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 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const307 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     if (!TC.FoundMSVCInstall() && !llvm::sys::fs::can_execute(linkPath))
473       C.getDriver().Diag(clang::diag::warn_drv_msvc_not_found);
474 
475 #ifdef _WIN32
476     // When cross-compiling with VS2017 or newer, link.exe expects to have
477     // its containing bin directory at the top of PATH, followed by the
478     // native target bin directory.
479     // e.g. when compiling for x86 on an x64 host, PATH should start with:
480     // /bin/HostX64/x86;/bin/HostX64/x64
481     // This doesn't attempt to handle ToolsetLayout::DevDivInternal.
482     if (TC.getIsVS2017OrNewer() &&
483         llvm::Triple(llvm::sys::getProcessTriple()).getArch() != TC.getArch()) {
484       auto HostArch = llvm::Triple(llvm::sys::getProcessTriple()).getArch();
485 
486       auto EnvBlockWide =
487           std::unique_ptr<wchar_t[], decltype(&FreeEnvironmentStringsW)>(
488               GetEnvironmentStringsW(), FreeEnvironmentStringsW);
489       if (!EnvBlockWide)
490         goto SkipSettingEnvironment;
491 
492       size_t EnvCount = 0;
493       size_t EnvBlockLen = 0;
494       while (EnvBlockWide[EnvBlockLen] != L'\0') {
495         ++EnvCount;
496         EnvBlockLen += std::wcslen(&EnvBlockWide[EnvBlockLen]) +
497                        1 /*string null-terminator*/;
498       }
499       ++EnvBlockLen; // add the block null-terminator
500 
501       std::string EnvBlock;
502       if (!llvm::convertUTF16ToUTF8String(
503               llvm::ArrayRef<char>(reinterpret_cast<char *>(EnvBlockWide.get()),
504                                    EnvBlockLen * sizeof(EnvBlockWide[0])),
505               EnvBlock))
506         goto SkipSettingEnvironment;
507 
508       Environment.reserve(EnvCount);
509 
510       // Now loop over each string in the block and copy them into the
511       // environment vector, adjusting the PATH variable as needed when we
512       // find it.
513       for (const char *Cursor = EnvBlock.data(); *Cursor != '\0';) {
514         llvm::StringRef EnvVar(Cursor);
515         if (EnvVar.startswith_lower("path=")) {
516           using SubDirectoryType = toolchains::MSVCToolChain::SubDirectoryType;
517           constexpr size_t PrefixLen = 5; // strlen("path=")
518           Environment.push_back(Args.MakeArgString(
519               EnvVar.substr(0, PrefixLen) +
520               TC.getSubDirectoryPath(SubDirectoryType::Bin) +
521               llvm::Twine(llvm::sys::EnvPathSeparator) +
522               TC.getSubDirectoryPath(SubDirectoryType::Bin, HostArch) +
523               (EnvVar.size() > PrefixLen
524                    ? llvm::Twine(llvm::sys::EnvPathSeparator) +
525                          EnvVar.substr(PrefixLen)
526                    : "")));
527         } else {
528           Environment.push_back(Args.MakeArgString(EnvVar));
529         }
530         Cursor += EnvVar.size() + 1 /*null-terminator*/;
531       }
532     }
533   SkipSettingEnvironment:;
534 #endif
535   } else {
536     linkPath = TC.GetProgramPath(Linker.str().c_str());
537   }
538 
539   auto LinkCmd = llvm::make_unique<Command>(
540       JA, *this, Args.MakeArgString(linkPath), CmdArgs, Inputs);
541   if (!Environment.empty())
542     LinkCmd->setEnvironment(Environment);
543   C.addCommand(std::move(LinkCmd));
544 }
545 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const546 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
547                                           const InputInfo &Output,
548                                           const InputInfoList &Inputs,
549                                           const ArgList &Args,
550                                           const char *LinkingOutput) const {
551   C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
552 }
553 
GetCommand(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const554 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
555     Compilation &C, const JobAction &JA, const InputInfo &Output,
556     const InputInfoList &Inputs, const ArgList &Args,
557     const char *LinkingOutput) const {
558   ArgStringList CmdArgs;
559   CmdArgs.push_back("/nologo");
560   CmdArgs.push_back("/c");  // Compile only.
561   CmdArgs.push_back("/W0"); // No warnings.
562 
563   // The goal is to be able to invoke this tool correctly based on
564   // any flag accepted by clang-cl.
565 
566   // These are spelled the same way in clang and cl.exe,.
567   Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
568 
569   // Optimization level.
570   if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
571     CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
572                                                                       : "/Oi-");
573   if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
574     if (A->getOption().getID() == options::OPT_O0) {
575       CmdArgs.push_back("/Od");
576     } else {
577       CmdArgs.push_back("/Og");
578 
579       StringRef OptLevel = A->getValue();
580       if (OptLevel == "s" || OptLevel == "z")
581         CmdArgs.push_back("/Os");
582       else
583         CmdArgs.push_back("/Ot");
584 
585       CmdArgs.push_back("/Ob2");
586     }
587   }
588   if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
589                                options::OPT_fno_omit_frame_pointer))
590     CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
591                           ? "/Oy"
592                           : "/Oy-");
593   if (!Args.hasArg(options::OPT_fwritable_strings))
594     CmdArgs.push_back("/GF");
595 
596   // Flags for which clang-cl has an alias.
597   // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
598 
599   if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
600                    /*default=*/false))
601     CmdArgs.push_back("/GR-");
602 
603   if (Args.hasFlag(options::OPT__SLASH_GS_, options::OPT__SLASH_GS,
604                    /*default=*/false))
605     CmdArgs.push_back("/GS-");
606 
607   if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
608                                options::OPT_fno_function_sections))
609     CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
610                           ? "/Gy"
611                           : "/Gy-");
612   if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
613                                options::OPT_fno_data_sections))
614     CmdArgs.push_back(
615         A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
616   if (Args.hasArg(options::OPT_fsyntax_only))
617     CmdArgs.push_back("/Zs");
618   if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
619                   options::OPT__SLASH_Z7))
620     CmdArgs.push_back("/Z7");
621 
622   std::vector<std::string> Includes =
623       Args.getAllArgValues(options::OPT_include);
624   for (const auto &Include : Includes)
625     CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
626 
627   // Flags that can simply be passed through.
628   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
629   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
630   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
631   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
632   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
633   Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
634 
635   // The order of these flags is relevant, so pick the last one.
636   if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
637                                options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
638     A->render(Args, CmdArgs);
639 
640   // Use MSVC's default threadsafe statics behaviour unless there was a flag.
641   if (Arg *A = Args.getLastArg(options::OPT_fthreadsafe_statics,
642                                options::OPT_fno_threadsafe_statics)) {
643     CmdArgs.push_back(A->getOption().getID() == options::OPT_fthreadsafe_statics
644                           ? "/Zc:threadSafeInit"
645                           : "/Zc:threadSafeInit-");
646   }
647 
648   // Pass through all unknown arguments so that the fallback command can see
649   // them too.
650   Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
651 
652   // Input filename.
653   assert(Inputs.size() == 1);
654   const InputInfo &II = Inputs[0];
655   assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
656   CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
657   if (II.isFilename())
658     CmdArgs.push_back(II.getFilename());
659   else
660     II.getInputArg().renderAsInput(Args, CmdArgs);
661 
662   // Output filename.
663   assert(Output.getType() == types::TY_Object);
664   const char *Fo =
665       Args.MakeArgString(std::string("/Fo") + Output.getFilename());
666   CmdArgs.push_back(Fo);
667 
668   std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe");
669   return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
670                                     CmdArgs, Inputs);
671 }
672 
MSVCToolChain(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)673 MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple &Triple,
674                              const ArgList &Args)
675     : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args) {
676   getProgramPaths().push_back(getDriver().getInstalledDir());
677   if (getDriver().getInstalledDir() != getDriver().Dir)
678     getProgramPaths().push_back(getDriver().Dir);
679 
680   // Check the environment first, since that's probably the user telling us
681   // what they want to use.
682   // Failing that, just try to find the newest Visual Studio version we can
683   // and use its default VC toolchain.
684   findVCToolChainViaEnvironment(VCToolChainPath, VSLayout) ||
685       findVCToolChainViaSetupConfig(VCToolChainPath, VSLayout) ||
686       findVCToolChainViaRegistry(VCToolChainPath, VSLayout);
687 }
688 
buildLinker() const689 Tool *MSVCToolChain::buildLinker() const {
690   return new tools::visualstudio::Linker(*this);
691 }
692 
buildAssembler() const693 Tool *MSVCToolChain::buildAssembler() const {
694   if (getTriple().isOSBinFormatMachO())
695     return new tools::darwin::Assembler(*this);
696   getDriver().Diag(clang::diag::err_no_external_assembler);
697   return nullptr;
698 }
699 
IsIntegratedAssemblerDefault() const700 bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
701   return true;
702 }
703 
IsUnwindTablesDefault(const ArgList & Args) const704 bool MSVCToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
705   // Emit unwind tables by default on Win64. All non-x86_32 Windows platforms
706   // such as ARM and PPC actually require unwind tables, but LLVM doesn't know
707   // how to generate them yet.
708 
709   // Don't emit unwind tables by default for MachO targets.
710   if (getTriple().isOSBinFormatMachO())
711     return false;
712 
713   return getArch() == llvm::Triple::x86_64;
714 }
715 
isPICDefault() const716 bool MSVCToolChain::isPICDefault() const {
717   return getArch() == llvm::Triple::x86_64;
718 }
719 
isPIEDefault() const720 bool MSVCToolChain::isPIEDefault() const {
721   return false;
722 }
723 
isPICDefaultForced() const724 bool MSVCToolChain::isPICDefaultForced() const {
725   return getArch() == llvm::Triple::x86_64;
726 }
727 
AddCudaIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const728 void MSVCToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
729                                        ArgStringList &CC1Args) const {
730   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
731 }
732 
printVerboseInfo(raw_ostream & OS) const733 void MSVCToolChain::printVerboseInfo(raw_ostream &OS) const {
734   CudaInstallation.print(OS);
735 }
736 
737 // Windows SDKs and VC Toolchains group their contents into subdirectories based
738 // on the target architecture. This function converts an llvm::Triple::ArchType
739 // to the corresponding subdirectory name.
llvmArchToWindowsSDKArch(llvm::Triple::ArchType Arch)740 static const char *llvmArchToWindowsSDKArch(llvm::Triple::ArchType Arch) {
741   using ArchType = llvm::Triple::ArchType;
742   switch (Arch) {
743   case ArchType::x86:
744     return "x86";
745   case ArchType::x86_64:
746     return "x64";
747   case ArchType::arm:
748     return "arm";
749   case ArchType::aarch64:
750     return "arm64";
751   default:
752     return "";
753   }
754 }
755 
756 // Similar to the above function, but for Visual Studios before VS2017.
llvmArchToLegacyVCArch(llvm::Triple::ArchType Arch)757 static const char *llvmArchToLegacyVCArch(llvm::Triple::ArchType Arch) {
758   using ArchType = llvm::Triple::ArchType;
759   switch (Arch) {
760   case ArchType::x86:
761     // x86 is default in legacy VC toolchains.
762     // e.g. x86 libs are directly in /lib as opposed to /lib/x86.
763     return "";
764   case ArchType::x86_64:
765     return "amd64";
766   case ArchType::arm:
767     return "arm";
768   case ArchType::aarch64:
769     return "arm64";
770   default:
771     return "";
772   }
773 }
774 
775 // Similar to the above function, but for DevDiv internal builds.
llvmArchToDevDivInternalArch(llvm::Triple::ArchType Arch)776 static const char *llvmArchToDevDivInternalArch(llvm::Triple::ArchType Arch) {
777   using ArchType = llvm::Triple::ArchType;
778   switch (Arch) {
779   case ArchType::x86:
780     return "i386";
781   case ArchType::x86_64:
782     return "amd64";
783   case ArchType::arm:
784     return "arm";
785   case ArchType::aarch64:
786     return "arm64";
787   default:
788     return "";
789   }
790 }
791 
792 // Get the path to a specific subdirectory in the current toolchain for
793 // a given target architecture.
794 // VS2017 changed the VC toolchain layout, so this should be used instead
795 // of hardcoding paths.
796 std::string
getSubDirectoryPath(SubDirectoryType Type,llvm::Triple::ArchType TargetArch) const797 MSVCToolChain::getSubDirectoryPath(SubDirectoryType Type,
798                                    llvm::Triple::ArchType TargetArch) const {
799   const char *SubdirName;
800   const char *IncludeName;
801   switch (VSLayout) {
802   case ToolsetLayout::OlderVS:
803     SubdirName = llvmArchToLegacyVCArch(TargetArch);
804     IncludeName = "include";
805     break;
806   case ToolsetLayout::VS2017OrNewer:
807     SubdirName = llvmArchToWindowsSDKArch(TargetArch);
808     IncludeName = "include";
809     break;
810   case ToolsetLayout::DevDivInternal:
811     SubdirName = llvmArchToDevDivInternalArch(TargetArch);
812     IncludeName = "inc";
813     break;
814   }
815 
816   llvm::SmallString<256> Path(VCToolChainPath);
817   switch (Type) {
818   case SubDirectoryType::Bin:
819     if (VSLayout == ToolsetLayout::VS2017OrNewer) {
820       const bool HostIsX64 =
821           llvm::Triple(llvm::sys::getProcessTriple()).isArch64Bit();
822       const char *const HostName = HostIsX64 ? "HostX64" : "HostX86";
823       llvm::sys::path::append(Path, "bin", HostName, SubdirName);
824     } else { // OlderVS or DevDivInternal
825       llvm::sys::path::append(Path, "bin", SubdirName);
826     }
827     break;
828   case SubDirectoryType::Include:
829     llvm::sys::path::append(Path, IncludeName);
830     break;
831   case SubDirectoryType::Lib:
832     llvm::sys::path::append(Path, "lib", SubdirName);
833     break;
834   }
835   return Path.str();
836 }
837 
838 #ifdef _WIN32
readFullStringValue(HKEY hkey,const char * valueName,std::string & value)839 static bool readFullStringValue(HKEY hkey, const char *valueName,
840                                 std::string &value) {
841   std::wstring WideValueName;
842   if (!llvm::ConvertUTF8toWide(valueName, WideValueName))
843     return false;
844 
845   DWORD result = 0;
846   DWORD valueSize = 0;
847   DWORD type = 0;
848   // First just query for the required size.
849   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, &type, NULL,
850                             &valueSize);
851   if (result != ERROR_SUCCESS || type != REG_SZ || !valueSize)
852     return false;
853   std::vector<BYTE> buffer(valueSize);
854   result = RegQueryValueExW(hkey, WideValueName.c_str(), NULL, NULL, &buffer[0],
855                             &valueSize);
856   if (result == ERROR_SUCCESS) {
857     std::wstring WideValue(reinterpret_cast<const wchar_t *>(buffer.data()),
858                            valueSize / sizeof(wchar_t));
859     if (valueSize && WideValue.back() == L'\0') {
860       WideValue.pop_back();
861     }
862     // The destination buffer must be empty as an invariant of the conversion
863     // function; but this function is sometimes called in a loop that passes in
864     // the same buffer, however. Simply clear it out so we can overwrite it.
865     value.clear();
866     return llvm::convertWideToUTF8(WideValue, value);
867   }
868   return false;
869 }
870 #endif
871 
872 /// Read registry string.
873 /// This also supports a means to look for high-versioned keys by use
874 /// of a $VERSION placeholder in the key path.
875 /// $VERSION in the key path is a placeholder for the version number,
876 /// causing the highest value path to be searched for and used.
877 /// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
878 /// There can be additional characters in the component.  Only the numeric
879 /// characters are compared.  This function only searches HKLM.
getSystemRegistryString(const char * keyPath,const char * valueName,std::string & value,std::string * phValue)880 static bool getSystemRegistryString(const char *keyPath, const char *valueName,
881                                     std::string &value, std::string *phValue) {
882 #ifndef _WIN32
883   return false;
884 #else
885   HKEY hRootKey = HKEY_LOCAL_MACHINE;
886   HKEY hKey = NULL;
887   long lResult;
888   bool returnValue = false;
889 
890   const char *placeHolder = strstr(keyPath, "$VERSION");
891   std::string bestName;
892   // If we have a $VERSION placeholder, do the highest-version search.
893   if (placeHolder) {
894     const char *keyEnd = placeHolder - 1;
895     const char *nextKey = placeHolder;
896     // Find end of previous key.
897     while ((keyEnd > keyPath) && (*keyEnd != '\\'))
898       keyEnd--;
899     // Find end of key containing $VERSION.
900     while (*nextKey && (*nextKey != '\\'))
901       nextKey++;
902     size_t partialKeyLength = keyEnd - keyPath;
903     char partialKey[256];
904     if (partialKeyLength >= sizeof(partialKey))
905       partialKeyLength = sizeof(partialKey) - 1;
906     strncpy(partialKey, keyPath, partialKeyLength);
907     partialKey[partialKeyLength] = '\0';
908     HKEY hTopKey = NULL;
909     lResult = RegOpenKeyExA(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
910                             &hTopKey);
911     if (lResult == ERROR_SUCCESS) {
912       char keyName[256];
913       double bestValue = 0.0;
914       DWORD index, size = sizeof(keyName) - 1;
915       for (index = 0; RegEnumKeyExA(hTopKey, index, keyName, &size, NULL, NULL,
916                                     NULL, NULL) == ERROR_SUCCESS;
917            index++) {
918         const char *sp = keyName;
919         while (*sp && !isDigit(*sp))
920           sp++;
921         if (!*sp)
922           continue;
923         const char *ep = sp + 1;
924         while (*ep && (isDigit(*ep) || (*ep == '.')))
925           ep++;
926         char numBuf[32];
927         strncpy(numBuf, sp, sizeof(numBuf) - 1);
928         numBuf[sizeof(numBuf) - 1] = '\0';
929         double dvalue = strtod(numBuf, NULL);
930         if (dvalue > bestValue) {
931           // Test that InstallDir is indeed there before keeping this index.
932           // Open the chosen key path remainder.
933           bestName = keyName;
934           // Append rest of key.
935           bestName.append(nextKey);
936           lResult = RegOpenKeyExA(hTopKey, bestName.c_str(), 0,
937                                   KEY_READ | KEY_WOW64_32KEY, &hKey);
938           if (lResult == ERROR_SUCCESS) {
939             if (readFullStringValue(hKey, valueName, value)) {
940               bestValue = dvalue;
941               if (phValue)
942                 *phValue = bestName;
943               returnValue = true;
944             }
945             RegCloseKey(hKey);
946           }
947         }
948         size = sizeof(keyName) - 1;
949       }
950       RegCloseKey(hTopKey);
951     }
952   } else {
953     lResult =
954         RegOpenKeyExA(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
955     if (lResult == ERROR_SUCCESS) {
956       if (readFullStringValue(hKey, valueName, value))
957         returnValue = true;
958       if (phValue)
959         phValue->clear();
960       RegCloseKey(hKey);
961     }
962   }
963   return returnValue;
964 #endif // _WIN32
965 }
966 
967 // Find the most recent version of Universal CRT or Windows 10 SDK.
968 // vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
969 // directory by name and uses the last one of the list.
970 // So we compare entry names lexicographically to find the greatest one.
getWindows10SDKVersionFromPath(const std::string & SDKPath,std::string & SDKVersion)971 static bool getWindows10SDKVersionFromPath(const std::string &SDKPath,
972                                            std::string &SDKVersion) {
973   SDKVersion.clear();
974 
975   std::error_code EC;
976   llvm::SmallString<128> IncludePath(SDKPath);
977   llvm::sys::path::append(IncludePath, "Include");
978   for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd;
979        DirIt != DirEnd && !EC; DirIt.increment(EC)) {
980     if (!llvm::sys::fs::is_directory(DirIt->path()))
981       continue;
982     StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
983     // If WDK is installed, there could be subfolders like "wdf" in the
984     // "Include" directory.
985     // Allow only directories which names start with "10.".
986     if (!CandidateName.startswith("10."))
987       continue;
988     if (CandidateName > SDKVersion)
989       SDKVersion = CandidateName;
990   }
991 
992   return !SDKVersion.empty();
993 }
994 
995 /// Get Windows SDK installation directory.
getWindowsSDKDir(std::string & Path,int & Major,std::string & WindowsSDKIncludeVersion,std::string & WindowsSDKLibVersion)996 static bool getWindowsSDKDir(std::string &Path, int &Major,
997                              std::string &WindowsSDKIncludeVersion,
998                              std::string &WindowsSDKLibVersion) {
999   std::string RegistrySDKVersion;
1000   // Try the Windows registry.
1001   if (!getSystemRegistryString(
1002           "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
1003           "InstallationFolder", Path, &RegistrySDKVersion))
1004     return false;
1005   if (Path.empty() || RegistrySDKVersion.empty())
1006     return false;
1007 
1008   WindowsSDKIncludeVersion.clear();
1009   WindowsSDKLibVersion.clear();
1010   Major = 0;
1011   std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
1012   if (Major <= 7)
1013     return true;
1014   if (Major == 8) {
1015     // Windows SDK 8.x installs libraries in a folder whose names depend on the
1016     // version of the OS you're targeting.  By default choose the newest, which
1017     // usually corresponds to the version of the OS you've installed the SDK on.
1018     const char *Tests[] = {"winv6.3", "win8", "win7"};
1019     for (const char *Test : Tests) {
1020       llvm::SmallString<128> TestPath(Path);
1021       llvm::sys::path::append(TestPath, "Lib", Test);
1022       if (llvm::sys::fs::exists(TestPath.c_str())) {
1023         WindowsSDKLibVersion = Test;
1024         break;
1025       }
1026     }
1027     return !WindowsSDKLibVersion.empty();
1028   }
1029   if (Major == 10) {
1030     if (!getWindows10SDKVersionFromPath(Path, WindowsSDKIncludeVersion))
1031       return false;
1032     WindowsSDKLibVersion = WindowsSDKIncludeVersion;
1033     return true;
1034   }
1035   // Unsupported SDK version
1036   return false;
1037 }
1038 
1039 // Gets the library path required to link against the Windows SDK.
getWindowsSDKLibraryPath(std::string & path) const1040 bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
1041   std::string sdkPath;
1042   int sdkMajor = 0;
1043   std::string windowsSDKIncludeVersion;
1044   std::string windowsSDKLibVersion;
1045 
1046   path.clear();
1047   if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion,
1048                         windowsSDKLibVersion))
1049     return false;
1050 
1051   llvm::SmallString<128> libPath(sdkPath);
1052   llvm::sys::path::append(libPath, "Lib");
1053   if (sdkMajor >= 8) {
1054     llvm::sys::path::append(libPath, windowsSDKLibVersion, "um",
1055                             llvmArchToWindowsSDKArch(getArch()));
1056   } else {
1057     switch (getArch()) {
1058     // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
1059     case llvm::Triple::x86:
1060       break;
1061     case llvm::Triple::x86_64:
1062       llvm::sys::path::append(libPath, "x64");
1063       break;
1064     case llvm::Triple::arm:
1065       // It is not necessary to link against Windows SDK 7.x when targeting ARM.
1066       return false;
1067     default:
1068       return false;
1069     }
1070   }
1071 
1072   path = libPath.str();
1073   return true;
1074 }
1075 
1076 // Check if the Include path of a specified version of Visual Studio contains
1077 // specific header files. If not, they are probably shipped with Universal CRT.
useUniversalCRT() const1078 bool MSVCToolChain::useUniversalCRT() const {
1079   llvm::SmallString<128> TestPath(
1080       getSubDirectoryPath(SubDirectoryType::Include));
1081   llvm::sys::path::append(TestPath, "stdlib.h");
1082   return !llvm::sys::fs::exists(TestPath);
1083 }
1084 
getUniversalCRTSdkDir(std::string & Path,std::string & UCRTVersion)1085 static bool getUniversalCRTSdkDir(std::string &Path, std::string &UCRTVersion) {
1086   // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
1087   // for the specific key "KitsRoot10". So do we.
1088   if (!getSystemRegistryString(
1089           "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
1090           Path, nullptr))
1091     return false;
1092 
1093   return getWindows10SDKVersionFromPath(Path, UCRTVersion);
1094 }
1095 
getUniversalCRTLibraryPath(std::string & Path) const1096 bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const {
1097   std::string UniversalCRTSdkPath;
1098   std::string UCRTVersion;
1099 
1100   Path.clear();
1101   if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion))
1102     return false;
1103 
1104   StringRef ArchName = llvmArchToWindowsSDKArch(getArch());
1105   if (ArchName.empty())
1106     return false;
1107 
1108   llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
1109   llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
1110 
1111   Path = LibPath.str();
1112   return true;
1113 }
1114 
getMSVCVersionFromTriple(const llvm::Triple & Triple)1115 static VersionTuple getMSVCVersionFromTriple(const llvm::Triple &Triple) {
1116   unsigned Major, Minor, Micro;
1117   Triple.getEnvironmentVersion(Major, Minor, Micro);
1118   if (Major || Minor || Micro)
1119     return VersionTuple(Major, Minor, Micro);
1120   return VersionTuple();
1121 }
1122 
getMSVCVersionFromExe(const std::string & BinDir)1123 static VersionTuple getMSVCVersionFromExe(const std::string &BinDir) {
1124   VersionTuple Version;
1125 #ifdef _WIN32
1126   SmallString<128> ClExe(BinDir);
1127   llvm::sys::path::append(ClExe, "cl.exe");
1128 
1129   std::wstring ClExeWide;
1130   if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
1131     return Version;
1132 
1133   const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
1134                                                       nullptr);
1135   if (VersionSize == 0)
1136     return Version;
1137 
1138   SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
1139   if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
1140                              VersionBlock.data()))
1141     return Version;
1142 
1143   VS_FIXEDFILEINFO *FileInfo = nullptr;
1144   UINT FileInfoSize = 0;
1145   if (!::VerQueryValueW(VersionBlock.data(), L"\\",
1146                         reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
1147       FileInfoSize < sizeof(*FileInfo))
1148     return Version;
1149 
1150   const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
1151   const unsigned Minor = (FileInfo->dwFileVersionMS      ) & 0xFFFF;
1152   const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
1153 
1154   Version = VersionTuple(Major, Minor, Micro);
1155 #endif
1156   return Version;
1157 }
1158 
AddSystemIncludeWithSubfolder(const ArgList & DriverArgs,ArgStringList & CC1Args,const std::string & folder,const Twine & subfolder1,const Twine & subfolder2,const Twine & subfolder3) const1159 void MSVCToolChain::AddSystemIncludeWithSubfolder(
1160     const ArgList &DriverArgs, ArgStringList &CC1Args,
1161     const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
1162     const Twine &subfolder3) const {
1163   llvm::SmallString<128> path(folder);
1164   llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
1165   addSystemInclude(DriverArgs, CC1Args, path);
1166 }
1167 
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1168 void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1169                                               ArgStringList &CC1Args) const {
1170   if (DriverArgs.hasArg(options::OPT_nostdinc))
1171     return;
1172 
1173   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
1174     AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
1175                                   "include");
1176   }
1177 
1178   // Add %INCLUDE%-like directories from the -imsvc flag.
1179   for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
1180     addSystemInclude(DriverArgs, CC1Args, Path);
1181 
1182   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
1183     return;
1184 
1185   // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
1186   if (llvm::Optional<std::string> cl_include_dir =
1187           llvm::sys::Process::GetEnv("INCLUDE")) {
1188     SmallVector<StringRef, 8> Dirs;
1189     StringRef(*cl_include_dir)
1190         .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1191     for (StringRef Dir : Dirs)
1192       addSystemInclude(DriverArgs, CC1Args, Dir);
1193     if (!Dirs.empty())
1194       return;
1195   }
1196 
1197   // When built with access to the proper Windows APIs, try to actually find
1198   // the correct include paths first.
1199   if (!VCToolChainPath.empty()) {
1200     addSystemInclude(DriverArgs, CC1Args,
1201                      getSubDirectoryPath(SubDirectoryType::Include));
1202 
1203     if (useUniversalCRT()) {
1204       std::string UniversalCRTSdkPath;
1205       std::string UCRTVersion;
1206       if (getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) {
1207         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
1208                                       "Include", UCRTVersion, "ucrt");
1209       }
1210     }
1211 
1212     std::string WindowsSDKDir;
1213     int major;
1214     std::string windowsSDKIncludeVersion;
1215     std::string windowsSDKLibVersion;
1216     if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion,
1217                          windowsSDKLibVersion)) {
1218       if (major >= 8) {
1219         // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
1220         // Anyway, llvm::sys::path::append is able to manage it.
1221         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1222                                       "include", windowsSDKIncludeVersion,
1223                                       "shared");
1224         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1225                                       "include", windowsSDKIncludeVersion,
1226                                       "um");
1227         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1228                                       "include", windowsSDKIncludeVersion,
1229                                       "winrt");
1230       } else {
1231         AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
1232                                       "include");
1233       }
1234     }
1235 
1236     return;
1237   }
1238 
1239 #if defined(_WIN32)
1240   // As a fallback, select default install paths.
1241   // FIXME: Don't guess drives and paths like this on Windows.
1242   const StringRef Paths[] = {
1243     "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
1244     "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
1245     "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
1246     "C:/Program Files/Microsoft Visual Studio 8/VC/include",
1247     "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
1248   };
1249   addSystemIncludes(DriverArgs, CC1Args, Paths);
1250 #endif
1251 }
1252 
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1253 void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1254                                                  ArgStringList &CC1Args) const {
1255   // FIXME: There should probably be logic here to find libc++ on Windows.
1256 }
1257 
computeMSVCVersion(const Driver * D,const ArgList & Args) const1258 VersionTuple MSVCToolChain::computeMSVCVersion(const Driver *D,
1259                                                const ArgList &Args) const {
1260   bool IsWindowsMSVC = getTriple().isWindowsMSVCEnvironment();
1261   VersionTuple MSVT = ToolChain::computeMSVCVersion(D, Args);
1262   if (MSVT.empty())
1263     MSVT = getMSVCVersionFromTriple(getTriple());
1264   if (MSVT.empty() && IsWindowsMSVC)
1265     MSVT = getMSVCVersionFromExe(getSubDirectoryPath(SubDirectoryType::Bin));
1266   if (MSVT.empty() &&
1267       Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
1268                    IsWindowsMSVC)) {
1269     // -fms-compatibility-version=19.11 is default, aka 2017
1270     MSVT = VersionTuple(19, 11);
1271   }
1272   return MSVT;
1273 }
1274 
1275 std::string
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const1276 MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1277                                            types::ID InputType) const {
1278   // The MSVC version doesn't care about the architecture, even though it
1279   // may look at the triple internally.
1280   VersionTuple MSVT = computeMSVCVersion(/*D=*/nullptr, Args);
1281   MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
1282                       MSVT.getSubminor().getValueOr(0));
1283 
1284   // For the rest of the triple, however, a computed architecture name may
1285   // be needed.
1286   llvm::Triple Triple(ToolChain::ComputeEffectiveClangTriple(Args, InputType));
1287   if (Triple.getEnvironment() == llvm::Triple::MSVC) {
1288     StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
1289     if (ObjFmt.empty())
1290       Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
1291     else
1292       Triple.setEnvironmentName(
1293           (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
1294   }
1295   return Triple.getTriple();
1296 }
1297 
getSupportedSanitizers() const1298 SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
1299   SanitizerMask Res = ToolChain::getSupportedSanitizers();
1300   Res |= SanitizerKind::Address;
1301   Res &= ~SanitizerKind::CFIMFCall;
1302   return Res;
1303 }
1304 
TranslateOptArg(Arg * A,llvm::opt::DerivedArgList & DAL,bool SupportsForcingFramePointer,const char * ExpandChar,const OptTable & Opts)1305 static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1306                             bool SupportsForcingFramePointer,
1307                             const char *ExpandChar, const OptTable &Opts) {
1308   assert(A->getOption().matches(options::OPT__SLASH_O));
1309 
1310   StringRef OptStr = A->getValue();
1311   for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1312     const char &OptChar = *(OptStr.data() + I);
1313     switch (OptChar) {
1314     default:
1315       break;
1316     case '1':
1317     case '2':
1318     case 'x':
1319     case 'd':
1320       // Ignore /O[12xd] flags that aren't the last one on the command line.
1321       // Only the last one gets expanded.
1322       if (&OptChar != ExpandChar) {
1323         A->claim();
1324         break;
1325       }
1326       if (OptChar == 'd') {
1327         DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
1328       } else {
1329         if (OptChar == '1') {
1330           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1331         } else if (OptChar == '2' || OptChar == 'x') {
1332           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1333           DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
1334         }
1335         if (SupportsForcingFramePointer &&
1336             !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
1337           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fomit_frame_pointer));
1338         if (OptChar == '1' || OptChar == '2')
1339           DAL.AddFlagArg(A, Opts.getOption(options::OPT_ffunction_sections));
1340       }
1341       break;
1342     case 'b':
1343       if (I + 1 != E && isdigit(OptStr[I + 1])) {
1344         switch (OptStr[I + 1]) {
1345         case '0':
1346           DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
1347           break;
1348         case '1':
1349           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_hint_functions));
1350           break;
1351         case '2':
1352           DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
1353           break;
1354         }
1355         ++I;
1356       }
1357       break;
1358     case 'g':
1359       break;
1360     case 'i':
1361       if (I + 1 != E && OptStr[I + 1] == '-') {
1362         ++I;
1363         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
1364       } else {
1365         DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
1366       }
1367       break;
1368     case 's':
1369       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
1370       break;
1371     case 't':
1372       DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
1373       break;
1374     case 'y': {
1375       bool OmitFramePointer = true;
1376       if (I + 1 != E && OptStr[I + 1] == '-') {
1377         OmitFramePointer = false;
1378         ++I;
1379       }
1380       if (SupportsForcingFramePointer) {
1381         if (OmitFramePointer)
1382           DAL.AddFlagArg(A,
1383                          Opts.getOption(options::OPT_fomit_frame_pointer));
1384         else
1385           DAL.AddFlagArg(
1386               A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
1387       } else {
1388         // Don't warn about /Oy- in 64-bit builds (where
1389         // SupportsForcingFramePointer is false).  The flag having no effect
1390         // there is a compiler-internal optimization, and people shouldn't have
1391         // to special-case their build files for 64-bit clang-cl.
1392         A->claim();
1393       }
1394       break;
1395     }
1396     }
1397   }
1398 }
1399 
TranslateDArg(Arg * A,llvm::opt::DerivedArgList & DAL,const OptTable & Opts)1400 static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
1401                           const OptTable &Opts) {
1402   assert(A->getOption().matches(options::OPT_D));
1403 
1404   StringRef Val = A->getValue();
1405   size_t Hash = Val.find('#');
1406   if (Hash == StringRef::npos || Hash > Val.find('=')) {
1407     DAL.append(A);
1408     return;
1409   }
1410 
1411   std::string NewVal = Val;
1412   NewVal[Hash] = '=';
1413   DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
1414 }
1415 
1416 llvm::opt::DerivedArgList *
TranslateArgs(const llvm::opt::DerivedArgList & Args,StringRef BoundArch,Action::OffloadKind) const1417 MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
1418                              StringRef BoundArch, Action::OffloadKind) const {
1419   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1420   const OptTable &Opts = getDriver().getOpts();
1421 
1422   // /Oy and /Oy- only has an effect under X86-32.
1423   bool SupportsForcingFramePointer = getArch() == llvm::Triple::x86;
1424 
1425   // The -O[12xd] flag actually expands to several flags.  We must desugar the
1426   // flags so that options embedded can be negated.  For example, the '-O2' flag
1427   // enables '-Oy'.  Expanding '-O2' into its constituent flags allows us to
1428   // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
1429   // aspect of '-O2'.
1430   //
1431   // Note that this expansion logic only applies to the *last* of '[12xd]'.
1432 
1433   // First step is to search for the character we'd like to expand.
1434   const char *ExpandChar = nullptr;
1435   for (Arg *A : Args.filtered(options::OPT__SLASH_O)) {
1436     StringRef OptStr = A->getValue();
1437     for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
1438       char OptChar = OptStr[I];
1439       char PrevChar = I > 0 ? OptStr[I - 1] : '0';
1440       if (PrevChar == 'b') {
1441         // OptChar does not expand; it's an argument to the previous char.
1442         continue;
1443       }
1444       if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
1445         ExpandChar = OptStr.data() + I;
1446     }
1447   }
1448 
1449   for (Arg *A : Args) {
1450     if (A->getOption().matches(options::OPT__SLASH_O)) {
1451       // The -O flag actually takes an amalgam of other options.  For example,
1452       // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
1453       TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
1454     } else if (A->getOption().matches(options::OPT_D)) {
1455       // Translate -Dfoo#bar into -Dfoo=bar.
1456       TranslateDArg(A, *DAL, Opts);
1457     } else {
1458       DAL->append(A);
1459     }
1460   }
1461 
1462   return DAL;
1463 }
1464