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