blob: 190df24e5a07f2b24c5036b39dcd6d0875ae83cf [file] [log] [blame]
Chandler Carruth1fc603e2011-12-17 23:10:01 +00001//===--- 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 "ToolChains.h"
David Majnemere11d3732015-06-08 00:22:46 +000011#include "Tools.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000012#include "clang/Basic/CharInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/Version.h"
Chandler Carruth1fc603e2011-12-17 23:10:01 +000014#include "clang/Driver/Compilation.h"
15#include "clang/Driver/Driver.h"
Rafael Espindola79764462013-03-24 15:06:53 +000016#include "clang/Driver/DriverDiagnostic.h"
Chandler Carruth1fc603e2011-12-17 23:10:01 +000017#include "clang/Driver/Options.h"
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000018#include "llvm/ADT/StringExtras.h"
Alp Tokerf1ffc842014-06-22 04:31:15 +000019#include "llvm/Config/llvm-config.h"
Reid Kleckner898229a2013-06-14 17:17:23 +000020#include "llvm/Option/Arg.h"
21#include "llvm/Option/ArgList.h"
Adrian McCarthye4b26fc2016-05-13 23:20:11 +000022#include "llvm/Support/ConvertUTF.h"
Chandler Carruth1fc603e2011-12-17 23:10:01 +000023#include "llvm/Support/ErrorHandling.h"
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000024#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/Process.h"
Reid Kleckner6b7156b2015-01-23 19:16:25 +000026#include <cstdio>
27
Chandler Carruth1fc603e2011-12-17 23:10:01 +000028// Include the necessary headers to interface with the Windows registry and
29// environment.
Alp Tokerf1ffc842014-06-22 04:31:15 +000030#if defined(LLVM_ON_WIN32)
Alp Tokerfcce1832014-06-22 03:27:45 +000031#define USE_WIN32
32#endif
33
34#ifdef USE_WIN32
Chandler Carruth1fc603e2011-12-17 23:10:01 +000035 #define WIN32_LEAN_AND_MEAN
36 #define NOGDI
Yaron Keren7fc6f1e2014-12-04 21:46:50 +000037 #ifndef NOMINMAX
38 #define NOMINMAX
39 #endif
Logan Chien733e3c62014-06-24 16:18:10 +000040 #include <windows.h>
Chandler Carruth1fc603e2011-12-17 23:10:01 +000041#endif
42
43using namespace clang::driver;
44using namespace clang::driver::toolchains;
45using namespace clang;
Reid Kleckner898229a2013-06-14 17:17:23 +000046using namespace llvm::opt;
Chandler Carruth1fc603e2011-12-17 23:10:01 +000047
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000048MSVCToolChain::MSVCToolChain(const Driver &D, const llvm::Triple& Triple,
49 const ArgList &Args)
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000050 : ToolChain(D, Triple, Args) {
Zachary Turner719f58c2014-12-01 23:06:47 +000051 getProgramPaths().push_back(getDriver().getInstalledDir());
52 if (getDriver().getInstalledDir() != getDriver().Dir)
53 getProgramPaths().push_back(getDriver().Dir);
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000054}
55
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000056Tool *MSVCToolChain::buildLinker() const {
Douglas Katzman95354292015-06-23 20:42:09 +000057 return new tools::visualstudio::Linker(*this);
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000058}
59
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000060Tool *MSVCToolChain::buildAssembler() const {
Saleem Abdulrasool377066a2014-03-27 22:50:18 +000061 if (getTriple().isOSBinFormatMachO())
Douglas Katzman95354292015-06-23 20:42:09 +000062 return new tools::darwin::Assembler(*this);
Alp Tokerc8d4f0f2013-11-22 08:27:46 +000063 getDriver().Diag(clang::diag::err_no_external_assembler);
Craig Topper92fc2df2014-05-17 16:56:41 +000064 return nullptr;
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000065}
66
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000067bool MSVCToolChain::IsIntegratedAssemblerDefault() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000068 return true;
69}
70
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000071bool MSVCToolChain::IsUnwindTablesDefault() const {
Reid Kleckner6b3a9402014-09-04 18:13:12 +000072 // Emit unwind tables by default on Win64. All non-x86_32 Windows platforms
73 // such as ARM and PPC actually require unwind tables, but LLVM doesn't know
74 // how to generate them yet.
Akira Hatanakae4218132016-05-05 01:41:07 +000075
76 // Don't emit unwind tables by default for MachO targets.
77 if (getTriple().isOSBinFormatMachO())
78 return false;
79
Reid Kleckner6b3a9402014-09-04 18:13:12 +000080 return getArch() == llvm::Triple::x86_64;
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000081}
82
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000083bool MSVCToolChain::isPICDefault() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000084 return getArch() == llvm::Triple::x86_64;
85}
86
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000087bool MSVCToolChain::isPIEDefault() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000088 return false;
89}
90
Saleem Abdulrasool819f3912014-10-22 02:37:29 +000091bool MSVCToolChain::isPICDefaultForced() const {
Hans Wennborg1cc6cce2013-08-30 09:42:06 +000092 return getArch() == llvm::Triple::x86_64;
93}
94
Zachary Turner0eaf8fc2014-10-22 20:40:28 +000095#ifdef USE_WIN32
96static bool readFullStringValue(HKEY hkey, const char *valueName,
97 std::string &value) {
98 // FIXME: We should be using the W versions of the registry functions, but
99 // doing so requires UTF8 / UTF16 conversions similar to how we handle command
100 // line arguments. The UTF8 conversion functions are not exposed publicly
101 // from LLVM though, so in order to do this we will probably need to create
102 // a registry abstraction in LLVMSupport that is Windows only.
103 DWORD result = 0;
104 DWORD valueSize = 0;
105 DWORD type = 0;
106 // First just query for the required size.
107 result = RegQueryValueEx(hkey, valueName, NULL, &type, NULL, &valueSize);
108 if (result != ERROR_SUCCESS || type != REG_SZ)
109 return false;
110 std::vector<BYTE> buffer(valueSize);
111 result = RegQueryValueEx(hkey, valueName, NULL, NULL, &buffer[0], &valueSize);
112 if (result == ERROR_SUCCESS)
113 value.assign(reinterpret_cast<const char *>(buffer.data()));
114 return result;
115}
116#endif
117
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000118/// \brief Read registry string.
119/// This also supports a means to look for high-versioned keys by use
120/// of a $VERSION placeholder in the key path.
121/// $VERSION in the key path is a placeholder for the version number,
122/// causing the highest value path to be searched for and used.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000123/// I.e. "SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
124/// There can be additional characters in the component. Only the numeric
125/// characters are compared. This function only searches HKLM.
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000126static bool getSystemRegistryString(const char *keyPath, const char *valueName,
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000127 std::string &value, std::string *phValue) {
Alp Tokerfcce1832014-06-22 03:27:45 +0000128#ifndef USE_WIN32
129 return false;
130#else
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000131 HKEY hRootKey = HKEY_LOCAL_MACHINE;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000132 HKEY hKey = NULL;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000133 long lResult;
134 bool returnValue = false;
135
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000136 const char *placeHolder = strstr(keyPath, "$VERSION");
137 std::string bestName;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000138 // If we have a $VERSION placeholder, do the highest-version search.
139 if (placeHolder) {
140 const char *keyEnd = placeHolder - 1;
141 const char *nextKey = placeHolder;
142 // Find end of previous key.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000143 while ((keyEnd > keyPath) && (*keyEnd != '\\'))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000144 keyEnd--;
145 // Find end of key containing $VERSION.
146 while (*nextKey && (*nextKey != '\\'))
147 nextKey++;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000148 size_t partialKeyLength = keyEnd - keyPath;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000149 char partialKey[256];
Daniel Marjamakie1146692016-01-27 07:33:50 +0000150 if (partialKeyLength >= sizeof(partialKey))
151 partialKeyLength = sizeof(partialKey) - 1;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000152 strncpy(partialKey, keyPath, partialKeyLength);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000153 partialKey[partialKeyLength] = '\0';
154 HKEY hTopKey = NULL;
Hans Wennborg935d01d2013-10-09 23:41:48 +0000155 lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ | KEY_WOW64_32KEY,
156 &hTopKey);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000157 if (lResult == ERROR_SUCCESS) {
158 char keyName[256];
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000159 double bestValue = 0.0;
160 DWORD index, size = sizeof(keyName) - 1;
161 for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
162 NULL, NULL, NULL) == ERROR_SUCCESS; index++) {
163 const char *sp = keyName;
Jordan Rosea7d03842013-02-08 22:30:41 +0000164 while (*sp && !isDigit(*sp))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000165 sp++;
166 if (!*sp)
167 continue;
168 const char *ep = sp + 1;
Jordan Rosea7d03842013-02-08 22:30:41 +0000169 while (*ep && (isDigit(*ep) || (*ep == '.')))
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000170 ep++;
171 char numBuf[32];
172 strncpy(numBuf, sp, sizeof(numBuf) - 1);
173 numBuf[sizeof(numBuf) - 1] = '\0';
Hans Wennborgd2192312013-10-10 18:03:08 +0000174 double dvalue = strtod(numBuf, NULL);
175 if (dvalue > bestValue) {
176 // Test that InstallDir is indeed there before keeping this index.
177 // Open the chosen key path remainder.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000178 bestName = keyName;
Hans Wennborgd2192312013-10-10 18:03:08 +0000179 // Append rest of key.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000180 bestName.append(nextKey);
181 lResult = RegOpenKeyEx(hTopKey, bestName.c_str(), 0,
Hans Wennborgd2192312013-10-10 18:03:08 +0000182 KEY_READ | KEY_WOW64_32KEY, &hKey);
183 if (lResult == ERROR_SUCCESS) {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000184 lResult = readFullStringValue(hKey, valueName, value);
Hans Wennborgd2192312013-10-10 18:03:08 +0000185 if (lResult == ERROR_SUCCESS) {
Hans Wennborgd2192312013-10-10 18:03:08 +0000186 bestValue = dvalue;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000187 if (phValue)
188 *phValue = bestName;
Hans Wennborgd2192312013-10-10 18:03:08 +0000189 returnValue = true;
190 }
191 RegCloseKey(hKey);
192 }
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000193 }
194 size = sizeof(keyName) - 1;
195 }
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000196 RegCloseKey(hTopKey);
197 }
198 } else {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000199 lResult =
200 RegOpenKeyEx(hRootKey, keyPath, 0, KEY_READ | KEY_WOW64_32KEY, &hKey);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000201 if (lResult == ERROR_SUCCESS) {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000202 lResult = readFullStringValue(hKey, valueName, value);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000203 if (lResult == ERROR_SUCCESS)
204 returnValue = true;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000205 if (phValue)
206 phValue->clear();
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000207 RegCloseKey(hKey);
208 }
209 }
210 return returnValue;
Alp Tokerfcce1832014-06-22 03:27:45 +0000211#endif // USE_WIN32
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000212}
213
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000214// Convert LLVM's ArchType
215// to the corresponding name of Windows SDK libraries subfolder
216static StringRef getWindowsSDKArch(llvm::Triple::ArchType Arch) {
217 switch (Arch) {
218 case llvm::Triple::x86:
219 return "x86";
220 case llvm::Triple::x86_64:
221 return "x64";
222 case llvm::Triple::arm:
223 return "arm";
224 default:
225 return "";
226 }
227}
228
Igor Kudrinf2e75242015-09-24 05:16:36 +0000229// Find the most recent version of Universal CRT or Windows 10 SDK.
230// vcvarsqueryregistry.bat from Visual Studio 2015 sorts entries in the include
231// directory by name and uses the last one of the list.
232// So we compare entry names lexicographically to find the greatest one.
233static bool getWindows10SDKVersion(const std::string &SDKPath,
234 std::string &SDKVersion) {
235 SDKVersion.clear();
236
237 std::error_code EC;
238 llvm::SmallString<128> IncludePath(SDKPath);
239 llvm::sys::path::append(IncludePath, "Include");
240 for (llvm::sys::fs::directory_iterator DirIt(IncludePath, EC), DirEnd;
241 DirIt != DirEnd && !EC; DirIt.increment(EC)) {
242 if (!llvm::sys::fs::is_directory(DirIt->path()))
243 continue;
244 StringRef CandidateName = llvm::sys::path::filename(DirIt->path());
245 // If WDK is installed, there could be subfolders like "wdf" in the
246 // "Include" directory.
247 // Allow only directories which names start with "10.".
248 if (!CandidateName.startswith("10."))
249 continue;
250 if (CandidateName > SDKVersion)
251 SDKVersion = CandidateName;
252 }
253
254 return !SDKVersion.empty();
255}
256
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000257/// \brief Get Windows SDK installation directory.
Igor Kudrinf2e75242015-09-24 05:16:36 +0000258bool MSVCToolChain::getWindowsSDKDir(std::string &Path, int &Major,
259 std::string &WindowsSDKIncludeVersion,
260 std::string &WindowsSDKLibVersion) const {
261 std::string RegistrySDKVersion;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000262 // Try the Windows registry.
Igor Kudrinf2e75242015-09-24 05:16:36 +0000263 if (!getSystemRegistryString(
264 "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION",
265 "InstallationFolder", Path, &RegistrySDKVersion))
266 return false;
267 if (Path.empty() || RegistrySDKVersion.empty())
268 return false;
269
270 WindowsSDKIncludeVersion.clear();
271 WindowsSDKLibVersion.clear();
272 Major = 0;
273 std::sscanf(RegistrySDKVersion.c_str(), "v%d.", &Major);
274 if (Major <= 7)
275 return true;
276 if (Major == 8) {
277 // Windows SDK 8.x installs libraries in a folder whose names depend on the
278 // version of the OS you're targeting. By default choose the newest, which
279 // usually corresponds to the version of the OS you've installed the SDK on.
280 const char *Tests[] = {"winv6.3", "win8", "win7"};
281 for (const char *Test : Tests) {
282 llvm::SmallString<128> TestPath(Path);
283 llvm::sys::path::append(TestPath, "Lib", Test);
284 if (llvm::sys::fs::exists(TestPath.c_str())) {
285 WindowsSDKLibVersion = Test;
286 break;
287 }
288 }
289 return !WindowsSDKLibVersion.empty();
290 }
291 if (Major == 10) {
292 if (!getWindows10SDKVersion(Path, WindowsSDKIncludeVersion))
293 return false;
294 WindowsSDKLibVersion = WindowsSDKIncludeVersion;
295 return true;
296 }
297 // Unsupported SDK version
298 return false;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000299}
300
Zachary Turner10d75b22014-10-22 20:40:43 +0000301// Gets the library path required to link against the Windows SDK.
302bool MSVCToolChain::getWindowsSDKLibraryPath(std::string &path) const {
303 std::string sdkPath;
304 int sdkMajor = 0;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000305 std::string windowsSDKIncludeVersion;
306 std::string windowsSDKLibVersion;
Zachary Turner10d75b22014-10-22 20:40:43 +0000307
308 path.clear();
Igor Kudrinf2e75242015-09-24 05:16:36 +0000309 if (!getWindowsSDKDir(sdkPath, sdkMajor, windowsSDKIncludeVersion,
310 windowsSDKLibVersion))
Zachary Turner10d75b22014-10-22 20:40:43 +0000311 return false;
312
313 llvm::SmallString<128> libPath(sdkPath);
314 llvm::sys::path::append(libPath, "Lib");
315 if (sdkMajor <= 7) {
316 switch (getArch()) {
317 // In Windows SDK 7.x, x86 libraries are directly in the Lib folder.
318 case llvm::Triple::x86:
319 break;
320 case llvm::Triple::x86_64:
321 llvm::sys::path::append(libPath, "x64");
322 break;
323 case llvm::Triple::arm:
324 // It is not necessary to link against Windows SDK 7.x when targeting ARM.
325 return false;
326 default:
327 return false;
328 }
329 } else {
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000330 const StringRef archName = getWindowsSDKArch(getArch());
331 if (archName.empty())
Zachary Turner10d75b22014-10-22 20:40:43 +0000332 return false;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000333 llvm::sys::path::append(libPath, windowsSDKLibVersion, "um", archName);
Zachary Turner10d75b22014-10-22 20:40:43 +0000334 }
335
336 path = libPath.str();
337 return true;
338}
339
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000340// Check if the Include path of a specified version of Visual Studio contains
341// specific header files. If not, they are probably shipped with Universal CRT.
342bool clang::driver::toolchains::MSVCToolChain::useUniversalCRT(
343 std::string &VisualStudioDir) const {
344 llvm::SmallString<128> TestPath(VisualStudioDir);
345 llvm::sys::path::append(TestPath, "VC\\include\\stdlib.h");
346
347 return !llvm::sys::fs::exists(TestPath);
348}
349
350bool MSVCToolChain::getUniversalCRTSdkDir(std::string &Path,
351 std::string &UCRTVersion) const {
352 // vcvarsqueryregistry.bat for Visual Studio 2015 queries the registry
353 // for the specific key "KitsRoot10". So do we.
354 if (!getSystemRegistryString(
355 "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10",
356 Path, nullptr))
357 return false;
358
Igor Kudrinf2e75242015-09-24 05:16:36 +0000359 return getWindows10SDKVersion(Path, UCRTVersion);
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000360}
361
362bool MSVCToolChain::getUniversalCRTLibraryPath(std::string &Path) const {
363 std::string UniversalCRTSdkPath;
364 std::string UCRTVersion;
365
366 Path.clear();
367 if (!getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion))
368 return false;
369
370 StringRef ArchName = getWindowsSDKArch(getArch());
371 if (ArchName.empty())
372 return false;
373
374 llvm::SmallString<128> LibPath(UniversalCRTSdkPath);
375 llvm::sys::path::append(LibPath, "Lib", UCRTVersion, "ucrt", ArchName);
376
377 Path = LibPath.str();
378 return true;
379}
380
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000381// Get the location to use for Visual Studio binaries. The location priority
382// is: %VCINSTALLDIR% > %PATH% > newest copy of Visual Studio installed on
383// system (as reported by the registry).
384bool MSVCToolChain::getVisualStudioBinariesFolder(const char *clangProgramPath,
385 std::string &path) const {
386 path.clear();
387
388 SmallString<128> BinDir;
389
390 // First check the environment variables that vsvars32.bat sets.
391 llvm::Optional<std::string> VcInstallDir =
392 llvm::sys::Process::GetEnv("VCINSTALLDIR");
393 if (VcInstallDir.hasValue()) {
394 BinDir = VcInstallDir.getValue();
395 llvm::sys::path::append(BinDir, "bin");
396 } else {
397 // Next walk the PATH, trying to find a cl.exe in the path. If we find one,
398 // use that. However, make sure it's not clang's cl.exe.
399 llvm::Optional<std::string> OptPath = llvm::sys::Process::GetEnv("PATH");
400 if (OptPath.hasValue()) {
401 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
402 SmallVector<StringRef, 8> PathSegments;
403 llvm::SplitString(OptPath.getValue(), PathSegments, EnvPathSeparatorStr);
404
405 for (StringRef PathSegment : PathSegments) {
406 if (PathSegment.empty())
407 continue;
408
409 SmallString<128> FilePath(PathSegment);
410 llvm::sys::path::append(FilePath, "cl.exe");
Adrian McCarthy8e0879a92016-05-20 15:46:23 +0000411 // Checking if cl.exe exists is a small optimization over calling
412 // can_execute, which really only checks for existence but will also do
413 // extra checks for cl.exe.exe. These add up when walking a long path.
414 if (llvm::sys::fs::exists(FilePath.c_str()) &&
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000415 !llvm::sys::fs::equivalent(FilePath.c_str(), clangProgramPath)) {
416 // If we found it on the PATH, use it exactly as is with no
417 // modifications.
418 path = PathSegment;
419 return true;
420 }
421 }
422 }
423
424 std::string installDir;
425 // With no VCINSTALLDIR and nothing on the PATH, if we can't find it in the
426 // registry then we have no choice but to fail.
427 if (!getVisualStudioInstallDir(installDir))
428 return false;
429
430 // Regardless of what binary we're ultimately trying to find, we make sure
431 // that this is a Visual Studio directory by checking for cl.exe. We use
432 // cl.exe instead of other binaries like link.exe because programs such as
433 // GnuWin32 also have a utility called link.exe, so cl.exe is the least
434 // ambiguous.
435 BinDir = installDir;
436 llvm::sys::path::append(BinDir, "VC", "bin");
437 SmallString<128> ClPath(BinDir);
438 llvm::sys::path::append(ClPath, "cl.exe");
439
440 if (!llvm::sys::fs::can_execute(ClPath.c_str()))
441 return false;
Hans Wennborge6b994e2014-10-20 23:26:03 +0000442 }
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000443
444 if (BinDir.empty())
445 return false;
446
447 switch (getArch()) {
448 case llvm::Triple::x86:
449 break;
450 case llvm::Triple::x86_64:
451 llvm::sys::path::append(BinDir, "amd64");
452 break;
453 case llvm::Triple::arm:
454 llvm::sys::path::append(BinDir, "arm");
455 break;
456 default:
457 // Whatever this is, Visual Studio doesn't have a toolchain for it.
458 return false;
459 }
460 path = BinDir.str();
461 return true;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000462}
463
Adrian McCarthye4b26fc2016-05-13 23:20:11 +0000464VersionTuple MSVCToolChain::getMSVCVersionFromExe() const {
465 VersionTuple Version;
466#ifdef USE_WIN32
467 std::string BinPath;
468 if (!getVisualStudioBinariesFolder("", BinPath))
469 return Version;
NAKAMURA Takumi4b8e3e52016-05-14 08:09:12 +0000470 SmallString<128> ClExe(BinPath);
Adrian McCarthye4b26fc2016-05-13 23:20:11 +0000471 llvm::sys::path::append(ClExe, "cl.exe");
472
473 std::wstring ClExeWide;
474 if (!llvm::ConvertUTF8toWide(ClExe.c_str(), ClExeWide))
475 return Version;
476
477 const DWORD VersionSize = ::GetFileVersionInfoSizeW(ClExeWide.c_str(),
478 nullptr);
479 if (VersionSize == 0)
480 return Version;
481
482 SmallVector<uint8_t, 4 * 1024> VersionBlock(VersionSize);
483 if (!::GetFileVersionInfoW(ClExeWide.c_str(), 0, VersionSize,
484 VersionBlock.data()))
485 return Version;
486
487 VS_FIXEDFILEINFO *FileInfo = nullptr;
488 UINT FileInfoSize = 0;
489 if (!::VerQueryValueW(VersionBlock.data(), L"\\",
490 reinterpret_cast<LPVOID *>(&FileInfo), &FileInfoSize) ||
491 FileInfoSize < sizeof(*FileInfo))
492 return Version;
493
494 const unsigned Major = (FileInfo->dwFileVersionMS >> 16) & 0xFFFF;
495 const unsigned Minor = (FileInfo->dwFileVersionMS ) & 0xFFFF;
496 const unsigned Micro = (FileInfo->dwFileVersionLS >> 16) & 0xFFFF;
497
498 Version = VersionTuple(Major, Minor, Micro);
499#endif
500 return Version;
501}
502
Alp Tokerfcce1832014-06-22 03:27:45 +0000503// Get Visual Studio installation directory.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000504bool MSVCToolChain::getVisualStudioInstallDir(std::string &path) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000505 // First check the environment variables that vsvars32.bat sets.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000506 const char *vcinstalldir = getenv("VCINSTALLDIR");
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000507 if (vcinstalldir) {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000508 path = vcinstalldir;
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000509 path = path.substr(0, path.find("\\VC"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000510 return true;
511 }
512
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000513 std::string vsIDEInstallDir;
514 std::string vsExpressIDEInstallDir;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000515 // Then try the windows registry.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000516 bool hasVCDir =
517 getSystemRegistryString("SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
518 "InstallDir", vsIDEInstallDir, nullptr);
519 if (hasVCDir && !vsIDEInstallDir.empty()) {
520 path = vsIDEInstallDir.substr(0, vsIDEInstallDir.find("\\Common7\\IDE"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000521 return true;
522 }
523
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000524 bool hasVCExpressDir =
525 getSystemRegistryString("SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
526 "InstallDir", vsExpressIDEInstallDir, nullptr);
527 if (hasVCExpressDir && !vsExpressIDEInstallDir.empty()) {
528 path = vsExpressIDEInstallDir.substr(
529 0, vsIDEInstallDir.find("\\Common7\\IDE"));
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000530 return true;
531 }
532
533 // Try the environment.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000534 const char *vs120comntools = getenv("VS120COMNTOOLS");
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000535 const char *vs100comntools = getenv("VS100COMNTOOLS");
536 const char *vs90comntools = getenv("VS90COMNTOOLS");
537 const char *vs80comntools = getenv("VS80COMNTOOLS");
Alp Tokerfcce1832014-06-22 03:27:45 +0000538
539 const char *vscomntools = nullptr;
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000540
Alp Tokera2074402014-06-22 03:27:52 +0000541 // Find any version we can
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000542 if (vs120comntools)
543 vscomntools = vs120comntools;
544 else if (vs100comntools)
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000545 vscomntools = vs100comntools;
546 else if (vs90comntools)
547 vscomntools = vs90comntools;
548 else if (vs80comntools)
549 vscomntools = vs80comntools;
550
551 if (vscomntools && *vscomntools) {
552 const char *p = strstr(vscomntools, "\\Common7\\Tools");
553 path = p ? std::string(vscomntools, p) : vscomntools;
554 return true;
555 }
556 return false;
557}
558
Igor Kudrinf2e75242015-09-24 05:16:36 +0000559void MSVCToolChain::AddSystemIncludeWithSubfolder(
560 const ArgList &DriverArgs, ArgStringList &CC1Args,
561 const std::string &folder, const Twine &subfolder1, const Twine &subfolder2,
562 const Twine &subfolder3) const {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000563 llvm::SmallString<128> path(folder);
Igor Kudrinf2e75242015-09-24 05:16:36 +0000564 llvm::sys::path::append(path, subfolder1, subfolder2, subfolder3);
Yaron Keren92e1b622015-03-18 10:17:07 +0000565 addSystemInclude(DriverArgs, CC1Args, path);
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000566}
567
Saleem Abdulrasool819f3912014-10-22 02:37:29 +0000568void MSVCToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
569 ArgStringList &CC1Args) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000570 if (DriverArgs.hasArg(options::OPT_nostdinc))
571 return;
572
573 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000574 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, getDriver().ResourceDir,
575 "include");
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000576 }
577
Nico Weberfd3e1ad2016-04-12 19:04:37 +0000578 // Add %INCLUDE%-like directories from the -imsvc flag.
579 for (const auto &Path : DriverArgs.getAllArgValues(options::OPT__SLASH_imsvc))
580 addSystemInclude(DriverArgs, CC1Args, Path);
581
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000582 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
583 return;
584
Joao Matos792d7af2012-09-04 17:29:52 +0000585 // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat.
586 if (const char *cl_include_dir = getenv("INCLUDE")) {
587 SmallVector<StringRef, 8> Dirs;
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000588 StringRef(cl_include_dir)
589 .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
590 for (StringRef Dir : Dirs)
591 addSystemInclude(DriverArgs, CC1Args, Dir);
592 if (!Dirs.empty())
593 return;
Joao Matos792d7af2012-09-04 17:29:52 +0000594 }
595
596 std::string VSDir;
Joao Matos792d7af2012-09-04 17:29:52 +0000597
598 // When built with access to the proper Windows APIs, try to actually find
599 // the correct include paths first.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000600 if (getVisualStudioInstallDir(VSDir)) {
601 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, VSDir, "VC\\include");
602
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000603 if (useUniversalCRT(VSDir)) {
604 std::string UniversalCRTSdkPath;
605 std::string UCRTVersion;
606 if (getUniversalCRTSdkDir(UniversalCRTSdkPath, UCRTVersion)) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000607 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, UniversalCRTSdkPath,
608 "Include", UCRTVersion, "ucrt");
Reid Kleckner7531f7d2015-09-11 00:09:39 +0000609 }
610 }
611
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000612 std::string WindowsSDKDir;
Igor Kudrinf2e75242015-09-24 05:16:36 +0000613 int major;
614 std::string windowsSDKIncludeVersion;
615 std::string windowsSDKLibVersion;
616 if (getWindowsSDKDir(WindowsSDKDir, major, windowsSDKIncludeVersion,
617 windowsSDKLibVersion)) {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000618 if (major >= 8) {
Igor Kudrinf2e75242015-09-24 05:16:36 +0000619 // Note: windowsSDKIncludeVersion is empty for SDKs prior to v10.
620 // Anyway, llvm::sys::path::append is able to manage it.
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000621 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000622 "include", windowsSDKIncludeVersion,
623 "shared");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000624 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000625 "include", windowsSDKIncludeVersion,
626 "um");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000627 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
Igor Kudrinf2e75242015-09-24 05:16:36 +0000628 "include", windowsSDKIncludeVersion,
629 "winrt");
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000630 } else {
631 AddSystemIncludeWithSubfolder(DriverArgs, CC1Args, WindowsSDKDir,
632 "include");
633 }
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000634 } else {
Zachary Turner0eaf8fc2014-10-22 20:40:28 +0000635 addSystemInclude(DriverArgs, CC1Args, VSDir);
Reid Kleckner77b45ba2014-04-23 00:15:01 +0000636 }
Joao Matos792d7af2012-09-04 17:29:52 +0000637 return;
638 }
Joao Matos792d7af2012-09-04 17:29:52 +0000639
640 // As a fallback, select default install paths.
Alp Tokerfcce1832014-06-22 03:27:45 +0000641 // FIXME: Don't guess drives and paths like this on Windows.
Joao Matos792d7af2012-09-04 17:29:52 +0000642 const StringRef Paths[] = {
643 "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
644 "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
645 "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
646 "C:/Program Files/Microsoft Visual Studio 8/VC/include",
647 "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
648 };
649 addSystemIncludes(DriverArgs, CC1Args, Paths);
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000650}
651
Saleem Abdulrasool819f3912014-10-22 02:37:29 +0000652void MSVCToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
653 ArgStringList &CC1Args) const {
Chandler Carruth1fc603e2011-12-17 23:10:01 +0000654 // FIXME: There should probably be logic here to find libc++ on Windows.
655}
David Majnemere11d3732015-06-08 00:22:46 +0000656
657std::string
658MSVCToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
659 types::ID InputType) const {
660 std::string TripleStr =
661 ToolChain::ComputeEffectiveClangTriple(Args, InputType);
662 llvm::Triple Triple(TripleStr);
663 VersionTuple MSVT =
Adrian McCarthye4b26fc2016-05-13 23:20:11 +0000664 tools::visualstudio::getMSVCVersion(/*D=*/nullptr, *this, Triple, Args,
David Majnemere11d3732015-06-08 00:22:46 +0000665 /*IsWindowsMSVC=*/true);
666 if (MSVT.empty())
667 return TripleStr;
668
669 MSVT = VersionTuple(MSVT.getMajor(), MSVT.getMinor().getValueOr(0),
670 MSVT.getSubminor().getValueOr(0));
671
David Majnemer75fdd6b2015-06-09 06:30:01 +0000672 if (Triple.getEnvironment() == llvm::Triple::MSVC) {
673 StringRef ObjFmt = Triple.getEnvironmentName().split('-').second;
674 if (ObjFmt.empty())
675 Triple.setEnvironmentName((Twine("msvc") + MSVT.getAsString()).str());
676 else
677 Triple.setEnvironmentName(
678 (Twine("msvc") + MSVT.getAsString() + Twine('-') + ObjFmt).str());
679 }
David Majnemere11d3732015-06-08 00:22:46 +0000680 return Triple.getTriple();
681}
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000682
683SanitizerMask MSVCToolChain::getSupportedSanitizers() const {
684 SanitizerMask Res = ToolChain::getSupportedSanitizers();
685 Res |= SanitizerKind::Address;
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000686 return Res;
687}
David Majnemer015ce0f2015-07-27 07:32:11 +0000688
Hans Wennborg21d73d22016-01-12 23:17:03 +0000689static void TranslateOptArg(Arg *A, llvm::opt::DerivedArgList &DAL,
690 bool SupportsForcingFramePointer,
691 const char *ExpandChar, const OptTable &Opts) {
692 assert(A->getOption().matches(options::OPT__SLASH_O));
693
694 StringRef OptStr = A->getValue();
695 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
696 const char &OptChar = *(OptStr.data() + I);
697 switch (OptChar) {
698 default:
699 break;
700 case '1':
701 case '2':
702 case 'x':
703 case 'd':
704 if (&OptChar == ExpandChar) {
705 if (OptChar == 'd') {
706 DAL.AddFlagArg(A, Opts.getOption(options::OPT_O0));
707 } else {
708 if (OptChar == '1') {
709 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
710 } else if (OptChar == '2' || OptChar == 'x') {
711 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
712 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
713 }
David Majnemer259d71a2016-01-21 23:01:11 +0000714 if (SupportsForcingFramePointer &&
715 !DAL.hasArgNoClaim(options::OPT_fno_omit_frame_pointer))
Hans Wennborg21d73d22016-01-12 23:17:03 +0000716 DAL.AddFlagArg(A,
717 Opts.getOption(options::OPT_fomit_frame_pointer));
718 if (OptChar == '1' || OptChar == '2')
719 DAL.AddFlagArg(A,
720 Opts.getOption(options::OPT_ffunction_sections));
721 }
722 }
723 break;
724 case 'b':
Hans Wennborg3270bdb2016-05-24 21:23:29 +0000725 if (I + 1 != E && isdigit(OptStr[I + 1])) {
726 switch (OptStr[I + 1]) {
727 case '0':
728 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_inline));
729 break;
730 case '1':
731 // TODO: Inline calls to 'inline functions' only.
732 break;
733 case '2':
734 DAL.AddFlagArg(A, Opts.getOption(options::OPT_finline_functions));
735 break;
736 }
Hans Wennborg21d73d22016-01-12 23:17:03 +0000737 ++I;
Hans Wennborg3270bdb2016-05-24 21:23:29 +0000738 }
Hans Wennborg21d73d22016-01-12 23:17:03 +0000739 break;
740 case 'g':
741 break;
742 case 'i':
743 if (I + 1 != E && OptStr[I + 1] == '-') {
744 ++I;
745 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fno_builtin));
746 } else {
747 DAL.AddFlagArg(A, Opts.getOption(options::OPT_fbuiltin));
748 }
749 break;
750 case 's':
751 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "s");
752 break;
753 case 't':
754 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_O), "2");
755 break;
756 case 'y': {
757 bool OmitFramePointer = true;
758 if (I + 1 != E && OptStr[I + 1] == '-') {
759 OmitFramePointer = false;
760 ++I;
761 }
762 if (SupportsForcingFramePointer) {
763 if (OmitFramePointer)
764 DAL.AddFlagArg(A,
765 Opts.getOption(options::OPT_fomit_frame_pointer));
766 else
767 DAL.AddFlagArg(
768 A, Opts.getOption(options::OPT_fno_omit_frame_pointer));
Nico Weber9c3fca32016-03-23 15:37:41 +0000769 } else {
770 // Don't warn about /Oy- in 64-bit builds (where
771 // SupportsForcingFramePointer is false). The flag having no effect
772 // there is a compiler-internal optimization, and people shouldn't have
773 // to special-case their build files for 64-bit clang-cl.
774 A->claim();
Hans Wennborg21d73d22016-01-12 23:17:03 +0000775 }
776 break;
777 }
778 }
779 }
780}
781
782static void TranslateDArg(Arg *A, llvm::opt::DerivedArgList &DAL,
783 const OptTable &Opts) {
784 assert(A->getOption().matches(options::OPT_D));
785
786 StringRef Val = A->getValue();
787 size_t Hash = Val.find('#');
788 if (Hash == StringRef::npos || Hash > Val.find('=')) {
789 DAL.append(A);
790 return;
791 }
792
793 std::string NewVal = Val;
794 NewVal[Hash] = '=';
795 DAL.AddJoinedArg(A, Opts.getOption(options::OPT_D), NewVal);
796}
797
David Majnemer015ce0f2015-07-27 07:32:11 +0000798llvm::opt::DerivedArgList *
799MSVCToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
800 const char *BoundArch) const {
801 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
802 const OptTable &Opts = getDriver().getOpts();
803
David Majnemer7ab76f22015-08-25 00:46:45 +0000804 // /Oy and /Oy- only has an effect under X86-32.
805 bool SupportsForcingFramePointer = getArch() == llvm::Triple::x86;
806
David Majnemer015ce0f2015-07-27 07:32:11 +0000807 // The -O[12xd] flag actually expands to several flags. We must desugar the
808 // flags so that options embedded can be negated. For example, the '-O2' flag
809 // enables '-Oy'. Expanding '-O2' into its constituent flags allows us to
810 // correctly handle '-O2 -Oy-' where the trailing '-Oy-' disables a single
811 // aspect of '-O2'.
812 //
813 // Note that this expansion logic only applies to the *last* of '[12xd]'.
814
815 // First step is to search for the character we'd like to expand.
816 const char *ExpandChar = nullptr;
817 for (Arg *A : Args) {
818 if (!A->getOption().matches(options::OPT__SLASH_O))
819 continue;
820 StringRef OptStr = A->getValue();
821 for (size_t I = 0, E = OptStr.size(); I != E; ++I) {
Hans Wennborgdebfed92016-05-25 00:43:45 +0000822 char OptChar = OptStr[I];
823 char PrevChar = I > 0 ? OptStr[I - 1] : '0';
824 if (PrevChar == 'b') {
825 // OptChar does not expand; it's an argument to the previous char.
826 continue;
827 }
David Majnemer015ce0f2015-07-27 07:32:11 +0000828 if (OptChar == '1' || OptChar == '2' || OptChar == 'x' || OptChar == 'd')
829 ExpandChar = OptStr.data() + I;
830 }
831 }
832
David Majnemer015ce0f2015-07-27 07:32:11 +0000833 for (Arg *A : Args) {
Hans Wennborg21d73d22016-01-12 23:17:03 +0000834 if (A->getOption().matches(options::OPT__SLASH_O)) {
835 // The -O flag actually takes an amalgam of other options. For example,
836 // '/Ogyb2' is equivalent to '/Og' '/Oy' '/Ob2'.
837 TranslateOptArg(A, *DAL, SupportsForcingFramePointer, ExpandChar, Opts);
838 } else if (A->getOption().matches(options::OPT_D)) {
839 // Translate -Dfoo#bar into -Dfoo=bar.
840 TranslateDArg(A, *DAL, Opts);
841 } else {
David Majnemer015ce0f2015-07-27 07:32:11 +0000842 DAL->append(A);
David Majnemer015ce0f2015-07-27 07:32:11 +0000843 }
844 }
Hans Wennborg21d73d22016-01-12 23:17:03 +0000845
David Majnemer015ce0f2015-07-27 07:32:11 +0000846 return DAL;
847}