clang 22.0.0git
MinGW.cpp
Go to the documentation of this file.
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 "clang/Config/config.h"
13#include "clang/Driver/Driver.h"
17#include "llvm/Config/llvm-config.h" // for LLVM_HOST_TRIPLE
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
24using namespace clang::diag;
25using namespace clang::driver;
26using namespace clang;
27using namespace llvm::opt;
28
29/// MinGW Tools
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
61void 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).starts_with("msvcr") ||
90 StringRef(Lib).starts_with("ucrt") ||
91 StringRef(Lib).starts_with("crtdll")) {
92 std::string CRTLib = (llvm::Twine("-l") + Lib).str();
93 // Respect the user's chosen crt variant, but still provide it
94 // again as the last linker argument, because some of the libraries
95 // we added above may depend on it.
96 CmdArgs.push_back(Args.MakeArgStringRef(CRTLib));
97 return;
98 }
99 }
100 CmdArgs.push_back("-lmsvcrt");
101}
102
104 const InputInfo &Output,
105 const InputInfoList &Inputs,
106 const ArgList &Args,
107 const char *LinkingOutput) const {
108 const ToolChain &TC = getToolChain();
109 const Driver &D = TC.getDriver();
110 const SanitizerArgs &Sanitize = TC.getSanitizerArgs(Args);
111
112 ArgStringList CmdArgs;
113
114 // Silence warning for "clang -g foo.o -o foo"
115 Args.ClaimAllArgs(options::OPT_g_Group);
116 // and "clang -emit-llvm foo.o -o foo"
117 Args.ClaimAllArgs(options::OPT_emit_llvm);
118 // and for "clang -w foo.o -o foo". Other warning options are already
119 // handled somewhere else.
120 Args.ClaimAllArgs(options::OPT_w);
121
122 if (!D.SysRoot.empty())
123 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
124
125 if (Args.hasArg(options::OPT_s))
126 CmdArgs.push_back("-s");
127
128 CmdArgs.push_back("-m");
129 switch (TC.getArch()) {
130 case llvm::Triple::x86:
131 CmdArgs.push_back("i386pe");
132 break;
133 case llvm::Triple::x86_64:
134 CmdArgs.push_back("i386pep");
135 break;
136 case llvm::Triple::arm:
137 case llvm::Triple::thumb:
138 // FIXME: this is incorrect for WinCE
139 CmdArgs.push_back("thumb2pe");
140 break;
141 case llvm::Triple::aarch64:
142 if (Args.hasArg(options::OPT_marm64x))
143 CmdArgs.push_back("arm64xpe");
144 else if (TC.getEffectiveTriple().isWindowsArm64EC())
145 CmdArgs.push_back("arm64ecpe");
146 else
147 CmdArgs.push_back("arm64pe");
148 break;
149 case llvm::Triple::mipsel:
150 CmdArgs.push_back("mipspe");
151 break;
152 default:
153 D.Diag(diag::err_target_unknown_triple) << TC.getEffectiveTriple().str();
154 }
155
156 Arg *SubsysArg =
157 Args.getLastArg(options::OPT_mwindows, options::OPT_mconsole);
158 if (SubsysArg && SubsysArg->getOption().matches(options::OPT_mwindows)) {
159 CmdArgs.push_back("--subsystem");
160 CmdArgs.push_back("windows");
161 } else if (SubsysArg &&
162 SubsysArg->getOption().matches(options::OPT_mconsole)) {
163 CmdArgs.push_back("--subsystem");
164 CmdArgs.push_back("console");
165 }
166
167 if (Args.hasArg(options::OPT_mdll))
168 CmdArgs.push_back("--dll");
169 else if (Args.hasArg(options::OPT_shared))
170 CmdArgs.push_back("--shared");
171 if (Args.hasArg(options::OPT_static))
172 CmdArgs.push_back("-Bstatic");
173 else
174 CmdArgs.push_back("-Bdynamic");
175 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
176 CmdArgs.push_back("-e");
177 if (TC.getArch() == llvm::Triple::x86)
178 CmdArgs.push_back("_DllMainCRTStartup@12");
179 else
180 CmdArgs.push_back("DllMainCRTStartup");
181 CmdArgs.push_back("--enable-auto-image-base");
182 }
183
184 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
185 CmdArgs.push_back("--no-demangle");
186
187 if (!Args.hasFlag(options::OPT_fauto_import, options::OPT_fno_auto_import,
188 true))
189 CmdArgs.push_back("--disable-auto-import");
190
191 if (Arg *A = Args.getLastArg(options::OPT_mguard_EQ)) {
192 StringRef GuardArgs = A->getValue();
193 if (GuardArgs == "none")
194 CmdArgs.push_back("--no-guard-cf");
195 else if (GuardArgs == "cf" || GuardArgs == "cf-nochecks")
196 CmdArgs.push_back("--guard-cf");
197 else
198 D.Diag(diag::err_drv_unsupported_option_argument)
199 << A->getSpelling() << GuardArgs;
200 }
201
202 if (Args.hasArg(options::OPT_fms_hotpatch))
203 CmdArgs.push_back("--functionpadmin");
204
205 CmdArgs.push_back("-o");
206 const char *OutputFile = Output.getFilename();
207 // GCC implicitly adds an .exe extension if it is given an output file name
208 // that lacks an extension.
209 // GCC used to do this only when the compiler itself runs on windows, but
210 // since GCC 8 it does the same when cross compiling as well.
211 if (!llvm::sys::path::has_extension(OutputFile)) {
212 CmdArgs.push_back(Args.MakeArgString(Twine(OutputFile) + ".exe"));
213 OutputFile = CmdArgs.back();
214 } else
215 CmdArgs.push_back(OutputFile);
216
217 // FIXME: add -N, -n flags
218 Args.AddLastArg(CmdArgs, options::OPT_r);
219 Args.AddLastArg(CmdArgs, options::OPT_s);
220 Args.AddLastArg(CmdArgs, options::OPT_t);
221 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
222
223 // Add asan_dynamic as the first import lib before other libs. This allows
224 // asan to be initialized as early as possible to increase its instrumentation
225 // coverage to include other user DLLs which has not been built with asan.
226 if (Sanitize.needsAsanRt() && !Args.hasArg(options::OPT_nostdlib) &&
227 !Args.hasArg(options::OPT_nodefaultlibs)) {
228 // MinGW always links against a shared MSVCRT.
229 CmdArgs.push_back(
230 TC.getCompilerRTArgString(Args, "asan_dynamic", ToolChain::FT_Shared));
231 }
232
233 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
234 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
235 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
236 } else {
237 if (Args.hasArg(options::OPT_municode))
238 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
239 else
240 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
241 }
242 if (Args.hasArg(options::OPT_pg))
243 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
244 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
245 }
246
247 Args.AddAllArgs(CmdArgs, options::OPT_L);
248 TC.AddFilePathLibArgs(Args, CmdArgs);
249
250 // Add the compiler-rt library directories if they exist to help
251 // the linker find the various sanitizer, builtin, and profiling runtimes.
252 for (const auto &LibPath : TC.getLibraryPaths()) {
253 if (TC.getVFS().exists(LibPath))
254 CmdArgs.push_back(Args.MakeArgString("-L" + LibPath));
255 }
256 auto CRTPath = TC.getCompilerRTPath();
257 if (TC.getVFS().exists(CRTPath))
258 CmdArgs.push_back(Args.MakeArgString("-L" + CRTPath));
259
260 AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
261
262 if (D.isUsingLTO())
263 addLTOOptions(TC, Args, CmdArgs, Output, Inputs,
264 D.getLTOMode() == LTOK_Thin);
265
266 if (C.getDriver().IsFlangMode() &&
267 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
268 TC.addFortranRuntimeLibraryPath(Args, CmdArgs);
269 TC.addFortranRuntimeLibs(Args, CmdArgs);
270 }
271
272 // TODO: Add profile stuff here
273
274 if (TC.ShouldLinkCXXStdlib(Args)) {
275 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
276 !Args.hasArg(options::OPT_static);
277 if (OnlyLibstdcxxStatic)
278 CmdArgs.push_back("-Bstatic");
279 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
280 if (OnlyLibstdcxxStatic)
281 CmdArgs.push_back("-Bdynamic");
282 }
283
284 bool HasWindowsApp = false;
285 for (auto Lib : Args.getAllArgValues(options::OPT_l)) {
286 if (Lib == "windowsapp") {
287 HasWindowsApp = true;
288 break;
289 }
290 }
291
292 if (!Args.hasArg(options::OPT_nostdlib)) {
293 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
294 if (Args.hasArg(options::OPT_static))
295 CmdArgs.push_back("--start-group");
296
297 if (Args.hasArg(options::OPT_fstack_protector) ||
298 Args.hasArg(options::OPT_fstack_protector_strong) ||
299 Args.hasArg(options::OPT_fstack_protector_all)) {
300 CmdArgs.push_back("-lssp_nonshared");
301 CmdArgs.push_back("-lssp");
302 }
303
304 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
305 options::OPT_fno_openmp, false)) {
306 switch (TC.getDriver().getOpenMPRuntime(Args)) {
308 CmdArgs.push_back("-lomp");
309 break;
311 CmdArgs.push_back("-liomp5md");
312 break;
314 CmdArgs.push_back("-lgomp");
315 break;
317 // Already diagnosed.
318 break;
319 }
320 }
321
322 AddLibGCC(Args, CmdArgs);
323
324 if (Args.hasArg(options::OPT_pg))
325 CmdArgs.push_back("-lgmon");
326
327 if (Args.hasArg(options::OPT_pthread))
328 CmdArgs.push_back("-lpthread");
329
330 if (Sanitize.needsAsanRt()) {
331 // MinGW always links against a shared MSVCRT.
332 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dynamic",
334 CmdArgs.push_back(
335 TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
336 CmdArgs.push_back("--require-defined");
337 CmdArgs.push_back(TC.getArch() == llvm::Triple::x86
338 ? "___asan_seh_interceptor"
339 : "__asan_seh_interceptor");
340 // Make sure the linker consider all object files from the dynamic
341 // runtime thunk.
342 CmdArgs.push_back("--whole-archive");
343 CmdArgs.push_back(
344 TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
345 CmdArgs.push_back("--no-whole-archive");
346 }
347
348 TC.addProfileRTLibs(Args, CmdArgs);
349
350 if (!HasWindowsApp) {
351 // Add system libraries. If linking to libwindowsapp.a, that import
352 // library replaces all these and we shouldn't accidentally try to
353 // link to the normal desktop mode dlls.
354 if (Args.hasArg(options::OPT_mwindows)) {
355 CmdArgs.push_back("-lgdi32");
356 CmdArgs.push_back("-lcomdlg32");
357 }
358 CmdArgs.push_back("-ladvapi32");
359 CmdArgs.push_back("-lshell32");
360 CmdArgs.push_back("-luser32");
361 CmdArgs.push_back("-lkernel32");
362 }
363
364 if (Args.hasArg(options::OPT_static)) {
365 CmdArgs.push_back("--end-group");
366 } else {
367 AddLibGCC(Args, CmdArgs);
368 if (!HasWindowsApp)
369 CmdArgs.push_back("-lkernel32");
370 }
371 }
372
373 if (!Args.hasArg(options::OPT_nostartfiles)) {
374 // Add crtfastmath.o if available and fast math is enabled.
375 TC.addFastMathRuntimeIfAvailable(Args, CmdArgs);
376
377 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
378 }
379 }
380 const char *Exec = Args.MakeArgString(TC.GetLinkerPath());
381 C.addCommand(std::make_unique<Command>(JA, *this,
383 Exec, CmdArgs, Inputs, Output));
384}
385
386static bool isCrossCompiling(const llvm::Triple &T, bool RequireArchMatch) {
387 llvm::Triple HostTriple(llvm::Triple::normalize(LLVM_HOST_TRIPLE));
388 if (HostTriple.getOS() != llvm::Triple::Win32)
389 return true;
390 if (RequireArchMatch && HostTriple.getArch() != T.getArch())
391 return true;
392 return false;
393}
394
395// Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple.
396static bool findGccVersion(StringRef LibDir, std::string &GccLibDir,
397 std::string &Ver,
400 std::error_code EC;
401 for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE;
402 LI = LI.increment(EC)) {
403 StringRef VersionText = llvm::sys::path::filename(LI->path());
404 auto CandidateVersion =
406 if (CandidateVersion.Major == -1)
407 continue;
408 if (CandidateVersion <= Version)
409 continue;
410 Version = CandidateVersion;
411 Ver = std::string(VersionText);
412 GccLibDir = LI->path();
413 }
414 return Ver.size();
415}
416
417static llvm::Triple getLiteralTriple(const Driver &D, const llvm::Triple &T) {
418 llvm::Triple LiteralTriple(D.getTargetTriple());
419 // The arch portion of the triple may be overridden by -m32/-m64.
420 LiteralTriple.setArchName(T.getArchName());
421 return LiteralTriple;
422}
423
424void toolchains::MinGW::findGccLibDir(const llvm::Triple &LiteralTriple) {
426 SubdirNames.emplace_back(LiteralTriple.str());
427 SubdirNames.emplace_back(getTriple().str());
428 SubdirNames.emplace_back(getTriple().getArchName());
429 SubdirNames.back() += "-w64-mingw32";
430 SubdirNames.emplace_back(getTriple().getArchName());
431 SubdirNames.back() += "-w64-mingw32ucrt";
432 SubdirNames.emplace_back("mingw32");
433 if (SubdirName.empty()) {
434 SubdirName = getTriple().getArchName();
435 SubdirName += "-w64-mingw32";
436 }
437 // lib: Arch Linux, Ubuntu, Windows
438 // lib64: openSUSE Linux
439 for (StringRef CandidateLib : {"lib", "lib64"}) {
440 for (StringRef CandidateSysroot : SubdirNames) {
442 llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateSysroot);
443 if (findGccVersion(LibDir, GccLibDir, Ver, GccVer)) {
444 SubdirName = std::string(CandidateSysroot);
445 return;
446 }
447 }
448 }
449}
450
451static llvm::ErrorOr<std::string> findGcc(const llvm::Triple &LiteralTriple,
452 const llvm::Triple &T) {
454 Gccs.emplace_back(LiteralTriple.str());
455 Gccs.back() += "-gcc";
456 Gccs.emplace_back(T.str());
457 Gccs.back() += "-gcc";
458 Gccs.emplace_back(T.getArchName());
459 Gccs.back() += "-w64-mingw32-gcc";
460 Gccs.emplace_back(T.getArchName());
461 Gccs.back() += "-w64-mingw32ucrt-gcc";
462 Gccs.emplace_back("mingw32-gcc");
463 // Please do not add "gcc" here
464 for (StringRef CandidateGcc : Gccs)
465 if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName(CandidateGcc))
466 return GPPName;
467 return make_error_code(std::errc::no_such_file_or_directory);
468}
469
470static llvm::ErrorOr<std::string>
471findClangRelativeSysroot(const Driver &D, const llvm::Triple &LiteralTriple,
472 const llvm::Triple &T, std::string &SubdirName) {
474 Subdirs.emplace_back(LiteralTriple.str());
475 Subdirs.emplace_back(T.str());
476 Subdirs.emplace_back(T.getArchName());
477 Subdirs.back() += "-w64-mingw32";
478 Subdirs.emplace_back(T.getArchName());
479 Subdirs.back() += "-w64-mingw32ucrt";
480 StringRef ClangRoot = llvm::sys::path::parent_path(D.Dir);
481 StringRef Sep = llvm::sys::path::get_separator();
482 for (StringRef CandidateSubdir : Subdirs) {
483 if (llvm::sys::fs::is_directory(ClangRoot + Sep + CandidateSubdir)) {
484 SubdirName = std::string(CandidateSubdir);
485 return (ClangRoot + Sep + CandidateSubdir).str();
486 }
487 }
488 return make_error_code(std::errc::no_such_file_or_directory);
489}
490
491static bool looksLikeMinGWSysroot(const std::string &Directory) {
492 StringRef Sep = llvm::sys::path::get_separator();
493 if (!llvm::sys::fs::exists(Directory + Sep + "include" + Sep + "_mingw.h"))
494 return false;
495 if (!llvm::sys::fs::exists(Directory + Sep + "lib" + Sep + "libkernel32.a"))
496 return false;
497 return true;
498}
499
500toolchains::MinGW::MinGW(const Driver &D, const llvm::Triple &Triple,
501 const ArgList &Args)
502 : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
503 RocmInstallation(D, Triple, Args) {
504 getProgramPaths().push_back(getDriver().Dir);
505
506 std::string InstallBase =
507 std::string(llvm::sys::path::parent_path(getDriver().Dir));
508 // The sequence for detecting a sysroot here should be kept in sync with
509 // the testTriple function below.
510 llvm::Triple LiteralTriple = getLiteralTriple(D, getTriple());
511 if (getDriver().SysRoot.size())
513 // Look for <clang-bin>/../<triplet>; if found, use <clang-bin>/.. as the
514 // base as it could still be a base for a gcc setup with libgcc.
515 else if (llvm::ErrorOr<std::string> TargetSubdir = findClangRelativeSysroot(
516 getDriver(), LiteralTriple, getTriple(), SubdirName))
517 Base = std::string(llvm::sys::path::parent_path(TargetSubdir.get()));
518 // If the install base of Clang seems to have mingw sysroot files directly
519 // in the toplevel include and lib directories, use this as base instead of
520 // looking for a triple prefixed GCC in the path.
521 else if (looksLikeMinGWSysroot(InstallBase))
522 Base = InstallBase;
523 else if (llvm::ErrorOr<std::string> GPPName =
524 findGcc(LiteralTriple, getTriple()))
525 Base = std::string(llvm::sys::path::parent_path(
526 llvm::sys::path::parent_path(GPPName.get())));
527 else
528 Base = InstallBase;
529
530 Base += llvm::sys::path::get_separator();
531 findGccLibDir(LiteralTriple);
532 TripleDirName = SubdirName;
533 // GccLibDir must precede Base/lib so that the
534 // correct crtbegin.o ,cetend.o would be found.
535 getFilePaths().push_back(GccLibDir);
536
537 // openSUSE/Fedora
538 std::string CandidateSubdir = SubdirName + "/sys-root/mingw";
539 if (getDriver().getVFS().exists(Base + CandidateSubdir))
540 SubdirName = CandidateSubdir;
541
542 getFilePaths().push_back(
543 (Base + SubdirName + llvm::sys::path::get_separator() + "lib").str());
544
545 // Gentoo
546 getFilePaths().push_back(
547 (Base + SubdirName + llvm::sys::path::get_separator() + "mingw/lib").str());
548
549 // Only include <base>/lib if we're not cross compiling (not even for
550 // windows->windows to a different arch), or if the sysroot has been set
551 // (where we presume the user has pointed it at an arch specific
552 // subdirectory).
553 if (!::isCrossCompiling(getTriple(), /*RequireArchMatch=*/true) ||
554 getDriver().SysRoot.size())
555 getFilePaths().push_back(Base + "lib");
556
557 NativeLLVMSupport =
558 Args.getLastArgValue(options::OPT_fuse_ld_EQ, D.getPreferredLinker())
559 .equals_insensitive("lld");
560}
561
563 switch (AC) {
565 if (!Preprocessor)
566 Preprocessor.reset(new tools::gcc::Preprocessor(*this));
567 return Preprocessor.get();
569 if (!Compiler)
570 Compiler.reset(new tools::gcc::Compiler(*this));
571 return Compiler.get();
572 default:
573 return ToolChain::getTool(AC);
574 }
575}
576
578 return new tools::MinGW::Assembler(*this);
579}
580
582 return new tools::MinGW::Linker(*this);
583}
584
586 return NativeLLVMSupport;
587}
588
591 Arg *ExceptionArg = Args.getLastArg(options::OPT_fsjlj_exceptions,
592 options::OPT_fseh_exceptions,
593 options::OPT_fdwarf_exceptions);
594 if (ExceptionArg &&
595 ExceptionArg->getOption().matches(options::OPT_fseh_exceptions))
596 return UnwindTableLevel::Asynchronous;
597
598 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::arm ||
599 getArch() == llvm::Triple::thumb || getArch() == llvm::Triple::aarch64)
600 return UnwindTableLevel::Asynchronous;
601 return UnwindTableLevel::None;
602}
603
605 return getArch() == llvm::Triple::x86_64 ||
606 getArch() == llvm::Triple::aarch64;
607}
608
609bool toolchains::MinGW::isPIEDefault(const llvm::opt::ArgList &Args) const {
610 return false;
611}
612
613bool toolchains::MinGW::isPICDefaultForced() const { return true; }
614
615llvm::ExceptionHandling
616toolchains::MinGW::GetExceptionModel(const ArgList &Args) const {
617 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::aarch64 ||
618 getArch() == llvm::Triple::arm || getArch() == llvm::Triple::thumb)
619 return llvm::ExceptionHandling::WinEH;
620 return llvm::ExceptionHandling::DwarfCFI;
621}
622
625 Res |= SanitizerKind::Address;
626 Res |= SanitizerKind::PointerCompare;
627 Res |= SanitizerKind::PointerSubtract;
628 Res |= SanitizerKind::Vptr;
629 return Res;
630}
631
632void toolchains::MinGW::AddCudaIncludeArgs(const ArgList &DriverArgs,
633 ArgStringList &CC1Args) const {
634 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
635}
636
637void toolchains::MinGW::AddHIPIncludeArgs(const ArgList &DriverArgs,
638 ArgStringList &CC1Args) const {
639 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
640}
641
642void toolchains::MinGW::printVerboseInfo(raw_ostream &OS) const {
643 CudaInstallation->print(OS);
644 RocmInstallation->print(OS);
645}
646
647// Include directories for various hosts:
648
649// Windows, mingw.org
650// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++
651// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32
652// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward
653// c:\mingw\include
654// c:\mingw\mingw32\include
655
656// Windows, mingw-w64 mingw-builds
657// c:\mingw32\i686-w64-mingw32\include
658// c:\mingw32\i686-w64-mingw32\include\c++
659// c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32
660// c:\mingw32\i686-w64-mingw32\include\c++\backward
661
662// Windows, mingw-w64 msys2
663// c:\msys64\mingw32\include
664// c:\msys64\mingw32\i686-w64-mingw32\include
665// c:\msys64\mingw32\include\c++\4.9.2
666// c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32
667// c:\msys64\mingw32\include\c++\4.9.2\backward
668
669// openSUSE
670// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++
671// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32
672// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward
673// /usr/x86_64-w64-mingw32/sys-root/mingw/include
674
675// Arch Linux
676// /usr/i686-w64-mingw32/include/c++/5.1.0
677// /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32
678// /usr/i686-w64-mingw32/include/c++/5.1.0/backward
679// /usr/i686-w64-mingw32/include
680
681// Ubuntu
682// /usr/include/c++/4.8
683// /usr/include/c++/4.8/x86_64-w64-mingw32
684// /usr/include/c++/4.8/backward
685// /usr/x86_64-w64-mingw32/include
686
687// Fedora
688// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/x86_64-w64-mingw32ucrt
689// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/backward
690// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include
691// /usr/lib/gcc/x86_64-w64-mingw32ucrt/12.2.1/include-fixed
692
693void toolchains::MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
694 ArgStringList &CC1Args) const {
695 if (DriverArgs.hasArg(options::OPT_nostdinc))
696 return;
697
698 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
699 SmallString<1024> P(getDriver().ResourceDir);
700 llvm::sys::path::append(P, "include");
701 addSystemInclude(DriverArgs, CC1Args, P.str());
702 }
703
704 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
705 return;
706
707 addSystemInclude(DriverArgs, CC1Args,
708 Base + SubdirName + llvm::sys::path::get_separator() +
709 "include");
710
711 // Gentoo
712 addSystemInclude(DriverArgs, CC1Args,
713 Base + SubdirName + llvm::sys::path::get_separator() + "usr/include");
714
715 // Only include <base>/include if we're not cross compiling (but do allow it
716 // if we're on Windows and building for Windows on another architecture),
717 // or if the sysroot has been set (where we presume the user has pointed it
718 // at an arch specific subdirectory).
719 if (!::isCrossCompiling(getTriple(), /*RequireArchMatch=*/false) ||
720 getDriver().SysRoot.size())
721 addSystemInclude(DriverArgs, CC1Args, Base + "include");
722}
723
725 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
726 Action::OffloadKind DeviceOffloadKind) const {
727 if (Arg *A = DriverArgs.getLastArg(options::OPT_mguard_EQ)) {
728 StringRef GuardArgs = A->getValue();
729 if (GuardArgs == "none") {
730 // Do nothing.
731 } else if (GuardArgs == "cf") {
732 // Emit CFG instrumentation and the table of address-taken functions.
733 CC1Args.push_back("-cfguard");
734 } else if (GuardArgs == "cf-nochecks") {
735 // Emit only the table of address-taken functions.
736 CC1Args.push_back("-cfguard-no-checks");
737 } else {
738 getDriver().Diag(diag::err_drv_unsupported_option_argument)
739 << A->getSpelling() << GuardArgs;
740 }
741 }
742
743 // Default to not enabling sized deallocation, but let user provided options
744 // override it.
745 //
746 // If using sized deallocation, user code that invokes delete will end up
747 // calling delete(void*,size_t). If the user wanted to override the
748 // operator delete(void*), there may be a fallback operator
749 // delete(void*,size_t) which calls the regular operator delete(void*).
750 //
751 // However, if the C++ standard library is linked in the form of a DLL,
752 // and the fallback operator delete(void*,size_t) is within this DLL (which is
753 // the case for libc++ at least) it will only redirect towards the library's
754 // default operator delete(void*), not towards the user's provided operator
755 // delete(void*).
756 //
757 // This issue can be avoided, if the fallback operators are linked statically
758 // into the callers, even if the C++ standard library is linked as a DLL.
759 //
760 // This is meant as a temporary workaround until libc++ implements this
761 // technique, which is tracked in
762 // https://github.com/llvm/llvm-project/issues/96899.
763 if (!DriverArgs.hasArgNoClaim(options::OPT_fsized_deallocation,
764 options::OPT_fno_sized_deallocation))
765 CC1Args.push_back("-fno-sized-deallocation");
766
767 CC1Args.push_back("-fno-use-init-array");
768
769 for (auto Opt : {options::OPT_mthreads, options::OPT_mwindows,
770 options::OPT_mconsole, options::OPT_mdll}) {
771 if (Arg *A = DriverArgs.getLastArgNoClaim(Opt))
772 A->ignoreTargetSpecific();
773 }
774}
775
777 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
778 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
779 options::OPT_nostdincxx))
780 return;
781
782 StringRef Slash = llvm::sys::path::get_separator();
783
784 switch (GetCXXStdlibType(DriverArgs)) {
786 std::string TargetDir = (Base + "include" + Slash + getTripleString() +
787 Slash + "c++" + Slash + "v1")
788 .str();
789 if (getDriver().getVFS().exists(TargetDir))
790 addSystemInclude(DriverArgs, CC1Args, TargetDir);
791 addSystemInclude(DriverArgs, CC1Args,
792 Base + SubdirName + Slash + "include" + Slash + "c++" +
793 Slash + "v1");
794 addSystemInclude(DriverArgs, CC1Args,
795 Base + "include" + Slash + "c++" + Slash + "v1");
796 break;
797 }
798
801 CppIncludeBases.emplace_back(Base);
802 llvm::sys::path::append(CppIncludeBases[0], SubdirName, "include", "c++");
803 CppIncludeBases.emplace_back(Base);
804 llvm::sys::path::append(CppIncludeBases[1], SubdirName, "include", "c++",
805 Ver);
806 CppIncludeBases.emplace_back(Base);
807 llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver);
808 CppIncludeBases.emplace_back(GccLibDir);
809 llvm::sys::path::append(CppIncludeBases[3], "include", "c++");
810 CppIncludeBases.emplace_back(GccLibDir);
811 llvm::sys::path::append(CppIncludeBases[4], "include",
812 "g++-v" + GccVer.Text);
813 CppIncludeBases.emplace_back(GccLibDir);
814 llvm::sys::path::append(CppIncludeBases[5], "include",
815 "g++-v" + GccVer.MajorStr + "." + GccVer.MinorStr);
816 CppIncludeBases.emplace_back(GccLibDir);
817 llvm::sys::path::append(CppIncludeBases[6], "include",
818 "g++-v" + GccVer.MajorStr);
819 for (auto &CppIncludeBase : CppIncludeBases) {
820 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase);
821 CppIncludeBase += Slash;
822 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + TripleDirName);
823 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward");
824 }
825 break;
826 }
827}
828
829static bool testTriple(const Driver &D, const llvm::Triple &Triple,
830 const ArgList &Args) {
831 // If an explicit sysroot is set, that will be used and we shouldn't try to
832 // detect anything else.
833 std::string SubdirName;
834 if (D.SysRoot.size())
835 return true;
836 llvm::Triple LiteralTriple = getLiteralTriple(D, Triple);
837 std::string InstallBase = std::string(llvm::sys::path::parent_path(D.Dir));
838 if (llvm::ErrorOr<std::string> TargetSubdir =
839 findClangRelativeSysroot(D, LiteralTriple, Triple, SubdirName))
840 return true;
841 // If the install base itself looks like a mingw sysroot, we'll use that
842 // - don't use any potentially unrelated gcc to influence what triple to use.
843 if (looksLikeMinGWSysroot(InstallBase))
844 return false;
845 if (llvm::ErrorOr<std::string> GPPName = findGcc(LiteralTriple, Triple))
846 return true;
847 // If we neither found a colocated sysroot or a matching gcc executable,
848 // conclude that we can't know if this is the correct spelling of the triple.
849 return false;
850}
851
852static llvm::Triple adjustTriple(const Driver &D, const llvm::Triple &Triple,
853 const ArgList &Args) {
854 // First test if the original triple can find a sysroot with the triple
855 // name.
856 if (testTriple(D, Triple, Args))
857 return Triple;
859 // If not, test a couple other possible arch names that might be what was
860 // intended.
861 if (Triple.getArch() == llvm::Triple::x86) {
862 Archs.emplace_back("i386");
863 Archs.emplace_back("i586");
864 Archs.emplace_back("i686");
865 } else if (Triple.getArch() == llvm::Triple::arm ||
866 Triple.getArch() == llvm::Triple::thumb) {
867 Archs.emplace_back("armv7");
868 }
869 for (auto A : Archs) {
870 llvm::Triple TestTriple(Triple);
871 TestTriple.setArchName(A);
872 if (testTriple(D, TestTriple, Args))
873 return TestTriple;
874 }
875 // If none was found, just proceed with the original value.
876 return Triple;
877}
878
879void toolchains::MinGW::fixTripleArch(const Driver &D, llvm::Triple &Triple,
880 const ArgList &Args) {
881 if (Triple.getArch() == llvm::Triple::x86 ||
882 Triple.getArch() == llvm::Triple::arm ||
883 Triple.getArch() == llvm::Triple::thumb)
884 Triple = adjustTriple(D, Triple, Args);
885}
StringRef P
const Decl * D
static llvm::Triple getLiteralTriple(const Driver &D, const llvm::Triple &T)
Definition: MinGW.cpp:417
static bool looksLikeMinGWSysroot(const std::string &Directory)
Definition: MinGW.cpp:491
static bool findGccVersion(StringRef LibDir, std::string &GccLibDir, std::string &Ver, toolchains::Generic_GCC::GCCVersion &Version)
Definition: MinGW.cpp:396
static bool testTriple(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
Definition: MinGW.cpp:829
static llvm::Triple adjustTriple(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
Definition: MinGW.cpp:852
static llvm::ErrorOr< std::string > findGcc(const llvm::Triple &LiteralTriple, const llvm::Triple &T)
Definition: MinGW.cpp:451
static llvm::ErrorOr< std::string > findClangRelativeSysroot(const Driver &D, const llvm::Triple &LiteralTriple, const llvm::Triple &T, std::string &SubdirName)
Definition: MinGW.cpp:471
static bool isCrossCompiling(const llvm::Triple &T, bool RequireArchMatch)
Definition: MinGW.cpp:386
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:99
std::string SysRoot
sysroot, if present
Definition: Driver.h:205
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition: Driver.cpp:881
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition: Driver.h:165
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition: Driver.h:155
@ OMPRT_Unknown
An unknown OpenMP runtime.
Definition: Driver.h:151
@ OMPRT_GOMP
The GNU OpenMP runtime.
Definition: Driver.h:160
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getFilename() const
Definition: InputInfo.h:83
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:92
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
Definition: ToolChain.cpp:1525
virtual void addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Adds the path for the Fortran runtime libraries to CmdArgs.
Definition: ToolChain.cpp:857
std::string GetFilePath(const char *Name) const
Definition: ToolChain.cpp:1090
virtual void addFortranRuntimeLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Adds Fortran runtime libraries to CmdArgs.
Definition: ToolChain.cpp:821
path_list & getFilePaths()
Definition: ToolChain.h:295
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:269
const Driver & getDriver() const
Definition: ToolChain.h:253
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:115
bool addFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
Definition: ToolChain.cpp:1598
path_list & getProgramPaths()
Definition: ToolChain.h:298
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:283
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition: ToolChain.cpp:1531
const llvm::Triple & getTriple() const
Definition: ToolChain.h:255
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
Definition: ToolChain.cpp:1310
virtual std::string getCompilerRTPath() const
Definition: ToolChain.cpp:723
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
Definition: ToolChain.cpp:1098
void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
Definition: ToolChain.cpp:1550
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:404
path_list & getLibraryPaths()
Definition: ToolChain.h:292
virtual Tool * getTool(Action::ActionClass AC) const
Definition: ToolChain.cpp:633
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
Definition: ToolChain.cpp:813
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:1614
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
Definition: ToolChain.cpp:1193
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
const ToolChain & getToolChain() const
Definition: Tool.h:52
Tool * getTool(Action::ActionClass AC) const override
Definition: MinGW.cpp:562
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition: MinGW.cpp:616
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition: MinGW.cpp:724
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition: MinGW.cpp:623
Tool * buildAssembler() const override
Definition: MinGW.cpp:577
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition: MinGW.cpp:642
Tool * buildLinker() const override
Definition: MinGW.cpp:581
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition: MinGW.cpp:637
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition: MinGW.cpp:609
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition: MinGW.cpp:632
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition: MinGW.cpp:585
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition: MinGW.cpp:604
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition: MinGW.cpp:613
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition: MinGW.cpp:693
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: MinGW.cpp:776
UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override
How detailed should the unwind tables be by default.
Definition: MinGW.cpp:590
MinGW(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: MinGW.cpp:500
static void fixTripleArch(const Driver &D, llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition: MinGW.cpp:879
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
MinGW Tools.
Definition: MinGW.cpp:30
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: MinGW.cpp:103
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void addLTOOptions(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const InputInfo &Output, const InputInfoList &Inputs, bool IsThinLTO)
void AddRunTimeLibs(const ToolChain &TC, const Driver &D, llvm::opt::ArgStringList &CmdArgs, const llvm::opt::ArgList &Args)
void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Output, const char *OutFile)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
The JSON file list parser is used to communicate input to InstallAPI.
std::error_code make_error_code(BuildPreambleError Error)
const FunctionProtoType * T
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition: Job.h:78
static constexpr ResponseFileSupport AtFileUTF8()
Definition: Job.h:85
Struct to store and manipulate GCC versions.
Definition: Gnu.h:163
static GCCVersion Parse(StringRef VersionText)
Parse a GCCVersion object out of a string of text.
Definition: Gnu.cpp:1985