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