1 //===--- MinGW.cpp - MinGWToolChain Implementation ------------------------===//
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 "MinGW.h"
10 #include "CommonArgs.h"
11 #include "clang/Config/config.h"
12 #include "clang/Driver/Compilation.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/InputInfo.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/SanitizerArgs.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/VirtualFileSystem.h"
22 #include <system_error>
23 
24 using namespace clang::diag;
25 using namespace clang::driver;
26 using namespace clang;
27 using namespace llvm::opt;
28 
29 /// MinGW Tools
30 void tools::MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
31                                            const InputInfo &Output,
32                                            const InputInfoList &Inputs,
33                                            const ArgList &Args,
34                                            const char *LinkingOutput) const {
35   claimNoWarnArgs(Args);
36   ArgStringList CmdArgs;
37 
38   if (getToolChain().getArch() == llvm::Triple::x86) {
39     CmdArgs.push_back("--32");
40   } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
41     CmdArgs.push_back("--64");
42   }
43 
44   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
45 
46   CmdArgs.push_back("-o");
47   CmdArgs.push_back(Output.getFilename());
48 
49   for (const auto &II : Inputs)
50     CmdArgs.push_back(II.getFilename());
51 
52   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
53   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
54                                          Exec, CmdArgs, Inputs, Output));
55 
56   if (Args.hasArg(options::OPT_gsplit_dwarf))
57     SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
58                    SplitDebugName(JA, Args, Inputs[0], Output));
59 }
60 
61 void tools::MinGW::Linker::AddLibGCC(const ArgList &Args,
62                                      ArgStringList &CmdArgs) const {
63   if (Args.hasArg(options::OPT_mthreads))
64     CmdArgs.push_back("-lmingwthrd");
65   CmdArgs.push_back("-lmingw32");
66 
67   // Make use of compiler-rt if --rtlib option is used
68   ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
69   if (RLT == ToolChain::RLT_Libgcc) {
70     bool Static = Args.hasArg(options::OPT_static_libgcc) ||
71                   Args.hasArg(options::OPT_static);
72     bool Shared = Args.hasArg(options::OPT_shared);
73     bool CXX = getToolChain().getDriver().CCCIsCXX();
74 
75     if (Static || (!CXX && !Shared)) {
76       CmdArgs.push_back("-lgcc");
77       CmdArgs.push_back("-lgcc_eh");
78     } else {
79       CmdArgs.push_back("-lgcc_s");
80       CmdArgs.push_back("-lgcc");
81     }
82   } else {
83     AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
84   }
85 
86   CmdArgs.push_back("-lmoldname");
87   CmdArgs.push_back("-lmingwex");
88   for (auto Lib : Args.getAllArgValues(options::OPT_l))
89     if (StringRef(Lib).startswith("msvcr") || StringRef(Lib).startswith("ucrt"))
90       return;
91   CmdArgs.push_back("-lmsvcrt");
92 }
93 
94 void tools::MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
95                                         const InputInfo &Output,
96                                         const InputInfoList &Inputs,
97                                         const ArgList &Args,
98                                         const char *LinkingOutput) const {
99   const ToolChain &TC = getToolChain();
100   const Driver &D = TC.getDriver();
101   const SanitizerArgs &Sanitize = TC.getSanitizerArgs(Args);
102 
103   ArgStringList CmdArgs;
104 
105   // Silence warning for "clang -g foo.o -o foo"
106   Args.ClaimAllArgs(options::OPT_g_Group);
107   // and "clang -emit-llvm foo.o -o foo"
108   Args.ClaimAllArgs(options::OPT_emit_llvm);
109   // and for "clang -w foo.o -o foo". Other warning options are already
110   // handled somewhere else.
111   Args.ClaimAllArgs(options::OPT_w);
112 
113   if (!D.SysRoot.empty())
114     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
115 
116   if (Args.hasArg(options::OPT_s))
117     CmdArgs.push_back("-s");
118 
119   CmdArgs.push_back("-m");
120   switch (TC.getArch()) {
121   case llvm::Triple::x86:
122     CmdArgs.push_back("i386pe");
123     break;
124   case llvm::Triple::x86_64:
125     CmdArgs.push_back("i386pep");
126     break;
127   case llvm::Triple::arm:
128   case llvm::Triple::thumb:
129     // FIXME: this is incorrect for WinCE
130     CmdArgs.push_back("thumb2pe");
131     break;
132   case llvm::Triple::aarch64:
133     CmdArgs.push_back("arm64pe");
134     break;
135   default:
136     llvm_unreachable("Unsupported target architecture.");
137   }
138 
139   Arg *SubsysArg =
140       Args.getLastArg(options::OPT_mwindows, options::OPT_mconsole);
141   if (SubsysArg && SubsysArg->getOption().matches(options::OPT_mwindows)) {
142     CmdArgs.push_back("--subsystem");
143     CmdArgs.push_back("windows");
144   } else if (SubsysArg &&
145              SubsysArg->getOption().matches(options::OPT_mconsole)) {
146     CmdArgs.push_back("--subsystem");
147     CmdArgs.push_back("console");
148   }
149 
150   if (Args.hasArg(options::OPT_mdll))
151     CmdArgs.push_back("--dll");
152   else if (Args.hasArg(options::OPT_shared))
153     CmdArgs.push_back("--shared");
154   if (Args.hasArg(options::OPT_static))
155     CmdArgs.push_back("-Bstatic");
156   else
157     CmdArgs.push_back("-Bdynamic");
158   if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
159     CmdArgs.push_back("-e");
160     if (TC.getArch() == llvm::Triple::x86)
161       CmdArgs.push_back("_DllMainCRTStartup@12");
162     else
163       CmdArgs.push_back("DllMainCRTStartup");
164     CmdArgs.push_back("--enable-auto-image-base");
165   }
166 
167   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
168     CmdArgs.push_back("--no-demangle");
169 
170   CmdArgs.push_back("-o");
171   const char *OutputFile = Output.getFilename();
172   // GCC implicitly adds an .exe extension if it is given an output file name
173   // that lacks an extension.
174   // GCC used to do this only when the compiler itself runs on windows, but
175   // since GCC 8 it does the same when cross compiling as well.
176   if (!llvm::sys::path::has_extension(OutputFile)) {
177     CmdArgs.push_back(Args.MakeArgString(Twine(OutputFile) + ".exe"));
178     OutputFile = CmdArgs.back();
179   } else
180     CmdArgs.push_back(OutputFile);
181 
182   Args.AddAllArgs(CmdArgs, options::OPT_e);
183   // FIXME: add -N, -n flags
184   Args.AddLastArg(CmdArgs, options::OPT_r);
185   Args.AddLastArg(CmdArgs, options::OPT_s);
186   Args.AddLastArg(CmdArgs, options::OPT_t);
187   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
188   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
189 
190   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
191     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
192       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
193     } else {
194       if (Args.hasArg(options::OPT_municode))
195         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
196       else
197         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
198     }
199     if (Args.hasArg(options::OPT_pg))
200       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
201     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
202   }
203 
204   Args.AddAllArgs(CmdArgs, options::OPT_L);
205   TC.AddFilePathLibArgs(Args, CmdArgs);
206 
207   // Add the compiler-rt library directories if they exist to help
208   // the linker find the various sanitizer, builtin, and profiling runtimes.
209   for (const auto &LibPath : TC.getLibraryPaths()) {
210     if (TC.getVFS().exists(LibPath))
211       CmdArgs.push_back(Args.MakeArgString("-L" + LibPath));
212   }
213   auto CRTPath = TC.getCompilerRTPath();
214   if (TC.getVFS().exists(CRTPath))
215     CmdArgs.push_back(Args.MakeArgString("-L" + CRTPath));
216 
217   AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
218 
219   // TODO: Add profile stuff here
220 
221   if (TC.ShouldLinkCXXStdlib(Args)) {
222     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
223                                !Args.hasArg(options::OPT_static);
224     if (OnlyLibstdcxxStatic)
225       CmdArgs.push_back("-Bstatic");
226     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
227     if (OnlyLibstdcxxStatic)
228       CmdArgs.push_back("-Bdynamic");
229   }
230 
231   bool HasWindowsApp = false;
232   for (auto Lib : Args.getAllArgValues(options::OPT_l)) {
233     if (Lib == "windowsapp") {
234       HasWindowsApp = true;
235       break;
236     }
237   }
238 
239   if (!Args.hasArg(options::OPT_nostdlib)) {
240     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
241       if (Args.hasArg(options::OPT_static))
242         CmdArgs.push_back("--start-group");
243 
244       if (Args.hasArg(options::OPT_fstack_protector) ||
245           Args.hasArg(options::OPT_fstack_protector_strong) ||
246           Args.hasArg(options::OPT_fstack_protector_all)) {
247         CmdArgs.push_back("-lssp_nonshared");
248         CmdArgs.push_back("-lssp");
249       }
250 
251       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
252                        options::OPT_fno_openmp, false)) {
253         switch (TC.getDriver().getOpenMPRuntime(Args)) {
254         case Driver::OMPRT_OMP:
255           CmdArgs.push_back("-lomp");
256           break;
257         case Driver::OMPRT_IOMP5:
258           CmdArgs.push_back("-liomp5md");
259           break;
260         case Driver::OMPRT_GOMP:
261           CmdArgs.push_back("-lgomp");
262           break;
263         case Driver::OMPRT_Unknown:
264           // Already diagnosed.
265           break;
266         }
267       }
268 
269       AddLibGCC(Args, CmdArgs);
270 
271       if (Args.hasArg(options::OPT_pg))
272         CmdArgs.push_back("-lgmon");
273 
274       if (Args.hasArg(options::OPT_pthread))
275         CmdArgs.push_back("-lpthread");
276 
277       if (Sanitize.needsAsanRt()) {
278         // MinGW always links against a shared MSVCRT.
279         CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dynamic",
280                                                     ToolChain::FT_Shared));
281         CmdArgs.push_back(
282             TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
283         CmdArgs.push_back("--require-defined");
284         CmdArgs.push_back(TC.getArch() == llvm::Triple::x86
285                               ? "___asan_seh_interceptor"
286                               : "__asan_seh_interceptor");
287         // Make sure the linker consider all object files from the dynamic
288         // runtime thunk.
289         CmdArgs.push_back("--whole-archive");
290         CmdArgs.push_back(
291             TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
292         CmdArgs.push_back("--no-whole-archive");
293       }
294 
295       TC.addProfileRTLibs(Args, CmdArgs);
296 
297       if (!HasWindowsApp) {
298         // Add system libraries. If linking to libwindowsapp.a, that import
299         // library replaces all these and we shouldn't accidentally try to
300         // link to the normal desktop mode dlls.
301         if (Args.hasArg(options::OPT_mwindows)) {
302           CmdArgs.push_back("-lgdi32");
303           CmdArgs.push_back("-lcomdlg32");
304         }
305         CmdArgs.push_back("-ladvapi32");
306         CmdArgs.push_back("-lshell32");
307         CmdArgs.push_back("-luser32");
308         CmdArgs.push_back("-lkernel32");
309       }
310 
311       if (Args.hasArg(options::OPT_static)) {
312         CmdArgs.push_back("--end-group");
313       } else {
314         AddLibGCC(Args, CmdArgs);
315         if (!HasWindowsApp)
316           CmdArgs.push_back("-lkernel32");
317       }
318     }
319 
320     if (!Args.hasArg(options::OPT_nostartfiles)) {
321       // Add crtfastmath.o if available and fast math is enabled.
322       TC.addFastMathRuntimeIfAvailable(Args, CmdArgs);
323 
324       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
325     }
326   }
327   const char *Exec = Args.MakeArgString(TC.GetLinkerPath());
328   C.addCommand(std::make_unique<Command>(JA, *this,
329                                          ResponseFileSupport::AtFileUTF8(),
330                                          Exec, CmdArgs, Inputs, Output));
331 }
332 
333 // Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple.
334 static bool findGccVersion(StringRef LibDir, std::string &GccLibDir,
335                            std::string &Ver) {
336   auto Version = toolchains::Generic_GCC::GCCVersion::Parse("0.0.0");
337   std::error_code EC;
338   for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE;
339        LI = LI.increment(EC)) {
340     StringRef VersionText = llvm::sys::path::filename(LI->path());
341     auto CandidateVersion =
342         toolchains::Generic_GCC::GCCVersion::Parse(VersionText);
343     if (CandidateVersion.Major == -1)
344       continue;
345     if (CandidateVersion <= Version)
346       continue;
347     Version = CandidateVersion;
348     Ver = std::string(VersionText);
349     GccLibDir = LI->path();
350   }
351   return Ver.size();
352 }
353 
354 void toolchains::MinGW::findGccLibDir() {
355   llvm::SmallVector<llvm::SmallString<32>, 2> SubdirNames;
356   SubdirNames.emplace_back(getTriple().getArchName());
357   SubdirNames[0] += "-w64-mingw32";
358   SubdirNames.emplace_back("mingw32");
359   if (SubdirName.empty())
360     SubdirName = std::string(SubdirNames[0].str());
361   // lib: Arch Linux, Ubuntu, Windows
362   // lib64: openSUSE Linux
363   for (StringRef CandidateLib : {"lib", "lib64"}) {
364     for (StringRef CandidateSysroot : SubdirNames) {
365       llvm::SmallString<1024> LibDir(Base);
366       llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateSysroot);
367       if (findGccVersion(LibDir, GccLibDir, Ver)) {
368         SubdirName = std::string(CandidateSysroot);
369         return;
370       }
371     }
372   }
373 }
374 
375 static llvm::ErrorOr<std::string> findGcc(const llvm::Triple &T) {
376   llvm::SmallVector<llvm::SmallString<32>, 2> Gccs;
377   Gccs.emplace_back(T.getArchName());
378   Gccs[0] += "-w64-mingw32-gcc";
379   Gccs.emplace_back("mingw32-gcc");
380   // Please do not add "gcc" here
381   for (StringRef CandidateGcc : Gccs)
382     if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName(CandidateGcc))
383       return GPPName;
384   return make_error_code(std::errc::no_such_file_or_directory);
385 }
386 
387 static llvm::ErrorOr<std::string>
388 findClangRelativeSysroot(const Driver &D, const llvm::Triple &T,
389                          std::string &SubdirName) {
390   llvm::SmallVector<llvm::SmallString<32>, 2> Subdirs;
391   Subdirs.emplace_back(T.str());
392   Subdirs.emplace_back(T.getArchName());
393   Subdirs[1] += "-w64-mingw32";
394   StringRef ClangRoot = llvm::sys::path::parent_path(D.getInstalledDir());
395   StringRef Sep = llvm::sys::path::get_separator();
396   for (StringRef CandidateSubdir : Subdirs) {
397     if (llvm::sys::fs::is_directory(ClangRoot + Sep + CandidateSubdir)) {
398       SubdirName = std::string(CandidateSubdir);
399       return (ClangRoot + Sep + CandidateSubdir).str();
400     }
401   }
402   return make_error_code(std::errc::no_such_file_or_directory);
403 }
404 
405 toolchains::MinGW::MinGW(const Driver &D, const llvm::Triple &Triple,
406                          const ArgList &Args)
407     : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
408       RocmInstallation(D, Triple, Args) {
409   getProgramPaths().push_back(getDriver().getInstalledDir());
410 
411   // The sequence for detecting a sysroot here should be kept in sync with
412   // the testTriple function below.
413   if (getDriver().SysRoot.size())
414     Base = getDriver().SysRoot;
415   // Look for <clang-bin>/../<triplet>; if found, use <clang-bin>/.. as the
416   // base as it could still be a base for a gcc setup with libgcc.
417   else if (llvm::ErrorOr<std::string> TargetSubdir =
418                findClangRelativeSysroot(getDriver(), getTriple(), SubdirName))
419     Base = std::string(llvm::sys::path::parent_path(TargetSubdir.get()));
420   else if (llvm::ErrorOr<std::string> GPPName = findGcc(getTriple()))
421     Base = std::string(llvm::sys::path::parent_path(
422         llvm::sys::path::parent_path(GPPName.get())));
423   else
424     Base = std::string(
425         llvm::sys::path::parent_path(getDriver().getInstalledDir()));
426 
427   Base += llvm::sys::path::get_separator();
428   findGccLibDir();
429   // GccLibDir must precede Base/lib so that the
430   // correct crtbegin.o ,cetend.o would be found.
431   getFilePaths().push_back(GccLibDir);
432   getFilePaths().push_back(
433       (Base + SubdirName + llvm::sys::path::get_separator() + "lib").str());
434   getFilePaths().push_back(Base + "lib");
435   // openSUSE
436   getFilePaths().push_back(Base + SubdirName + "/sys-root/mingw/lib");
437 
438   NativeLLVMSupport =
439       Args.getLastArgValue(options::OPT_fuse_ld_EQ, CLANG_DEFAULT_LINKER)
440           .equals_insensitive("lld");
441 }
442 
443 bool toolchains::MinGW::IsIntegratedAssemblerDefault() const { return true; }
444 
445 Tool *toolchains::MinGW::getTool(Action::ActionClass AC) const {
446   switch (AC) {
447   case Action::PreprocessJobClass:
448     if (!Preprocessor)
449       Preprocessor.reset(new tools::gcc::Preprocessor(*this));
450     return Preprocessor.get();
451   case Action::CompileJobClass:
452     if (!Compiler)
453       Compiler.reset(new tools::gcc::Compiler(*this));
454     return Compiler.get();
455   default:
456     return ToolChain::getTool(AC);
457   }
458 }
459 
460 Tool *toolchains::MinGW::buildAssembler() const {
461   return new tools::MinGW::Assembler(*this);
462 }
463 
464 Tool *toolchains::MinGW::buildLinker() const {
465   return new tools::MinGW::Linker(*this);
466 }
467 
468 bool toolchains::MinGW::HasNativeLLVMSupport() const {
469   return NativeLLVMSupport;
470 }
471 
472 bool toolchains::MinGW::IsUnwindTablesDefault(const ArgList &Args) const {
473   Arg *ExceptionArg = Args.getLastArg(options::OPT_fsjlj_exceptions,
474                                       options::OPT_fseh_exceptions,
475                                       options::OPT_fdwarf_exceptions);
476   if (ExceptionArg &&
477       ExceptionArg->getOption().matches(options::OPT_fseh_exceptions))
478     return true;
479   return getArch() == llvm::Triple::x86_64 ||
480          getArch() == llvm::Triple::aarch64;
481 }
482 
483 bool toolchains::MinGW::isPICDefault() const {
484   return getArch() == llvm::Triple::x86_64 ||
485          getArch() == llvm::Triple::aarch64;
486 }
487 
488 bool toolchains::MinGW::isPIEDefault(const llvm::opt::ArgList &Args) const {
489   return false;
490 }
491 
492 bool toolchains::MinGW::isPICDefaultForced() const { return true; }
493 
494 llvm::ExceptionHandling
495 toolchains::MinGW::GetExceptionModel(const ArgList &Args) const {
496   if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::aarch64)
497     return llvm::ExceptionHandling::WinEH;
498   return llvm::ExceptionHandling::DwarfCFI;
499 }
500 
501 SanitizerMask toolchains::MinGW::getSupportedSanitizers() const {
502   SanitizerMask Res = ToolChain::getSupportedSanitizers();
503   Res |= SanitizerKind::Address;
504   Res |= SanitizerKind::PointerCompare;
505   Res |= SanitizerKind::PointerSubtract;
506   Res |= SanitizerKind::Vptr;
507   return Res;
508 }
509 
510 void toolchains::MinGW::AddCudaIncludeArgs(const ArgList &DriverArgs,
511                                            ArgStringList &CC1Args) const {
512   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
513 }
514 
515 void toolchains::MinGW::AddHIPIncludeArgs(const ArgList &DriverArgs,
516                                           ArgStringList &CC1Args) const {
517   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
518 }
519 
520 void toolchains::MinGW::printVerboseInfo(raw_ostream &OS) const {
521   CudaInstallation.print(OS);
522   RocmInstallation.print(OS);
523 }
524 
525 // Include directories for various hosts:
526 
527 // Windows, mingw.org
528 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++
529 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32
530 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward
531 // c:\mingw\include
532 // c:\mingw\mingw32\include
533 
534 // Windows, mingw-w64 mingw-builds
535 // c:\mingw32\i686-w64-mingw32\include
536 // c:\mingw32\i686-w64-mingw32\include\c++
537 // c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32
538 // c:\mingw32\i686-w64-mingw32\include\c++\backward
539 
540 // Windows, mingw-w64 msys2
541 // c:\msys64\mingw32\include
542 // c:\msys64\mingw32\i686-w64-mingw32\include
543 // c:\msys64\mingw32\include\c++\4.9.2
544 // c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32
545 // c:\msys64\mingw32\include\c++\4.9.2\backward
546 
547 // openSUSE
548 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++
549 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32
550 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward
551 // /usr/x86_64-w64-mingw32/sys-root/mingw/include
552 
553 // Arch Linux
554 // /usr/i686-w64-mingw32/include/c++/5.1.0
555 // /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32
556 // /usr/i686-w64-mingw32/include/c++/5.1.0/backward
557 // /usr/i686-w64-mingw32/include
558 
559 // Ubuntu
560 // /usr/include/c++/4.8
561 // /usr/include/c++/4.8/x86_64-w64-mingw32
562 // /usr/include/c++/4.8/backward
563 // /usr/x86_64-w64-mingw32/include
564 
565 void toolchains::MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
566                                                   ArgStringList &CC1Args) const {
567   if (DriverArgs.hasArg(options::OPT_nostdinc))
568     return;
569 
570   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
571     SmallString<1024> P(getDriver().ResourceDir);
572     llvm::sys::path::append(P, "include");
573     addSystemInclude(DriverArgs, CC1Args, P.str());
574   }
575 
576   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
577     return;
578 
579   if (GetRuntimeLibType(DriverArgs) == ToolChain::RLT_Libgcc) {
580     // openSUSE
581     addSystemInclude(DriverArgs, CC1Args,
582                      Base + SubdirName + "/sys-root/mingw/include");
583   }
584 
585   addSystemInclude(DriverArgs, CC1Args,
586                    Base + SubdirName + llvm::sys::path::get_separator() +
587                        "include");
588   addSystemInclude(DriverArgs, CC1Args, Base + "include");
589 }
590 
591 void toolchains::MinGW::AddClangCXXStdlibIncludeArgs(
592     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
593   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
594       DriverArgs.hasArg(options::OPT_nostdincxx))
595     return;
596 
597   StringRef Slash = llvm::sys::path::get_separator();
598 
599   switch (GetCXXStdlibType(DriverArgs)) {
600   case ToolChain::CST_Libcxx: {
601     std::string TargetDir = (Base + "include" + Slash + getTripleString() +
602                              Slash + "c++" + Slash + "v1")
603                                 .str();
604     if (getDriver().getVFS().exists(TargetDir))
605       addSystemInclude(DriverArgs, CC1Args, TargetDir);
606     addSystemInclude(DriverArgs, CC1Args,
607                      Base + SubdirName + Slash + "include" + Slash + "c++" +
608                          Slash + "v1");
609     addSystemInclude(DriverArgs, CC1Args,
610                      Base + "include" + Slash + "c++" + Slash + "v1");
611     break;
612   }
613 
614   case ToolChain::CST_Libstdcxx:
615     llvm::SmallVector<llvm::SmallString<1024>, 4> CppIncludeBases;
616     CppIncludeBases.emplace_back(Base);
617     llvm::sys::path::append(CppIncludeBases[0], SubdirName, "include", "c++");
618     CppIncludeBases.emplace_back(Base);
619     llvm::sys::path::append(CppIncludeBases[1], SubdirName, "include", "c++",
620                             Ver);
621     CppIncludeBases.emplace_back(Base);
622     llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver);
623     CppIncludeBases.emplace_back(GccLibDir);
624     llvm::sys::path::append(CppIncludeBases[3], "include", "c++");
625     for (auto &CppIncludeBase : CppIncludeBases) {
626       addSystemInclude(DriverArgs, CC1Args, CppIncludeBase);
627       CppIncludeBase += Slash;
628       addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + SubdirName);
629       addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward");
630     }
631     break;
632   }
633 }
634 
635 static bool testTriple(const Driver &D, const llvm::Triple &Triple,
636                        const ArgList &Args) {
637   // If an explicit sysroot is set, that will be used and we shouldn't try to
638   // detect anything else.
639   std::string SubdirName;
640   if (D.SysRoot.size())
641     return true;
642   if (llvm::ErrorOr<std::string> TargetSubdir =
643           findClangRelativeSysroot(D, Triple, SubdirName))
644     return true;
645   if (llvm::ErrorOr<std::string> GPPName = findGcc(Triple))
646     return true;
647   // If we neither found a colocated sysroot or a matching gcc executable,
648   // conclude that we can't know if this is the correct spelling of the triple.
649   return false;
650 }
651 
652 static llvm::Triple adjustTriple(const Driver &D, const llvm::Triple &Triple,
653                                  const ArgList &Args) {
654   // First test if the original triple can find a sysroot with the triple
655   // name.
656   if (testTriple(D, Triple, Args))
657     return Triple;
658   llvm::SmallVector<llvm::StringRef, 3> Archs;
659   // If not, test a couple other possible arch names that might be what was
660   // intended.
661   if (Triple.getArch() == llvm::Triple::x86) {
662     Archs.emplace_back("i386");
663     Archs.emplace_back("i586");
664     Archs.emplace_back("i686");
665   } else if (Triple.getArch() == llvm::Triple::arm ||
666              Triple.getArch() == llvm::Triple::thumb) {
667     Archs.emplace_back("armv7");
668   }
669   for (auto A : Archs) {
670     llvm::Triple TestTriple(Triple);
671     TestTriple.setArchName(A);
672     if (testTriple(D, TestTriple, Args))
673       return TestTriple;
674   }
675   // If none was found, just proceed with the original value.
676   return Triple;
677 }
678 
679 void toolchains::MinGW::fixTripleArch(const Driver &D, llvm::Triple &Triple,
680                                       const ArgList &Args) {
681   if (Triple.getArch() == llvm::Triple::x86 ||
682       Triple.getArch() == llvm::Triple::arm ||
683       Triple.getArch() == llvm::Triple::thumb)
684     Triple = adjustTriple(D, Triple, Args);
685 }
686