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