1 //===--- ToolChain.cpp - Collections of tools for one platform ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Tools.h"
11 #include "clang/Basic/ObjCRuntime.h"
12 #include "clang/Driver/Action.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Options.h"
16 #include "clang/Driver/SanitizerArgs.h"
17 #include "clang/Driver/ToolChain.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Option/Arg.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Option/Option.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/TargetRegistry.h"
26 
27 using namespace clang::driver;
28 using namespace clang::driver::tools;
29 using namespace clang;
30 using namespace llvm::opt;
31 
32 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
33   return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
34                          options::OPT_fno_rtti, options::OPT_frtti);
35 }
36 
37 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
38                                              const llvm::Triple &Triple,
39                                              const Arg *CachedRTTIArg) {
40   // Explicit rtti/no-rtti args
41   if (CachedRTTIArg) {
42     if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
43       return ToolChain::RM_EnabledExplicitly;
44     else
45       return ToolChain::RM_DisabledExplicitly;
46   }
47 
48   // -frtti is default, except for the PS4 CPU.
49   if (!Triple.isPS4CPU())
50     return ToolChain::RM_EnabledImplicitly;
51 
52   // On the PS4, turning on c++ exceptions turns on rtti.
53   // We're assuming that, if we see -fexceptions, rtti gets turned on.
54   Arg *Exceptions = Args.getLastArgNoClaim(
55       options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
56       options::OPT_fexceptions, options::OPT_fno_exceptions);
57   if (Exceptions &&
58       (Exceptions->getOption().matches(options::OPT_fexceptions) ||
59        Exceptions->getOption().matches(options::OPT_fcxx_exceptions)))
60     return ToolChain::RM_EnabledImplicitly;
61 
62   return ToolChain::RM_DisabledImplicitly;
63 }
64 
65 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
66                      const ArgList &Args)
67     : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
68       CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
69   if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
70     if (!isThreadModelSupported(A->getValue()))
71       D.Diag(diag::err_drv_invalid_thread_model_for_target)
72           << A->getValue() << A->getAsString(Args);
73 }
74 
75 ToolChain::~ToolChain() {
76 }
77 
78 vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); }
79 
80 bool ToolChain::useIntegratedAs() const {
81   return Args.hasFlag(options::OPT_fintegrated_as,
82                       options::OPT_fno_integrated_as,
83                       IsIntegratedAssemblerDefault());
84 }
85 
86 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
87   if (!SanitizerArguments.get())
88     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
89   return *SanitizerArguments.get();
90 }
91 
92 namespace {
93 struct DriverSuffix {
94   const char *Suffix;
95   const char *ModeFlag;
96 };
97 
98 const DriverSuffix *FindDriverSuffix(StringRef ProgName) {
99   // A list of known driver suffixes. Suffixes are compared against the
100   // program name in order. If there is a match, the frontend type is updated as
101   // necessary by applying the ModeFlag.
102   static const DriverSuffix DriverSuffixes[] = {
103       {"clang", nullptr},
104       {"clang++", "--driver-mode=g++"},
105       {"clang-c++", "--driver-mode=g++"},
106       {"clang-cc", nullptr},
107       {"clang-cpp", "--driver-mode=cpp"},
108       {"clang-g++", "--driver-mode=g++"},
109       {"clang-gcc", nullptr},
110       {"clang-cl", "--driver-mode=cl"},
111       {"cc", nullptr},
112       {"cpp", "--driver-mode=cpp"},
113       {"cl", "--driver-mode=cl"},
114       {"++", "--driver-mode=g++"},
115   };
116 
117   for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i)
118     if (ProgName.endswith(DriverSuffixes[i].Suffix))
119       return &DriverSuffixes[i];
120   return nullptr;
121 }
122 
123 /// Normalize the program name from argv[0] by stripping the file extension if
124 /// present and lower-casing the string on Windows.
125 std::string normalizeProgramName(llvm::StringRef Argv0) {
126   std::string ProgName = llvm::sys::path::stem(Argv0);
127 #ifdef LLVM_ON_WIN32
128   // Transform to lowercase for case insensitive file systems.
129   std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
130 #endif
131   return ProgName;
132 }
133 
134 const DriverSuffix *parseDriverSuffix(StringRef ProgName) {
135   // Try to infer frontend type and default target from the program name by
136   // comparing it against DriverSuffixes in order.
137 
138   // If there is a match, the function tries to identify a target as prefix.
139   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
140   // prefix "x86_64-linux". If such a target prefix is found, it may be
141   // added via -target as implicit first argument.
142   const DriverSuffix *DS = FindDriverSuffix(ProgName);
143 
144   if (!DS) {
145     // Try again after stripping any trailing version number:
146     // clang++3.5 -> clang++
147     ProgName = ProgName.rtrim("0123456789.");
148     DS = FindDriverSuffix(ProgName);
149   }
150 
151   if (!DS) {
152     // Try again after stripping trailing -component.
153     // clang++-tot -> clang++
154     ProgName = ProgName.slice(0, ProgName.rfind('-'));
155     DS = FindDriverSuffix(ProgName);
156   }
157   return DS;
158 }
159 } // anonymous namespace
160 
161 std::pair<std::string, std::string>
162 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
163   std::string ProgName = normalizeProgramName(PN);
164   const DriverSuffix *DS = parseDriverSuffix(ProgName);
165   if (!DS)
166     return std::make_pair("", "");
167   std::string ModeFlag = DS->ModeFlag == nullptr ? "" : DS->ModeFlag;
168 
169   std::string::size_type LastComponent =
170       ProgName.rfind('-', ProgName.size() - strlen(DS->Suffix));
171   if (LastComponent == std::string::npos)
172     return std::make_pair("", ModeFlag);
173 
174   // Infer target from the prefix.
175   StringRef Prefix(ProgName);
176   Prefix = Prefix.slice(0, LastComponent);
177   std::string IgnoredError;
178   std::string Target;
179   if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
180     Target = Prefix;
181   }
182   return std::make_pair(Target, ModeFlag);
183 }
184 
185 StringRef ToolChain::getDefaultUniversalArchName() const {
186   // In universal driver terms, the arch name accepted by -arch isn't exactly
187   // the same as the ones that appear in the triple. Roughly speaking, this is
188   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
189   // only interesting special case is powerpc.
190   switch (Triple.getArch()) {
191   case llvm::Triple::ppc:
192     return "ppc";
193   case llvm::Triple::ppc64:
194     return "ppc64";
195   case llvm::Triple::ppc64le:
196     return "ppc64le";
197   default:
198     return Triple.getArchName();
199   }
200 }
201 
202 bool ToolChain::IsUnwindTablesDefault() const {
203   return false;
204 }
205 
206 Tool *ToolChain::getClang() const {
207   if (!Clang)
208     Clang.reset(new tools::Clang(*this));
209   return Clang.get();
210 }
211 
212 Tool *ToolChain::buildAssembler() const {
213   return new tools::ClangAs(*this);
214 }
215 
216 Tool *ToolChain::buildLinker() const {
217   llvm_unreachable("Linking is not supported by this toolchain");
218 }
219 
220 Tool *ToolChain::getAssemble() const {
221   if (!Assemble)
222     Assemble.reset(buildAssembler());
223   return Assemble.get();
224 }
225 
226 Tool *ToolChain::getClangAs() const {
227   if (!Assemble)
228     Assemble.reset(new tools::ClangAs(*this));
229   return Assemble.get();
230 }
231 
232 Tool *ToolChain::getLink() const {
233   if (!Link)
234     Link.reset(buildLinker());
235   return Link.get();
236 }
237 
238 Tool *ToolChain::getTool(Action::ActionClass AC) const {
239   switch (AC) {
240   case Action::AssembleJobClass:
241     return getAssemble();
242 
243   case Action::LinkJobClass:
244     return getLink();
245 
246   case Action::InputClass:
247   case Action::BindArchClass:
248   case Action::CudaDeviceClass:
249   case Action::CudaHostClass:
250   case Action::LipoJobClass:
251   case Action::DsymutilJobClass:
252   case Action::VerifyDebugInfoJobClass:
253     llvm_unreachable("Invalid tool kind.");
254 
255   case Action::CompileJobClass:
256   case Action::PrecompileJobClass:
257   case Action::PreprocessJobClass:
258   case Action::AnalyzeJobClass:
259   case Action::MigrateJobClass:
260   case Action::VerifyPCHJobClass:
261   case Action::BackendJobClass:
262     return getClang();
263   }
264 
265   llvm_unreachable("Invalid tool kind.");
266 }
267 
268 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
269                                              const ArgList &Args) {
270   const llvm::Triple &Triple = TC.getTriple();
271   bool IsWindows = Triple.isOSWindows();
272 
273   if (Triple.isWindowsMSVCEnvironment() && TC.getArch() == llvm::Triple::x86)
274     return "i386";
275 
276   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
277     return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
278                ? "armhf"
279                : "arm";
280 
281   return TC.getArchName();
282 }
283 
284 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
285                                      bool Shared) const {
286   const llvm::Triple &TT = getTriple();
287   const char *Env = TT.isAndroid() ? "-android" : "";
288   bool IsITANMSVCWindows =
289       TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
290 
291   StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
292   const char *Prefix = IsITANMSVCWindows ? "" : "lib";
293   const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so")
294                               : (IsITANMSVCWindows ? ".lib" : ".a");
295 
296   SmallString<128> Path(getDriver().ResourceDir);
297   StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS();
298   llvm::sys::path::append(Path, "lib", OSLibName);
299   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
300                                     Arch + Env + Suffix);
301   return Path.str();
302 }
303 
304 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
305                                               StringRef Component,
306                                               bool Shared) const {
307   return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
308 }
309 
310 bool ToolChain::needsProfileRT(const ArgList &Args) {
311   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
312                    false) ||
313       Args.hasArg(options::OPT_fprofile_generate) ||
314       Args.hasArg(options::OPT_fprofile_generate_EQ) ||
315       Args.hasArg(options::OPT_fprofile_instr_generate) ||
316       Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
317       Args.hasArg(options::OPT_fcreate_profile) ||
318       Args.hasArg(options::OPT_coverage))
319     return true;
320 
321   return false;
322 }
323 
324 Tool *ToolChain::SelectTool(const JobAction &JA) const {
325   if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
326   Action::ActionClass AC = JA.getKind();
327   if (AC == Action::AssembleJobClass && useIntegratedAs())
328     return getClangAs();
329   return getTool(AC);
330 }
331 
332 std::string ToolChain::GetFilePath(const char *Name) const {
333   return D.GetFilePath(Name, *this);
334 
335 }
336 
337 std::string ToolChain::GetProgramPath(const char *Name) const {
338   return D.GetProgramPath(Name, *this);
339 }
340 
341 std::string ToolChain::GetLinkerPath() const {
342   if (Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
343     StringRef Suffix = A->getValue();
344 
345     // If we're passed -fuse-ld= with no argument, or with the argument ld,
346     // then use whatever the default system linker is.
347     if (Suffix.empty() || Suffix == "ld")
348       return GetProgramPath("ld");
349 
350     llvm::SmallString<8> LinkerName("ld.");
351     LinkerName.append(Suffix);
352 
353     std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
354     if (llvm::sys::fs::exists(LinkerPath))
355       return LinkerPath;
356 
357     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
358     return "";
359   }
360 
361   return GetProgramPath("ld");
362 }
363 
364 types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
365   return types::lookupTypeForExtension(Ext);
366 }
367 
368 bool ToolChain::HasNativeLLVMSupport() const {
369   return false;
370 }
371 
372 bool ToolChain::isCrossCompiling() const {
373   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
374   switch (HostTriple.getArch()) {
375   // The A32/T32/T16 instruction sets are not separate architectures in this
376   // context.
377   case llvm::Triple::arm:
378   case llvm::Triple::armeb:
379   case llvm::Triple::thumb:
380   case llvm::Triple::thumbeb:
381     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
382            getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
383   default:
384     return HostTriple.getArch() != getArch();
385   }
386 }
387 
388 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
389   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
390                      VersionTuple());
391 }
392 
393 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
394   if (Model == "single") {
395     // FIXME: 'single' is only supported on ARM and WebAssembly so far.
396     return Triple.getArch() == llvm::Triple::arm ||
397            Triple.getArch() == llvm::Triple::armeb ||
398            Triple.getArch() == llvm::Triple::thumb ||
399            Triple.getArch() == llvm::Triple::thumbeb ||
400            Triple.getArch() == llvm::Triple::wasm32 ||
401            Triple.getArch() == llvm::Triple::wasm64;
402   } else if (Model == "posix")
403     return true;
404 
405   return false;
406 }
407 
408 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
409                                          types::ID InputType) const {
410   switch (getTriple().getArch()) {
411   default:
412     return getTripleString();
413 
414   case llvm::Triple::x86_64: {
415     llvm::Triple Triple = getTriple();
416     if (!Triple.isOSBinFormatMachO())
417       return getTripleString();
418 
419     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
420       // x86_64h goes in the triple. Other -march options just use the
421       // vanilla triple we already have.
422       StringRef MArch = A->getValue();
423       if (MArch == "x86_64h")
424         Triple.setArchName(MArch);
425     }
426     return Triple.getTriple();
427   }
428   case llvm::Triple::aarch64: {
429     llvm::Triple Triple = getTriple();
430     if (!Triple.isOSBinFormatMachO())
431       return getTripleString();
432 
433     // FIXME: older versions of ld64 expect the "arm64" component in the actual
434     // triple string and query it to determine whether an LTO file can be
435     // handled. Remove this when we don't care any more.
436     Triple.setArchName("arm64");
437     return Triple.getTriple();
438   }
439   case llvm::Triple::arm:
440   case llvm::Triple::armeb:
441   case llvm::Triple::thumb:
442   case llvm::Triple::thumbeb: {
443     // FIXME: Factor into subclasses.
444     llvm::Triple Triple = getTriple();
445     bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
446                        getTriple().getArch() == llvm::Triple::thumbeb;
447 
448     // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
449     // '-mbig-endian'/'-EB'.
450     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
451                                  options::OPT_mbig_endian)) {
452       IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
453     }
454 
455     // Thumb2 is the default for V7 on Darwin.
456     //
457     // FIXME: Thumb should just be another -target-feaure, not in the triple.
458     StringRef MCPU, MArch;
459     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
460       MCPU = A->getValue();
461     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
462       MArch = A->getValue();
463     std::string CPU =
464         Triple.isOSBinFormatMachO()
465             ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
466             : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
467     StringRef Suffix =
468       tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
469     bool ThumbDefault = Suffix.startswith("v6m") || Suffix.startswith("v7m") ||
470       Suffix.startswith("v7em") ||
471       (Suffix.startswith("v7") && getTriple().isOSBinFormatMachO());
472     // FIXME: this is invalid for WindowsCE
473     if (getTriple().isOSWindows())
474       ThumbDefault = true;
475     std::string ArchName;
476     if (IsBigEndian)
477       ArchName = "armeb";
478     else
479       ArchName = "arm";
480 
481     // Assembly files should start in ARM mode.
482     if (InputType != types::TY_PP_Asm &&
483         Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
484     {
485       if (IsBigEndian)
486         ArchName = "thumbeb";
487       else
488         ArchName = "thumb";
489     }
490     Triple.setArchName(ArchName + Suffix.str());
491 
492     return Triple.getTriple();
493   }
494   }
495 }
496 
497 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
498                                                    types::ID InputType) const {
499   return ComputeLLVMTriple(Args, InputType);
500 }
501 
502 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
503                                           ArgStringList &CC1Args) const {
504   // Each toolchain should provide the appropriate include flags.
505 }
506 
507 void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
508                                       ArgStringList &CC1Args) const {
509 }
510 
511 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
512 
513 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
514                                  llvm::opt::ArgStringList &CmdArgs) const {
515   if (!needsProfileRT(Args)) return;
516 
517   CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
518   return;
519 }
520 
521 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
522     const ArgList &Args) const {
523   if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
524     StringRef Value = A->getValue();
525     if (Value == "compiler-rt")
526       return ToolChain::RLT_CompilerRT;
527     if (Value == "libgcc")
528       return ToolChain::RLT_Libgcc;
529     getDriver().Diag(diag::err_drv_invalid_rtlib_name)
530       << A->getAsString(Args);
531   }
532 
533   return GetDefaultRuntimeLibType();
534 }
535 
536 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
537   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
538     StringRef Value = A->getValue();
539     if (Value == "libc++")
540       return ToolChain::CST_Libcxx;
541     if (Value == "libstdc++")
542       return ToolChain::CST_Libstdcxx;
543     getDriver().Diag(diag::err_drv_invalid_stdlib_name)
544       << A->getAsString(Args);
545   }
546 
547   return ToolChain::CST_Libstdcxx;
548 }
549 
550 /// \brief Utility function to add a system include directory to CC1 arguments.
551 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
552                                             ArgStringList &CC1Args,
553                                             const Twine &Path) {
554   CC1Args.push_back("-internal-isystem");
555   CC1Args.push_back(DriverArgs.MakeArgString(Path));
556 }
557 
558 /// \brief Utility function to add a system include directory with extern "C"
559 /// semantics to CC1 arguments.
560 ///
561 /// Note that this should be used rarely, and only for directories that
562 /// historically and for legacy reasons are treated as having implicit extern
563 /// "C" semantics. These semantics are *ignored* by and large today, but its
564 /// important to preserve the preprocessor changes resulting from the
565 /// classification.
566 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
567                                                    ArgStringList &CC1Args,
568                                                    const Twine &Path) {
569   CC1Args.push_back("-internal-externc-isystem");
570   CC1Args.push_back(DriverArgs.MakeArgString(Path));
571 }
572 
573 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
574                                                 ArgStringList &CC1Args,
575                                                 const Twine &Path) {
576   if (llvm::sys::fs::exists(Path))
577     addExternCSystemInclude(DriverArgs, CC1Args, Path);
578 }
579 
580 /// \brief Utility function to add a list of system include directories to CC1.
581 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
582                                              ArgStringList &CC1Args,
583                                              ArrayRef<StringRef> Paths) {
584   for (StringRef Path : Paths) {
585     CC1Args.push_back("-internal-isystem");
586     CC1Args.push_back(DriverArgs.MakeArgString(Path));
587   }
588 }
589 
590 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
591                                              ArgStringList &CC1Args) const {
592   // Header search paths should be handled by each of the subclasses.
593   // Historically, they have not been, and instead have been handled inside of
594   // the CC1-layer frontend. As the logic is hoisted out, this generic function
595   // will slowly stop being called.
596   //
597   // While it is being called, replicate a bit of a hack to propagate the
598   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
599   // header search paths with it. Once all systems are overriding this
600   // function, the CC1 flag and this line can be removed.
601   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
602 }
603 
604 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
605                                     ArgStringList &CmdArgs) const {
606   CXXStdlibType Type = GetCXXStdlibType(Args);
607 
608   switch (Type) {
609   case ToolChain::CST_Libcxx:
610     CmdArgs.push_back("-lc++");
611     break;
612 
613   case ToolChain::CST_Libstdcxx:
614     CmdArgs.push_back("-lstdc++");
615     break;
616   }
617 }
618 
619 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
620                                  ArgStringList &CmdArgs) const {
621   CmdArgs.push_back("-lcc_kext");
622 }
623 
624 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
625                                               ArgStringList &CmdArgs) const {
626   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
627   // (to keep the linker options consistent with gcc and clang itself).
628   if (!isOptimizationLevelFast(Args)) {
629     // Check if -ffast-math or -funsafe-math.
630     Arg *A =
631         Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
632                         options::OPT_funsafe_math_optimizations,
633                         options::OPT_fno_unsafe_math_optimizations);
634 
635     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
636         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
637       return false;
638   }
639   // If crtfastmath.o exists add it to the arguments.
640   std::string Path = GetFilePath("crtfastmath.o");
641   if (Path == "crtfastmath.o") // Not found.
642     return false;
643 
644   CmdArgs.push_back(Args.MakeArgString(Path));
645   return true;
646 }
647 
648 SanitizerMask ToolChain::getSupportedSanitizers() const {
649   // Return sanitizers which don't require runtime support and are not
650   // platform dependent.
651   using namespace SanitizerKind;
652   SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
653                       CFICastStrict | UnsignedIntegerOverflow | LocalBounds;
654   if (getTriple().getArch() == llvm::Triple::x86 ||
655       getTriple().getArch() == llvm::Triple::x86_64)
656     Res |= CFIICall;
657   return Res;
658 }
659