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