1 //===- ToolChain.cpp - Collections of tools for one platform --------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/Driver/ToolChain.h"
10 #include "InputInfo.h"
11 #include "ToolChains/Arch/ARM.h"
12 #include "ToolChains/Clang.h"
13 #include "ToolChains/InterfaceStubs.h"
14 #include "ToolChains/Flang.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Sanitizers.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Driver.h"
20 #include "clang/Driver/DriverDiagnostic.h"
21 #include "clang/Driver/Job.h"
22 #include "clang/Driver/Options.h"
23 #include "clang/Driver/SanitizerArgs.h"
24 #include "clang/Driver/XRayArgs.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/MC/MCTargetOptions.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Option/Option.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/TargetParser.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/VersionTuple.h"
42 #include "llvm/Support/VirtualFileSystem.h"
48 using namespace clang;
49 using namespace driver;
50 using namespace tools;
52 using namespace llvm::opt;
54 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
55 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
56 options::OPT_fno_rtti, options::OPT_frtti);
59 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
60 const llvm::Triple &Triple,
61 const Arg *CachedRTTIArg) {
62 // Explicit rtti/no-rtti args
64 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
65 return ToolChain::RM_Enabled;
67 return ToolChain::RM_Disabled;
70 // -frtti is default, except for the PS4 CPU.
71 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
74 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
76 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
77 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
79 if (auto CXXStdlibPath = getCXXStdlibPath())
80 getFilePaths().push_back(*CXXStdlibPath);
83 if (auto RuntimePath = getRuntimePath())
84 getLibraryPaths().push_back(*RuntimePath);
86 std::string CandidateLibPath = getArchSpecificLibPath();
87 if (getVFS().exists(CandidateLibPath))
88 getFilePaths().push_back(CandidateLibPath);
91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
92 Triple.setEnvironment(Env);
93 if (EffectiveTriple != llvm::Triple())
94 EffectiveTriple.setEnvironment(Env);
97 ToolChain::~ToolChain() = default;
99 llvm::vfs::FileSystem &ToolChain::getVFS() const {
100 return getDriver().getVFS();
103 bool ToolChain::useIntegratedAs() const {
104 return Args.hasFlag(options::OPT_fintegrated_as,
105 options::OPT_fno_integrated_as,
106 IsIntegratedAssemblerDefault());
109 bool ToolChain::useRelaxRelocations() const {
110 return ENABLE_X86_RELAX_RELOCATIONS;
113 bool ToolChain::isNoExecStackDefault() const {
117 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
118 if (!SanitizerArguments.get())
119 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
120 return *SanitizerArguments.get();
123 const XRayArgs& ToolChain::getXRayArgs() const {
124 if (!XRayArguments.get())
125 XRayArguments.reset(new XRayArgs(*this, Args));
126 return *XRayArguments.get();
131 struct DriverSuffix {
133 const char *ModeFlag;
138 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
139 // A list of known driver suffixes. Suffixes are compared against the
140 // program name in order. If there is a match, the frontend type is updated as
141 // necessary by applying the ModeFlag.
142 static const DriverSuffix DriverSuffixes[] = {
144 {"clang++", "--driver-mode=g++"},
145 {"clang-c++", "--driver-mode=g++"},
146 {"clang-cc", nullptr},
147 {"clang-cpp", "--driver-mode=cpp"},
148 {"clang-g++", "--driver-mode=g++"},
149 {"clang-gcc", nullptr},
150 {"clang-cl", "--driver-mode=cl"},
152 {"cpp", "--driver-mode=cpp"},
153 {"cl", "--driver-mode=cl"},
154 {"++", "--driver-mode=g++"},
155 {"flang", "--driver-mode=flang"},
158 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
159 StringRef Suffix(DriverSuffixes[i].Suffix);
160 if (ProgName.endswith(Suffix)) {
161 Pos = ProgName.size() - Suffix.size();
162 return &DriverSuffixes[i];
168 /// Normalize the program name from argv[0] by stripping the file extension if
169 /// present and lower-casing the string on Windows.
170 static std::string normalizeProgramName(llvm::StringRef Argv0) {
171 std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
173 // Transform to lowercase for case insensitive file systems.
174 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
179 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
180 // Try to infer frontend type and default target from the program name by
181 // comparing it against DriverSuffixes in order.
183 // If there is a match, the function tries to identify a target as prefix.
184 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
185 // prefix "x86_64-linux". If such a target prefix is found, it may be
186 // added via -target as implicit first argument.
187 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
190 // Try again after stripping any trailing version number:
191 // clang++3.5 -> clang++
192 ProgName = ProgName.rtrim("0123456789.");
193 DS = FindDriverSuffix(ProgName, Pos);
197 // Try again after stripping trailing -component.
198 // clang++-tot -> clang++
199 ProgName = ProgName.slice(0, ProgName.rfind('-'));
200 DS = FindDriverSuffix(ProgName, Pos);
206 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
207 std::string ProgName = normalizeProgramName(PN);
209 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
212 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
214 size_t LastComponent = ProgName.rfind('-', SuffixPos);
215 if (LastComponent == std::string::npos)
216 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
217 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
218 SuffixEnd - LastComponent - 1);
220 // Infer target from the prefix.
221 StringRef Prefix(ProgName);
222 Prefix = Prefix.slice(0, LastComponent);
223 std::string IgnoredError;
225 llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
226 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
230 StringRef ToolChain::getDefaultUniversalArchName() const {
231 // In universal driver terms, the arch name accepted by -arch isn't exactly
232 // the same as the ones that appear in the triple. Roughly speaking, this is
233 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
234 switch (Triple.getArch()) {
235 case llvm::Triple::aarch64:
237 case llvm::Triple::aarch64_32:
239 case llvm::Triple::ppc:
241 case llvm::Triple::ppc64:
243 case llvm::Triple::ppc64le:
246 return Triple.getArchName();
250 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
251 return Input.getFilename();
254 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
258 Tool *ToolChain::getClang() const {
260 Clang.reset(new tools::Clang(*this));
264 Tool *ToolChain::getFlang() const {
266 Flang.reset(new tools::Flang(*this));
270 Tool *ToolChain::buildAssembler() const {
271 return new tools::ClangAs(*this);
274 Tool *ToolChain::buildLinker() const {
275 llvm_unreachable("Linking is not supported by this toolchain");
278 Tool *ToolChain::buildStaticLibTool() const {
279 llvm_unreachable("Creating static lib is not supported by this toolchain");
282 Tool *ToolChain::getAssemble() const {
284 Assemble.reset(buildAssembler());
285 return Assemble.get();
288 Tool *ToolChain::getClangAs() const {
290 Assemble.reset(new tools::ClangAs(*this));
291 return Assemble.get();
294 Tool *ToolChain::getLink() const {
296 Link.reset(buildLinker());
300 Tool *ToolChain::getStaticLibTool() const {
302 StaticLibTool.reset(buildStaticLibTool());
303 return StaticLibTool.get();
306 Tool *ToolChain::getIfsMerge() const {
308 IfsMerge.reset(new tools::ifstool::Merger(*this));
309 return IfsMerge.get();
312 Tool *ToolChain::getOffloadBundler() const {
314 OffloadBundler.reset(new tools::OffloadBundler(*this));
315 return OffloadBundler.get();
318 Tool *ToolChain::getOffloadWrapper() const {
320 OffloadWrapper.reset(new tools::OffloadWrapper(*this));
321 return OffloadWrapper.get();
324 Tool *ToolChain::getTool(Action::ActionClass AC) const {
326 case Action::AssembleJobClass:
327 return getAssemble();
329 case Action::IfsMergeJobClass:
330 return getIfsMerge();
332 case Action::LinkJobClass:
335 case Action::StaticLibJobClass:
336 return getStaticLibTool();
338 case Action::InputClass:
339 case Action::BindArchClass:
340 case Action::OffloadClass:
341 case Action::LipoJobClass:
342 case Action::DsymutilJobClass:
343 case Action::VerifyDebugInfoJobClass:
344 llvm_unreachable("Invalid tool kind.");
346 case Action::CompileJobClass:
347 case Action::PrecompileJobClass:
348 case Action::HeaderModulePrecompileJobClass:
349 case Action::PreprocessJobClass:
350 case Action::AnalyzeJobClass:
351 case Action::MigrateJobClass:
352 case Action::VerifyPCHJobClass:
353 case Action::BackendJobClass:
356 case Action::OffloadBundlingJobClass:
357 case Action::OffloadUnbundlingJobClass:
358 return getOffloadBundler();
360 case Action::OffloadWrapperJobClass:
361 return getOffloadWrapper();
364 llvm_unreachable("Invalid tool kind.");
367 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
368 const ArgList &Args) {
369 const llvm::Triple &Triple = TC.getTriple();
370 bool IsWindows = Triple.isOSWindows();
372 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
373 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
377 // For historic reasons, Android library is using i686 instead of i386.
378 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
381 return llvm::Triple::getArchTypeName(TC.getArch());
384 StringRef ToolChain::getOSLibName() const {
385 switch (Triple.getOS()) {
386 case llvm::Triple::FreeBSD:
388 case llvm::Triple::NetBSD:
390 case llvm::Triple::OpenBSD:
392 case llvm::Triple::Solaris:
394 case llvm::Triple::AIX:
401 std::string ToolChain::getCompilerRTPath() const {
402 SmallString<128> Path(getDriver().ResourceDir);
403 if (Triple.isOSUnknown()) {
404 llvm::sys::path::append(Path, "lib");
406 llvm::sys::path::append(Path, "lib", getOSLibName());
408 return std::string(Path.str());
411 std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
412 StringRef Component, FileType Type,
413 bool AddArch) const {
414 const llvm::Triple &TT = getTriple();
415 bool IsITANMSVCWindows =
416 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
419 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
422 case ToolChain::FT_Object:
423 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
425 case ToolChain::FT_Static:
426 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
428 case ToolChain::FT_Shared:
429 Suffix = Triple.isOSWindows()
430 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
435 std::string ArchAndEnv;
437 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
438 const char *Env = TT.isAndroid() ? "-android" : "";
439 ArchAndEnv = ("-" + Arch + Env).str();
441 return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
444 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
445 FileType Type) const {
446 // Check for runtime files in the new layout without the architecture first.
447 std::string CRTBasename =
448 getCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
449 for (const auto &LibPath : getLibraryPaths()) {
450 SmallString<128> P(LibPath);
451 llvm::sys::path::append(P, CRTBasename);
452 if (getVFS().exists(P))
453 return std::string(P.str());
456 // Fall back to the old expected compiler-rt name if the new one does not
458 CRTBasename = getCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
459 SmallString<128> Path(getCompilerRTPath());
460 llvm::sys::path::append(Path, CRTBasename);
461 return std::string(Path.str());
464 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
466 FileType Type) const {
467 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
471 Optional<std::string> ToolChain::getRuntimePath() const {
474 // First try the triple passed to driver as --target=<triple>.
475 P.assign(D.ResourceDir);
476 llvm::sys::path::append(P, "lib", D.getTargetTriple());
477 if (getVFS().exists(P))
478 return llvm::Optional<std::string>(std::string(P.str()));
480 // Second try the normalized triple.
481 P.assign(D.ResourceDir);
482 llvm::sys::path::append(P, "lib", Triple.str());
483 if (getVFS().exists(P))
484 return llvm::Optional<std::string>(std::string(P.str()));
489 Optional<std::string> ToolChain::getCXXStdlibPath() const {
492 // First try the triple passed to driver as --target=<triple>.
494 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
495 if (getVFS().exists(P))
496 return llvm::Optional<std::string>(std::string(P.str()));
498 // Second try the normalized triple.
500 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
501 if (getVFS().exists(P))
502 return llvm::Optional<std::string>(std::string(P.str()));
507 std::string ToolChain::getArchSpecificLibPath() const {
508 SmallString<128> Path(getDriver().ResourceDir);
509 llvm::sys::path::append(Path, "lib", getOSLibName(),
510 llvm::Triple::getArchTypeName(getArch()));
511 return std::string(Path.str());
514 bool ToolChain::needsProfileRT(const ArgList &Args) {
515 if (Args.hasArg(options::OPT_noprofilelib))
518 return Args.hasArg(options::OPT_fprofile_generate) ||
519 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
520 Args.hasArg(options::OPT_fcs_profile_generate) ||
521 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
522 Args.hasArg(options::OPT_fprofile_instr_generate) ||
523 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
524 Args.hasArg(options::OPT_fcreate_profile) ||
525 Args.hasArg(options::OPT_forder_file_instrumentation);
528 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
529 return Args.hasArg(options::OPT_coverage) ||
530 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
534 Tool *ToolChain::SelectTool(const JobAction &JA) const {
535 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
536 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
537 Action::ActionClass AC = JA.getKind();
538 if (AC == Action::AssembleJobClass && useIntegratedAs())
543 std::string ToolChain::GetFilePath(const char *Name) const {
544 return D.GetFilePath(Name, *this);
547 std::string ToolChain::GetProgramPath(const char *Name) const {
548 return D.GetProgramPath(Name, *this);
551 std::string ToolChain::GetLinkerPath() const {
552 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
553 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
554 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
555 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
557 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
558 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
559 // contain a path component separator.
560 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
561 std::string Path(A->getValue());
563 if (llvm::sys::path::parent_path(Path).empty())
564 Path = GetProgramPath(A->getValue());
565 if (llvm::sys::fs::can_execute(Path))
566 return std::string(Path);
568 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
569 return GetProgramPath(getDefaultLinker());
571 // If we're passed -fuse-ld= with no argument, or with the argument ld,
572 // then use whatever the default system linker is.
573 if (UseLinker.empty() || UseLinker == "ld") {
574 const char *DefaultLinker = getDefaultLinker();
575 if (llvm::sys::path::is_absolute(DefaultLinker))
576 return std::string(DefaultLinker);
578 return GetProgramPath(DefaultLinker);
581 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
582 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
583 // to a relative path is surprising. This is more complex due to priorities
584 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
585 if (UseLinker.find('/') != StringRef::npos)
586 getDriver().Diag(diag::warn_drv_fuse_ld_path);
588 if (llvm::sys::path::is_absolute(UseLinker)) {
589 // If we're passed what looks like an absolute path, don't attempt to
590 // second-guess that.
591 if (llvm::sys::fs::can_execute(UseLinker))
592 return std::string(UseLinker);
594 llvm::SmallString<8> LinkerName;
595 if (Triple.isOSDarwin())
596 LinkerName.append("ld64.");
598 LinkerName.append("ld.");
599 LinkerName.append(UseLinker);
601 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
602 if (llvm::sys::fs::can_execute(LinkerPath))
607 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
609 return GetProgramPath(getDefaultLinker());
612 std::string ToolChain::GetStaticLibToolPath() const {
613 // TODO: Add support for static lib archiving on Windows
614 return GetProgramPath("llvm-ar");
617 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
618 types::ID id = types::lookupTypeForExtension(Ext);
620 // Flang always runs the preprocessor and has no notion of "preprocessed
621 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
623 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
624 id = types::TY_Fortran;
629 bool ToolChain::HasNativeLLVMSupport() const {
633 bool ToolChain::isCrossCompiling() const {
634 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
635 switch (HostTriple.getArch()) {
636 // The A32/T32/T16 instruction sets are not separate architectures in this
638 case llvm::Triple::arm:
639 case llvm::Triple::armeb:
640 case llvm::Triple::thumb:
641 case llvm::Triple::thumbeb:
642 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
643 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
645 return HostTriple.getArch() != getArch();
649 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
650 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
654 llvm::ExceptionHandling
655 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
656 return llvm::ExceptionHandling::None;
659 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
660 if (Model == "single") {
661 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
662 return Triple.getArch() == llvm::Triple::arm ||
663 Triple.getArch() == llvm::Triple::armeb ||
664 Triple.getArch() == llvm::Triple::thumb ||
665 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
666 } else if (Model == "posix")
672 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
673 types::ID InputType) const {
674 switch (getTriple().getArch()) {
676 return getTripleString();
678 case llvm::Triple::x86_64: {
679 llvm::Triple Triple = getTriple();
680 if (!Triple.isOSBinFormatMachO())
681 return getTripleString();
683 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
684 // x86_64h goes in the triple. Other -march options just use the
685 // vanilla triple we already have.
686 StringRef MArch = A->getValue();
687 if (MArch == "x86_64h")
688 Triple.setArchName(MArch);
690 return Triple.getTriple();
692 case llvm::Triple::aarch64: {
693 llvm::Triple Triple = getTriple();
694 if (!Triple.isOSBinFormatMachO())
695 return getTripleString();
697 // FIXME: older versions of ld64 expect the "arm64" component in the actual
698 // triple string and query it to determine whether an LTO file can be
699 // handled. Remove this when we don't care any more.
700 Triple.setArchName("arm64");
701 return Triple.getTriple();
703 case llvm::Triple::aarch64_32:
704 return getTripleString();
705 case llvm::Triple::arm:
706 case llvm::Triple::armeb:
707 case llvm::Triple::thumb:
708 case llvm::Triple::thumbeb: {
709 // FIXME: Factor into subclasses.
710 llvm::Triple Triple = getTriple();
711 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
712 getTriple().getArch() == llvm::Triple::thumbeb;
714 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
715 // '-mbig-endian'/'-EB'.
716 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
717 options::OPT_mbig_endian)) {
718 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
721 // Thumb2 is the default for V7 on Darwin.
723 // FIXME: Thumb should just be another -target-feaure, not in the triple.
724 StringRef MCPU, MArch;
725 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
726 MCPU = A->getValue();
727 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
728 MArch = A->getValue();
730 Triple.isOSBinFormatMachO()
731 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
732 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
734 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
735 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
736 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
737 getTriple().isOSBinFormatMachO());
738 // FIXME: this is invalid for WindowsCE
739 if (getTriple().isOSWindows())
741 std::string ArchName;
747 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
748 // M-Class CPUs/architecture variants, which is not supported.
749 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
750 options::OPT_mno_thumb, ThumbDefault);
751 if (IsMProfile && ARMModeRequested) {
753 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
755 getDriver().Diag(diag::err_arch_unsupported_isa)
756 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
759 // Check to see if an explicit choice to use thumb has been made via
760 // -mthumb. For assembler files we must check for -mthumb in the options
761 // passed to the assembler via -Wa or -Xassembler.
762 bool IsThumb = false;
763 if (InputType != types::TY_PP_Asm)
764 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
767 // Ideally we would check for these flags in
768 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
769 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
772 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
773 for (StringRef Value : A->getValues()) {
774 if (Value == "-mthumb")
779 // Assembly files should start in ARM mode, unless arch is M-profile, or
780 // -mthumb has been passed explicitly to the assembler. Windows is always
782 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
784 ArchName = "thumbeb";
788 Triple.setArchName(ArchName + Suffix.str());
790 return Triple.getTriple();
795 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
796 types::ID InputType) const {
797 return ComputeLLVMTriple(Args, InputType);
800 std::string ToolChain::computeSysRoot() const {
804 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
805 ArgStringList &CC1Args) const {
806 // Each toolchain should provide the appropriate include flags.
809 void ToolChain::addClangTargetOptions(
810 const ArgList &DriverArgs, ArgStringList &CC1Args,
811 Action::OffloadKind DeviceOffloadKind) const {}
813 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
815 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
816 llvm::opt::ArgStringList &CmdArgs) const {
817 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
820 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
823 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
824 const ArgList &Args) const {
825 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
826 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
828 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
829 if (LibName == "compiler-rt")
830 return ToolChain::RLT_CompilerRT;
831 else if (LibName == "libgcc")
832 return ToolChain::RLT_Libgcc;
833 else if (LibName == "platform")
834 return GetDefaultRuntimeLibType();
837 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
839 return GetDefaultRuntimeLibType();
842 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
843 const ArgList &Args) const {
844 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
845 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
847 if (LibName == "none")
848 return ToolChain::UNW_None;
849 else if (LibName == "platform" || LibName == "") {
850 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
851 if (RtLibType == ToolChain::RLT_CompilerRT)
852 return ToolChain::UNW_None;
853 else if (RtLibType == ToolChain::RLT_Libgcc)
854 return ToolChain::UNW_Libgcc;
855 } else if (LibName == "libunwind") {
856 if (GetRuntimeLibType(Args) == RLT_Libgcc)
857 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
858 return ToolChain::UNW_CompilerRT;
859 } else if (LibName == "libgcc")
860 return ToolChain::UNW_Libgcc;
863 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
864 << A->getAsString(Args);
866 return GetDefaultUnwindLibType();
869 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
870 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
871 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
873 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
874 if (LibName == "libc++")
875 return ToolChain::CST_Libcxx;
876 else if (LibName == "libstdc++")
877 return ToolChain::CST_Libstdcxx;
878 else if (LibName == "platform")
879 return GetDefaultCXXStdlibType();
882 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
884 return GetDefaultCXXStdlibType();
887 /// Utility function to add a system include directory to CC1 arguments.
888 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
889 ArgStringList &CC1Args,
891 CC1Args.push_back("-internal-isystem");
892 CC1Args.push_back(DriverArgs.MakeArgString(Path));
895 /// Utility function to add a system include directory with extern "C"
896 /// semantics to CC1 arguments.
898 /// Note that this should be used rarely, and only for directories that
899 /// historically and for legacy reasons are treated as having implicit extern
900 /// "C" semantics. These semantics are *ignored* by and large today, but its
901 /// important to preserve the preprocessor changes resulting from the
903 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
904 ArgStringList &CC1Args,
906 CC1Args.push_back("-internal-externc-isystem");
907 CC1Args.push_back(DriverArgs.MakeArgString(Path));
910 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
911 ArgStringList &CC1Args,
913 if (llvm::sys::fs::exists(Path))
914 addExternCSystemInclude(DriverArgs, CC1Args, Path);
917 /// Utility function to add a list of system include directories to CC1.
918 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
919 ArgStringList &CC1Args,
920 ArrayRef<StringRef> Paths) {
921 for (const auto &Path : Paths) {
922 CC1Args.push_back("-internal-isystem");
923 CC1Args.push_back(DriverArgs.MakeArgString(Path));
927 std::string ToolChain::detectLibcxxIncludePath(StringRef Base) const {
930 std::string MaxVersionString;
931 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Base, EC), LE;
932 !EC && LI != LE; LI = LI.increment(EC)) {
933 StringRef VersionText = llvm::sys::path::filename(LI->path());
935 if (VersionText[0] == 'v' &&
936 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
937 if (Version > MaxVersion) {
938 MaxVersion = Version;
939 MaxVersionString = std::string(VersionText);
945 SmallString<128> P(Base);
946 llvm::sys::path::append(P, MaxVersionString);
947 return std::string(P.str());
950 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
951 ArgStringList &CC1Args) const {
952 // Header search paths should be handled by each of the subclasses.
953 // Historically, they have not been, and instead have been handled inside of
954 // the CC1-layer frontend. As the logic is hoisted out, this generic function
955 // will slowly stop being called.
957 // While it is being called, replicate a bit of a hack to propagate the
958 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
959 // header search paths with it. Once all systems are overriding this
960 // function, the CC1 flag and this line can be removed.
961 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
964 void ToolChain::AddClangCXXStdlibIsystemArgs(
965 const llvm::opt::ArgList &DriverArgs,
966 llvm::opt::ArgStringList &CC1Args) const {
967 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
968 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
970 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
971 addSystemInclude(DriverArgs, CC1Args, P);
974 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
975 return getDriver().CCCIsCXX() &&
976 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
977 options::OPT_nostdlibxx);
980 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
981 ArgStringList &CmdArgs) const {
982 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
983 "should not have called this");
984 CXXStdlibType Type = GetCXXStdlibType(Args);
987 case ToolChain::CST_Libcxx:
988 CmdArgs.push_back("-lc++");
991 case ToolChain::CST_Libstdcxx:
992 CmdArgs.push_back("-lstdc++");
997 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
998 ArgStringList &CmdArgs) const {
999 for (const auto &LibPath : getFilePaths())
1000 if(LibPath.length() > 0)
1001 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1004 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1005 ArgStringList &CmdArgs) const {
1006 CmdArgs.push_back("-lcc_kext");
1009 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
1010 std::string &Path) const {
1011 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1012 // (to keep the linker options consistent with gcc and clang itself).
1013 if (!isOptimizationLevelFast(Args)) {
1014 // Check if -ffast-math or -funsafe-math.
1016 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
1017 options::OPT_funsafe_math_optimizations,
1018 options::OPT_fno_unsafe_math_optimizations);
1020 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1021 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1024 // If crtfastmath.o exists add it to the arguments.
1025 Path = GetFilePath("crtfastmath.o");
1026 return (Path != "crtfastmath.o"); // Not found.
1029 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
1030 ArgStringList &CmdArgs) const {
1032 if (isFastMathRuntimeAvailable(Args, Path)) {
1033 CmdArgs.push_back(Args.MakeArgString(Path));
1040 SanitizerMask ToolChain::getSupportedSanitizers() const {
1041 // Return sanitizers which don't require runtime support and are not
1042 // platform dependent.
1045 (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
1046 ~SanitizerKind::Function) |
1047 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1048 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1049 SanitizerKind::UnsignedIntegerOverflow |
1050 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1051 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1052 if (getTriple().getArch() == llvm::Triple::x86 ||
1053 getTriple().getArch() == llvm::Triple::x86_64 ||
1054 getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
1055 getTriple().isAArch64())
1056 Res |= SanitizerKind::CFIICall;
1057 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1058 getTriple().isAArch64() || getTriple().isRISCV())
1059 Res |= SanitizerKind::ShadowCallStack;
1060 if (getTriple().isAArch64())
1061 Res |= SanitizerKind::MemTag;
1065 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1066 ArgStringList &CC1Args) const {}
1068 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1069 ArgStringList &CC1Args) const {}
1071 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1072 ArgStringList &CC1Args) const {}
1074 static VersionTuple separateMSVCFullVersion(unsigned Version) {
1076 return VersionTuple(Version);
1078 if (Version < 10000)
1079 return VersionTuple(Version / 100, Version % 100);
1081 unsigned Build = 0, Factor = 1;
1082 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1083 Build = Build + (Version % 10) * Factor;
1084 return VersionTuple(Version / 100, Version % 100, Build);
1088 ToolChain::computeMSVCVersion(const Driver *D,
1089 const llvm::opt::ArgList &Args) const {
1090 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1091 const Arg *MSCompatibilityVersion =
1092 Args.getLastArg(options::OPT_fms_compatibility_version);
1094 if (MSCVersion && MSCompatibilityVersion) {
1096 D->Diag(diag::err_drv_argument_not_allowed_with)
1097 << MSCVersion->getAsString(Args)
1098 << MSCompatibilityVersion->getAsString(Args);
1099 return VersionTuple();
1102 if (MSCompatibilityVersion) {
1104 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1106 D->Diag(diag::err_drv_invalid_value)
1107 << MSCompatibilityVersion->getAsString(Args)
1108 << MSCompatibilityVersion->getValue();
1115 unsigned Version = 0;
1116 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1118 D->Diag(diag::err_drv_invalid_value)
1119 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1121 return separateMSVCFullVersion(Version);
1125 return VersionTuple();
1128 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1129 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1130 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1131 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1132 const OptTable &Opts = getDriver().getOpts();
1133 bool Modified = false;
1135 // Handle -Xopenmp-target flags
1136 for (auto *A : Args) {
1137 // Exclude flags which may only apply to the host toolchain.
1138 // Do not exclude flags when the host triple (AuxTriple)
1139 // matches the current toolchain triple. If it is not present
1140 // at all, target and host share a toolchain.
1141 if (A->getOption().matches(options::OPT_m_Group)) {
1142 if (SameTripleAsHost)
1151 bool XOpenMPTargetNoTriple =
1152 A->getOption().matches(options::OPT_Xopenmp_target);
1154 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1155 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1156 if (A->getValue(0) == getTripleString())
1157 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1160 } else if (XOpenMPTargetNoTriple) {
1161 // Passing device args: -Xopenmp-target -opt=val.
1162 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1168 // Parse the argument to -Xopenmp-target.
1170 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1171 if (!XOpenMPTargetArg || Index > Prev + 1) {
1172 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1173 << A->getAsString(Args);
1176 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1177 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1178 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1181 XOpenMPTargetArg->setBaseArg(A);
1182 A = XOpenMPTargetArg.release();
1183 AllocatedArgs.push_back(A);
1195 // TODO: Currently argument values separated by space e.g.
1196 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1198 void ToolChain::TranslateXarchArgs(
1199 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1200 llvm::opt::DerivedArgList *DAL,
1201 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1202 const OptTable &Opts = getDriver().getOpts();
1203 unsigned ValuePos = 1;
1204 if (A->getOption().matches(options::OPT_Xarch_device) ||
1205 A->getOption().matches(options::OPT_Xarch_host))
1208 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1209 unsigned Prev = Index;
1210 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1212 // If the argument parsing failed or more than one argument was
1213 // consumed, the -Xarch_ argument's parameter tried to consume
1214 // extra arguments. Emit an error and ignore.
1216 // We also want to disallow any options which would alter the
1217 // driver behavior; that isn't going to work in our model. We
1218 // use isDriverOption() as an approximation, although things
1219 // like -O4 are going to slip through.
1220 if (!XarchArg || Index > Prev + 1) {
1221 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1222 << A->getAsString(Args);
1224 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
1225 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
1226 << A->getAsString(Args);
1229 XarchArg->setBaseArg(A);
1230 A = XarchArg.release();
1232 DAL->AddSynthesizedArg(A);
1234 AllocatedArgs->push_back(A);
1237 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1238 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1239 Action::OffloadKind OFK,
1240 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1241 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1242 bool Modified = false;
1244 bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP;
1245 for (Arg *A : Args) {
1246 bool NeedTrans = false;
1248 if (A->getOption().matches(options::OPT_Xarch_device)) {
1251 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1254 } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) {
1255 // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1256 // they may need special translation.
1257 // Skip this argument unless the architecture matches BoundArch
1258 if (BoundArch.empty() || A->getValue(0) != BoundArch)
1263 if (NeedTrans || Skip)
1266 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);