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