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 "clang/Driver/ToolChain.h"
11 #include "InputInfo.h"
12 #include "ToolChains/Arch/ARM.h"
13 #include "ToolChains/Clang.h"
14 #include "clang/Basic/ObjCRuntime.h"
15 #include "clang/Basic/Sanitizers.h"
16 #include "clang/Basic/VersionTuple.h"
17 #include "clang/Basic/VirtualFileSystem.h"
18 #include "clang/Config/config.h"
19 #include "clang/Driver/Action.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/XRayArgs.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Config/llvm-config.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Option/Option.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/MC/MCTargetOptions.h"
40 #include "llvm/Support/TargetParser.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include <cassert>
43 #include <cstddef>
44 #include <cstring>
45 #include <string>
46 
47 using namespace clang;
48 using namespace driver;
49 using namespace tools;
50 using namespace llvm;
51 using namespace llvm::opt;
52 
53 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
54   return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
55                          options::OPT_fno_rtti, options::OPT_frtti);
56 }
57 
58 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
59                                              const llvm::Triple &Triple,
60                                              const Arg *CachedRTTIArg) {
61   // Explicit rtti/no-rtti args
62   if (CachedRTTIArg) {
63     if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
64       return ToolChain::RM_EnabledExplicitly;
65     else
66       return ToolChain::RM_DisabledExplicitly;
67   }
68 
69   // -frtti is default, except for the PS4 CPU.
70   if (!Triple.isPS4CPU())
71     return ToolChain::RM_EnabledImplicitly;
72 
73   // On the PS4, turning on c++ exceptions turns on rtti.
74   // We're assuming that, if we see -fexceptions, rtti gets turned on.
75   Arg *Exceptions = Args.getLastArgNoClaim(
76       options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
77       options::OPT_fexceptions, options::OPT_fno_exceptions);
78   if (Exceptions &&
79       (Exceptions->getOption().matches(options::OPT_fexceptions) ||
80        Exceptions->getOption().matches(options::OPT_fcxx_exceptions)))
81     return ToolChain::RM_EnabledImplicitly;
82 
83   return ToolChain::RM_DisabledImplicitly;
84 }
85 
86 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
87                      const ArgList &Args)
88     : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
89       CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
90   std::string CandidateLibPath = getArchSpecificLibPath();
91   if (getVFS().exists(CandidateLibPath))
92     getFilePaths().push_back(CandidateLibPath);
93 }
94 
95 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
96   Triple.setEnvironment(Env);
97   if (EffectiveTriple != llvm::Triple())
98     EffectiveTriple.setEnvironment(Env);
99 }
100 
101 ToolChain::~ToolChain() = default;
102 
103 vfs::FileSystem &ToolChain::getVFS() const { return getDriver().getVFS(); }
104 
105 bool ToolChain::useIntegratedAs() const {
106   return Args.hasFlag(options::OPT_fintegrated_as,
107                       options::OPT_fno_integrated_as,
108                       IsIntegratedAssemblerDefault());
109 }
110 
111 bool ToolChain::useRelaxRelocations() const {
112   return ENABLE_X86_RELAX_RELOCATIONS;
113 }
114 
115 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
116   if (!SanitizerArguments.get())
117     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
118   return *SanitizerArguments.get();
119 }
120 
121 const XRayArgs& ToolChain::getXRayArgs() const {
122   if (!XRayArguments.get())
123     XRayArguments.reset(new XRayArgs(*this, Args));
124   return *XRayArguments.get();
125 }
126 
127 namespace {
128 
129 struct DriverSuffix {
130   const char *Suffix;
131   const char *ModeFlag;
132 };
133 
134 } // namespace
135 
136 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
137   // A list of known driver suffixes. Suffixes are compared against the
138   // program name in order. If there is a match, the frontend type is updated as
139   // necessary by applying the ModeFlag.
140   static const DriverSuffix DriverSuffixes[] = {
141       {"clang", nullptr},
142       {"clang++", "--driver-mode=g++"},
143       {"clang-c++", "--driver-mode=g++"},
144       {"clang-cc", nullptr},
145       {"clang-cpp", "--driver-mode=cpp"},
146       {"clang-g++", "--driver-mode=g++"},
147       {"clang-gcc", nullptr},
148       {"clang-cl", "--driver-mode=cl"},
149       {"cc", nullptr},
150       {"cpp", "--driver-mode=cpp"},
151       {"cl", "--driver-mode=cl"},
152       {"++", "--driver-mode=g++"},
153   };
154 
155   for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
156     StringRef Suffix(DriverSuffixes[i].Suffix);
157     if (ProgName.endswith(Suffix)) {
158       Pos = ProgName.size() - Suffix.size();
159       return &DriverSuffixes[i];
160     }
161   }
162   return nullptr;
163 }
164 
165 /// Normalize the program name from argv[0] by stripping the file extension if
166 /// present and lower-casing the string on Windows.
167 static std::string normalizeProgramName(llvm::StringRef Argv0) {
168   std::string ProgName = llvm::sys::path::stem(Argv0);
169 #ifdef _WIN32
170   // Transform to lowercase for case insensitive file systems.
171   std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
172 #endif
173   return ProgName;
174 }
175 
176 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
177   // Try to infer frontend type and default target from the program name by
178   // comparing it against DriverSuffixes in order.
179 
180   // If there is a match, the function tries to identify a target as prefix.
181   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
182   // prefix "x86_64-linux". If such a target prefix is found, it may be
183   // added via -target as implicit first argument.
184   const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
185 
186   if (!DS) {
187     // Try again after stripping any trailing version number:
188     // clang++3.5 -> clang++
189     ProgName = ProgName.rtrim("0123456789.");
190     DS = FindDriverSuffix(ProgName, Pos);
191   }
192 
193   if (!DS) {
194     // Try again after stripping trailing -component.
195     // clang++-tot -> clang++
196     ProgName = ProgName.slice(0, ProgName.rfind('-'));
197     DS = FindDriverSuffix(ProgName, Pos);
198   }
199   return DS;
200 }
201 
202 ParsedClangName
203 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
204   std::string ProgName = normalizeProgramName(PN);
205   size_t SuffixPos;
206   const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
207   if (!DS)
208     return {};
209   size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
210 
211   size_t LastComponent = ProgName.rfind('-', SuffixPos);
212   if (LastComponent == std::string::npos)
213     return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
214   std::string ModeSuffix = ProgName.substr(LastComponent + 1,
215                                            SuffixEnd - LastComponent - 1);
216 
217   // Infer target from the prefix.
218   StringRef Prefix(ProgName);
219   Prefix = Prefix.slice(0, LastComponent);
220   std::string IgnoredError;
221   bool IsRegistered = llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError);
222   return ParsedClangName{Prefix, ModeSuffix, DS->ModeFlag, IsRegistered};
223 }
224 
225 StringRef ToolChain::getDefaultUniversalArchName() const {
226   // In universal driver terms, the arch name accepted by -arch isn't exactly
227   // the same as the ones that appear in the triple. Roughly speaking, this is
228   // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
229   // only interesting special case is powerpc.
230   switch (Triple.getArch()) {
231   case llvm::Triple::ppc:
232     return "ppc";
233   case llvm::Triple::ppc64:
234     return "ppc64";
235   case llvm::Triple::ppc64le:
236     return "ppc64le";
237   default:
238     return Triple.getArchName();
239   }
240 }
241 
242 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
243   return Input.getFilename();
244 }
245 
246 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
247   return false;
248 }
249 
250 Tool *ToolChain::getClang() const {
251   if (!Clang)
252     Clang.reset(new tools::Clang(*this));
253   return Clang.get();
254 }
255 
256 Tool *ToolChain::buildAssembler() const {
257   return new tools::ClangAs(*this);
258 }
259 
260 Tool *ToolChain::buildLinker() const {
261   llvm_unreachable("Linking is not supported by this toolchain");
262 }
263 
264 Tool *ToolChain::getAssemble() const {
265   if (!Assemble)
266     Assemble.reset(buildAssembler());
267   return Assemble.get();
268 }
269 
270 Tool *ToolChain::getClangAs() const {
271   if (!Assemble)
272     Assemble.reset(new tools::ClangAs(*this));
273   return Assemble.get();
274 }
275 
276 Tool *ToolChain::getLink() const {
277   if (!Link)
278     Link.reset(buildLinker());
279   return Link.get();
280 }
281 
282 Tool *ToolChain::getOffloadBundler() const {
283   if (!OffloadBundler)
284     OffloadBundler.reset(new tools::OffloadBundler(*this));
285   return OffloadBundler.get();
286 }
287 
288 Tool *ToolChain::getTool(Action::ActionClass AC) const {
289   switch (AC) {
290   case Action::AssembleJobClass:
291     return getAssemble();
292 
293   case Action::LinkJobClass:
294     return getLink();
295 
296   case Action::InputClass:
297   case Action::BindArchClass:
298   case Action::OffloadClass:
299   case Action::LipoJobClass:
300   case Action::DsymutilJobClass:
301   case Action::VerifyDebugInfoJobClass:
302     llvm_unreachable("Invalid tool kind.");
303 
304   case Action::CompileJobClass:
305   case Action::PrecompileJobClass:
306   case Action::PreprocessJobClass:
307   case Action::AnalyzeJobClass:
308   case Action::MigrateJobClass:
309   case Action::VerifyPCHJobClass:
310   case Action::BackendJobClass:
311     return getClang();
312 
313   case Action::OffloadBundlingJobClass:
314   case Action::OffloadUnbundlingJobClass:
315     return getOffloadBundler();
316   }
317 
318   llvm_unreachable("Invalid tool kind.");
319 }
320 
321 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
322                                              const ArgList &Args) {
323   const llvm::Triple &Triple = TC.getTriple();
324   bool IsWindows = Triple.isOSWindows();
325 
326   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
327     return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
328                ? "armhf"
329                : "arm";
330 
331   // For historic reasons, Android library is using i686 instead of i386.
332   if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
333     return "i686";
334 
335   return llvm::Triple::getArchTypeName(TC.getArch());
336 }
337 
338 StringRef ToolChain::getOSLibName() const {
339   switch (Triple.getOS()) {
340   case llvm::Triple::FreeBSD:
341     return "freebsd";
342   case llvm::Triple::NetBSD:
343     return "netbsd";
344   case llvm::Triple::OpenBSD:
345     return "openbsd";
346   case llvm::Triple::Solaris:
347     return "sunos";
348   default:
349     return getOS();
350   }
351 }
352 
353 std::string ToolChain::getCompilerRTPath() const {
354   SmallString<128> Path(getDriver().ResourceDir);
355   if (Triple.isOSUnknown()) {
356     llvm::sys::path::append(Path, "lib");
357   } else {
358     llvm::sys::path::append(Path, "lib", getOSLibName());
359   }
360   return Path.str();
361 }
362 
363 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
364                                      bool Shared) const {
365   const llvm::Triple &TT = getTriple();
366   const char *Env = TT.isAndroid() ? "-android" : "";
367   bool IsITANMSVCWindows =
368       TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
369 
370   StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
371   const char *Prefix = IsITANMSVCWindows ? "" : "lib";
372   const char *Suffix = Shared ? (Triple.isOSWindows() ? ".dll" : ".so")
373                               : (IsITANMSVCWindows ? ".lib" : ".a");
374 
375   SmallString<128> Path(getCompilerRTPath());
376   llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
377                                     Arch + Env + Suffix);
378   return Path.str();
379 }
380 
381 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
382                                               StringRef Component,
383                                               bool Shared) const {
384   return Args.MakeArgString(getCompilerRT(Args, Component, Shared));
385 }
386 
387 std::string ToolChain::getArchSpecificLibPath() const {
388   SmallString<128> Path(getDriver().ResourceDir);
389   llvm::sys::path::append(Path, "lib", getOSLibName(),
390                           llvm::Triple::getArchTypeName(getArch()));
391   return Path.str();
392 }
393 
394 bool ToolChain::needsProfileRT(const ArgList &Args) {
395   if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
396                    false) ||
397       Args.hasArg(options::OPT_fprofile_generate) ||
398       Args.hasArg(options::OPT_fprofile_generate_EQ) ||
399       Args.hasArg(options::OPT_fprofile_instr_generate) ||
400       Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
401       Args.hasArg(options::OPT_fcreate_profile) ||
402       Args.hasArg(options::OPT_coverage))
403     return true;
404 
405   return false;
406 }
407 
408 Tool *ToolChain::SelectTool(const JobAction &JA) const {
409   if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
410   Action::ActionClass AC = JA.getKind();
411   if (AC == Action::AssembleJobClass && useIntegratedAs())
412     return getClangAs();
413   return getTool(AC);
414 }
415 
416 std::string ToolChain::GetFilePath(const char *Name) const {
417   return D.GetFilePath(Name, *this);
418 }
419 
420 std::string ToolChain::GetProgramPath(const char *Name) const {
421   return D.GetProgramPath(Name, *this);
422 }
423 
424 std::string ToolChain::GetLinkerPath() const {
425   const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
426   StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
427 
428   if (llvm::sys::path::is_absolute(UseLinker)) {
429     // If we're passed what looks like an absolute path, don't attempt to
430     // second-guess that.
431     if (llvm::sys::fs::can_execute(UseLinker))
432       return UseLinker;
433   } else if (UseLinker.empty() || UseLinker == "ld") {
434     // If we're passed -fuse-ld= with no argument, or with the argument ld,
435     // then use whatever the default system linker is.
436     return GetProgramPath(getDefaultLinker());
437   } else {
438     llvm::SmallString<8> LinkerName;
439     if (Triple.isOSDarwin())
440       LinkerName.append("ld64.");
441     else
442       LinkerName.append("ld.");
443     LinkerName.append(UseLinker);
444 
445     std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
446     if (llvm::sys::fs::can_execute(LinkerPath))
447       return LinkerPath;
448   }
449 
450   if (A)
451     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
452 
453   return GetProgramPath(getDefaultLinker());
454 }
455 
456 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
457   return types::lookupTypeForExtension(Ext);
458 }
459 
460 bool ToolChain::HasNativeLLVMSupport() const {
461   return false;
462 }
463 
464 bool ToolChain::isCrossCompiling() const {
465   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
466   switch (HostTriple.getArch()) {
467   // The A32/T32/T16 instruction sets are not separate architectures in this
468   // context.
469   case llvm::Triple::arm:
470   case llvm::Triple::armeb:
471   case llvm::Triple::thumb:
472   case llvm::Triple::thumbeb:
473     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
474            getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
475   default:
476     return HostTriple.getArch() != getArch();
477   }
478 }
479 
480 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
481   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
482                      VersionTuple());
483 }
484 
485 llvm::ExceptionHandling
486 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
487   if (Triple.isOSWindows() && Triple.getArch() != llvm::Triple::x86)
488     return llvm::ExceptionHandling::WinEH;
489   return llvm::ExceptionHandling::None;
490 }
491 
492 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
493   if (Model == "single") {
494     // FIXME: 'single' is only supported on ARM and WebAssembly so far.
495     return Triple.getArch() == llvm::Triple::arm ||
496            Triple.getArch() == llvm::Triple::armeb ||
497            Triple.getArch() == llvm::Triple::thumb ||
498            Triple.getArch() == llvm::Triple::thumbeb ||
499            Triple.getArch() == llvm::Triple::wasm32 ||
500            Triple.getArch() == llvm::Triple::wasm64;
501   } else if (Model == "posix")
502     return true;
503 
504   return false;
505 }
506 
507 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
508                                          types::ID InputType) const {
509   switch (getTriple().getArch()) {
510   default:
511     return getTripleString();
512 
513   case llvm::Triple::x86_64: {
514     llvm::Triple Triple = getTriple();
515     if (!Triple.isOSBinFormatMachO())
516       return getTripleString();
517 
518     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
519       // x86_64h goes in the triple. Other -march options just use the
520       // vanilla triple we already have.
521       StringRef MArch = A->getValue();
522       if (MArch == "x86_64h")
523         Triple.setArchName(MArch);
524     }
525     return Triple.getTriple();
526   }
527   case llvm::Triple::aarch64: {
528     llvm::Triple Triple = getTriple();
529     if (!Triple.isOSBinFormatMachO())
530       return getTripleString();
531 
532     // FIXME: older versions of ld64 expect the "arm64" component in the actual
533     // triple string and query it to determine whether an LTO file can be
534     // handled. Remove this when we don't care any more.
535     Triple.setArchName("arm64");
536     return Triple.getTriple();
537   }
538   case llvm::Triple::arm:
539   case llvm::Triple::armeb:
540   case llvm::Triple::thumb:
541   case llvm::Triple::thumbeb: {
542     // FIXME: Factor into subclasses.
543     llvm::Triple Triple = getTriple();
544     bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
545                        getTriple().getArch() == llvm::Triple::thumbeb;
546 
547     // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
548     // '-mbig-endian'/'-EB'.
549     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
550                                  options::OPT_mbig_endian)) {
551       IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
552     }
553 
554     // Thumb2 is the default for V7 on Darwin.
555     //
556     // FIXME: Thumb should just be another -target-feaure, not in the triple.
557     StringRef MCPU, MArch;
558     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
559       MCPU = A->getValue();
560     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
561       MArch = A->getValue();
562     std::string CPU =
563         Triple.isOSBinFormatMachO()
564             ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
565             : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
566     StringRef Suffix =
567       tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
568     bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
569     bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
570                                        getTriple().isOSBinFormatMachO());
571     // FIXME: this is invalid for WindowsCE
572     if (getTriple().isOSWindows())
573       ThumbDefault = true;
574     std::string ArchName;
575     if (IsBigEndian)
576       ArchName = "armeb";
577     else
578       ArchName = "arm";
579 
580     // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
581     // M-Class CPUs/architecture variants, which is not supported.
582     bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
583                                           options::OPT_mno_thumb, ThumbDefault);
584     if (IsMProfile && ARMModeRequested) {
585       if (!MCPU.empty())
586         getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
587        else
588         getDriver().Diag(diag::err_arch_unsupported_isa)
589           << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
590     }
591 
592     // Check to see if an explicit choice to use thumb has been made via
593     // -mthumb. For assembler files we must check for -mthumb in the options
594     // passed to the assember via -Wa or -Xassembler.
595     bool IsThumb = false;
596     if (InputType != types::TY_PP_Asm)
597       IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
598                               ThumbDefault);
599     else {
600       // Ideally we would check for these flags in
601       // CollectArgsForIntegratedAssembler but we can't change the ArchName at
602       // that point. There is no assembler equivalent of -mno-thumb, -marm, or
603       // -mno-arm.
604       for (const auto *A :
605            Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
606         for (StringRef Value : A->getValues()) {
607           if (Value == "-mthumb")
608             IsThumb = true;
609         }
610       }
611     }
612     // Assembly files should start in ARM mode, unless arch is M-profile, or
613     // -mthumb has been passed explicitly to the assembler. Windows is always
614     // thumb.
615     if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
616       if (IsBigEndian)
617         ArchName = "thumbeb";
618       else
619         ArchName = "thumb";
620     }
621     Triple.setArchName(ArchName + Suffix.str());
622 
623     return Triple.getTriple();
624   }
625   }
626 }
627 
628 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
629                                                    types::ID InputType) const {
630   return ComputeLLVMTriple(Args, InputType);
631 }
632 
633 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
634                                           ArgStringList &CC1Args) const {
635   // Each toolchain should provide the appropriate include flags.
636 }
637 
638 void ToolChain::addClangTargetOptions(
639     const ArgList &DriverArgs, ArgStringList &CC1Args,
640     Action::OffloadKind DeviceOffloadKind) const {}
641 
642 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
643 
644 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
645                                  llvm::opt::ArgStringList &CmdArgs) const {
646   if (!needsProfileRT(Args)) return;
647 
648   CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
649 }
650 
651 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
652     const ArgList &Args) const {
653   const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
654   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
655 
656   // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
657   if (LibName == "compiler-rt")
658     return ToolChain::RLT_CompilerRT;
659   else if (LibName == "libgcc")
660     return ToolChain::RLT_Libgcc;
661   else if (LibName == "platform")
662     return GetDefaultRuntimeLibType();
663 
664   if (A)
665     getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
666 
667   return GetDefaultRuntimeLibType();
668 }
669 
670 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
671   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
672   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
673 
674   // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
675   if (LibName == "libc++")
676     return ToolChain::CST_Libcxx;
677   else if (LibName == "libstdc++")
678     return ToolChain::CST_Libstdcxx;
679   else if (LibName == "platform")
680     return GetDefaultCXXStdlibType();
681 
682   if (A)
683     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
684 
685   return GetDefaultCXXStdlibType();
686 }
687 
688 /// Utility function to add a system include directory to CC1 arguments.
689 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
690                                             ArgStringList &CC1Args,
691                                             const Twine &Path) {
692   CC1Args.push_back("-internal-isystem");
693   CC1Args.push_back(DriverArgs.MakeArgString(Path));
694 }
695 
696 /// Utility function to add a system include directory with extern "C"
697 /// semantics to CC1 arguments.
698 ///
699 /// Note that this should be used rarely, and only for directories that
700 /// historically and for legacy reasons are treated as having implicit extern
701 /// "C" semantics. These semantics are *ignored* by and large today, but its
702 /// important to preserve the preprocessor changes resulting from the
703 /// classification.
704 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
705                                                    ArgStringList &CC1Args,
706                                                    const Twine &Path) {
707   CC1Args.push_back("-internal-externc-isystem");
708   CC1Args.push_back(DriverArgs.MakeArgString(Path));
709 }
710 
711 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
712                                                 ArgStringList &CC1Args,
713                                                 const Twine &Path) {
714   if (llvm::sys::fs::exists(Path))
715     addExternCSystemInclude(DriverArgs, CC1Args, Path);
716 }
717 
718 /// Utility function to add a list of system include directories to CC1.
719 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
720                                              ArgStringList &CC1Args,
721                                              ArrayRef<StringRef> Paths) {
722   for (const auto Path : Paths) {
723     CC1Args.push_back("-internal-isystem");
724     CC1Args.push_back(DriverArgs.MakeArgString(Path));
725   }
726 }
727 
728 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
729                                              ArgStringList &CC1Args) const {
730   // Header search paths should be handled by each of the subclasses.
731   // Historically, they have not been, and instead have been handled inside of
732   // the CC1-layer frontend. As the logic is hoisted out, this generic function
733   // will slowly stop being called.
734   //
735   // While it is being called, replicate a bit of a hack to propagate the
736   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
737   // header search paths with it. Once all systems are overriding this
738   // function, the CC1 flag and this line can be removed.
739   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
740 }
741 
742 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
743   return getDriver().CCCIsCXX() &&
744          !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
745                       options::OPT_nostdlibxx);
746 }
747 
748 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
749                                     ArgStringList &CmdArgs) const {
750   assert(!Args.hasArg(options::OPT_nostdlibxx) &&
751          "should not have called this");
752   CXXStdlibType Type = GetCXXStdlibType(Args);
753 
754   switch (Type) {
755   case ToolChain::CST_Libcxx:
756     CmdArgs.push_back("-lc++");
757     break;
758 
759   case ToolChain::CST_Libstdcxx:
760     CmdArgs.push_back("-lstdc++");
761     break;
762   }
763 }
764 
765 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
766                                    ArgStringList &CmdArgs) const {
767   for (const auto &LibPath : getFilePaths())
768     if(LibPath.length() > 0)
769       CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
770 }
771 
772 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
773                                  ArgStringList &CmdArgs) const {
774   CmdArgs.push_back("-lcc_kext");
775 }
776 
777 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
778                                               ArgStringList &CmdArgs) const {
779   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
780   // (to keep the linker options consistent with gcc and clang itself).
781   if (!isOptimizationLevelFast(Args)) {
782     // Check if -ffast-math or -funsafe-math.
783     Arg *A =
784         Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
785                         options::OPT_funsafe_math_optimizations,
786                         options::OPT_fno_unsafe_math_optimizations);
787 
788     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
789         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
790       return false;
791   }
792   // If crtfastmath.o exists add it to the arguments.
793   std::string Path = GetFilePath("crtfastmath.o");
794   if (Path == "crtfastmath.o") // Not found.
795     return false;
796 
797   CmdArgs.push_back(Args.MakeArgString(Path));
798   return true;
799 }
800 
801 SanitizerMask ToolChain::getSupportedSanitizers() const {
802   // Return sanitizers which don't require runtime support and are not
803   // platform dependent.
804 
805   using namespace SanitizerKind;
806 
807   SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
808                       CFICastStrict | UnsignedIntegerOverflow | Nullability |
809                       LocalBounds;
810   if (getTriple().getArch() == llvm::Triple::x86 ||
811       getTriple().getArch() == llvm::Triple::x86_64 ||
812       getTriple().getArch() == llvm::Triple::arm ||
813       getTriple().getArch() == llvm::Triple::aarch64 ||
814       getTriple().getArch() == llvm::Triple::wasm32 ||
815       getTriple().getArch() == llvm::Triple::wasm64)
816     Res |= CFIICall;
817   if (getTriple().getArch() == llvm::Triple::x86_64 ||
818       getTriple().getArch() == llvm::Triple::aarch64)
819     Res |= ShadowCallStack;
820   return Res;
821 }
822 
823 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
824                                    ArgStringList &CC1Args) const {}
825 
826 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
827                                     ArgStringList &CC1Args) const {}
828 
829 static VersionTuple separateMSVCFullVersion(unsigned Version) {
830   if (Version < 100)
831     return VersionTuple(Version);
832 
833   if (Version < 10000)
834     return VersionTuple(Version / 100, Version % 100);
835 
836   unsigned Build = 0, Factor = 1;
837   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
838     Build = Build + (Version % 10) * Factor;
839   return VersionTuple(Version / 100, Version % 100, Build);
840 }
841 
842 VersionTuple
843 ToolChain::computeMSVCVersion(const Driver *D,
844                               const llvm::opt::ArgList &Args) const {
845   const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
846   const Arg *MSCompatibilityVersion =
847       Args.getLastArg(options::OPT_fms_compatibility_version);
848 
849   if (MSCVersion && MSCompatibilityVersion) {
850     if (D)
851       D->Diag(diag::err_drv_argument_not_allowed_with)
852           << MSCVersion->getAsString(Args)
853           << MSCompatibilityVersion->getAsString(Args);
854     return VersionTuple();
855   }
856 
857   if (MSCompatibilityVersion) {
858     VersionTuple MSVT;
859     if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
860       if (D)
861         D->Diag(diag::err_drv_invalid_value)
862             << MSCompatibilityVersion->getAsString(Args)
863             << MSCompatibilityVersion->getValue();
864     } else {
865       return MSVT;
866     }
867   }
868 
869   if (MSCVersion) {
870     unsigned Version = 0;
871     if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
872       if (D)
873         D->Diag(diag::err_drv_invalid_value)
874             << MSCVersion->getAsString(Args) << MSCVersion->getValue();
875     } else {
876       return separateMSVCFullVersion(Version);
877     }
878   }
879 
880   return VersionTuple();
881 }
882 
883 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
884     const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
885     SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
886   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
887   const OptTable &Opts = getDriver().getOpts();
888   bool Modified = false;
889 
890   // Handle -Xopenmp-target flags
891   for (auto *A : Args) {
892     // Exclude flags which may only apply to the host toolchain.
893     // Do not exclude flags when the host triple (AuxTriple)
894     // matches the current toolchain triple. If it is not present
895     // at all, target and host share a toolchain.
896     if (A->getOption().matches(options::OPT_m_Group)) {
897       if (SameTripleAsHost)
898         DAL->append(A);
899       else
900         Modified = true;
901       continue;
902     }
903 
904     unsigned Index;
905     unsigned Prev;
906     bool XOpenMPTargetNoTriple =
907         A->getOption().matches(options::OPT_Xopenmp_target);
908 
909     if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
910       // Passing device args: -Xopenmp-target=<triple> -opt=val.
911       if (A->getValue(0) == getTripleString())
912         Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
913       else
914         continue;
915     } else if (XOpenMPTargetNoTriple) {
916       // Passing device args: -Xopenmp-target -opt=val.
917       Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
918     } else {
919       DAL->append(A);
920       continue;
921     }
922 
923     // Parse the argument to -Xopenmp-target.
924     Prev = Index;
925     std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
926     if (!XOpenMPTargetArg || Index > Prev + 1) {
927       getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
928           << A->getAsString(Args);
929       continue;
930     }
931     if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
932         Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
933       getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
934       continue;
935     }
936     XOpenMPTargetArg->setBaseArg(A);
937     A = XOpenMPTargetArg.release();
938     AllocatedArgs.push_back(A);
939     DAL->append(A);
940     Modified = true;
941   }
942 
943   if (Modified)
944     return DAL;
945 
946   delete DAL;
947   return nullptr;
948 }
949