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