ToolChain.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. //===- ToolChain.cpp - Collections of tools for one platform --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Driver/ToolChain.h"
  9. #include "InputInfo.h"
  10. #include "ToolChains/Arch/ARM.h"
  11. #include "ToolChains/Clang.h"
  12. #include "ToolChains/InterfaceStubs.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. if (D.CCCIsCXX()) {
  72. if (auto CXXStdlibPath = getCXXStdlibPath())
  73. getFilePaths().push_back(*CXXStdlibPath);
  74. }
  75. if (auto RuntimePath = getRuntimePath())
  76. getLibraryPaths().push_back(*RuntimePath);
  77. std::string CandidateLibPath = getArchSpecificLibPath();
  78. if (getVFS().exists(CandidateLibPath))
  79. getFilePaths().push_back(CandidateLibPath);
  80. }
  81. void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
  82. Triple.setEnvironment(Env);
  83. if (EffectiveTriple != llvm::Triple())
  84. EffectiveTriple.setEnvironment(Env);
  85. }
  86. ToolChain::~ToolChain() = default;
  87. llvm::vfs::FileSystem &ToolChain::getVFS() const {
  88. return getDriver().getVFS();
  89. }
  90. bool ToolChain::useIntegratedAs() const {
  91. return Args.hasFlag(options::OPT_fintegrated_as,
  92. options::OPT_fno_integrated_as,
  93. IsIntegratedAssemblerDefault());
  94. }
  95. bool ToolChain::useRelaxRelocations() const {
  96. return ENABLE_X86_RELAX_RELOCATIONS;
  97. }
  98. bool ToolChain::isNoExecStackDefault() const {
  99. return false;
  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::getIfsMerge() const {
  245. if (!IfsMerge)
  246. IfsMerge.reset(new tools::ifstool::Merger(*this));
  247. return IfsMerge.get();
  248. }
  249. Tool *ToolChain::getOffloadBundler() const {
  250. if (!OffloadBundler)
  251. OffloadBundler.reset(new tools::OffloadBundler(*this));
  252. return OffloadBundler.get();
  253. }
  254. Tool *ToolChain::getTool(Action::ActionClass AC) const {
  255. switch (AC) {
  256. case Action::AssembleJobClass:
  257. return getAssemble();
  258. case Action::IfsMergeJobClass:
  259. return getIfsMerge();
  260. case Action::LinkJobClass:
  261. return getLink();
  262. case Action::InputClass:
  263. case Action::BindArchClass:
  264. case Action::OffloadClass:
  265. case Action::LipoJobClass:
  266. case Action::DsymutilJobClass:
  267. case Action::VerifyDebugInfoJobClass:
  268. llvm_unreachable("Invalid tool kind.");
  269. case Action::CompileJobClass:
  270. case Action::PrecompileJobClass:
  271. case Action::HeaderModulePrecompileJobClass:
  272. case Action::PreprocessJobClass:
  273. case Action::AnalyzeJobClass:
  274. case Action::MigrateJobClass:
  275. case Action::VerifyPCHJobClass:
  276. case Action::BackendJobClass:
  277. return getClang();
  278. case Action::OffloadBundlingJobClass:
  279. case Action::OffloadUnbundlingJobClass:
  280. return getOffloadBundler();
  281. }
  282. llvm_unreachable("Invalid tool kind.");
  283. }
  284. static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
  285. const ArgList &Args) {
  286. const llvm::Triple &Triple = TC.getTriple();
  287. bool IsWindows = Triple.isOSWindows();
  288. if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
  289. return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
  290. ? "armhf"
  291. : "arm";
  292. // For historic reasons, Android library is using i686 instead of i386.
  293. if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
  294. return "i686";
  295. return llvm::Triple::getArchTypeName(TC.getArch());
  296. }
  297. StringRef ToolChain::getOSLibName() const {
  298. switch (Triple.getOS()) {
  299. case llvm::Triple::FreeBSD:
  300. return "freebsd";
  301. case llvm::Triple::NetBSD:
  302. return "netbsd";
  303. case llvm::Triple::OpenBSD:
  304. return "openbsd";
  305. case llvm::Triple::Solaris:
  306. return "sunos";
  307. default:
  308. return getOS();
  309. }
  310. }
  311. std::string ToolChain::getCompilerRTPath() const {
  312. SmallString<128> Path(getDriver().ResourceDir);
  313. if (Triple.isOSUnknown()) {
  314. llvm::sys::path::append(Path, "lib");
  315. } else {
  316. llvm::sys::path::append(Path, "lib", getOSLibName());
  317. }
  318. return Path.str();
  319. }
  320. std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
  321. FileType Type) const {
  322. const llvm::Triple &TT = getTriple();
  323. bool IsITANMSVCWindows =
  324. TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
  325. const char *Prefix =
  326. IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
  327. const char *Suffix;
  328. switch (Type) {
  329. case ToolChain::FT_Object:
  330. Suffix = IsITANMSVCWindows ? ".obj" : ".o";
  331. break;
  332. case ToolChain::FT_Static:
  333. Suffix = IsITANMSVCWindows ? ".lib" : ".a";
  334. break;
  335. case ToolChain::FT_Shared:
  336. Suffix = Triple.isOSWindows()
  337. ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
  338. : ".so";
  339. break;
  340. }
  341. for (const auto &LibPath : getLibraryPaths()) {
  342. SmallString<128> P(LibPath);
  343. llvm::sys::path::append(P, Prefix + Twine("clang_rt.") + Component + Suffix);
  344. if (getVFS().exists(P))
  345. return P.str();
  346. }
  347. StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
  348. const char *Env = TT.isAndroid() ? "-android" : "";
  349. SmallString<128> Path(getCompilerRTPath());
  350. llvm::sys::path::append(Path, Prefix + Twine("clang_rt.") + Component + "-" +
  351. Arch + Env + Suffix);
  352. return Path.str();
  353. }
  354. const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
  355. StringRef Component,
  356. FileType Type) const {
  357. return Args.MakeArgString(getCompilerRT(Args, Component, Type));
  358. }
  359. Optional<std::string> ToolChain::getRuntimePath() const {
  360. SmallString<128> P;
  361. // First try the triple passed to driver as --target=<triple>.
  362. P.assign(D.ResourceDir);
  363. llvm::sys::path::append(P, "lib", D.getTargetTriple());
  364. if (getVFS().exists(P))
  365. return llvm::Optional<std::string>(P.str());
  366. // Second try the normalized triple.
  367. P.assign(D.ResourceDir);
  368. llvm::sys::path::append(P, "lib", Triple.str());
  369. if (getVFS().exists(P))
  370. return llvm::Optional<std::string>(P.str());
  371. return None;
  372. }
  373. Optional<std::string> ToolChain::getCXXStdlibPath() const {
  374. SmallString<128> P;
  375. // First try the triple passed to driver as --target=<triple>.
  376. P.assign(D.Dir);
  377. llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
  378. if (getVFS().exists(P))
  379. return llvm::Optional<std::string>(P.str());
  380. // Second try the normalized triple.
  381. P.assign(D.Dir);
  382. llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
  383. if (getVFS().exists(P))
  384. return llvm::Optional<std::string>(P.str());
  385. return None;
  386. }
  387. std::string ToolChain::getArchSpecificLibPath() const {
  388. SmallString<128> Path(getDriver().ResourceDir);
  389. llvm::sys::path::append(Path, "lib", getOSLibName(),
  390. llvm::Triple::getArchTypeName(getArch()));
  391. return Path.str();
  392. }
  393. bool ToolChain::needsProfileRT(const ArgList &Args) {
  394. if (Args.hasArg(options::OPT_noprofilelib))
  395. return false;
  396. if (needsGCovInstrumentation(Args) ||
  397. Args.hasArg(options::OPT_fprofile_generate) ||
  398. Args.hasArg(options::OPT_fprofile_generate_EQ) ||
  399. Args.hasArg(options::OPT_fcs_profile_generate) ||
  400. Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
  401. Args.hasArg(options::OPT_fprofile_instr_generate) ||
  402. Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
  403. Args.hasArg(options::OPT_fcreate_profile) ||
  404. Args.hasArg(options::OPT_forder_file_instrumentation))
  405. return true;
  406. return false;
  407. }
  408. bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
  409. return Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  410. false) ||
  411. Args.hasArg(options::OPT_coverage);
  412. }
  413. Tool *ToolChain::SelectTool(const JobAction &JA) const {
  414. if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
  415. Action::ActionClass AC = JA.getKind();
  416. if (AC == Action::AssembleJobClass && useIntegratedAs())
  417. return getClangAs();
  418. return getTool(AC);
  419. }
  420. std::string ToolChain::GetFilePath(const char *Name) const {
  421. return D.GetFilePath(Name, *this);
  422. }
  423. std::string ToolChain::GetProgramPath(const char *Name) const {
  424. return D.GetProgramPath(Name, *this);
  425. }
  426. std::string ToolChain::GetLinkerPath() const {
  427. const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
  428. StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
  429. if (llvm::sys::path::is_absolute(UseLinker)) {
  430. // If we're passed what looks like an absolute path, don't attempt to
  431. // second-guess that.
  432. if (llvm::sys::fs::can_execute(UseLinker))
  433. return UseLinker;
  434. } else if (UseLinker.empty() || UseLinker == "ld") {
  435. // If we're passed -fuse-ld= with no argument, or with the argument ld,
  436. // then use whatever the default system linker is.
  437. return GetProgramPath(getDefaultLinker());
  438. } else {
  439. llvm::SmallString<8> LinkerName;
  440. if (Triple.isOSDarwin())
  441. LinkerName.append("ld64.");
  442. else
  443. LinkerName.append("ld.");
  444. LinkerName.append(UseLinker);
  445. std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
  446. if (llvm::sys::fs::can_execute(LinkerPath))
  447. return LinkerPath;
  448. }
  449. if (A)
  450. getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
  451. return GetProgramPath(getDefaultLinker());
  452. }
  453. types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
  454. return types::lookupTypeForExtension(Ext);
  455. }
  456. bool ToolChain::HasNativeLLVMSupport() const {
  457. return false;
  458. }
  459. bool ToolChain::isCrossCompiling() const {
  460. llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
  461. switch (HostTriple.getArch()) {
  462. // The A32/T32/T16 instruction sets are not separate architectures in this
  463. // context.
  464. case llvm::Triple::arm:
  465. case llvm::Triple::armeb:
  466. case llvm::Triple::thumb:
  467. case llvm::Triple::thumbeb:
  468. return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
  469. getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
  470. default:
  471. return HostTriple.getArch() != getArch();
  472. }
  473. }
  474. ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
  475. return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
  476. VersionTuple());
  477. }
  478. llvm::ExceptionHandling
  479. ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
  480. return llvm::ExceptionHandling::None;
  481. }
  482. bool ToolChain::isThreadModelSupported(const StringRef Model) const {
  483. if (Model == "single") {
  484. // FIXME: 'single' is only supported on ARM and WebAssembly so far.
  485. return Triple.getArch() == llvm::Triple::arm ||
  486. Triple.getArch() == llvm::Triple::armeb ||
  487. Triple.getArch() == llvm::Triple::thumb ||
  488. Triple.getArch() == llvm::Triple::thumbeb ||
  489. Triple.getArch() == llvm::Triple::wasm32 ||
  490. Triple.getArch() == llvm::Triple::wasm64;
  491. } else if (Model == "posix")
  492. return true;
  493. return false;
  494. }
  495. std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
  496. types::ID InputType) const {
  497. switch (getTriple().getArch()) {
  498. default:
  499. return getTripleString();
  500. case llvm::Triple::x86_64: {
  501. llvm::Triple Triple = getTriple();
  502. if (!Triple.isOSBinFormatMachO())
  503. return getTripleString();
  504. if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  505. // x86_64h goes in the triple. Other -march options just use the
  506. // vanilla triple we already have.
  507. StringRef MArch = A->getValue();
  508. if (MArch == "x86_64h")
  509. Triple.setArchName(MArch);
  510. }
  511. return Triple.getTriple();
  512. }
  513. case llvm::Triple::aarch64: {
  514. llvm::Triple Triple = getTriple();
  515. if (!Triple.isOSBinFormatMachO())
  516. return getTripleString();
  517. // FIXME: older versions of ld64 expect the "arm64" component in the actual
  518. // triple string and query it to determine whether an LTO file can be
  519. // handled. Remove this when we don't care any more.
  520. Triple.setArchName("arm64");
  521. return Triple.getTriple();
  522. }
  523. case llvm::Triple::arm:
  524. case llvm::Triple::armeb:
  525. case llvm::Triple::thumb:
  526. case llvm::Triple::thumbeb: {
  527. // FIXME: Factor into subclasses.
  528. llvm::Triple Triple = getTriple();
  529. bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
  530. getTriple().getArch() == llvm::Triple::thumbeb;
  531. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  532. // '-mbig-endian'/'-EB'.
  533. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  534. options::OPT_mbig_endian)) {
  535. IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
  536. }
  537. // Thumb2 is the default for V7 on Darwin.
  538. //
  539. // FIXME: Thumb should just be another -target-feaure, not in the triple.
  540. StringRef MCPU, MArch;
  541. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  542. MCPU = A->getValue();
  543. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  544. MArch = A->getValue();
  545. std::string CPU =
  546. Triple.isOSBinFormatMachO()
  547. ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
  548. : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
  549. StringRef Suffix =
  550. tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  551. bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
  552. bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
  553. getTriple().isOSBinFormatMachO());
  554. // FIXME: this is invalid for WindowsCE
  555. if (getTriple().isOSWindows())
  556. ThumbDefault = true;
  557. std::string ArchName;
  558. if (IsBigEndian)
  559. ArchName = "armeb";
  560. else
  561. ArchName = "arm";
  562. // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
  563. // M-Class CPUs/architecture variants, which is not supported.
  564. bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
  565. options::OPT_mno_thumb, ThumbDefault);
  566. if (IsMProfile && ARMModeRequested) {
  567. if (!MCPU.empty())
  568. getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
  569. else
  570. getDriver().Diag(diag::err_arch_unsupported_isa)
  571. << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
  572. }
  573. // Check to see if an explicit choice to use thumb has been made via
  574. // -mthumb. For assembler files we must check for -mthumb in the options
  575. // passed to the assembler via -Wa or -Xassembler.
  576. bool IsThumb = false;
  577. if (InputType != types::TY_PP_Asm)
  578. IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
  579. ThumbDefault);
  580. else {
  581. // Ideally we would check for these flags in
  582. // CollectArgsForIntegratedAssembler but we can't change the ArchName at
  583. // that point. There is no assembler equivalent of -mno-thumb, -marm, or
  584. // -mno-arm.
  585. for (const auto *A :
  586. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  587. for (StringRef Value : A->getValues()) {
  588. if (Value == "-mthumb")
  589. IsThumb = true;
  590. }
  591. }
  592. }
  593. // Assembly files should start in ARM mode, unless arch is M-profile, or
  594. // -mthumb has been passed explicitly to the assembler. Windows is always
  595. // thumb.
  596. if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
  597. if (IsBigEndian)
  598. ArchName = "thumbeb";
  599. else
  600. ArchName = "thumb";
  601. }
  602. Triple.setArchName(ArchName + Suffix.str());
  603. return Triple.getTriple();
  604. }
  605. }
  606. }
  607. std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
  608. types::ID InputType) const {
  609. return ComputeLLVMTriple(Args, InputType);
  610. }
  611. void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
  612. ArgStringList &CC1Args) const {
  613. // Each toolchain should provide the appropriate include flags.
  614. }
  615. void ToolChain::addClangTargetOptions(
  616. const ArgList &DriverArgs, ArgStringList &CC1Args,
  617. Action::OffloadKind DeviceOffloadKind) const {}
  618. void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
  619. void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
  620. llvm::opt::ArgStringList &CmdArgs) const {
  621. if (!needsProfileRT(Args)) return;
  622. CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
  623. }
  624. ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
  625. const ArgList &Args) const {
  626. const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
  627. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
  628. // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
  629. if (LibName == "compiler-rt")
  630. return ToolChain::RLT_CompilerRT;
  631. else if (LibName == "libgcc")
  632. return ToolChain::RLT_Libgcc;
  633. else if (LibName == "platform")
  634. return GetDefaultRuntimeLibType();
  635. if (A)
  636. getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
  637. return GetDefaultRuntimeLibType();
  638. }
  639. ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
  640. const ArgList &Args) const {
  641. const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
  642. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
  643. if (LibName == "none")
  644. return ToolChain::UNW_None;
  645. else if (LibName == "platform" || LibName == "") {
  646. ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
  647. if (RtLibType == ToolChain::RLT_CompilerRT)
  648. return ToolChain::UNW_None;
  649. else if (RtLibType == ToolChain::RLT_Libgcc)
  650. return ToolChain::UNW_Libgcc;
  651. } else if (LibName == "libunwind") {
  652. if (GetRuntimeLibType(Args) == RLT_Libgcc)
  653. getDriver().Diag(diag::err_drv_incompatible_unwindlib);
  654. return ToolChain::UNW_CompilerRT;
  655. } else if (LibName == "libgcc")
  656. return ToolChain::UNW_Libgcc;
  657. if (A)
  658. getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
  659. << A->getAsString(Args);
  660. return GetDefaultUnwindLibType();
  661. }
  662. ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
  663. const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
  664. StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
  665. // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
  666. if (LibName == "libc++")
  667. return ToolChain::CST_Libcxx;
  668. else if (LibName == "libstdc++")
  669. return ToolChain::CST_Libstdcxx;
  670. else if (LibName == "platform")
  671. return GetDefaultCXXStdlibType();
  672. if (A)
  673. getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
  674. return GetDefaultCXXStdlibType();
  675. }
  676. /// Utility function to add a system include directory to CC1 arguments.
  677. /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
  678. ArgStringList &CC1Args,
  679. const Twine &Path) {
  680. CC1Args.push_back("-internal-isystem");
  681. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  682. }
  683. /// Utility function to add a system include directory with extern "C"
  684. /// semantics to CC1 arguments.
  685. ///
  686. /// Note that this should be used rarely, and only for directories that
  687. /// historically and for legacy reasons are treated as having implicit extern
  688. /// "C" semantics. These semantics are *ignored* by and large today, but its
  689. /// important to preserve the preprocessor changes resulting from the
  690. /// classification.
  691. /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
  692. ArgStringList &CC1Args,
  693. const Twine &Path) {
  694. CC1Args.push_back("-internal-externc-isystem");
  695. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  696. }
  697. void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
  698. ArgStringList &CC1Args,
  699. const Twine &Path) {
  700. if (llvm::sys::fs::exists(Path))
  701. addExternCSystemInclude(DriverArgs, CC1Args, Path);
  702. }
  703. /// Utility function to add a list of system include directories to CC1.
  704. /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
  705. ArgStringList &CC1Args,
  706. ArrayRef<StringRef> Paths) {
  707. for (const auto Path : Paths) {
  708. CC1Args.push_back("-internal-isystem");
  709. CC1Args.push_back(DriverArgs.MakeArgString(Path));
  710. }
  711. }
  712. void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
  713. ArgStringList &CC1Args) const {
  714. // Header search paths should be handled by each of the subclasses.
  715. // Historically, they have not been, and instead have been handled inside of
  716. // the CC1-layer frontend. As the logic is hoisted out, this generic function
  717. // will slowly stop being called.
  718. //
  719. // While it is being called, replicate a bit of a hack to propagate the
  720. // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
  721. // header search paths with it. Once all systems are overriding this
  722. // function, the CC1 flag and this line can be removed.
  723. DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
  724. }
  725. void ToolChain::AddClangCXXStdlibIsystemArgs(
  726. const llvm::opt::ArgList &DriverArgs,
  727. llvm::opt::ArgStringList &CC1Args) const {
  728. DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
  729. if (!DriverArgs.hasArg(options::OPT_nostdincxx))
  730. for (const auto &P :
  731. DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
  732. addSystemInclude(DriverArgs, CC1Args, P);
  733. }
  734. bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
  735. return getDriver().CCCIsCXX() &&
  736. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
  737. options::OPT_nostdlibxx);
  738. }
  739. void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
  740. ArgStringList &CmdArgs) const {
  741. assert(!Args.hasArg(options::OPT_nostdlibxx) &&
  742. "should not have called this");
  743. CXXStdlibType Type = GetCXXStdlibType(Args);
  744. switch (Type) {
  745. case ToolChain::CST_Libcxx:
  746. CmdArgs.push_back("-lc++");
  747. break;
  748. case ToolChain::CST_Libstdcxx:
  749. CmdArgs.push_back("-lstdc++");
  750. break;
  751. }
  752. }
  753. void ToolChain::AddFilePathLibArgs(const ArgList &Args,
  754. ArgStringList &CmdArgs) const {
  755. for (const auto &LibPath : getFilePaths())
  756. if(LibPath.length() > 0)
  757. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  758. }
  759. void ToolChain::AddCCKextLibArgs(const ArgList &Args,
  760. ArgStringList &CmdArgs) const {
  761. CmdArgs.push_back("-lcc_kext");
  762. }
  763. bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
  764. ArgStringList &CmdArgs) const {
  765. // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
  766. // (to keep the linker options consistent with gcc and clang itself).
  767. if (!isOptimizationLevelFast(Args)) {
  768. // Check if -ffast-math or -funsafe-math.
  769. Arg *A =
  770. Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
  771. options::OPT_funsafe_math_optimizations,
  772. options::OPT_fno_unsafe_math_optimizations);
  773. if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
  774. A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
  775. return false;
  776. }
  777. // If crtfastmath.o exists add it to the arguments.
  778. std::string Path = GetFilePath("crtfastmath.o");
  779. if (Path == "crtfastmath.o") // Not found.
  780. return false;
  781. CmdArgs.push_back(Args.MakeArgString(Path));
  782. return true;
  783. }
  784. SanitizerMask ToolChain::getSupportedSanitizers() const {
  785. // Return sanitizers which don't require runtime support and are not
  786. // platform dependent.
  787. SanitizerMask Res = (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
  788. ~SanitizerKind::Function) |
  789. (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
  790. SanitizerKind::CFICastStrict |
  791. SanitizerKind::FloatDivideByZero |
  792. SanitizerKind::UnsignedIntegerOverflow |
  793. SanitizerKind::ImplicitConversion |
  794. SanitizerKind::Nullability | SanitizerKind::LocalBounds;
  795. if (getTriple().getArch() == llvm::Triple::x86 ||
  796. getTriple().getArch() == llvm::Triple::x86_64 ||
  797. getTriple().getArch() == llvm::Triple::arm ||
  798. getTriple().getArch() == llvm::Triple::aarch64 ||
  799. getTriple().getArch() == llvm::Triple::wasm32 ||
  800. getTriple().getArch() == llvm::Triple::wasm64)
  801. Res |= SanitizerKind::CFIICall;
  802. if (getTriple().getArch() == llvm::Triple::x86_64 ||
  803. getTriple().getArch() == llvm::Triple::aarch64)
  804. Res |= SanitizerKind::ShadowCallStack;
  805. if (getTriple().getArch() == llvm::Triple::aarch64 ||
  806. getTriple().getArch() == llvm::Triple::aarch64_be)
  807. Res |= SanitizerKind::MemTag;
  808. return Res;
  809. }
  810. void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
  811. ArgStringList &CC1Args) const {}
  812. void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
  813. ArgStringList &CC1Args) const {}
  814. static VersionTuple separateMSVCFullVersion(unsigned Version) {
  815. if (Version < 100)
  816. return VersionTuple(Version);
  817. if (Version < 10000)
  818. return VersionTuple(Version / 100, Version % 100);
  819. unsigned Build = 0, Factor = 1;
  820. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  821. Build = Build + (Version % 10) * Factor;
  822. return VersionTuple(Version / 100, Version % 100, Build);
  823. }
  824. VersionTuple
  825. ToolChain::computeMSVCVersion(const Driver *D,
  826. const llvm::opt::ArgList &Args) const {
  827. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  828. const Arg *MSCompatibilityVersion =
  829. Args.getLastArg(options::OPT_fms_compatibility_version);
  830. if (MSCVersion && MSCompatibilityVersion) {
  831. if (D)
  832. D->Diag(diag::err_drv_argument_not_allowed_with)
  833. << MSCVersion->getAsString(Args)
  834. << MSCompatibilityVersion->getAsString(Args);
  835. return VersionTuple();
  836. }
  837. if (MSCompatibilityVersion) {
  838. VersionTuple MSVT;
  839. if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
  840. if (D)
  841. D->Diag(diag::err_drv_invalid_value)
  842. << MSCompatibilityVersion->getAsString(Args)
  843. << MSCompatibilityVersion->getValue();
  844. } else {
  845. return MSVT;
  846. }
  847. }
  848. if (MSCVersion) {
  849. unsigned Version = 0;
  850. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
  851. if (D)
  852. D->Diag(diag::err_drv_invalid_value)
  853. << MSCVersion->getAsString(Args) << MSCVersion->getValue();
  854. } else {
  855. return separateMSVCFullVersion(Version);
  856. }
  857. }
  858. return VersionTuple();
  859. }
  860. llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
  861. const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
  862. SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
  863. DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
  864. const OptTable &Opts = getDriver().getOpts();
  865. bool Modified = false;
  866. // Handle -Xopenmp-target flags
  867. for (auto *A : Args) {
  868. // Exclude flags which may only apply to the host toolchain.
  869. // Do not exclude flags when the host triple (AuxTriple)
  870. // matches the current toolchain triple. If it is not present
  871. // at all, target and host share a toolchain.
  872. if (A->getOption().matches(options::OPT_m_Group)) {
  873. if (SameTripleAsHost)
  874. DAL->append(A);
  875. else
  876. Modified = true;
  877. continue;
  878. }
  879. unsigned Index;
  880. unsigned Prev;
  881. bool XOpenMPTargetNoTriple =
  882. A->getOption().matches(options::OPT_Xopenmp_target);
  883. if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
  884. // Passing device args: -Xopenmp-target=<triple> -opt=val.
  885. if (A->getValue(0) == getTripleString())
  886. Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
  887. else
  888. continue;
  889. } else if (XOpenMPTargetNoTriple) {
  890. // Passing device args: -Xopenmp-target -opt=val.
  891. Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
  892. } else {
  893. DAL->append(A);
  894. continue;
  895. }
  896. // Parse the argument to -Xopenmp-target.
  897. Prev = Index;
  898. std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
  899. if (!XOpenMPTargetArg || Index > Prev + 1) {
  900. getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
  901. << A->getAsString(Args);
  902. continue;
  903. }
  904. if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
  905. Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
  906. getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
  907. continue;
  908. }
  909. XOpenMPTargetArg->setBaseArg(A);
  910. A = XOpenMPTargetArg.release();
  911. AllocatedArgs.push_back(A);
  912. DAL->append(A);
  913. Modified = true;
  914. }
  915. if (Modified)
  916. return DAL;
  917. delete DAL;
  918. return nullptr;
  919. }