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