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