xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/MinGW.cpp (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
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") ||
90         StringRef(Lib).startswith("ucrt") ||
91         StringRef(Lib).startswith("crtdll"))
92       return;
93   CmdArgs.push_back("-lmsvcrt");
94 }
95 
96 void tools::MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
97                                         const InputInfo &Output,
98                                         const InputInfoList &Inputs,
99                                         const ArgList &Args,
100                                         const char *LinkingOutput) const {
101   const ToolChain &TC = getToolChain();
102   const Driver &D = TC.getDriver();
103   const SanitizerArgs &Sanitize = TC.getSanitizerArgs(Args);
104 
105   ArgStringList CmdArgs;
106 
107   // Silence warning for "clang -g foo.o -o foo"
108   Args.ClaimAllArgs(options::OPT_g_Group);
109   // and "clang -emit-llvm foo.o -o foo"
110   Args.ClaimAllArgs(options::OPT_emit_llvm);
111   // and for "clang -w foo.o -o foo". Other warning options are already
112   // handled somewhere else.
113   Args.ClaimAllArgs(options::OPT_w);
114 
115   if (!D.SysRoot.empty())
116     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
117 
118   if (Args.hasArg(options::OPT_s))
119     CmdArgs.push_back("-s");
120 
121   CmdArgs.push_back("-m");
122   switch (TC.getArch()) {
123   case llvm::Triple::x86:
124     CmdArgs.push_back("i386pe");
125     break;
126   case llvm::Triple::x86_64:
127     CmdArgs.push_back("i386pep");
128     break;
129   case llvm::Triple::arm:
130   case llvm::Triple::thumb:
131     // FIXME: this is incorrect for WinCE
132     CmdArgs.push_back("thumb2pe");
133     break;
134   case llvm::Triple::aarch64:
135     CmdArgs.push_back("arm64pe");
136     break;
137   default:
138     D.Diag(diag::err_target_unknown_triple) << TC.getEffectiveTriple().str();
139   }
140 
141   Arg *SubsysArg =
142       Args.getLastArg(options::OPT_mwindows, options::OPT_mconsole);
143   if (SubsysArg && SubsysArg->getOption().matches(options::OPT_mwindows)) {
144     CmdArgs.push_back("--subsystem");
145     CmdArgs.push_back("windows");
146   } else if (SubsysArg &&
147              SubsysArg->getOption().matches(options::OPT_mconsole)) {
148     CmdArgs.push_back("--subsystem");
149     CmdArgs.push_back("console");
150   }
151 
152   if (Args.hasArg(options::OPT_mdll))
153     CmdArgs.push_back("--dll");
154   else if (Args.hasArg(options::OPT_shared))
155     CmdArgs.push_back("--shared");
156   if (Args.hasArg(options::OPT_static))
157     CmdArgs.push_back("-Bstatic");
158   else
159     CmdArgs.push_back("-Bdynamic");
160   if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
161     CmdArgs.push_back("-e");
162     if (TC.getArch() == llvm::Triple::x86)
163       CmdArgs.push_back("_DllMainCRTStartup@12");
164     else
165       CmdArgs.push_back("DllMainCRTStartup");
166     CmdArgs.push_back("--enable-auto-image-base");
167   }
168 
169   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
170     CmdArgs.push_back("--no-demangle");
171 
172   if (Arg *A = Args.getLastArg(options::OPT_mguard_EQ)) {
173     StringRef GuardArgs = A->getValue();
174     if (GuardArgs == "none")
175       CmdArgs.push_back("--no-guard-cf");
176     else if (GuardArgs == "cf" || GuardArgs == "cf-nochecks")
177       CmdArgs.push_back("--guard-cf");
178     else
179       D.Diag(diag::err_drv_unsupported_option_argument)
180           << A->getSpelling() << GuardArgs;
181   }
182 
183   CmdArgs.push_back("-o");
184   const char *OutputFile = Output.getFilename();
185   // GCC implicitly adds an .exe extension if it is given an output file name
186   // that lacks an extension.
187   // GCC used to do this only when the compiler itself runs on windows, but
188   // since GCC 8 it does the same when cross compiling as well.
189   if (!llvm::sys::path::has_extension(OutputFile)) {
190     CmdArgs.push_back(Args.MakeArgString(Twine(OutputFile) + ".exe"));
191     OutputFile = CmdArgs.back();
192   } else
193     CmdArgs.push_back(OutputFile);
194 
195   // FIXME: add -N, -n flags
196   Args.AddLastArg(CmdArgs, options::OPT_r);
197   Args.AddLastArg(CmdArgs, options::OPT_s);
198   Args.AddLastArg(CmdArgs, options::OPT_t);
199   Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
200   Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
201 
202   // Add asan_dynamic as the first import lib before other libs. This allows
203   // asan to be initialized as early as possible to increase its instrumentation
204   // coverage to include other user DLLs which has not been built with asan.
205   if (Sanitize.needsAsanRt() && !Args.hasArg(options::OPT_nostdlib) &&
206       !Args.hasArg(options::OPT_nodefaultlibs)) {
207     // MinGW always links against a shared MSVCRT.
208     CmdArgs.push_back(
209         TC.getCompilerRTArgString(Args, "asan_dynamic", ToolChain::FT_Shared));
210   }
211 
212   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
213     if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
214       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
215     } else {
216       if (Args.hasArg(options::OPT_municode))
217         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
218       else
219         CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
220     }
221     if (Args.hasArg(options::OPT_pg))
222       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
223     CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
224   }
225 
226   Args.AddAllArgs(CmdArgs, options::OPT_L);
227   TC.AddFilePathLibArgs(Args, CmdArgs);
228 
229   // Add the compiler-rt library directories if they exist to help
230   // the linker find the various sanitizer, builtin, and profiling runtimes.
231   for (const auto &LibPath : TC.getLibraryPaths()) {
232     if (TC.getVFS().exists(LibPath))
233       CmdArgs.push_back(Args.MakeArgString("-L" + LibPath));
234   }
235   auto CRTPath = TC.getCompilerRTPath();
236   if (TC.getVFS().exists(CRTPath))
237     CmdArgs.push_back(Args.MakeArgString("-L" + CRTPath));
238 
239   AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
240 
241   if (C.getDriver().IsFlangMode()) {
242     addFortranRuntimeLibraryPath(TC, Args, CmdArgs);
243     addFortranRuntimeLibs(TC, CmdArgs);
244   }
245 
246   // TODO: Add profile stuff here
247 
248   if (TC.ShouldLinkCXXStdlib(Args)) {
249     bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
250                                !Args.hasArg(options::OPT_static);
251     if (OnlyLibstdcxxStatic)
252       CmdArgs.push_back("-Bstatic");
253     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
254     if (OnlyLibstdcxxStatic)
255       CmdArgs.push_back("-Bdynamic");
256   }
257 
258   bool HasWindowsApp = false;
259   for (auto Lib : Args.getAllArgValues(options::OPT_l)) {
260     if (Lib == "windowsapp") {
261       HasWindowsApp = true;
262       break;
263     }
264   }
265 
266   if (!Args.hasArg(options::OPT_nostdlib)) {
267     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
268       if (Args.hasArg(options::OPT_static))
269         CmdArgs.push_back("--start-group");
270 
271       if (Args.hasArg(options::OPT_fstack_protector) ||
272           Args.hasArg(options::OPT_fstack_protector_strong) ||
273           Args.hasArg(options::OPT_fstack_protector_all)) {
274         CmdArgs.push_back("-lssp_nonshared");
275         CmdArgs.push_back("-lssp");
276       }
277 
278       if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
279                        options::OPT_fno_openmp, false)) {
280         switch (TC.getDriver().getOpenMPRuntime(Args)) {
281         case Driver::OMPRT_OMP:
282           CmdArgs.push_back("-lomp");
283           break;
284         case Driver::OMPRT_IOMP5:
285           CmdArgs.push_back("-liomp5md");
286           break;
287         case Driver::OMPRT_GOMP:
288           CmdArgs.push_back("-lgomp");
289           break;
290         case Driver::OMPRT_Unknown:
291           // Already diagnosed.
292           break;
293         }
294       }
295 
296       AddLibGCC(Args, CmdArgs);
297 
298       if (Args.hasArg(options::OPT_pg))
299         CmdArgs.push_back("-lgmon");
300 
301       if (Args.hasArg(options::OPT_pthread))
302         CmdArgs.push_back("-lpthread");
303 
304       if (Sanitize.needsAsanRt()) {
305         // MinGW always links against a shared MSVCRT.
306         CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dynamic",
307                                                     ToolChain::FT_Shared));
308         CmdArgs.push_back(
309             TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
310         CmdArgs.push_back("--require-defined");
311         CmdArgs.push_back(TC.getArch() == llvm::Triple::x86
312                               ? "___asan_seh_interceptor"
313                               : "__asan_seh_interceptor");
314         // Make sure the linker consider all object files from the dynamic
315         // runtime thunk.
316         CmdArgs.push_back("--whole-archive");
317         CmdArgs.push_back(
318             TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
319         CmdArgs.push_back("--no-whole-archive");
320       }
321 
322       TC.addProfileRTLibs(Args, CmdArgs);
323 
324       if (!HasWindowsApp) {
325         // Add system libraries. If linking to libwindowsapp.a, that import
326         // library replaces all these and we shouldn't accidentally try to
327         // link to the normal desktop mode dlls.
328         if (Args.hasArg(options::OPT_mwindows)) {
329           CmdArgs.push_back("-lgdi32");
330           CmdArgs.push_back("-lcomdlg32");
331         }
332         CmdArgs.push_back("-ladvapi32");
333         CmdArgs.push_back("-lshell32");
334         CmdArgs.push_back("-luser32");
335         CmdArgs.push_back("-lkernel32");
336       }
337 
338       if (Args.hasArg(options::OPT_static)) {
339         CmdArgs.push_back("--end-group");
340       } else {
341         AddLibGCC(Args, CmdArgs);
342         if (!HasWindowsApp)
343           CmdArgs.push_back("-lkernel32");
344       }
345     }
346 
347     if (!Args.hasArg(options::OPT_nostartfiles)) {
348       // Add crtfastmath.o if available and fast math is enabled.
349       TC.addFastMathRuntimeIfAvailable(Args, CmdArgs);
350 
351       CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
352     }
353   }
354   const char *Exec = Args.MakeArgString(TC.GetLinkerPath());
355   C.addCommand(std::make_unique<Command>(JA, *this,
356                                          ResponseFileSupport::AtFileUTF8(),
357                                          Exec, CmdArgs, Inputs, Output));
358 }
359 
360 static bool isCrossCompiling(const llvm::Triple &T, bool RequireArchMatch) {
361   llvm::Triple HostTriple(llvm::Triple::normalize(LLVM_HOST_TRIPLE));
362   if (HostTriple.getOS() != llvm::Triple::Win32)
363     return true;
364   if (RequireArchMatch && HostTriple.getArch() != T.getArch())
365     return true;
366   return false;
367 }
368 
369 // Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple.
370 static bool findGccVersion(StringRef LibDir, std::string &GccLibDir,
371                            std::string &Ver,
372                            toolchains::Generic_GCC::GCCVersion &Version) {
373   Version = toolchains::Generic_GCC::GCCVersion::Parse("0.0.0");
374   std::error_code EC;
375   for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE;
376        LI = LI.increment(EC)) {
377     StringRef VersionText = llvm::sys::path::filename(LI->path());
378     auto CandidateVersion =
379         toolchains::Generic_GCC::GCCVersion::Parse(VersionText);
380     if (CandidateVersion.Major == -1)
381       continue;
382     if (CandidateVersion <= Version)
383       continue;
384     Version = CandidateVersion;
385     Ver = std::string(VersionText);
386     GccLibDir = LI->path();
387   }
388   return Ver.size();
389 }
390 
391 static llvm::Triple getLiteralTriple(const Driver &D, const llvm::Triple &T) {
392   llvm::Triple LiteralTriple(D.getTargetTriple());
393   // The arch portion of the triple may be overridden by -m32/-m64.
394   LiteralTriple.setArchName(T.getArchName());
395   return LiteralTriple;
396 }
397 
398 void toolchains::MinGW::findGccLibDir(const llvm::Triple &LiteralTriple) {
399   llvm::SmallVector<llvm::SmallString<32>, 5> SubdirNames;
400   SubdirNames.emplace_back(LiteralTriple.str());
401   SubdirNames.emplace_back(getTriple().str());
402   SubdirNames.emplace_back(getTriple().getArchName());
403   SubdirNames.back() += "-w64-mingw32";
404   SubdirNames.emplace_back(getTriple().getArchName());
405   SubdirNames.back() += "-w64-mingw32ucrt";
406   SubdirNames.emplace_back("mingw32");
407   if (SubdirName.empty()) {
408     SubdirName = getTriple().getArchName();
409     SubdirName += "-w64-mingw32";
410   }
411   // lib: Arch Linux, Ubuntu, Windows
412   // lib64: openSUSE Linux
413   for (StringRef CandidateLib : {"lib", "lib64"}) {
414     for (StringRef CandidateSysroot : SubdirNames) {
415       llvm::SmallString<1024> LibDir(Base);
416       llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateSysroot);
417       if (findGccVersion(LibDir, GccLibDir, Ver, GccVer)) {
418         SubdirName = std::string(CandidateSysroot);
419         return;
420       }
421     }
422   }
423 }
424 
425 static llvm::ErrorOr<std::string> findGcc(const llvm::Triple &LiteralTriple,
426                                           const llvm::Triple &T) {
427   llvm::SmallVector<llvm::SmallString<32>, 5> Gccs;
428   Gccs.emplace_back(LiteralTriple.str());
429   Gccs.back() += "-gcc";
430   Gccs.emplace_back(T.str());
431   Gccs.back() += "-gcc";
432   Gccs.emplace_back(T.getArchName());
433   Gccs.back() += "-w64-mingw32-gcc";
434   Gccs.emplace_back(T.getArchName());
435   Gccs.back() += "-w64-mingw32ucrt-gcc";
436   Gccs.emplace_back("mingw32-gcc");
437   // Please do not add "gcc" here
438   for (StringRef CandidateGcc : Gccs)
439     if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName(CandidateGcc))
440       return GPPName;
441   return make_error_code(std::errc::no_such_file_or_directory);
442 }
443 
444 static llvm::ErrorOr<std::string>
445 findClangRelativeSysroot(const Driver &D, const llvm::Triple &LiteralTriple,
446                          const llvm::Triple &T, std::string &SubdirName) {
447   llvm::SmallVector<llvm::SmallString<32>, 4> Subdirs;
448   Subdirs.emplace_back(LiteralTriple.str());
449   Subdirs.emplace_back(T.str());
450   Subdirs.emplace_back(T.getArchName());
451   Subdirs.back() += "-w64-mingw32";
452   Subdirs.emplace_back(T.getArchName());
453   Subdirs.back() += "-w64-mingw32ucrt";
454   StringRef ClangRoot = llvm::sys::path::parent_path(D.getInstalledDir());
455   StringRef Sep = llvm::sys::path::get_separator();
456   for (StringRef CandidateSubdir : Subdirs) {
457     if (llvm::sys::fs::is_directory(ClangRoot + Sep + CandidateSubdir)) {
458       SubdirName = std::string(CandidateSubdir);
459       return (ClangRoot + Sep + CandidateSubdir).str();
460     }
461   }
462   return make_error_code(std::errc::no_such_file_or_directory);
463 }
464 
465 toolchains::MinGW::MinGW(const Driver &D, const llvm::Triple &Triple,
466                          const ArgList &Args)
467     : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
468       RocmInstallation(D, Triple, Args) {
469   getProgramPaths().push_back(getDriver().getInstalledDir());
470 
471   // The sequence for detecting a sysroot here should be kept in sync with
472   // the testTriple function below.
473   llvm::Triple LiteralTriple = getLiteralTriple(D, getTriple());
474   if (getDriver().SysRoot.size())
475     Base = getDriver().SysRoot;
476   // Look for <clang-bin>/../<triplet>; if found, use <clang-bin>/.. as the
477   // base as it could still be a base for a gcc setup with libgcc.
478   else if (llvm::ErrorOr<std::string> TargetSubdir = findClangRelativeSysroot(
479                getDriver(), LiteralTriple, getTriple(), SubdirName))
480     Base = std::string(llvm::sys::path::parent_path(TargetSubdir.get()));
481   else if (llvm::ErrorOr<std::string> GPPName =
482                findGcc(LiteralTriple, getTriple()))
483     Base = std::string(llvm::sys::path::parent_path(
484         llvm::sys::path::parent_path(GPPName.get())));
485   else
486     Base = std::string(
487         llvm::sys::path::parent_path(getDriver().getInstalledDir()));
488 
489   Base += llvm::sys::path::get_separator();
490   findGccLibDir(LiteralTriple);
491   TripleDirName = SubdirName;
492   // GccLibDir must precede Base/lib so that the
493   // correct crtbegin.o ,cetend.o would be found.
494   getFilePaths().push_back(GccLibDir);
495 
496   // openSUSE/Fedora
497   std::string CandidateSubdir = SubdirName + "/sys-root/mingw";
498   if (getDriver().getVFS().exists(Base + CandidateSubdir))
499     SubdirName = CandidateSubdir;
500 
501   getFilePaths().push_back(
502       (Base + SubdirName + llvm::sys::path::get_separator() + "lib").str());
503 
504   // Gentoo
505   getFilePaths().push_back(
506       (Base + SubdirName + llvm::sys::path::get_separator() + "mingw/lib").str());
507 
508   // Only include <base>/lib if we're not cross compiling (not even for
509   // windows->windows to a different arch), or if the sysroot has been set
510   // (where we presume the user has pointed it at an arch specific
511   // subdirectory).
512   if (!::isCrossCompiling(getTriple(), /*RequireArchMatch=*/true) ||
513       getDriver().SysRoot.size())
514     getFilePaths().push_back(Base + "lib");
515 
516   NativeLLVMSupport =
517       Args.getLastArgValue(options::OPT_fuse_ld_EQ, CLANG_DEFAULT_LINKER)
518           .equals_insensitive("lld");
519 }
520 
521 Tool *toolchains::MinGW::getTool(Action::ActionClass AC) const {
522   switch (AC) {
523   case Action::PreprocessJobClass:
524     if (!Preprocessor)
525       Preprocessor.reset(new tools::gcc::Preprocessor(*this));
526     return Preprocessor.get();
527   case Action::CompileJobClass:
528     if (!Compiler)
529       Compiler.reset(new tools::gcc::Compiler(*this));
530     return Compiler.get();
531   default:
532     return ToolChain::getTool(AC);
533   }
534 }
535 
536 Tool *toolchains::MinGW::buildAssembler() const {
537   return new tools::MinGW::Assembler(*this);
538 }
539 
540 Tool *toolchains::MinGW::buildLinker() const {
541   return new tools::MinGW::Linker(*this);
542 }
543 
544 bool toolchains::MinGW::HasNativeLLVMSupport() const {
545   return NativeLLVMSupport;
546 }
547 
548 ToolChain::UnwindTableLevel
549 toolchains::MinGW::getDefaultUnwindTableLevel(const ArgList &Args) const {
550   Arg *ExceptionArg = Args.getLastArg(options::OPT_fsjlj_exceptions,
551                                       options::OPT_fseh_exceptions,
552                                       options::OPT_fdwarf_exceptions);
553   if (ExceptionArg &&
554       ExceptionArg->getOption().matches(options::OPT_fseh_exceptions))
555     return UnwindTableLevel::Asynchronous;
556 
557   if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::arm ||
558       getArch() == llvm::Triple::thumb || getArch() == llvm::Triple::aarch64)
559     return UnwindTableLevel::Asynchronous;
560   return UnwindTableLevel::None;
561 }
562 
563 bool toolchains::MinGW::isPICDefault() const {
564   return getArch() == llvm::Triple::x86_64 ||
565          getArch() == llvm::Triple::aarch64;
566 }
567 
568 bool toolchains::MinGW::isPIEDefault(const llvm::opt::ArgList &Args) const {
569   return false;
570 }
571 
572 bool toolchains::MinGW::isPICDefaultForced() const { return true; }
573 
574 llvm::ExceptionHandling
575 toolchains::MinGW::GetExceptionModel(const ArgList &Args) const {
576   if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::aarch64 ||
577       getArch() == llvm::Triple::arm || getArch() == llvm::Triple::thumb)
578     return llvm::ExceptionHandling::WinEH;
579   return llvm::ExceptionHandling::DwarfCFI;
580 }
581 
582 SanitizerMask toolchains::MinGW::getSupportedSanitizers() const {
583   SanitizerMask Res = ToolChain::getSupportedSanitizers();
584   Res |= SanitizerKind::Address;
585   Res |= SanitizerKind::PointerCompare;
586   Res |= SanitizerKind::PointerSubtract;
587   Res |= SanitizerKind::Vptr;
588   return Res;
589 }
590 
591 void toolchains::MinGW::AddCudaIncludeArgs(const ArgList &DriverArgs,
592                                            ArgStringList &CC1Args) const {
593   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
594 }
595 
596 void toolchains::MinGW::AddHIPIncludeArgs(const ArgList &DriverArgs,
597                                           ArgStringList &CC1Args) const {
598   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
599 }
600 
601 void toolchains::MinGW::printVerboseInfo(raw_ostream &OS) const {
602   CudaInstallation.print(OS);
603   RocmInstallation.print(OS);
604 }
605 
606 // Include directories for various hosts:
607 
608 // Windows, mingw.org
609 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++
610 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32
611 // c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward
612 // c:\mingw\include
613 // c:\mingw\mingw32\include
614 
615 // Windows, mingw-w64 mingw-builds
616 // c:\mingw32\i686-w64-mingw32\include
617 // c:\mingw32\i686-w64-mingw32\include\c++
618 // c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32
619 // c:\mingw32\i686-w64-mingw32\include\c++\backward
620 
621 // Windows, mingw-w64 msys2
622 // c:\msys64\mingw32\include
623 // c:\msys64\mingw32\i686-w64-mingw32\include
624 // c:\msys64\mingw32\include\c++\4.9.2
625 // c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32
626 // c:\msys64\mingw32\include\c++\4.9.2\backward
627 
628 // openSUSE
629 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++
630 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32
631 // /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward
632 // /usr/x86_64-w64-mingw32/sys-root/mingw/include
633 
634 // Arch Linux
635 // /usr/i686-w64-mingw32/include/c++/5.1.0
636 // /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32
637 // /usr/i686-w64-mingw32/include/c++/5.1.0/backward
638 // /usr/i686-w64-mingw32/include
639 
640 // Ubuntu
641 // /usr/include/c++/4.8
642 // /usr/include/c++/4.8/x86_64-w64-mingw32
643 // /usr/include/c++/4.8/backward
644 // /usr/x86_64-w64-mingw32/include
645 
646 // Fedora
647 // /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/x86_64-w64-mingw32ucrt
648 // /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/backward
649 // /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include
650 // /usr/lib/gcc/x86_64-w64-mingw32ucrt/12.2.1/include-fixed
651 
652 void toolchains::MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
653                                                   ArgStringList &CC1Args) const {
654   if (DriverArgs.hasArg(options::OPT_nostdinc))
655     return;
656 
657   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
658     SmallString<1024> P(getDriver().ResourceDir);
659     llvm::sys::path::append(P, "include");
660     addSystemInclude(DriverArgs, CC1Args, P.str());
661   }
662 
663   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
664     return;
665 
666   addSystemInclude(DriverArgs, CC1Args,
667                    Base + SubdirName + llvm::sys::path::get_separator() +
668                        "include");
669 
670   // Gentoo
671   addSystemInclude(DriverArgs, CC1Args,
672                    Base + SubdirName + llvm::sys::path::get_separator() + "usr/include");
673 
674   // Only include <base>/include if we're not cross compiling (but do allow it
675   // if we're on Windows and building for Windows on another architecture),
676   // or if the sysroot has been set (where we presume the user has pointed it
677   // at an arch specific subdirectory).
678   if (!::isCrossCompiling(getTriple(), /*RequireArchMatch=*/false) ||
679       getDriver().SysRoot.size())
680     addSystemInclude(DriverArgs, CC1Args, Base + "include");
681 }
682 
683 void toolchains::MinGW::addClangTargetOptions(
684     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
685     Action::OffloadKind DeviceOffloadKind) const {
686   if (Arg *A = DriverArgs.getLastArg(options::OPT_mguard_EQ)) {
687     StringRef GuardArgs = A->getValue();
688     if (GuardArgs == "none") {
689       // Do nothing.
690     } else if (GuardArgs == "cf") {
691       // Emit CFG instrumentation and the table of address-taken functions.
692       CC1Args.push_back("-cfguard");
693     } else if (GuardArgs == "cf-nochecks") {
694       // Emit only the table of address-taken functions.
695       CC1Args.push_back("-cfguard-no-checks");
696     } else {
697       getDriver().Diag(diag::err_drv_unsupported_option_argument)
698           << A->getSpelling() << GuardArgs;
699     }
700   }
701 
702   CC1Args.push_back("-fno-use-init-array");
703 
704   for (auto Opt : {options::OPT_mthreads, options::OPT_mwindows,
705                    options::OPT_mconsole, options::OPT_mdll}) {
706     if (Arg *A = DriverArgs.getLastArgNoClaim(Opt))
707       A->ignoreTargetSpecific();
708   }
709 }
710 
711 void toolchains::MinGW::AddClangCXXStdlibIncludeArgs(
712     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
713   if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
714                         options::OPT_nostdincxx))
715     return;
716 
717   StringRef Slash = llvm::sys::path::get_separator();
718 
719   switch (GetCXXStdlibType(DriverArgs)) {
720   case ToolChain::CST_Libcxx: {
721     std::string TargetDir = (Base + "include" + Slash + getTripleString() +
722                              Slash + "c++" + Slash + "v1")
723                                 .str();
724     if (getDriver().getVFS().exists(TargetDir))
725       addSystemInclude(DriverArgs, CC1Args, TargetDir);
726     addSystemInclude(DriverArgs, CC1Args,
727                      Base + SubdirName + Slash + "include" + Slash + "c++" +
728                          Slash + "v1");
729     addSystemInclude(DriverArgs, CC1Args,
730                      Base + "include" + Slash + "c++" + Slash + "v1");
731     break;
732   }
733 
734   case ToolChain::CST_Libstdcxx:
735     llvm::SmallVector<llvm::SmallString<1024>, 7> CppIncludeBases;
736     CppIncludeBases.emplace_back(Base);
737     llvm::sys::path::append(CppIncludeBases[0], SubdirName, "include", "c++");
738     CppIncludeBases.emplace_back(Base);
739     llvm::sys::path::append(CppIncludeBases[1], SubdirName, "include", "c++",
740                             Ver);
741     CppIncludeBases.emplace_back(Base);
742     llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver);
743     CppIncludeBases.emplace_back(GccLibDir);
744     llvm::sys::path::append(CppIncludeBases[3], "include", "c++");
745     CppIncludeBases.emplace_back(GccLibDir);
746     llvm::sys::path::append(CppIncludeBases[4], "include",
747                             "g++-v" + GccVer.Text);
748     CppIncludeBases.emplace_back(GccLibDir);
749     llvm::sys::path::append(CppIncludeBases[5], "include",
750                             "g++-v" + GccVer.MajorStr + "." + GccVer.MinorStr);
751     CppIncludeBases.emplace_back(GccLibDir);
752     llvm::sys::path::append(CppIncludeBases[6], "include",
753                             "g++-v" + GccVer.MajorStr);
754     for (auto &CppIncludeBase : CppIncludeBases) {
755       addSystemInclude(DriverArgs, CC1Args, CppIncludeBase);
756       CppIncludeBase += Slash;
757       addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + TripleDirName);
758       addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward");
759     }
760     break;
761   }
762 }
763 
764 static bool testTriple(const Driver &D, const llvm::Triple &Triple,
765                        const ArgList &Args) {
766   // If an explicit sysroot is set, that will be used and we shouldn't try to
767   // detect anything else.
768   std::string SubdirName;
769   if (D.SysRoot.size())
770     return true;
771   llvm::Triple LiteralTriple = getLiteralTriple(D, Triple);
772   if (llvm::ErrorOr<std::string> TargetSubdir =
773           findClangRelativeSysroot(D, LiteralTriple, Triple, SubdirName))
774     return true;
775   if (llvm::ErrorOr<std::string> GPPName = findGcc(LiteralTriple, Triple))
776     return true;
777   // If we neither found a colocated sysroot or a matching gcc executable,
778   // conclude that we can't know if this is the correct spelling of the triple.
779   return false;
780 }
781 
782 static llvm::Triple adjustTriple(const Driver &D, const llvm::Triple &Triple,
783                                  const ArgList &Args) {
784   // First test if the original triple can find a sysroot with the triple
785   // name.
786   if (testTriple(D, Triple, Args))
787     return Triple;
788   llvm::SmallVector<llvm::StringRef, 3> Archs;
789   // If not, test a couple other possible arch names that might be what was
790   // intended.
791   if (Triple.getArch() == llvm::Triple::x86) {
792     Archs.emplace_back("i386");
793     Archs.emplace_back("i586");
794     Archs.emplace_back("i686");
795   } else if (Triple.getArch() == llvm::Triple::arm ||
796              Triple.getArch() == llvm::Triple::thumb) {
797     Archs.emplace_back("armv7");
798   }
799   for (auto A : Archs) {
800     llvm::Triple TestTriple(Triple);
801     TestTriple.setArchName(A);
802     if (testTriple(D, TestTriple, Args))
803       return TestTriple;
804   }
805   // If none was found, just proceed with the original value.
806   return Triple;
807 }
808 
809 void toolchains::MinGW::fixTripleArch(const Driver &D, llvm::Triple &Triple,
810                                       const ArgList &Args) {
811   if (Triple.getArch() == llvm::Triple::x86 ||
812       Triple.getArch() == llvm::Triple::arm ||
813       Triple.getArch() == llvm::Triple::thumb)
814     Triple = adjustTriple(D, Triple, Args);
815 }
816