xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Linux.cpp (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 //===--- Linux.h - Linux ToolChain Implementations --------------*- C++ -*-===//
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 "Linux.h"
10 #include "Arch/ARM.h"
11 #include "Arch/LoongArch.h"
12 #include "Arch/Mips.h"
13 #include "Arch/PPC.h"
14 #include "Arch/RISCV.h"
15 #include "CommonArgs.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Distro.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/SanitizerArgs.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/ProfileData/InstrProf.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/ScopedPrinter.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include <system_error>
27 
28 using namespace clang::driver;
29 using namespace clang::driver::toolchains;
30 using namespace clang;
31 using namespace llvm::opt;
32 
33 using tools::addPathIfExists;
34 
35 /// Get our best guess at the multiarch triple for a target.
36 ///
37 /// Debian-based systems are starting to use a multiarch setup where they use
38 /// a target-triple directory in the library and header search paths.
39 /// Unfortunately, this triple does not align with the vanilla target triple,
40 /// so we provide a rough mapping here.
41 std::string Linux::getMultiarchTriple(const Driver &D,
42                                       const llvm::Triple &TargetTriple,
43                                       StringRef SysRoot) const {
44   llvm::Triple::EnvironmentType TargetEnvironment =
45       TargetTriple.getEnvironment();
46   bool IsAndroid = TargetTriple.isAndroid();
47   bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
48   bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
49 
50   // For most architectures, just use whatever we have rather than trying to be
51   // clever.
52   switch (TargetTriple.getArch()) {
53   default:
54     break;
55 
56   // We use the existence of '/lib/<triple>' as a directory to detect some
57   // common linux triples that don't quite match the Clang triple for both
58   // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
59   // regardless of what the actual target triple is.
60   case llvm::Triple::arm:
61   case llvm::Triple::thumb:
62     if (IsAndroid)
63       return "arm-linux-androideabi";
64     if (TargetEnvironment == llvm::Triple::GNUEABIHF)
65       return "arm-linux-gnueabihf";
66     return "arm-linux-gnueabi";
67   case llvm::Triple::armeb:
68   case llvm::Triple::thumbeb:
69     if (TargetEnvironment == llvm::Triple::GNUEABIHF)
70       return "armeb-linux-gnueabihf";
71     return "armeb-linux-gnueabi";
72   case llvm::Triple::x86:
73     if (IsAndroid)
74       return "i686-linux-android";
75     return "i386-linux-gnu";
76   case llvm::Triple::x86_64:
77     if (IsAndroid)
78       return "x86_64-linux-android";
79     if (TargetEnvironment == llvm::Triple::GNUX32)
80       return "x86_64-linux-gnux32";
81     return "x86_64-linux-gnu";
82   case llvm::Triple::aarch64:
83     if (IsAndroid)
84       return "aarch64-linux-android";
85     return "aarch64-linux-gnu";
86   case llvm::Triple::aarch64_be:
87     return "aarch64_be-linux-gnu";
88 
89   case llvm::Triple::m68k:
90     return "m68k-linux-gnu";
91 
92   case llvm::Triple::mips:
93     return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
94   case llvm::Triple::mipsel:
95     if (IsAndroid)
96       return "mipsel-linux-android";
97     return IsMipsR6 ? "mipsisa32r6el-linux-gnu" : "mipsel-linux-gnu";
98   case llvm::Triple::mips64: {
99     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
100                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
101     if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
102       return MT;
103     if (D.getVFS().exists(concat(SysRoot, "/lib/mips64-linux-gnu")))
104       return "mips64-linux-gnu";
105     break;
106   }
107   case llvm::Triple::mips64el: {
108     if (IsAndroid)
109       return "mips64el-linux-android";
110     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
111                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
112     if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
113       return MT;
114     if (D.getVFS().exists(concat(SysRoot, "/lib/mips64el-linux-gnu")))
115       return "mips64el-linux-gnu";
116     break;
117   }
118   case llvm::Triple::ppc:
119     if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
120       return "powerpc-linux-gnuspe";
121     return "powerpc-linux-gnu";
122   case llvm::Triple::ppcle:
123     return "powerpcle-linux-gnu";
124   case llvm::Triple::ppc64:
125     return "powerpc64-linux-gnu";
126   case llvm::Triple::ppc64le:
127     return "powerpc64le-linux-gnu";
128   case llvm::Triple::riscv64:
129     return "riscv64-linux-gnu";
130   case llvm::Triple::sparc:
131     return "sparc-linux-gnu";
132   case llvm::Triple::sparcv9:
133     return "sparc64-linux-gnu";
134   case llvm::Triple::systemz:
135     return "s390x-linux-gnu";
136   }
137   return TargetTriple.str();
138 }
139 
140 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
141   if (Triple.isMIPS()) {
142     if (Triple.isAndroid()) {
143       StringRef CPUName;
144       StringRef ABIName;
145       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
146       if (CPUName == "mips32r6")
147         return "libr6";
148       if (CPUName == "mips32r2")
149         return "libr2";
150     }
151     // lib32 directory has a special meaning on MIPS targets.
152     // It contains N32 ABI binaries. Use this folder if produce
153     // code for N32 ABI only.
154     if (tools::mips::hasMipsAbiArg(Args, "n32"))
155       return "lib32";
156     return Triple.isArch32Bit() ? "lib" : "lib64";
157   }
158 
159   // It happens that only x86, PPC and SPARC use the 'lib32' variant of
160   // oslibdir, and using that variant while targeting other architectures causes
161   // problems because the libraries are laid out in shared system roots that
162   // can't cope with a 'lib32' library search path being considered. So we only
163   // enable them when we know we may need it.
164   //
165   // FIXME: This is a bit of a hack. We should really unify this code for
166   // reasoning about oslibdir spellings with the lib dir spellings in the
167   // GCCInstallationDetector, but that is a more significant refactoring.
168   if (Triple.getArch() == llvm::Triple::x86 || Triple.isPPC32() ||
169       Triple.getArch() == llvm::Triple::sparc)
170     return "lib32";
171 
172   if (Triple.getArch() == llvm::Triple::x86_64 && Triple.isX32())
173     return "libx32";
174 
175   if (Triple.getArch() == llvm::Triple::riscv32)
176     return "lib32";
177 
178   return Triple.isArch32Bit() ? "lib" : "lib64";
179 }
180 
181 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
182     : Generic_ELF(D, Triple, Args) {
183   GCCInstallation.init(Triple, Args);
184   Multilibs = GCCInstallation.getMultilibs();
185   SelectedMultilib = GCCInstallation.getMultilib();
186   llvm::Triple::ArchType Arch = Triple.getArch();
187   std::string SysRoot = computeSysRoot();
188   ToolChain::path_list &PPaths = getProgramPaths();
189 
190   Generic_GCC::PushPPaths(PPaths);
191 
192   Distro Distro(D.getVFS(), Triple);
193 
194   if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
195     ExtraOpts.push_back("-z");
196     ExtraOpts.push_back("now");
197   }
198 
199   if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
200       Triple.isAndroid()) {
201     ExtraOpts.push_back("-z");
202     ExtraOpts.push_back("relro");
203   }
204 
205   // Android ARM/AArch64 use max-page-size=4096 to reduce VMA usage. Note, lld
206   // from 11 onwards default max-page-size to 65536 for both ARM and AArch64.
207   if ((Triple.isARM() || Triple.isAArch64()) && Triple.isAndroid()) {
208     ExtraOpts.push_back("-z");
209     ExtraOpts.push_back("max-page-size=4096");
210   }
211 
212   if (GCCInstallation.getParentLibPath().contains("opt/rh/"))
213     // With devtoolset on RHEL, we want to add a bin directory that is relative
214     // to the detected gcc install, because if we are using devtoolset gcc then
215     // we want to use other tools from devtoolset (e.g. ld) instead of the
216     // standard system tools.
217     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
218                      "/../bin").str());
219 
220   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
221     ExtraOpts.push_back("-X");
222 
223   const bool IsAndroid = Triple.isAndroid();
224   const bool IsMips = Triple.isMIPS();
225   const bool IsHexagon = Arch == llvm::Triple::hexagon;
226   const bool IsRISCV = Triple.isRISCV();
227   const bool IsCSKY = Triple.isCSKY();
228 
229   if (IsCSKY)
230     SysRoot = SysRoot + SelectedMultilib.osSuffix();
231 
232   if ((IsMips || IsCSKY) && !SysRoot.empty())
233     ExtraOpts.push_back("--sysroot=" + SysRoot);
234 
235   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
236   // and the MIPS ABI require .dynsym to be sorted in different ways.
237   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
238   // ABI requires a mapping between the GOT and the symbol table.
239   // Android loader does not support .gnu.hash until API 23.
240   // Hexagon linker/loader does not support .gnu.hash
241   if (!IsMips && !IsHexagon) {
242     if (Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid ||
243         Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic ||
244         (IsAndroid && Triple.isAndroidVersionLT(23)))
245       ExtraOpts.push_back("--hash-style=both");
246     else
247       ExtraOpts.push_back("--hash-style=gnu");
248   }
249 
250 #ifdef ENABLE_LINKER_BUILD_ID
251   ExtraOpts.push_back("--build-id");
252 #endif
253 
254   // The selection of paths to try here is designed to match the patterns which
255   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
256   // This was determined by running GCC in a fake filesystem, creating all
257   // possible permutations of these directories, and seeing which ones it added
258   // to the link paths.
259   path_list &Paths = getFilePaths();
260 
261   const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
262   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
263 
264   // mips32: Debian multilib, we use /libo32, while in other case, /lib is
265   // used. We need add both libo32 and /lib.
266   if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel) {
267     Generic_GCC::AddMultilibPaths(D, SysRoot, "libo32", MultiarchTriple, Paths);
268     addPathIfExists(D, concat(SysRoot, "/libo32"), Paths);
269     addPathIfExists(D, concat(SysRoot, "/usr/libo32"), Paths);
270   }
271   Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
272 
273   addPathIfExists(D, concat(SysRoot, "/lib", MultiarchTriple), Paths);
274   addPathIfExists(D, concat(SysRoot, "/lib/..", OSLibDir), Paths);
275 
276   if (IsAndroid) {
277     // Android sysroots contain a library directory for each supported OS
278     // version as well as some unversioned libraries in the usual multiarch
279     // directory.
280     addPathIfExists(
281         D,
282         concat(SysRoot, "/usr/lib", MultiarchTriple,
283                llvm::to_string(Triple.getEnvironmentVersion().getMajor())),
284         Paths);
285   }
286 
287   addPathIfExists(D, concat(SysRoot, "/usr/lib", MultiarchTriple), Paths);
288   // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot
289   // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle
290   // this here.
291   if (Triple.getVendor() == llvm::Triple::OpenEmbedded &&
292       Triple.isArch64Bit())
293     addPathIfExists(D, concat(SysRoot, "/usr", OSLibDir), Paths);
294   else
295     addPathIfExists(D, concat(SysRoot, "/usr/lib/..", OSLibDir), Paths);
296   if (IsRISCV) {
297     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
298     addPathIfExists(D, concat(SysRoot, "/", OSLibDir, ABIName), Paths);
299     addPathIfExists(D, concat(SysRoot, "/usr", OSLibDir, ABIName), Paths);
300   }
301 
302   Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
303 
304   // The deprecated -DLLVM_ENABLE_PROJECTS=libcxx configuration installs
305   // libc++.so in D.Dir+"/../lib/". Detect this path.
306   // TODO Remove once LLVM_ENABLE_PROJECTS=libcxx is unsupported.
307   if (StringRef(D.Dir).startswith(SysRoot) &&
308       D.getVFS().exists(D.Dir + "/../lib/libc++.so"))
309     addPathIfExists(D, D.Dir + "/../lib", Paths);
310 
311   addPathIfExists(D, concat(SysRoot, "/lib"), Paths);
312   addPathIfExists(D, concat(SysRoot, "/usr/lib"), Paths);
313 }
314 
315 ToolChain::RuntimeLibType Linux::GetDefaultRuntimeLibType() const {
316   if (getTriple().isAndroid())
317     return ToolChain::RLT_CompilerRT;
318   return Generic_ELF::GetDefaultRuntimeLibType();
319 }
320 
321 unsigned Linux::GetDefaultDwarfVersion() const {
322   if (getTriple().isAndroid())
323     return 4;
324   return ToolChain::GetDefaultDwarfVersion();
325 }
326 
327 ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
328   if (getTriple().isAndroid())
329     return ToolChain::CST_Libcxx;
330   return ToolChain::CST_Libstdcxx;
331 }
332 
333 bool Linux::HasNativeLLVMSupport() const { return true; }
334 
335 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
336 
337 Tool *Linux::buildStaticLibTool() const {
338   return new tools::gnutools::StaticLibTool(*this);
339 }
340 
341 Tool *Linux::buildAssembler() const {
342   return new tools::gnutools::Assembler(*this);
343 }
344 
345 std::string Linux::computeSysRoot() const {
346   if (!getDriver().SysRoot.empty())
347     return getDriver().SysRoot;
348 
349   if (getTriple().isAndroid()) {
350     // Android toolchains typically include a sysroot at ../sysroot relative to
351     // the clang binary.
352     const StringRef ClangDir = getDriver().getInstalledDir();
353     std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
354     if (getVFS().exists(AndroidSysRootPath))
355       return AndroidSysRootPath;
356   }
357 
358   if (getTriple().isCSKY()) {
359     // CSKY toolchains use different names for sysroot folder.
360     if (!GCCInstallation.isValid())
361       return std::string();
362     // GCCInstallation.getInstallPath() =
363     //   $GCCToolchainPath/lib/gcc/csky-linux-gnuabiv2/6.3.0
364     // Path = $GCCToolchainPath/csky-linux-gnuabiv2/libc
365     std::string Path = (GCCInstallation.getInstallPath() + "/../../../../" +
366                         GCCInstallation.getTriple().str() + "/libc")
367                            .str();
368     if (getVFS().exists(Path))
369       return Path;
370     return std::string();
371   }
372 
373   if (!GCCInstallation.isValid() || !getTriple().isMIPS())
374     return std::string();
375 
376   // Standalone MIPS toolchains use different names for sysroot folder
377   // and put it into different places. Here we try to check some known
378   // variants.
379 
380   const StringRef InstallDir = GCCInstallation.getInstallPath();
381   const StringRef TripleStr = GCCInstallation.getTriple().str();
382   const Multilib &Multilib = GCCInstallation.getMultilib();
383 
384   std::string Path =
385       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
386           .str();
387 
388   if (getVFS().exists(Path))
389     return Path;
390 
391   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
392 
393   if (getVFS().exists(Path))
394     return Path;
395 
396   return std::string();
397 }
398 
399 std::string Linux::getDynamicLinker(const ArgList &Args) const {
400   const llvm::Triple::ArchType Arch = getArch();
401   const llvm::Triple &Triple = getTriple();
402 
403   const Distro Distro(getDriver().getVFS(), Triple);
404 
405   if (Triple.isAndroid())
406     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
407 
408   if (Triple.isMusl()) {
409     std::string ArchName;
410     bool IsArm = false;
411 
412     switch (Arch) {
413     case llvm::Triple::arm:
414     case llvm::Triple::thumb:
415       ArchName = "arm";
416       IsArm = true;
417       break;
418     case llvm::Triple::armeb:
419     case llvm::Triple::thumbeb:
420       ArchName = "armeb";
421       IsArm = true;
422       break;
423     case llvm::Triple::x86:
424       ArchName = "i386";
425       break;
426     case llvm::Triple::x86_64:
427       ArchName = Triple.isX32() ? "x32" : Triple.getArchName().str();
428       break;
429     default:
430       ArchName = Triple.getArchName().str();
431     }
432     if (IsArm &&
433         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
434          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
435       ArchName += "hf";
436     if (Arch == llvm::Triple::ppc &&
437         Triple.getSubArch() == llvm::Triple::PPCSubArch_spe)
438       ArchName = "powerpc-sf";
439 
440     return "/lib/ld-musl-" + ArchName + ".so.1";
441   }
442 
443   std::string LibDir;
444   std::string Loader;
445 
446   switch (Arch) {
447   default:
448     llvm_unreachable("unsupported architecture");
449 
450   case llvm::Triple::aarch64:
451     LibDir = "lib";
452     Loader = "ld-linux-aarch64.so.1";
453     break;
454   case llvm::Triple::aarch64_be:
455     LibDir = "lib";
456     Loader = "ld-linux-aarch64_be.so.1";
457     break;
458   case llvm::Triple::arm:
459   case llvm::Triple::thumb:
460   case llvm::Triple::armeb:
461   case llvm::Triple::thumbeb: {
462     const bool HF =
463         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
464         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
465 
466     LibDir = "lib";
467     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
468     break;
469   }
470   case llvm::Triple::loongarch32: {
471     LibDir = "lib32";
472     Loader =
473         ("ld-linux-loongarch-" +
474          tools::loongarch::getLoongArchABI(getDriver(), Args, Triple) + ".so.1")
475             .str();
476     break;
477   }
478   case llvm::Triple::loongarch64: {
479     LibDir = "lib64";
480     Loader =
481         ("ld-linux-loongarch-" +
482          tools::loongarch::getLoongArchABI(getDriver(), Args, Triple) + ".so.1")
483             .str();
484     break;
485   }
486   case llvm::Triple::m68k:
487     LibDir = "lib";
488     Loader = "ld.so.1";
489     break;
490   case llvm::Triple::mips:
491   case llvm::Triple::mipsel:
492   case llvm::Triple::mips64:
493   case llvm::Triple::mips64el: {
494     bool IsNaN2008 = tools::mips::isNaN2008(getDriver(), Args, Triple);
495 
496     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
497 
498     if (tools::mips::isUCLibc(Args))
499       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
500     else if (!Triple.hasEnvironment() &&
501              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
502       Loader =
503           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
504     else
505       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
506 
507     break;
508   }
509   case llvm::Triple::ppc:
510     LibDir = "lib";
511     Loader = "ld.so.1";
512     break;
513   case llvm::Triple::ppcle:
514     LibDir = "lib";
515     Loader = "ld.so.1";
516     break;
517   case llvm::Triple::ppc64:
518     LibDir = "lib64";
519     Loader =
520         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
521     break;
522   case llvm::Triple::ppc64le:
523     LibDir = "lib64";
524     Loader =
525         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
526     break;
527   case llvm::Triple::riscv32: {
528     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
529     LibDir = "lib";
530     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
531     break;
532   }
533   case llvm::Triple::riscv64: {
534     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
535     LibDir = "lib";
536     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
537     break;
538   }
539   case llvm::Triple::sparc:
540   case llvm::Triple::sparcel:
541     LibDir = "lib";
542     Loader = "ld-linux.so.2";
543     break;
544   case llvm::Triple::sparcv9:
545     LibDir = "lib64";
546     Loader = "ld-linux.so.2";
547     break;
548   case llvm::Triple::systemz:
549     LibDir = "lib";
550     Loader = "ld64.so.1";
551     break;
552   case llvm::Triple::x86:
553     LibDir = "lib";
554     Loader = "ld-linux.so.2";
555     break;
556   case llvm::Triple::x86_64: {
557     bool X32 = Triple.isX32();
558 
559     LibDir = X32 ? "libx32" : "lib64";
560     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
561     break;
562   }
563   case llvm::Triple::ve:
564     return "/opt/nec/ve/lib/ld-linux-ve.so.1";
565   case llvm::Triple::csky: {
566     LibDir = "lib";
567     Loader = "ld.so.1";
568     break;
569   }
570   }
571 
572   if (Distro == Distro::Exherbo &&
573       (Triple.getVendor() == llvm::Triple::UnknownVendor ||
574        Triple.getVendor() == llvm::Triple::PC))
575     return "/usr/" + Triple.str() + "/lib/" + Loader;
576   return "/" + LibDir + "/" + Loader;
577 }
578 
579 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
580                                       ArgStringList &CC1Args) const {
581   const Driver &D = getDriver();
582   std::string SysRoot = computeSysRoot();
583 
584   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
585     return;
586 
587   // Add 'include' in the resource directory, which is similar to
588   // GCC_INCLUDE_DIR (private headers) in GCC. Note: the include directory
589   // contains some files conflicting with system /usr/include. musl systems
590   // prefer the /usr/include copies which are more relevant.
591   SmallString<128> ResourceDirInclude(D.ResourceDir);
592   llvm::sys::path::append(ResourceDirInclude, "include");
593   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) &&
594       (!getTriple().isMusl() || DriverArgs.hasArg(options::OPT_nostdlibinc)))
595     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
596 
597   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
598     return;
599 
600   // LOCAL_INCLUDE_DIR
601   addSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/usr/local/include"));
602   // TOOL_INCLUDE_DIR
603   AddMultilibIncludeArgs(DriverArgs, CC1Args);
604 
605   // Check for configure-time C include directories.
606   StringRef CIncludeDirs(C_INCLUDE_DIRS);
607   if (CIncludeDirs != "") {
608     SmallVector<StringRef, 5> dirs;
609     CIncludeDirs.split(dirs, ":");
610     for (StringRef dir : dirs) {
611       StringRef Prefix =
612           llvm::sys::path::is_absolute(dir) ? "" : StringRef(SysRoot);
613       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
614     }
615     return;
616   }
617 
618   // On systems using multiarch and Android, add /usr/include/$triple before
619   // /usr/include.
620   std::string MultiarchIncludeDir = getMultiarchTriple(D, getTriple(), SysRoot);
621   if (!MultiarchIncludeDir.empty() &&
622       D.getVFS().exists(concat(SysRoot, "/usr/include", MultiarchIncludeDir)))
623     addExternCSystemInclude(
624         DriverArgs, CC1Args,
625         concat(SysRoot, "/usr/include", MultiarchIncludeDir));
626 
627   if (getTriple().getOS() == llvm::Triple::RTEMS)
628     return;
629 
630   // Add an include of '/include' directly. This isn't provided by default by
631   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
632   // add even when Clang is acting as-if it were a system compiler.
633   addExternCSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/include"));
634 
635   addExternCSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/usr/include"));
636 
637   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) && getTriple().isMusl())
638     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
639 }
640 
641 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
642                                      llvm::opt::ArgStringList &CC1Args) const {
643   // We need a detected GCC installation on Linux to provide libstdc++'s
644   // headers in odd Linuxish places.
645   if (!GCCInstallation.isValid())
646     return;
647 
648   // Detect Debian g++-multiarch-incdir.diff.
649   StringRef TripleStr = GCCInstallation.getTriple().str();
650   StringRef DebianMultiarch =
651       GCCInstallation.getTriple().getArch() == llvm::Triple::x86
652           ? "i386-linux-gnu"
653           : TripleStr;
654 
655   // Try generic GCC detection first.
656   if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
657                                                DebianMultiarch))
658     return;
659 
660   StringRef LibDir = GCCInstallation.getParentLibPath();
661   const Multilib &Multilib = GCCInstallation.getMultilib();
662   const GCCVersion &Version = GCCInstallation.getVersion();
663 
664   const std::string LibStdCXXIncludePathCandidates[] = {
665       // Android standalone toolchain has C++ headers in yet another place.
666       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
667       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
668       // without a subdirectory corresponding to the gcc version.
669       LibDir.str() + "/../include/c++",
670       // Cray's gcc installation puts headers under "g++" without a
671       // version suffix.
672       LibDir.str() + "/../include/g++",
673   };
674 
675   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
676     if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
677                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
678       break;
679   }
680 }
681 
682 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
683                                ArgStringList &CC1Args) const {
684   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
685 }
686 
687 void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
688                               ArgStringList &CC1Args) const {
689   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
690 }
691 
692 void Linux::AddHIPRuntimeLibArgs(const ArgList &Args,
693                                  ArgStringList &CmdArgs) const {
694   CmdArgs.push_back(
695       Args.MakeArgString(StringRef("-L") + RocmInstallation.getLibPath()));
696 
697   if (Args.hasFlag(options::OPT_offload_add_rpath,
698                    options::OPT_no_offload_add_rpath, false))
699     CmdArgs.append(
700         {"-rpath", Args.MakeArgString(RocmInstallation.getLibPath())});
701 
702   CmdArgs.push_back("-lamdhip64");
703 }
704 
705 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
706                                 ArgStringList &CC1Args) const {
707   if (GCCInstallation.isValid()) {
708     CC1Args.push_back("-isystem");
709     CC1Args.push_back(DriverArgs.MakeArgString(
710         GCCInstallation.getParentLibPath() + "/../" +
711         GCCInstallation.getTriple().str() + "/include"));
712   }
713 }
714 
715 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
716   return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
717          getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
718 }
719 
720 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
721   // Outline atomics for AArch64 are supported by compiler-rt
722   // and libgcc since 9.3.1
723   assert(getTriple().isAArch64() && "expected AArch64 target!");
724   ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
725   if (RtLib == ToolChain::RLT_CompilerRT)
726     return true;
727   assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
728   if (GCCInstallation.getVersion().isOlderThan(9, 3, 1))
729     return false;
730   return true;
731 }
732 
733 bool Linux::IsMathErrnoDefault() const {
734   if (getTriple().isAndroid() || getTriple().isMusl())
735     return false;
736   return Generic_ELF::IsMathErrnoDefault();
737 }
738 
739 SanitizerMask Linux::getSupportedSanitizers() const {
740   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
741   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
742   const bool IsMIPS = getTriple().isMIPS32();
743   const bool IsMIPS64 = getTriple().isMIPS64();
744   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
745                            getTriple().getArch() == llvm::Triple::ppc64le;
746   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
747                          getTriple().getArch() == llvm::Triple::aarch64_be;
748   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
749                          getTriple().getArch() == llvm::Triple::thumb ||
750                          getTriple().getArch() == llvm::Triple::armeb ||
751                          getTriple().getArch() == llvm::Triple::thumbeb;
752   const bool IsLoongArch64 = getTriple().getArch() == llvm::Triple::loongarch64;
753   const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
754   const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
755   const bool IsHexagon = getTriple().getArch() == llvm::Triple::hexagon;
756   SanitizerMask Res = ToolChain::getSupportedSanitizers();
757   Res |= SanitizerKind::Address;
758   Res |= SanitizerKind::PointerCompare;
759   Res |= SanitizerKind::PointerSubtract;
760   Res |= SanitizerKind::Fuzzer;
761   Res |= SanitizerKind::FuzzerNoLink;
762   Res |= SanitizerKind::KernelAddress;
763   Res |= SanitizerKind::Memory;
764   Res |= SanitizerKind::Vptr;
765   Res |= SanitizerKind::SafeStack;
766   if (IsX86_64 || IsMIPS64 || IsAArch64)
767     Res |= SanitizerKind::DataFlow;
768   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
769       IsRISCV64 || IsSystemZ || IsHexagon || IsLoongArch64)
770     Res |= SanitizerKind::Leak;
771   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64 || IsSystemZ ||
772       IsLoongArch64)
773     Res |= SanitizerKind::Thread;
774   if (IsX86_64)
775     Res |= SanitizerKind::KernelMemory;
776   if (IsX86 || IsX86_64)
777     Res |= SanitizerKind::Function;
778   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
779       IsPowerPC64 || IsHexagon || IsLoongArch64)
780     Res |= SanitizerKind::Scudo;
781   if (IsX86_64 || IsAArch64 || IsRISCV64) {
782     Res |= SanitizerKind::HWAddress;
783   }
784   if (IsX86_64 || IsAArch64) {
785     Res |= SanitizerKind::KernelHWAddress;
786   }
787   return Res;
788 }
789 
790 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
791                              llvm::opt::ArgStringList &CmdArgs) const {
792   // Add linker option -u__llvm_profile_runtime to cause runtime
793   // initialization module to be linked in.
794   if (needsProfileRT(Args))
795     CmdArgs.push_back(Args.MakeArgString(
796         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
797   ToolChain::addProfileRTLibs(Args, CmdArgs);
798 }
799 
800 llvm::DenormalMode
801 Linux::getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs,
802                                      const JobAction &JA,
803                                      const llvm::fltSemantics *FPType) const {
804   switch (getTriple().getArch()) {
805   case llvm::Triple::x86:
806   case llvm::Triple::x86_64: {
807     std::string Unused;
808     // DAZ and FTZ are turned on in crtfastmath.o
809     if (!DriverArgs.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
810         isFastMathRuntimeAvailable(DriverArgs, Unused))
811       return llvm::DenormalMode::getPreserveSign();
812     return llvm::DenormalMode::getIEEE();
813   }
814   default:
815     return llvm::DenormalMode::getIEEE();
816   }
817 }
818 
819 void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
820   for (const auto &Opt : ExtraOpts)
821     CmdArgs.push_back(Opt.c_str());
822 }
823 
824 const char *Linux::getDefaultLinker() const {
825   if (getTriple().isAndroid())
826     return "ld.lld";
827   return Generic_ELF::getDefaultLinker();
828 }
829