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