ToolChain.cpp 32 KB

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