Bug Summary

File:build/source/clang/lib/Driver/ToolChains/MinGW.cpp
Warning:line 191, column 5
Value stored to 'OutputFile' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name MinGW.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16 -I tools/clang/lib/Driver -I /build/source/clang/lib/Driver -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1670191760 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-12-05-012027-15999-1 -x c++ /build/source/clang/lib/Driver/ToolChains/MinGW.cpp
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
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("--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).startswith("msvcr") ||
90 StringRef(Lib).startswith("ucrt") ||
91 StringRef(Lib).startswith("crtdll"))
92 return;
93 CmdArgs.push_back("-lmsvcrt");
94}
95
96void 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 llvm_unreachable("Unsupported target architecture.")::llvm::llvm_unreachable_internal("Unsupported target architecture."
, "clang/lib/Driver/ToolChains/MinGW.cpp", 138)
;
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();
Value stored to 'OutputFile' is never read
192 } else
193 CmdArgs.push_back(OutputFile);
194
195 Args.AddAllArgs(CmdArgs, options::OPT_e);
196 // FIXME: add -N, -n flags
197 Args.AddLastArg(CmdArgs, options::OPT_r);
198 Args.AddLastArg(CmdArgs, options::OPT_s);
199 Args.AddLastArg(CmdArgs, options::OPT_t);
200 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
201 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
202
203 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
204 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
205 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
206 } else {
207 if (Args.hasArg(options::OPT_municode))
208 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
209 else
210 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
211 }
212 if (Args.hasArg(options::OPT_pg))
213 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
214 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
215 }
216
217 Args.AddAllArgs(CmdArgs, options::OPT_L);
218 TC.AddFilePathLibArgs(Args, CmdArgs);
219
220 // Add the compiler-rt library directories if they exist to help
221 // the linker find the various sanitizer, builtin, and profiling runtimes.
222 for (const auto &LibPath : TC.getLibraryPaths()) {
223 if (TC.getVFS().exists(LibPath))
224 CmdArgs.push_back(Args.MakeArgString("-L" + LibPath));
225 }
226 auto CRTPath = TC.getCompilerRTPath();
227 if (TC.getVFS().exists(CRTPath))
228 CmdArgs.push_back(Args.MakeArgString("-L" + CRTPath));
229
230 AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA);
231
232 if (C.getDriver().IsFlangMode()) {
233 addFortranRuntimeLibraryPath(TC, Args, CmdArgs);
234 addFortranRuntimeLibs(TC, CmdArgs);
235 }
236
237 // TODO: Add profile stuff here
238
239 if (TC.ShouldLinkCXXStdlib(Args)) {
240 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
241 !Args.hasArg(options::OPT_static);
242 if (OnlyLibstdcxxStatic)
243 CmdArgs.push_back("-Bstatic");
244 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
245 if (OnlyLibstdcxxStatic)
246 CmdArgs.push_back("-Bdynamic");
247 }
248
249 bool HasWindowsApp = false;
250 for (auto Lib : Args.getAllArgValues(options::OPT_l)) {
251 if (Lib == "windowsapp") {
252 HasWindowsApp = true;
253 break;
254 }
255 }
256
257 if (!Args.hasArg(options::OPT_nostdlib)) {
258 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
259 if (Args.hasArg(options::OPT_static))
260 CmdArgs.push_back("--start-group");
261
262 if (Args.hasArg(options::OPT_fstack_protector) ||
263 Args.hasArg(options::OPT_fstack_protector_strong) ||
264 Args.hasArg(options::OPT_fstack_protector_all)) {
265 CmdArgs.push_back("-lssp_nonshared");
266 CmdArgs.push_back("-lssp");
267 }
268
269 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
270 options::OPT_fno_openmp, false)) {
271 switch (TC.getDriver().getOpenMPRuntime(Args)) {
272 case Driver::OMPRT_OMP:
273 CmdArgs.push_back("-lomp");
274 break;
275 case Driver::OMPRT_IOMP5:
276 CmdArgs.push_back("-liomp5md");
277 break;
278 case Driver::OMPRT_GOMP:
279 CmdArgs.push_back("-lgomp");
280 break;
281 case Driver::OMPRT_Unknown:
282 // Already diagnosed.
283 break;
284 }
285 }
286
287 AddLibGCC(Args, CmdArgs);
288
289 if (Args.hasArg(options::OPT_pg))
290 CmdArgs.push_back("-lgmon");
291
292 if (Args.hasArg(options::OPT_pthread))
293 CmdArgs.push_back("-lpthread");
294
295 if (Sanitize.needsAsanRt()) {
296 // MinGW always links against a shared MSVCRT.
297 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dynamic",
298 ToolChain::FT_Shared));
299 CmdArgs.push_back(
300 TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
301 CmdArgs.push_back("--require-defined");
302 CmdArgs.push_back(TC.getArch() == llvm::Triple::x86
303 ? "___asan_seh_interceptor"
304 : "__asan_seh_interceptor");
305 // Make sure the linker consider all object files from the dynamic
306 // runtime thunk.
307 CmdArgs.push_back("--whole-archive");
308 CmdArgs.push_back(
309 TC.getCompilerRTArgString(Args, "asan_dynamic_runtime_thunk"));
310 CmdArgs.push_back("--no-whole-archive");
311 }
312
313 TC.addProfileRTLibs(Args, CmdArgs);
314
315 if (!HasWindowsApp) {
316 // Add system libraries. If linking to libwindowsapp.a, that import
317 // library replaces all these and we shouldn't accidentally try to
318 // link to the normal desktop mode dlls.
319 if (Args.hasArg(options::OPT_mwindows)) {
320 CmdArgs.push_back("-lgdi32");
321 CmdArgs.push_back("-lcomdlg32");
322 }
323 CmdArgs.push_back("-ladvapi32");
324 CmdArgs.push_back("-lshell32");
325 CmdArgs.push_back("-luser32");
326 CmdArgs.push_back("-lkernel32");
327 }
328
329 if (Args.hasArg(options::OPT_static)) {
330 CmdArgs.push_back("--end-group");
331 } else {
332 AddLibGCC(Args, CmdArgs);
333 if (!HasWindowsApp)
334 CmdArgs.push_back("-lkernel32");
335 }
336 }
337
338 if (!Args.hasArg(options::OPT_nostartfiles)) {
339 // Add crtfastmath.o if available and fast math is enabled.
340 TC.addFastMathRuntimeIfAvailable(Args, CmdArgs);
341
342 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
343 }
344 }
345 const char *Exec = Args.MakeArgString(TC.GetLinkerPath());
346 C.addCommand(std::make_unique<Command>(JA, *this,
347 ResponseFileSupport::AtFileUTF8(),
348 Exec, CmdArgs, Inputs, Output));
349}
350
351// Simplified from Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple.
352static bool findGccVersion(StringRef LibDir, std::string &GccLibDir,
353 std::string &Ver,
354 toolchains::Generic_GCC::GCCVersion &Version) {
355 Version = toolchains::Generic_GCC::GCCVersion::Parse("0.0.0");
356 std::error_code EC;
357 for (llvm::sys::fs::directory_iterator LI(LibDir, EC), LE; !EC && LI != LE;
358 LI = LI.increment(EC)) {
359 StringRef VersionText = llvm::sys::path::filename(LI->path());
360 auto CandidateVersion =
361 toolchains::Generic_GCC::GCCVersion::Parse(VersionText);
362 if (CandidateVersion.Major == -1)
363 continue;
364 if (CandidateVersion <= Version)
365 continue;
366 Version = CandidateVersion;
367 Ver = std::string(VersionText);
368 GccLibDir = LI->path();
369 }
370 return Ver.size();
371}
372
373static llvm::Triple getLiteralTriple(const Driver &D, const llvm::Triple &T) {
374 llvm::Triple LiteralTriple(D.getTargetTriple());
375 // The arch portion of the triple may be overridden by -m32/-m64.
376 LiteralTriple.setArchName(T.getArchName());
377 return LiteralTriple;
378}
379
380void toolchains::MinGW::findGccLibDir(const llvm::Triple &LiteralTriple) {
381 llvm::SmallVector<llvm::SmallString<32>, 5> SubdirNames;
382 SubdirNames.emplace_back(LiteralTriple.str());
383 SubdirNames.emplace_back(getTriple().str());
384 SubdirNames.emplace_back(getTriple().getArchName());
385 SubdirNames.back() += "-w64-mingw32";
386 SubdirNames.emplace_back(getTriple().getArchName());
387 SubdirNames.back() += "-w64-mingw32ucrt";
388 SubdirNames.emplace_back("mingw32");
389 if (SubdirName.empty()) {
390 SubdirName = getTriple().getArchName();
391 SubdirName += "-w64-mingw32";
392 }
393 // lib: Arch Linux, Ubuntu, Windows
394 // lib64: openSUSE Linux
395 for (StringRef CandidateLib : {"lib", "lib64"}) {
396 for (StringRef CandidateSysroot : SubdirNames) {
397 llvm::SmallString<1024> LibDir(Base);
398 llvm::sys::path::append(LibDir, CandidateLib, "gcc", CandidateSysroot);
399 if (findGccVersion(LibDir, GccLibDir, Ver, GccVer)) {
400 SubdirName = std::string(CandidateSysroot);
401 return;
402 }
403 }
404 }
405}
406
407static llvm::ErrorOr<std::string> findGcc(const llvm::Triple &LiteralTriple,
408 const llvm::Triple &T) {
409 llvm::SmallVector<llvm::SmallString<32>, 5> Gccs;
410 Gccs.emplace_back(LiteralTriple.str());
411 Gccs.back() += "-gcc";
412 Gccs.emplace_back(T.str());
413 Gccs.back() += "-gcc";
414 Gccs.emplace_back(T.getArchName());
415 Gccs.back() += "-w64-mingw32-gcc";
416 Gccs.emplace_back(T.getArchName());
417 Gccs.back() += "-w64-mingw32ucrt-gcc";
418 Gccs.emplace_back("mingw32-gcc");
419 // Please do not add "gcc" here
420 for (StringRef CandidateGcc : Gccs)
421 if (llvm::ErrorOr<std::string> GPPName = llvm::sys::findProgramByName(CandidateGcc))
422 return GPPName;
423 return make_error_code(std::errc::no_such_file_or_directory);
424}
425
426static llvm::ErrorOr<std::string>
427findClangRelativeSysroot(const Driver &D, const llvm::Triple &LiteralTriple,
428 const llvm::Triple &T, std::string &SubdirName) {
429 llvm::SmallVector<llvm::SmallString<32>, 4> Subdirs;
430 Subdirs.emplace_back(LiteralTriple.str());
431 Subdirs.emplace_back(T.str());
432 Subdirs.emplace_back(T.getArchName());
433 Subdirs.back() += "-w64-mingw32";
434 Subdirs.emplace_back(T.getArchName());
435 Subdirs.back() += "-w64-mingw32ucrt";
436 StringRef ClangRoot = llvm::sys::path::parent_path(D.getInstalledDir());
437 StringRef Sep = llvm::sys::path::get_separator();
438 for (StringRef CandidateSubdir : Subdirs) {
439 if (llvm::sys::fs::is_directory(ClangRoot + Sep + CandidateSubdir)) {
440 SubdirName = std::string(CandidateSubdir);
441 return (ClangRoot + Sep + CandidateSubdir).str();
442 }
443 }
444 return make_error_code(std::errc::no_such_file_or_directory);
445}
446
447toolchains::MinGW::MinGW(const Driver &D, const llvm::Triple &Triple,
448 const ArgList &Args)
449 : ToolChain(D, Triple, Args), CudaInstallation(D, Triple, Args),
450 RocmInstallation(D, Triple, Args) {
451 getProgramPaths().push_back(getDriver().getInstalledDir());
452
453 // The sequence for detecting a sysroot here should be kept in sync with
454 // the testTriple function below.
455 llvm::Triple LiteralTriple = getLiteralTriple(D, getTriple());
456 if (getDriver().SysRoot.size())
457 Base = getDriver().SysRoot;
458 // Look for <clang-bin>/../<triplet>; if found, use <clang-bin>/.. as the
459 // base as it could still be a base for a gcc setup with libgcc.
460 else if (llvm::ErrorOr<std::string> TargetSubdir = findClangRelativeSysroot(
461 getDriver(), LiteralTriple, getTriple(), SubdirName))
462 Base = std::string(llvm::sys::path::parent_path(TargetSubdir.get()));
463 else if (llvm::ErrorOr<std::string> GPPName =
464 findGcc(LiteralTriple, getTriple()))
465 Base = std::string(llvm::sys::path::parent_path(
466 llvm::sys::path::parent_path(GPPName.get())));
467 else
468 Base = std::string(
469 llvm::sys::path::parent_path(getDriver().getInstalledDir()));
470
471 Base += llvm::sys::path::get_separator();
472 findGccLibDir(LiteralTriple);
473 TripleDirName = SubdirName;
474 // GccLibDir must precede Base/lib so that the
475 // correct crtbegin.o ,cetend.o would be found.
476 getFilePaths().push_back(GccLibDir);
477
478 // openSUSE/Fedora
479 std::string CandidateSubdir = SubdirName + "/sys-root/mingw";
480 if (getDriver().getVFS().exists(Base + CandidateSubdir))
481 SubdirName = CandidateSubdir;
482
483 getFilePaths().push_back(
484 (Base + SubdirName + llvm::sys::path::get_separator() + "lib").str());
485
486 // Gentoo
487 getFilePaths().push_back(
488 (Base + SubdirName + llvm::sys::path::get_separator() + "mingw/lib").str());
489
490 getFilePaths().push_back(Base + "lib");
491
492 NativeLLVMSupport =
493 Args.getLastArgValue(options::OPT_fuse_ld_EQ, CLANG_DEFAULT_LINKER"ld")
494 .equals_insensitive("lld");
495}
496
497bool toolchains::MinGW::IsIntegratedAssemblerDefault() const { return true; }
498
499Tool *toolchains::MinGW::getTool(Action::ActionClass AC) const {
500 switch (AC) {
501 case Action::PreprocessJobClass:
502 if (!Preprocessor)
503 Preprocessor.reset(new tools::gcc::Preprocessor(*this));
504 return Preprocessor.get();
505 case Action::CompileJobClass:
506 if (!Compiler)
507 Compiler.reset(new tools::gcc::Compiler(*this));
508 return Compiler.get();
509 default:
510 return ToolChain::getTool(AC);
511 }
512}
513
514Tool *toolchains::MinGW::buildAssembler() const {
515 return new tools::MinGW::Assembler(*this);
516}
517
518Tool *toolchains::MinGW::buildLinker() const {
519 return new tools::MinGW::Linker(*this);
520}
521
522bool toolchains::MinGW::HasNativeLLVMSupport() const {
523 return NativeLLVMSupport;
524}
525
526ToolChain::UnwindTableLevel
527toolchains::MinGW::getDefaultUnwindTableLevel(const ArgList &Args) const {
528 Arg *ExceptionArg = Args.getLastArg(options::OPT_fsjlj_exceptions,
529 options::OPT_fseh_exceptions,
530 options::OPT_fdwarf_exceptions);
531 if (ExceptionArg &&
532 ExceptionArg->getOption().matches(options::OPT_fseh_exceptions))
533 return UnwindTableLevel::Asynchronous;
534
535 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::arm ||
536 getArch() == llvm::Triple::thumb || getArch() == llvm::Triple::aarch64)
537 return UnwindTableLevel::Asynchronous;
538 return UnwindTableLevel::None;
539}
540
541bool toolchains::MinGW::isPICDefault() const {
542 return getArch() == llvm::Triple::x86_64 ||
543 getArch() == llvm::Triple::aarch64;
544}
545
546bool toolchains::MinGW::isPIEDefault(const llvm::opt::ArgList &Args) const {
547 return false;
548}
549
550bool toolchains::MinGW::isPICDefaultForced() const { return true; }
551
552llvm::ExceptionHandling
553toolchains::MinGW::GetExceptionModel(const ArgList &Args) const {
554 if (getArch() == llvm::Triple::x86_64 || getArch() == llvm::Triple::aarch64 ||
555 getArch() == llvm::Triple::arm || getArch() == llvm::Triple::thumb)
556 return llvm::ExceptionHandling::WinEH;
557 return llvm::ExceptionHandling::DwarfCFI;
558}
559
560SanitizerMask toolchains::MinGW::getSupportedSanitizers() const {
561 SanitizerMask Res = ToolChain::getSupportedSanitizers();
562 Res |= SanitizerKind::Address;
563 Res |= SanitizerKind::PointerCompare;
564 Res |= SanitizerKind::PointerSubtract;
565 Res |= SanitizerKind::Vptr;
566 return Res;
567}
568
569void toolchains::MinGW::AddCudaIncludeArgs(const ArgList &DriverArgs,
570 ArgStringList &CC1Args) const {
571 CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
572}
573
574void toolchains::MinGW::AddHIPIncludeArgs(const ArgList &DriverArgs,
575 ArgStringList &CC1Args) const {
576 RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
577}
578
579void toolchains::MinGW::printVerboseInfo(raw_ostream &OS) const {
580 CudaInstallation.print(OS);
581 RocmInstallation.print(OS);
582}
583
584// Include directories for various hosts:
585
586// Windows, mingw.org
587// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++
588// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\mingw32
589// c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\backward
590// c:\mingw\include
591// c:\mingw\mingw32\include
592
593// Windows, mingw-w64 mingw-builds
594// c:\mingw32\i686-w64-mingw32\include
595// c:\mingw32\i686-w64-mingw32\include\c++
596// c:\mingw32\i686-w64-mingw32\include\c++\i686-w64-mingw32
597// c:\mingw32\i686-w64-mingw32\include\c++\backward
598
599// Windows, mingw-w64 msys2
600// c:\msys64\mingw32\include
601// c:\msys64\mingw32\i686-w64-mingw32\include
602// c:\msys64\mingw32\include\c++\4.9.2
603// c:\msys64\mingw32\include\c++\4.9.2\i686-w64-mingw32
604// c:\msys64\mingw32\include\c++\4.9.2\backward
605
606// openSUSE
607// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++
608// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/x86_64-w64-mingw32
609// /usr/lib64/gcc/x86_64-w64-mingw32/5.1.0/include/c++/backward
610// /usr/x86_64-w64-mingw32/sys-root/mingw/include
611
612// Arch Linux
613// /usr/i686-w64-mingw32/include/c++/5.1.0
614// /usr/i686-w64-mingw32/include/c++/5.1.0/i686-w64-mingw32
615// /usr/i686-w64-mingw32/include/c++/5.1.0/backward
616// /usr/i686-w64-mingw32/include
617
618// Ubuntu
619// /usr/include/c++/4.8
620// /usr/include/c++/4.8/x86_64-w64-mingw32
621// /usr/include/c++/4.8/backward
622// /usr/x86_64-w64-mingw32/include
623
624// Fedora
625// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/x86_64-w64-mingw32ucrt
626// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include/c++/backward
627// /usr/x86_64-w64-mingw32ucrt/sys-root/mingw/include
628// /usr/lib/gcc/x86_64-w64-mingw32ucrt/12.2.1/include-fixed
629
630void toolchains::MinGW::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
631 ArgStringList &CC1Args) const {
632 if (DriverArgs.hasArg(options::OPT_nostdinc))
633 return;
634
635 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
636 SmallString<1024> P(getDriver().ResourceDir);
637 llvm::sys::path::append(P, "include");
638 addSystemInclude(DriverArgs, CC1Args, P.str());
639 }
640
641 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
642 return;
643
644 addSystemInclude(DriverArgs, CC1Args,
645 Base + SubdirName + llvm::sys::path::get_separator() +
646 "include");
647
648 // Gentoo
649 addSystemInclude(DriverArgs, CC1Args,
650 Base + SubdirName + llvm::sys::path::get_separator() + "usr/include");
651
652 addSystemInclude(DriverArgs, CC1Args, Base + "include");
653}
654
655void toolchains::MinGW::addClangTargetOptions(
656 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
657 Action::OffloadKind DeviceOffloadKind) const {
658 if (Arg *A = DriverArgs.getLastArg(options::OPT_mguard_EQ)) {
659 StringRef GuardArgs = A->getValue();
660 if (GuardArgs == "none") {
661 // Do nothing.
662 } else if (GuardArgs == "cf") {
663 // Emit CFG instrumentation and the table of address-taken functions.
664 CC1Args.push_back("-cfguard");
665 } else if (GuardArgs == "cf-nochecks") {
666 // Emit only the table of address-taken functions.
667 CC1Args.push_back("-cfguard-no-checks");
668 } else {
669 getDriver().Diag(diag::err_drv_unsupported_option_argument)
670 << A->getSpelling() << GuardArgs;
671 }
672 }
673}
674
675void toolchains::MinGW::AddClangCXXStdlibIncludeArgs(
676 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
677 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
678 options::OPT_nostdincxx))
679 return;
680
681 StringRef Slash = llvm::sys::path::get_separator();
682
683 switch (GetCXXStdlibType(DriverArgs)) {
684 case ToolChain::CST_Libcxx: {
685 std::string TargetDir = (Base + "include" + Slash + getTripleString() +
686 Slash + "c++" + Slash + "v1")
687 .str();
688 if (getDriver().getVFS().exists(TargetDir))
689 addSystemInclude(DriverArgs, CC1Args, TargetDir);
690 addSystemInclude(DriverArgs, CC1Args,
691 Base + SubdirName + Slash + "include" + Slash + "c++" +
692 Slash + "v1");
693 addSystemInclude(DriverArgs, CC1Args,
694 Base + "include" + Slash + "c++" + Slash + "v1");
695 break;
696 }
697
698 case ToolChain::CST_Libstdcxx:
699 llvm::SmallVector<llvm::SmallString<1024>, 7> CppIncludeBases;
700 CppIncludeBases.emplace_back(Base);
701 llvm::sys::path::append(CppIncludeBases[0], SubdirName, "include", "c++");
702 CppIncludeBases.emplace_back(Base);
703 llvm::sys::path::append(CppIncludeBases[1], SubdirName, "include", "c++",
704 Ver);
705 CppIncludeBases.emplace_back(Base);
706 llvm::sys::path::append(CppIncludeBases[2], "include", "c++", Ver);
707 CppIncludeBases.emplace_back(GccLibDir);
708 llvm::sys::path::append(CppIncludeBases[3], "include", "c++");
709 CppIncludeBases.emplace_back(GccLibDir);
710 llvm::sys::path::append(CppIncludeBases[4], "include",
711 "g++-v" + GccVer.Text);
712 CppIncludeBases.emplace_back(GccLibDir);
713 llvm::sys::path::append(CppIncludeBases[5], "include",
714 "g++-v" + GccVer.MajorStr + "." + GccVer.MinorStr);
715 CppIncludeBases.emplace_back(GccLibDir);
716 llvm::sys::path::append(CppIncludeBases[6], "include",
717 "g++-v" + GccVer.MajorStr);
718 for (auto &CppIncludeBase : CppIncludeBases) {
719 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase);
720 CppIncludeBase += Slash;
721 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + TripleDirName);
722 addSystemInclude(DriverArgs, CC1Args, CppIncludeBase + "backward");
723 }
724 break;
725 }
726}
727
728static bool testTriple(const Driver &D, const llvm::Triple &Triple,
729 const ArgList &Args) {
730 // If an explicit sysroot is set, that will be used and we shouldn't try to
731 // detect anything else.
732 std::string SubdirName;
733 if (D.SysRoot.size())
734 return true;
735 llvm::Triple LiteralTriple = getLiteralTriple(D, Triple);
736 if (llvm::ErrorOr<std::string> TargetSubdir =
737 findClangRelativeSysroot(D, LiteralTriple, Triple, SubdirName))
738 return true;
739 if (llvm::ErrorOr<std::string> GPPName = findGcc(LiteralTriple, Triple))
740 return true;
741 // If we neither found a colocated sysroot or a matching gcc executable,
742 // conclude that we can't know if this is the correct spelling of the triple.
743 return false;
744}
745
746static llvm::Triple adjustTriple(const Driver &D, const llvm::Triple &Triple,
747 const ArgList &Args) {
748 // First test if the original triple can find a sysroot with the triple
749 // name.
750 if (testTriple(D, Triple, Args))
751 return Triple;
752 llvm::SmallVector<llvm::StringRef, 3> Archs;
753 // If not, test a couple other possible arch names that might be what was
754 // intended.
755 if (Triple.getArch() == llvm::Triple::x86) {
756 Archs.emplace_back("i386");
757 Archs.emplace_back("i586");
758 Archs.emplace_back("i686");
759 } else if (Triple.getArch() == llvm::Triple::arm ||
760 Triple.getArch() == llvm::Triple::thumb) {
761 Archs.emplace_back("armv7");
762 }
763 for (auto A : Archs) {
764 llvm::Triple TestTriple(Triple);
765 TestTriple.setArchName(A);
766 if (testTriple(D, TestTriple, Args))
767 return TestTriple;
768 }
769 // If none was found, just proceed with the original value.
770 return Triple;
771}
772
773void toolchains::MinGW::fixTripleArch(const Driver &D, llvm::Triple &Triple,
774 const ArgList &Args) {
775 if (Triple.getArch() == llvm::Triple::x86 ||
776 Triple.getArch() == llvm::Triple::arm ||
777 Triple.getArch() == llvm::Triple::thumb)
778 Triple = adjustTriple(D, Triple, Args);
779}