Coverage Report

Created: 2019-07-24 05:18

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