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