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