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/VersionTuple.h"
17 #include "clang/Basic/VirtualFileSystem.h"
18 #include "clang/Config/config.h"
19 #include "clang/Driver/Action.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/XRayArgs.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Config/llvm-config.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/MC/MCTargetOptions.h"
40 #include "llvm/Support/TargetParser.h"
41 #include "llvm/Support/TargetRegistry.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   if (Triple.isOSWindows() && Triple.getArch() != llvm::Triple::x86)
475     return llvm::ExceptionHandling::WinEH;
476   return llvm::ExceptionHandling::None;
477 }
478 
479 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
480   if (Model == "single") {
481     // FIXME: 'single' is only supported on ARM and WebAssembly so far.
482     return Triple.getArch() == llvm::Triple::arm ||
483            Triple.getArch() == llvm::Triple::armeb ||
484            Triple.getArch() == llvm::Triple::thumb ||
485            Triple.getArch() == llvm::Triple::thumbeb ||
486            Triple.getArch() == llvm::Triple::wasm32 ||
487            Triple.getArch() == llvm::Triple::wasm64;
488   } else if (Model == "posix")
489     return true;
490 
491   return false;
492 }
493 
494 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
495                                          types::ID InputType) const {
496   switch (getTriple().getArch()) {
497   default:
498     return getTripleString();
499 
500   case llvm::Triple::x86_64: {
501     llvm::Triple Triple = getTriple();
502     if (!Triple.isOSBinFormatMachO())
503       return getTripleString();
504 
505     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
506       // x86_64h goes in the triple. Other -march options just use the
507       // vanilla triple we already have.
508       StringRef MArch = A->getValue();
509       if (MArch == "x86_64h")
510         Triple.setArchName(MArch);
511     }
512     return Triple.getTriple();
513   }
514   case llvm::Triple::aarch64: {
515     llvm::Triple Triple = getTriple();
516     if (!Triple.isOSBinFormatMachO())
517       return getTripleString();
518 
519     // FIXME: older versions of ld64 expect the "arm64" component in the actual
520     // triple string and query it to determine whether an LTO file can be
521     // handled. Remove this when we don't care any more.
522     Triple.setArchName("arm64");
523     return Triple.getTriple();
524   }
525   case llvm::Triple::arm:
526   case llvm::Triple::armeb:
527   case llvm::Triple::thumb:
528   case llvm::Triple::thumbeb: {
529     // FIXME: Factor into subclasses.
530     llvm::Triple Triple = getTriple();
531     bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
532                        getTriple().getArch() == llvm::Triple::thumbeb;
533 
534     // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
535     // '-mbig-endian'/'-EB'.
536     if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
537                                  options::OPT_mbig_endian)) {
538       IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
539     }
540 
541     // Thumb2 is the default for V7 on Darwin.
542     //
543     // FIXME: Thumb should just be another -target-feaure, not in the triple.
544     StringRef MCPU, MArch;
545     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
546       MCPU = A->getValue();
547     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
548       MArch = A->getValue();
549     std::string CPU =
550         Triple.isOSBinFormatMachO()
551             ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
552             : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
553     StringRef Suffix =
554       tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
555     bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
556     bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
557                                        getTriple().isOSBinFormatMachO());
558     // FIXME: this is invalid for WindowsCE
559     if (getTriple().isOSWindows())
560       ThumbDefault = true;
561     std::string ArchName;
562     if (IsBigEndian)
563       ArchName = "armeb";
564     else
565       ArchName = "arm";
566 
567     // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
568     // M-Class CPUs/architecture variants, which is not supported.
569     bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
570                                           options::OPT_mno_thumb, ThumbDefault);
571     if (IsMProfile && ARMModeRequested) {
572       if (!MCPU.empty())
573         getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
574        else
575         getDriver().Diag(diag::err_arch_unsupported_isa)
576           << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
577     }
578 
579     // Check to see if an explicit choice to use thumb has been made via
580     // -mthumb. For assembler files we must check for -mthumb in the options
581     // passed to the assember via -Wa or -Xassembler.
582     bool IsThumb = false;
583     if (InputType != types::TY_PP_Asm)
584       IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
585                               ThumbDefault);
586     else {
587       // Ideally we would check for these flags in
588       // CollectArgsForIntegratedAssembler but we can't change the ArchName at
589       // that point. There is no assembler equivalent of -mno-thumb, -marm, or
590       // -mno-arm.
591       for (const auto *A :
592            Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
593         for (StringRef Value : A->getValues()) {
594           if (Value == "-mthumb")
595             IsThumb = true;
596         }
597       }
598     }
599     // Assembly files should start in ARM mode, unless arch is M-profile, or
600     // -mthumb has been passed explicitly to the assembler. Windows is always
601     // thumb.
602     if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
603       if (IsBigEndian)
604         ArchName = "thumbeb";
605       else
606         ArchName = "thumb";
607     }
608     Triple.setArchName(ArchName + Suffix.str());
609 
610     return Triple.getTriple();
611   }
612   }
613 }
614 
615 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
616                                                    types::ID InputType) const {
617   return ComputeLLVMTriple(Args, InputType);
618 }
619 
620 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
621                                           ArgStringList &CC1Args) const {
622   // Each toolchain should provide the appropriate include flags.
623 }
624 
625 void ToolChain::addClangTargetOptions(
626     const ArgList &DriverArgs, ArgStringList &CC1Args,
627     Action::OffloadKind DeviceOffloadKind) const {}
628 
629 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
630 
631 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
632                                  llvm::opt::ArgStringList &CmdArgs) const {
633   if (!needsProfileRT(Args)) return;
634 
635   CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
636 }
637 
638 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
639     const ArgList &Args) const {
640   const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
641   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
642 
643   // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
644   if (LibName == "compiler-rt")
645     return ToolChain::RLT_CompilerRT;
646   else if (LibName == "libgcc")
647     return ToolChain::RLT_Libgcc;
648   else if (LibName == "platform")
649     return GetDefaultRuntimeLibType();
650 
651   if (A)
652     getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
653 
654   return GetDefaultRuntimeLibType();
655 }
656 
657 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
658   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
659   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
660 
661   // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
662   if (LibName == "libc++")
663     return ToolChain::CST_Libcxx;
664   else if (LibName == "libstdc++")
665     return ToolChain::CST_Libstdcxx;
666   else if (LibName == "platform")
667     return GetDefaultCXXStdlibType();
668 
669   if (A)
670     getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
671 
672   return GetDefaultCXXStdlibType();
673 }
674 
675 /// Utility function to add a system include directory to CC1 arguments.
676 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
677                                             ArgStringList &CC1Args,
678                                             const Twine &Path) {
679   CC1Args.push_back("-internal-isystem");
680   CC1Args.push_back(DriverArgs.MakeArgString(Path));
681 }
682 
683 /// Utility function to add a system include directory with extern "C"
684 /// semantics to CC1 arguments.
685 ///
686 /// Note that this should be used rarely, and only for directories that
687 /// historically and for legacy reasons are treated as having implicit extern
688 /// "C" semantics. These semantics are *ignored* by and large today, but its
689 /// important to preserve the preprocessor changes resulting from the
690 /// classification.
691 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
692                                                    ArgStringList &CC1Args,
693                                                    const Twine &Path) {
694   CC1Args.push_back("-internal-externc-isystem");
695   CC1Args.push_back(DriverArgs.MakeArgString(Path));
696 }
697 
698 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
699                                                 ArgStringList &CC1Args,
700                                                 const Twine &Path) {
701   if (llvm::sys::fs::exists(Path))
702     addExternCSystemInclude(DriverArgs, CC1Args, Path);
703 }
704 
705 /// Utility function to add a list of system include directories to CC1.
706 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
707                                              ArgStringList &CC1Args,
708                                              ArrayRef<StringRef> Paths) {
709   for (const auto Path : Paths) {
710     CC1Args.push_back("-internal-isystem");
711     CC1Args.push_back(DriverArgs.MakeArgString(Path));
712   }
713 }
714 
715 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
716                                              ArgStringList &CC1Args) const {
717   // Header search paths should be handled by each of the subclasses.
718   // Historically, they have not been, and instead have been handled inside of
719   // the CC1-layer frontend. As the logic is hoisted out, this generic function
720   // will slowly stop being called.
721   //
722   // While it is being called, replicate a bit of a hack to propagate the
723   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
724   // header search paths with it. Once all systems are overriding this
725   // function, the CC1 flag and this line can be removed.
726   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
727 }
728 
729 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
730   return getDriver().CCCIsCXX() &&
731          !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
732                       options::OPT_nostdlibxx);
733 }
734 
735 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
736                                     ArgStringList &CmdArgs) const {
737   assert(!Args.hasArg(options::OPT_nostdlibxx) &&
738          "should not have called this");
739   CXXStdlibType Type = GetCXXStdlibType(Args);
740 
741   switch (Type) {
742   case ToolChain::CST_Libcxx:
743     CmdArgs.push_back("-lc++");
744     break;
745 
746   case ToolChain::CST_Libstdcxx:
747     CmdArgs.push_back("-lstdc++");
748     break;
749   }
750 }
751 
752 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
753                                    ArgStringList &CmdArgs) const {
754   for (const auto &LibPath : getFilePaths())
755     if(LibPath.length() > 0)
756       CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
757 }
758 
759 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
760                                  ArgStringList &CmdArgs) const {
761   CmdArgs.push_back("-lcc_kext");
762 }
763 
764 bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
765                                               ArgStringList &CmdArgs) const {
766   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
767   // (to keep the linker options consistent with gcc and clang itself).
768   if (!isOptimizationLevelFast(Args)) {
769     // Check if -ffast-math or -funsafe-math.
770     Arg *A =
771         Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
772                         options::OPT_funsafe_math_optimizations,
773                         options::OPT_fno_unsafe_math_optimizations);
774 
775     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
776         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
777       return false;
778   }
779   // If crtfastmath.o exists add it to the arguments.
780   std::string Path = GetFilePath("crtfastmath.o");
781   if (Path == "crtfastmath.o") // Not found.
782     return false;
783 
784   CmdArgs.push_back(Args.MakeArgString(Path));
785   return true;
786 }
787 
788 SanitizerMask ToolChain::getSupportedSanitizers() const {
789   // Return sanitizers which don't require runtime support and are not
790   // platform dependent.
791 
792   using namespace SanitizerKind;
793 
794   SanitizerMask Res = (Undefined & ~Vptr & ~Function) | (CFI & ~CFIICall) |
795                       CFICastStrict | UnsignedIntegerOverflow | Nullability |
796                       LocalBounds;
797   if (getTriple().getArch() == llvm::Triple::x86 ||
798       getTriple().getArch() == llvm::Triple::x86_64 ||
799       getTriple().getArch() == llvm::Triple::arm ||
800       getTriple().getArch() == llvm::Triple::aarch64 ||
801       getTriple().getArch() == llvm::Triple::wasm32 ||
802       getTriple().getArch() == llvm::Triple::wasm64)
803     Res |= CFIICall;
804   if (getTriple().getArch() == llvm::Triple::x86_64 ||
805       getTriple().getArch() == llvm::Triple::aarch64)
806     Res |= ShadowCallStack;
807   return Res;
808 }
809 
810 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
811                                    ArgStringList &CC1Args) const {}
812 
813 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
814                                     ArgStringList &CC1Args) const {}
815 
816 static VersionTuple separateMSVCFullVersion(unsigned Version) {
817   if (Version < 100)
818     return VersionTuple(Version);
819 
820   if (Version < 10000)
821     return VersionTuple(Version / 100, Version % 100);
822 
823   unsigned Build = 0, Factor = 1;
824   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
825     Build = Build + (Version % 10) * Factor;
826   return VersionTuple(Version / 100, Version % 100, Build);
827 }
828 
829 VersionTuple
830 ToolChain::computeMSVCVersion(const Driver *D,
831                               const llvm::opt::ArgList &Args) const {
832   const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
833   const Arg *MSCompatibilityVersion =
834       Args.getLastArg(options::OPT_fms_compatibility_version);
835 
836   if (MSCVersion && MSCompatibilityVersion) {
837     if (D)
838       D->Diag(diag::err_drv_argument_not_allowed_with)
839           << MSCVersion->getAsString(Args)
840           << MSCompatibilityVersion->getAsString(Args);
841     return VersionTuple();
842   }
843 
844   if (MSCompatibilityVersion) {
845     VersionTuple MSVT;
846     if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
847       if (D)
848         D->Diag(diag::err_drv_invalid_value)
849             << MSCompatibilityVersion->getAsString(Args)
850             << MSCompatibilityVersion->getValue();
851     } else {
852       return MSVT;
853     }
854   }
855 
856   if (MSCVersion) {
857     unsigned Version = 0;
858     if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
859       if (D)
860         D->Diag(diag::err_drv_invalid_value)
861             << MSCVersion->getAsString(Args) << MSCVersion->getValue();
862     } else {
863       return separateMSVCFullVersion(Version);
864     }
865   }
866 
867   return VersionTuple();
868 }
869 
870 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
871     const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
872     SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
873   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
874   const OptTable &Opts = getDriver().getOpts();
875   bool Modified = false;
876 
877   // Handle -Xopenmp-target flags
878   for (auto *A : Args) {
879     // Exclude flags which may only apply to the host toolchain.
880     // Do not exclude flags when the host triple (AuxTriple)
881     // matches the current toolchain triple. If it is not present
882     // at all, target and host share a toolchain.
883     if (A->getOption().matches(options::OPT_m_Group)) {
884       if (SameTripleAsHost)
885         DAL->append(A);
886       else
887         Modified = true;
888       continue;
889     }
890 
891     unsigned Index;
892     unsigned Prev;
893     bool XOpenMPTargetNoTriple =
894         A->getOption().matches(options::OPT_Xopenmp_target);
895 
896     if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
897       // Passing device args: -Xopenmp-target=<triple> -opt=val.
898       if (A->getValue(0) == getTripleString())
899         Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
900       else
901         continue;
902     } else if (XOpenMPTargetNoTriple) {
903       // Passing device args: -Xopenmp-target -opt=val.
904       Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
905     } else {
906       DAL->append(A);
907       continue;
908     }
909 
910     // Parse the argument to -Xopenmp-target.
911     Prev = Index;
912     std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
913     if (!XOpenMPTargetArg || Index > Prev + 1) {
914       getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
915           << A->getAsString(Args);
916       continue;
917     }
918     if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
919         Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
920       getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
921       continue;
922     }
923     XOpenMPTargetArg->setBaseArg(A);
924     A = XOpenMPTargetArg.release();
925     AllocatedArgs.push_back(A);
926     DAL->append(A);
927     Modified = true;
928   }
929 
930   if (Modified)
931     return DAL;
932 
933   delete DAL;
934   return nullptr;
935 }
936