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