CommonArgs.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
  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 "CommonArgs.h"
  9. #include "Arch/AArch64.h"
  10. #include "Arch/ARM.h"
  11. #include "Arch/Mips.h"
  12. #include "Arch/PPC.h"
  13. #include "Arch/RISCV.h"
  14. #include "Arch/Sparc.h"
  15. #include "Arch/SystemZ.h"
  16. #include "Arch/X86.h"
  17. #include "AMDGPU.h"
  18. #include "MSP430.h"
  19. #include "HIP.h"
  20. #include "Hexagon.h"
  21. #include "InputInfo.h"
  22. #include "clang/Basic/CharInfo.h"
  23. #include "clang/Basic/LangOptions.h"
  24. #include "clang/Basic/ObjCRuntime.h"
  25. #include "clang/Basic/Version.h"
  26. #include "clang/Config/config.h"
  27. #include "clang/Driver/Action.h"
  28. #include "clang/Driver/Compilation.h"
  29. #include "clang/Driver/Driver.h"
  30. #include "clang/Driver/DriverDiagnostic.h"
  31. #include "clang/Driver/Job.h"
  32. #include "clang/Driver/Options.h"
  33. #include "clang/Driver/SanitizerArgs.h"
  34. #include "clang/Driver/ToolChain.h"
  35. #include "clang/Driver/Util.h"
  36. #include "clang/Driver/XRayArgs.h"
  37. #include "llvm/ADT/STLExtras.h"
  38. #include "llvm/ADT/SmallString.h"
  39. #include "llvm/ADT/StringExtras.h"
  40. #include "llvm/ADT/StringSwitch.h"
  41. #include "llvm/ADT/Twine.h"
  42. #include "llvm/Option/Arg.h"
  43. #include "llvm/Option/ArgList.h"
  44. #include "llvm/Option/Option.h"
  45. #include "llvm/Support/CodeGen.h"
  46. #include "llvm/Support/Compression.h"
  47. #include "llvm/Support/Debug.h"
  48. #include "llvm/Support/ErrorHandling.h"
  49. #include "llvm/Support/FileSystem.h"
  50. #include "llvm/Support/Host.h"
  51. #include "llvm/Support/Path.h"
  52. #include "llvm/Support/Process.h"
  53. #include "llvm/Support/Program.h"
  54. #include "llvm/Support/ScopedPrinter.h"
  55. #include "llvm/Support/TargetParser.h"
  56. #include "llvm/Support/VirtualFileSystem.h"
  57. #include "llvm/Support/YAMLParser.h"
  58. using namespace clang::driver;
  59. using namespace clang::driver::tools;
  60. using namespace clang;
  61. using namespace llvm::opt;
  62. void tools::addPathIfExists(const Driver &D, const Twine &Path,
  63. ToolChain::path_list &Paths) {
  64. if (D.getVFS().exists(Path))
  65. Paths.push_back(Path.str());
  66. }
  67. void tools::handleTargetFeaturesGroup(const ArgList &Args,
  68. std::vector<StringRef> &Features,
  69. OptSpecifier Group) {
  70. for (const Arg *A : Args.filtered(Group)) {
  71. StringRef Name = A->getOption().getName();
  72. A->claim();
  73. // Skip over "-m".
  74. assert(Name.startswith("m") && "Invalid feature name.");
  75. Name = Name.substr(1);
  76. bool IsNegative = Name.startswith("no-");
  77. if (IsNegative)
  78. Name = Name.substr(3);
  79. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  80. }
  81. }
  82. void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  83. const char *ArgName, const char *EnvVar) {
  84. const char *DirList = ::getenv(EnvVar);
  85. bool CombinedArg = false;
  86. if (!DirList)
  87. return; // Nothing to do.
  88. StringRef Name(ArgName);
  89. if (Name.equals("-I") || Name.equals("-L"))
  90. CombinedArg = true;
  91. StringRef Dirs(DirList);
  92. if (Dirs.empty()) // Empty string should not add '.'.
  93. return;
  94. StringRef::size_type Delim;
  95. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  96. if (Delim == 0) { // Leading colon.
  97. if (CombinedArg) {
  98. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  99. } else {
  100. CmdArgs.push_back(ArgName);
  101. CmdArgs.push_back(".");
  102. }
  103. } else {
  104. if (CombinedArg) {
  105. CmdArgs.push_back(
  106. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  107. } else {
  108. CmdArgs.push_back(ArgName);
  109. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  110. }
  111. }
  112. Dirs = Dirs.substr(Delim + 1);
  113. }
  114. if (Dirs.empty()) { // Trailing colon.
  115. if (CombinedArg) {
  116. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  117. } else {
  118. CmdArgs.push_back(ArgName);
  119. CmdArgs.push_back(".");
  120. }
  121. } else { // Add the last path.
  122. if (CombinedArg) {
  123. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  124. } else {
  125. CmdArgs.push_back(ArgName);
  126. CmdArgs.push_back(Args.MakeArgString(Dirs));
  127. }
  128. }
  129. }
  130. void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  131. const ArgList &Args, ArgStringList &CmdArgs,
  132. const JobAction &JA) {
  133. const Driver &D = TC.getDriver();
  134. // Add extra linker input arguments which are not treated as inputs
  135. // (constructed via -Xarch_).
  136. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  137. // LIBRARY_PATH are included before user inputs and only supported on native
  138. // toolchains.
  139. if (!TC.isCrossCompiling())
  140. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  141. for (const auto &II : Inputs) {
  142. // If the current tool chain refers to an OpenMP or HIP offloading host, we
  143. // should ignore inputs that refer to OpenMP or HIP offloading devices -
  144. // they will be embedded according to a proper linker script.
  145. if (auto *IA = II.getAction())
  146. if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
  147. IA->isDeviceOffloading(Action::OFK_OpenMP)) ||
  148. (JA.isHostOffloading(Action::OFK_HIP) &&
  149. IA->isDeviceOffloading(Action::OFK_HIP)))
  150. continue;
  151. if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
  152. // Don't try to pass LLVM inputs unless we have native support.
  153. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  154. // Add filenames immediately.
  155. if (II.isFilename()) {
  156. CmdArgs.push_back(II.getFilename());
  157. continue;
  158. }
  159. // Otherwise, this is a linker input argument.
  160. const Arg &A = II.getInputArg();
  161. // Handle reserved library options.
  162. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  163. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  164. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  165. TC.AddCCKextLibArgs(Args, CmdArgs);
  166. else if (A.getOption().matches(options::OPT_z)) {
  167. // Pass -z prefix for gcc linker compatibility.
  168. A.claim();
  169. A.render(Args, CmdArgs);
  170. } else {
  171. A.renderAsInput(Args, CmdArgs);
  172. }
  173. }
  174. }
  175. void tools::AddTargetFeature(const ArgList &Args,
  176. std::vector<StringRef> &Features,
  177. OptSpecifier OnOpt, OptSpecifier OffOpt,
  178. StringRef FeatureName) {
  179. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  180. if (A->getOption().matches(OnOpt))
  181. Features.push_back(Args.MakeArgString("+" + FeatureName));
  182. else
  183. Features.push_back(Args.MakeArgString("-" + FeatureName));
  184. }
  185. }
  186. /// Get the (LLVM) name of the R600 gpu we are targeting.
  187. static std::string getR600TargetGPU(const ArgList &Args) {
  188. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  189. const char *GPUName = A->getValue();
  190. return llvm::StringSwitch<const char *>(GPUName)
  191. .Cases("rv630", "rv635", "r600")
  192. .Cases("rv610", "rv620", "rs780", "rs880")
  193. .Case("rv740", "rv770")
  194. .Case("palm", "cedar")
  195. .Cases("sumo", "sumo2", "sumo")
  196. .Case("hemlock", "cypress")
  197. .Case("aruba", "cayman")
  198. .Default(GPUName);
  199. }
  200. return "";
  201. }
  202. static std::string getLanaiTargetCPU(const ArgList &Args) {
  203. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  204. return A->getValue();
  205. }
  206. return "";
  207. }
  208. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  209. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  210. // If we have -mcpu=, use that.
  211. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  212. StringRef CPU = A->getValue();
  213. #ifdef __wasm__
  214. // Handle "native" by examining the host. "native" isn't meaningful when
  215. // cross compiling, so only support this when the host is also WebAssembly.
  216. if (CPU == "native")
  217. return llvm::sys::getHostCPUName();
  218. #endif
  219. return CPU;
  220. }
  221. return "generic";
  222. }
  223. std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
  224. bool FromAs) {
  225. Arg *A;
  226. switch (T.getArch()) {
  227. default:
  228. return "";
  229. case llvm::Triple::aarch64:
  230. case llvm::Triple::aarch64_be:
  231. return aarch64::getAArch64TargetCPU(Args, T, A);
  232. case llvm::Triple::arm:
  233. case llvm::Triple::armeb:
  234. case llvm::Triple::thumb:
  235. case llvm::Triple::thumbeb: {
  236. StringRef MArch, MCPU;
  237. arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  238. return arm::getARMTargetCPU(MCPU, MArch, T);
  239. }
  240. case llvm::Triple::avr:
  241. if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
  242. return A->getValue();
  243. return "";
  244. case llvm::Triple::mips:
  245. case llvm::Triple::mipsel:
  246. case llvm::Triple::mips64:
  247. case llvm::Triple::mips64el: {
  248. StringRef CPUName;
  249. StringRef ABIName;
  250. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  251. return CPUName;
  252. }
  253. case llvm::Triple::nvptx:
  254. case llvm::Triple::nvptx64:
  255. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  256. return A->getValue();
  257. return "";
  258. case llvm::Triple::ppc:
  259. case llvm::Triple::ppc64:
  260. case llvm::Triple::ppc64le: {
  261. std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
  262. // LLVM may default to generating code for the native CPU,
  263. // but, like gcc, we default to a more generic option for
  264. // each architecture. (except on Darwin)
  265. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  266. if (T.getArch() == llvm::Triple::ppc64)
  267. TargetCPUName = "ppc64";
  268. else if (T.getArch() == llvm::Triple::ppc64le)
  269. TargetCPUName = "ppc64le";
  270. else
  271. TargetCPUName = "ppc";
  272. }
  273. return TargetCPUName;
  274. }
  275. case llvm::Triple::bpfel:
  276. case llvm::Triple::bpfeb:
  277. case llvm::Triple::sparc:
  278. case llvm::Triple::sparcel:
  279. case llvm::Triple::sparcv9:
  280. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  281. return A->getValue();
  282. return "";
  283. case llvm::Triple::x86:
  284. case llvm::Triple::x86_64:
  285. return x86::getX86TargetCPU(Args, T);
  286. case llvm::Triple::hexagon:
  287. return "hexagon" +
  288. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  289. case llvm::Triple::lanai:
  290. return getLanaiTargetCPU(Args);
  291. case llvm::Triple::systemz:
  292. return systemz::getSystemZTargetCPU(Args);
  293. case llvm::Triple::r600:
  294. case llvm::Triple::amdgcn:
  295. return getR600TargetGPU(Args);
  296. case llvm::Triple::wasm32:
  297. case llvm::Triple::wasm64:
  298. return getWebAssemblyTargetCPU(Args);
  299. }
  300. }
  301. unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
  302. unsigned Parallelism = 0;
  303. Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
  304. if (LtoJobsArg &&
  305. StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
  306. D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
  307. << LtoJobsArg->getValue();
  308. return Parallelism;
  309. }
  310. // CloudABI uses -ffunction-sections and -fdata-sections by default.
  311. bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
  312. return Triple.getOS() == llvm::Triple::CloudABI;
  313. }
  314. void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  315. ArgStringList &CmdArgs, const InputInfo &Output,
  316. const InputInfo &Input, bool IsThinLTO) {
  317. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  318. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  319. // forward.
  320. CmdArgs.push_back("-plugin");
  321. #if defined(_WIN32)
  322. const char *Suffix = ".dll";
  323. #elif defined(__APPLE__)
  324. const char *Suffix = ".dylib";
  325. #else
  326. const char *Suffix = ".so";
  327. #endif
  328. SmallString<1024> Plugin;
  329. llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
  330. "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
  331. Suffix,
  332. Plugin);
  333. CmdArgs.push_back(Args.MakeArgString(Plugin));
  334. // Try to pass driver level flags relevant to LTO code generation down to
  335. // the plugin.
  336. // Handle flags for selecting CPU variants.
  337. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  338. if (!CPU.empty())
  339. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  340. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  341. StringRef OOpt;
  342. if (A->getOption().matches(options::OPT_O4) ||
  343. A->getOption().matches(options::OPT_Ofast))
  344. OOpt = "3";
  345. else if (A->getOption().matches(options::OPT_O))
  346. OOpt = A->getValue();
  347. else if (A->getOption().matches(options::OPT_O0))
  348. OOpt = "0";
  349. if (!OOpt.empty())
  350. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  351. }
  352. if (Args.hasArg(options::OPT_gsplit_dwarf)) {
  353. CmdArgs.push_back(
  354. Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
  355. Output.getFilename() + "_dwo"));
  356. }
  357. if (IsThinLTO)
  358. CmdArgs.push_back("-plugin-opt=thinlto");
  359. if (unsigned Parallelism = getLTOParallelism(Args, ToolChain.getDriver()))
  360. CmdArgs.push_back(
  361. Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
  362. // If an explicit debugger tuning argument appeared, pass it along.
  363. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  364. options::OPT_ggdbN_Group)) {
  365. if (A->getOption().matches(options::OPT_glldb))
  366. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  367. else if (A->getOption().matches(options::OPT_gsce))
  368. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  369. else
  370. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  371. }
  372. bool UseSeparateSections =
  373. isUseSeparateSections(ToolChain.getEffectiveTriple());
  374. if (Args.hasFlag(options::OPT_ffunction_sections,
  375. options::OPT_fno_function_sections, UseSeparateSections)) {
  376. CmdArgs.push_back("-plugin-opt=-function-sections");
  377. }
  378. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  379. UseSeparateSections)) {
  380. CmdArgs.push_back("-plugin-opt=-data-sections");
  381. }
  382. if (Arg *A = getLastProfileSampleUseArg(Args)) {
  383. StringRef FName = A->getValue();
  384. if (!llvm::sys::fs::exists(FName))
  385. ToolChain.getDriver().Diag(diag::err_drv_no_such_file) << FName;
  386. else
  387. CmdArgs.push_back(
  388. Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
  389. }
  390. auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
  391. options::OPT_fcs_profile_generate_EQ,
  392. options::OPT_fno_profile_generate);
  393. if (CSPGOGenerateArg &&
  394. CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  395. CSPGOGenerateArg = nullptr;
  396. auto *ProfileUseArg = getLastProfileUseArg(Args);
  397. if (CSPGOGenerateArg) {
  398. CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
  399. if (CSPGOGenerateArg->getOption().matches(
  400. options::OPT_fcs_profile_generate_EQ)) {
  401. SmallString<128> Path(CSPGOGenerateArg->getValue());
  402. llvm::sys::path::append(Path, "default_%m.profraw");
  403. CmdArgs.push_back(
  404. Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
  405. } else
  406. CmdArgs.push_back(
  407. Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
  408. } else if (ProfileUseArg) {
  409. SmallString<128> Path(
  410. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  411. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  412. llvm::sys::path::append(Path, "default.profdata");
  413. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
  414. Path));
  415. }
  416. // Need this flag to turn on new pass manager via Gold plugin.
  417. if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
  418. options::OPT_fno_experimental_new_pass_manager,
  419. /* Default */ ENABLE_EXPERIMENTAL_NEW_PASS_MANAGER)) {
  420. CmdArgs.push_back("-plugin-opt=new-pass-manager");
  421. }
  422. // Setup statistics file output.
  423. SmallString<128> StatsFile =
  424. getStatsFileName(Args, Output, Input, ToolChain.getDriver());
  425. if (!StatsFile.empty())
  426. CmdArgs.push_back(
  427. Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
  428. getTargetFeatures(ToolChain, ToolChain.getTriple(), Args, CmdArgs,
  429. /* ForAS= */ false, /* ForLTOPlugin= */ true);
  430. StringRef ABIName = tools::getTargetABI(Args, ToolChain.getTriple());
  431. if (!ABIName.empty())
  432. CmdArgs.push_back(
  433. Args.MakeArgString(Twine("-plugin-opt=-target-abi=") + ABIName));
  434. }
  435. void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
  436. ArgStringList &CmdArgs) {
  437. if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
  438. options::OPT_fno_rtlib_add_rpath, false))
  439. return;
  440. std::string CandidateRPath = TC.getArchSpecificLibPath();
  441. if (TC.getVFS().exists(CandidateRPath)) {
  442. CmdArgs.push_back("-rpath");
  443. CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
  444. }
  445. }
  446. bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  447. const ArgList &Args, bool ForceStaticHostRuntime,
  448. bool IsOffloadingHost, bool GompNeedsRT) {
  449. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  450. options::OPT_fno_openmp, false))
  451. return false;
  452. Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
  453. if (RTKind == Driver::OMPRT_Unknown)
  454. // Already diagnosed.
  455. return false;
  456. if (ForceStaticHostRuntime)
  457. CmdArgs.push_back("-Bstatic");
  458. switch (RTKind) {
  459. case Driver::OMPRT_OMP:
  460. CmdArgs.push_back("-lomp");
  461. break;
  462. case Driver::OMPRT_GOMP:
  463. CmdArgs.push_back("-lgomp");
  464. break;
  465. case Driver::OMPRT_IOMP5:
  466. CmdArgs.push_back("-liomp5");
  467. break;
  468. case Driver::OMPRT_Unknown:
  469. break;
  470. }
  471. if (ForceStaticHostRuntime)
  472. CmdArgs.push_back("-Bdynamic");
  473. if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
  474. CmdArgs.push_back("-lrt");
  475. if (IsOffloadingHost)
  476. CmdArgs.push_back("-lomptarget");
  477. addArchSpecificRPath(TC, Args, CmdArgs);
  478. return true;
  479. }
  480. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  481. ArgStringList &CmdArgs, StringRef Sanitizer,
  482. bool IsShared, bool IsWhole) {
  483. // Wrap any static runtimes that must be forced into executable in
  484. // whole-archive.
  485. if (IsWhole) CmdArgs.push_back("--whole-archive");
  486. CmdArgs.push_back(TC.getCompilerRTArgString(
  487. Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
  488. if (IsWhole) CmdArgs.push_back("--no-whole-archive");
  489. if (IsShared) {
  490. addArchSpecificRPath(TC, Args, CmdArgs);
  491. }
  492. }
  493. // Tries to use a file with the list of dynamic symbols that need to be exported
  494. // from the runtime library. Returns true if the file was found.
  495. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  496. ArgStringList &CmdArgs,
  497. StringRef Sanitizer) {
  498. // Solaris ld defaults to --export-dynamic behaviour but doesn't support
  499. // the option, so don't try to pass it.
  500. if (TC.getTriple().getOS() == llvm::Triple::Solaris)
  501. return true;
  502. // Myriad is static linking only. Furthermore, some versions of its
  503. // linker have the bug where --export-dynamic overrides -static, so
  504. // don't use --export-dynamic on that platform.
  505. if (TC.getTriple().getVendor() == llvm::Triple::Myriad)
  506. return true;
  507. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  508. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  509. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  510. return true;
  511. }
  512. return false;
  513. }
  514. void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
  515. ArgStringList &CmdArgs) {
  516. // Force linking against the system libraries sanitizers depends on
  517. // (see PR15823 why this is necessary).
  518. CmdArgs.push_back("--no-as-needed");
  519. // There's no libpthread or librt on RTEMS & Android.
  520. if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
  521. !TC.getTriple().isAndroid()) {
  522. CmdArgs.push_back("-lpthread");
  523. if (!TC.getTriple().isOSOpenBSD())
  524. CmdArgs.push_back("-lrt");
  525. }
  526. CmdArgs.push_back("-lm");
  527. // There's no libdl on all OSes.
  528. if (!TC.getTriple().isOSFreeBSD() &&
  529. !TC.getTriple().isOSNetBSD() &&
  530. !TC.getTriple().isOSOpenBSD() &&
  531. TC.getTriple().getOS() != llvm::Triple::RTEMS)
  532. CmdArgs.push_back("-ldl");
  533. // Required for backtrace on some OSes
  534. if (TC.getTriple().isOSFreeBSD() ||
  535. TC.getTriple().isOSNetBSD())
  536. CmdArgs.push_back("-lexecinfo");
  537. }
  538. static void
  539. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  540. SmallVectorImpl<StringRef> &SharedRuntimes,
  541. SmallVectorImpl<StringRef> &StaticRuntimes,
  542. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  543. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  544. SmallVectorImpl<StringRef> &RequiredSymbols) {
  545. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  546. // Collect shared runtimes.
  547. if (SanArgs.needsSharedRt()) {
  548. if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
  549. SharedRuntimes.push_back("asan");
  550. if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
  551. HelperStaticRuntimes.push_back("asan-preinit");
  552. }
  553. if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
  554. if (SanArgs.requiresMinimalRuntime())
  555. SharedRuntimes.push_back("ubsan_minimal");
  556. else
  557. SharedRuntimes.push_back("ubsan_standalone");
  558. }
  559. if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
  560. if (SanArgs.requiresMinimalRuntime())
  561. SharedRuntimes.push_back("scudo_minimal");
  562. else
  563. SharedRuntimes.push_back("scudo");
  564. }
  565. if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes())
  566. SharedRuntimes.push_back("hwasan");
  567. }
  568. // The stats_client library is also statically linked into DSOs.
  569. if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
  570. StaticRuntimes.push_back("stats_client");
  571. // Collect static runtimes.
  572. if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
  573. // Don't link static runtimes into DSOs or if -shared-libasan.
  574. return;
  575. }
  576. if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
  577. StaticRuntimes.push_back("asan");
  578. if (SanArgs.linkCXXRuntimes())
  579. StaticRuntimes.push_back("asan_cxx");
  580. }
  581. if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
  582. StaticRuntimes.push_back("hwasan");
  583. if (SanArgs.linkCXXRuntimes())
  584. StaticRuntimes.push_back("hwasan_cxx");
  585. }
  586. if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
  587. StaticRuntimes.push_back("dfsan");
  588. if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
  589. StaticRuntimes.push_back("lsan");
  590. if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
  591. StaticRuntimes.push_back("msan");
  592. if (SanArgs.linkCXXRuntimes())
  593. StaticRuntimes.push_back("msan_cxx");
  594. }
  595. if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes()) {
  596. StaticRuntimes.push_back("tsan");
  597. if (SanArgs.linkCXXRuntimes())
  598. StaticRuntimes.push_back("tsan_cxx");
  599. }
  600. if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
  601. if (SanArgs.requiresMinimalRuntime()) {
  602. StaticRuntimes.push_back("ubsan_minimal");
  603. } else {
  604. StaticRuntimes.push_back("ubsan_standalone");
  605. if (SanArgs.linkCXXRuntimes())
  606. StaticRuntimes.push_back("ubsan_standalone_cxx");
  607. }
  608. }
  609. if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
  610. NonWholeStaticRuntimes.push_back("safestack");
  611. RequiredSymbols.push_back("__safestack_init");
  612. }
  613. if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
  614. StaticRuntimes.push_back("cfi");
  615. if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
  616. StaticRuntimes.push_back("cfi_diag");
  617. if (SanArgs.linkCXXRuntimes())
  618. StaticRuntimes.push_back("ubsan_standalone_cxx");
  619. }
  620. if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
  621. NonWholeStaticRuntimes.push_back("stats");
  622. RequiredSymbols.push_back("__sanitizer_stats_register");
  623. }
  624. if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
  625. if (SanArgs.requiresMinimalRuntime()) {
  626. StaticRuntimes.push_back("scudo_minimal");
  627. if (SanArgs.linkCXXRuntimes())
  628. StaticRuntimes.push_back("scudo_cxx_minimal");
  629. } else {
  630. StaticRuntimes.push_back("scudo");
  631. if (SanArgs.linkCXXRuntimes())
  632. StaticRuntimes.push_back("scudo_cxx");
  633. }
  634. }
  635. }
  636. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  637. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  638. bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  639. ArgStringList &CmdArgs) {
  640. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  641. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  642. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  643. NonWholeStaticRuntimes, HelperStaticRuntimes,
  644. RequiredSymbols);
  645. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  646. // Inject libfuzzer dependencies.
  647. if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
  648. !Args.hasArg(options::OPT_shared)) {
  649. addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
  650. if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
  651. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  652. }
  653. for (auto RT : SharedRuntimes)
  654. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  655. for (auto RT : HelperStaticRuntimes)
  656. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  657. bool AddExportDynamic = false;
  658. for (auto RT : StaticRuntimes) {
  659. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  660. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  661. }
  662. for (auto RT : NonWholeStaticRuntimes) {
  663. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  664. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  665. }
  666. for (auto S : RequiredSymbols) {
  667. CmdArgs.push_back("-u");
  668. CmdArgs.push_back(Args.MakeArgString(S));
  669. }
  670. // If there is a static runtime with no dynamic list, force all the symbols
  671. // to be dynamic to be sure we export sanitizer interface functions.
  672. if (AddExportDynamic)
  673. CmdArgs.push_back("--export-dynamic");
  674. if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
  675. CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
  676. return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
  677. }
  678. bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
  679. if (Args.hasArg(options::OPT_shared))
  680. return false;
  681. if (TC.getXRayArgs().needsXRayRt()) {
  682. CmdArgs.push_back("-whole-archive");
  683. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
  684. for (const auto &Mode : TC.getXRayArgs().modeList())
  685. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
  686. CmdArgs.push_back("-no-whole-archive");
  687. return true;
  688. }
  689. return false;
  690. }
  691. void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
  692. CmdArgs.push_back("--no-as-needed");
  693. CmdArgs.push_back("-lpthread");
  694. if (!TC.getTriple().isOSOpenBSD())
  695. CmdArgs.push_back("-lrt");
  696. CmdArgs.push_back("-lm");
  697. if (!TC.getTriple().isOSFreeBSD() &&
  698. !TC.getTriple().isOSNetBSD() &&
  699. !TC.getTriple().isOSOpenBSD())
  700. CmdArgs.push_back("-ldl");
  701. }
  702. bool tools::areOptimizationsEnabled(const ArgList &Args) {
  703. // Find the last -O arg and see if it is non-zero.
  704. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  705. return !A->getOption().matches(options::OPT_O0);
  706. // Defaults to -O0.
  707. return false;
  708. }
  709. const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input,
  710. const InputInfo &Output) {
  711. if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
  712. if (StringRef(A->getValue()) == "single")
  713. return Args.MakeArgString(Output.getFilename());
  714. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  715. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  716. SmallString<128> T(FinalOutput->getValue());
  717. llvm::sys::path::replace_extension(T, "dwo");
  718. return Args.MakeArgString(T);
  719. } else {
  720. // Use the compilation dir.
  721. SmallString<128> T(
  722. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  723. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  724. llvm::sys::path::replace_extension(F, "dwo");
  725. T += F;
  726. return Args.MakeArgString(F);
  727. }
  728. }
  729. void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  730. const JobAction &JA, const ArgList &Args,
  731. const InputInfo &Output, const char *OutFile) {
  732. ArgStringList ExtractArgs;
  733. ExtractArgs.push_back("--extract-dwo");
  734. ArgStringList StripArgs;
  735. StripArgs.push_back("--strip-dwo");
  736. // Grabbing the output of the earlier compile step.
  737. StripArgs.push_back(Output.getFilename());
  738. ExtractArgs.push_back(Output.getFilename());
  739. ExtractArgs.push_back(OutFile);
  740. const char *Exec =
  741. Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
  742. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  743. // First extract the dwo sections.
  744. C.addCommand(std::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  745. // Then remove them from the original .o file.
  746. C.addCommand(std::make_unique<Command>(JA, T, Exec, StripArgs, II));
  747. }
  748. // Claim options we don't want to warn if they are unused. We do this for
  749. // options that build systems might add but are unused when assembling or only
  750. // running the preprocessor for example.
  751. void tools::claimNoWarnArgs(const ArgList &Args) {
  752. // Don't warn about unused -f(no-)?lto. This can happen when we're
  753. // preprocessing, precompiling or assembling.
  754. Args.ClaimAllArgs(options::OPT_flto_EQ);
  755. Args.ClaimAllArgs(options::OPT_flto);
  756. Args.ClaimAllArgs(options::OPT_fno_lto);
  757. }
  758. Arg *tools::getLastProfileUseArg(const ArgList &Args) {
  759. auto *ProfileUseArg = Args.getLastArg(
  760. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  761. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  762. options::OPT_fno_profile_instr_use);
  763. if (ProfileUseArg &&
  764. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  765. ProfileUseArg = nullptr;
  766. return ProfileUseArg;
  767. }
  768. Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
  769. auto *ProfileSampleUseArg = Args.getLastArg(
  770. options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
  771. options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
  772. options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
  773. if (ProfileSampleUseArg &&
  774. (ProfileSampleUseArg->getOption().matches(
  775. options::OPT_fno_profile_sample_use) ||
  776. ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
  777. return nullptr;
  778. return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
  779. options::OPT_fauto_profile_EQ);
  780. }
  781. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  782. /// smooshes them together with platform defaults, to decide whether
  783. /// this compile should be using PIC mode or not. Returns a tuple of
  784. /// (RelocationModel, PICLevel, IsPIE).
  785. std::tuple<llvm::Reloc::Model, unsigned, bool>
  786. tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
  787. const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
  788. const llvm::Triple &Triple = ToolChain.getTriple();
  789. bool PIE = ToolChain.isPIEDefault();
  790. bool PIC = PIE || ToolChain.isPICDefault();
  791. // The Darwin/MachO default to use PIC does not apply when using -static.
  792. if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
  793. PIE = PIC = false;
  794. bool IsPICLevelTwo = PIC;
  795. bool KernelOrKext =
  796. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  797. // Android-specific defaults for PIC/PIE
  798. if (Triple.isAndroid()) {
  799. switch (Triple.getArch()) {
  800. case llvm::Triple::arm:
  801. case llvm::Triple::armeb:
  802. case llvm::Triple::thumb:
  803. case llvm::Triple::thumbeb:
  804. case llvm::Triple::aarch64:
  805. case llvm::Triple::mips:
  806. case llvm::Triple::mipsel:
  807. case llvm::Triple::mips64:
  808. case llvm::Triple::mips64el:
  809. PIC = true; // "-fpic"
  810. break;
  811. case llvm::Triple::x86:
  812. case llvm::Triple::x86_64:
  813. PIC = true; // "-fPIC"
  814. IsPICLevelTwo = true;
  815. break;
  816. default:
  817. break;
  818. }
  819. }
  820. // OpenBSD-specific defaults for PIE
  821. if (Triple.isOSOpenBSD()) {
  822. switch (ToolChain.getArch()) {
  823. case llvm::Triple::arm:
  824. case llvm::Triple::aarch64:
  825. case llvm::Triple::mips64:
  826. case llvm::Triple::mips64el:
  827. case llvm::Triple::x86:
  828. case llvm::Triple::x86_64:
  829. IsPICLevelTwo = false; // "-fpie"
  830. break;
  831. case llvm::Triple::ppc:
  832. case llvm::Triple::sparc:
  833. case llvm::Triple::sparcel:
  834. case llvm::Triple::sparcv9:
  835. IsPICLevelTwo = true; // "-fPIE"
  836. break;
  837. default:
  838. break;
  839. }
  840. }
  841. // AMDGPU-specific defaults for PIC.
  842. if (Triple.getArch() == llvm::Triple::amdgcn)
  843. PIC = true;
  844. // The last argument relating to either PIC or PIE wins, and no
  845. // other argument is used. If the last argument is any flavor of the
  846. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  847. // option implicitly enables PIC at the same level.
  848. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  849. options::OPT_fpic, options::OPT_fno_pic,
  850. options::OPT_fPIE, options::OPT_fno_PIE,
  851. options::OPT_fpie, options::OPT_fno_pie);
  852. if (Triple.isOSWindows() && LastPICArg &&
  853. LastPICArg ==
  854. Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
  855. options::OPT_fPIE, options::OPT_fpie)) {
  856. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  857. << LastPICArg->getSpelling() << Triple.str();
  858. if (Triple.getArch() == llvm::Triple::x86_64)
  859. return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
  860. return std::make_tuple(llvm::Reloc::Static, 0U, false);
  861. }
  862. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  863. // is forced, then neither PIC nor PIE flags will have no effect.
  864. if (!ToolChain.isPICDefaultForced()) {
  865. if (LastPICArg) {
  866. Option O = LastPICArg->getOption();
  867. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  868. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  869. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  870. PIC =
  871. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  872. IsPICLevelTwo =
  873. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  874. } else {
  875. PIE = PIC = false;
  876. if (EffectiveTriple.isPS4CPU()) {
  877. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  878. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  879. if (Model != "kernel") {
  880. PIC = true;
  881. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  882. << LastPICArg->getSpelling();
  883. }
  884. }
  885. }
  886. }
  887. }
  888. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  889. // PIC level would've been set to level 1, force it back to level 2 PIC
  890. // instead.
  891. if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
  892. IsPICLevelTwo |= ToolChain.isPICDefault();
  893. // This kernel flags are a trump-card: they will disable PIC/PIE
  894. // generation, independent of the argument order.
  895. if (KernelOrKext &&
  896. ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
  897. !EffectiveTriple.isWatchOS()))
  898. PIC = PIE = false;
  899. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  900. // This is a very special mode. It trumps the other modes, almost no one
  901. // uses it, and it isn't even valid on any OS but Darwin.
  902. if (!Triple.isOSDarwin())
  903. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  904. << A->getSpelling() << Triple.str();
  905. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  906. // Only a forced PIC mode can cause the actual compile to have PIC defines
  907. // etc., no flags are sufficient. This behavior was selected to closely
  908. // match that of llvm-gcc and Apple GCC before that.
  909. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  910. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
  911. }
  912. bool EmbeddedPISupported;
  913. switch (Triple.getArch()) {
  914. case llvm::Triple::arm:
  915. case llvm::Triple::armeb:
  916. case llvm::Triple::thumb:
  917. case llvm::Triple::thumbeb:
  918. EmbeddedPISupported = true;
  919. break;
  920. default:
  921. EmbeddedPISupported = false;
  922. break;
  923. }
  924. bool ROPI = false, RWPI = false;
  925. Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
  926. if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
  927. if (!EmbeddedPISupported)
  928. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  929. << LastROPIArg->getSpelling() << Triple.str();
  930. ROPI = true;
  931. }
  932. Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
  933. if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
  934. if (!EmbeddedPISupported)
  935. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  936. << LastRWPIArg->getSpelling() << Triple.str();
  937. RWPI = true;
  938. }
  939. // ROPI and RWPI are not compatible with PIC or PIE.
  940. if ((ROPI || RWPI) && (PIC || PIE))
  941. ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
  942. if (Triple.isMIPS()) {
  943. StringRef CPUName;
  944. StringRef ABIName;
  945. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  946. // When targeting the N64 ABI, PIC is the default, except in the case
  947. // when the -mno-abicalls option is used. In that case we exit
  948. // at next check regardless of PIC being set below.
  949. if (ABIName == "n64")
  950. PIC = true;
  951. // When targettng MIPS with -mno-abicalls, it's always static.
  952. if(Args.hasArg(options::OPT_mno_abicalls))
  953. return std::make_tuple(llvm::Reloc::Static, 0U, false);
  954. // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
  955. // does not use PIC level 2 for historical reasons.
  956. IsPICLevelTwo = false;
  957. }
  958. if (PIC)
  959. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
  960. llvm::Reloc::Model RelocM = llvm::Reloc::Static;
  961. if (ROPI && RWPI)
  962. RelocM = llvm::Reloc::ROPI_RWPI;
  963. else if (ROPI)
  964. RelocM = llvm::Reloc::ROPI;
  965. else if (RWPI)
  966. RelocM = llvm::Reloc::RWPI;
  967. return std::make_tuple(RelocM, 0U, false);
  968. }
  969. // `-falign-functions` indicates that the functions should be aligned to a
  970. // 16-byte boundary.
  971. //
  972. // `-falign-functions=1` is the same as `-fno-align-functions`.
  973. //
  974. // The scalar `n` in `-falign-functions=n` must be an integral value between
  975. // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
  976. // the nearest power-of-two.
  977. //
  978. // If we return `0`, the frontend will default to the backend's preferred
  979. // alignment.
  980. //
  981. // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
  982. // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
  983. // alignment. For unaligned functions, we default to the backend's preferred
  984. // alignment.
  985. unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
  986. const ArgList &Args) {
  987. const Arg *A = Args.getLastArg(options::OPT_falign_functions,
  988. options::OPT_falign_functions_EQ,
  989. options::OPT_fno_align_functions);
  990. if (!A || A->getOption().matches(options::OPT_fno_align_functions))
  991. return 0;
  992. if (A->getOption().matches(options::OPT_falign_functions))
  993. return 0;
  994. unsigned Value = 0;
  995. if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
  996. TC.getDriver().Diag(diag::err_drv_invalid_int_value)
  997. << A->getAsString(Args) << A->getValue();
  998. return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
  999. }
  1000. void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  1001. ArgStringList &CmdArgs) {
  1002. llvm::Reloc::Model RelocationModel;
  1003. unsigned PICLevel;
  1004. bool IsPIE;
  1005. std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
  1006. if (RelocationModel != llvm::Reloc::Static)
  1007. CmdArgs.push_back("-KPIC");
  1008. }
  1009. /// Determine whether Objective-C automated reference counting is
  1010. /// enabled.
  1011. bool tools::isObjCAutoRefCount(const ArgList &Args) {
  1012. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  1013. }
  1014. enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
  1015. static LibGccType getLibGccType(const Driver &D, const ArgList &Args) {
  1016. if (Args.hasArg(options::OPT_static_libgcc) ||
  1017. Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
  1018. return LibGccType::StaticLibGcc;
  1019. if (Args.hasArg(options::OPT_shared_libgcc) || D.CCCIsCXX())
  1020. return LibGccType::SharedLibGcc;
  1021. return LibGccType::UnspecifiedLibGcc;
  1022. }
  1023. // Gcc adds libgcc arguments in various ways:
  1024. //
  1025. // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
  1026. // g++ <none>: -lgcc_s -lgcc
  1027. // gcc shared: -lgcc_s -lgcc
  1028. // g++ shared: -lgcc_s -lgcc
  1029. // gcc static: -lgcc -lgcc_eh
  1030. // g++ static: -lgcc -lgcc_eh
  1031. // gcc static-pie: -lgcc -lgcc_eh
  1032. // g++ static-pie: -lgcc -lgcc_eh
  1033. //
  1034. // Also, certain targets need additional adjustments.
  1035. static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
  1036. ArgStringList &CmdArgs, const ArgList &Args) {
  1037. ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
  1038. // Targets that don't use unwind libraries.
  1039. if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() ||
  1040. TC.getTriple().isOSBinFormatWasm() ||
  1041. UNW == ToolChain::UNW_None)
  1042. return;
  1043. LibGccType LGT = getLibGccType(D, Args);
  1044. bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
  1045. !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing();
  1046. if (AsNeeded)
  1047. CmdArgs.push_back("--as-needed");
  1048. switch (UNW) {
  1049. case ToolChain::UNW_None:
  1050. return;
  1051. case ToolChain::UNW_Libgcc: {
  1052. if (LGT == LibGccType::StaticLibGcc)
  1053. CmdArgs.push_back("-lgcc_eh");
  1054. else
  1055. CmdArgs.push_back("-lgcc_s");
  1056. break;
  1057. }
  1058. case ToolChain::UNW_CompilerRT:
  1059. CmdArgs.push_back("-lunwind");
  1060. break;
  1061. }
  1062. if (AsNeeded)
  1063. CmdArgs.push_back("--no-as-needed");
  1064. }
  1065. static void AddLibgcc(const ToolChain &TC, const Driver &D,
  1066. ArgStringList &CmdArgs, const ArgList &Args) {
  1067. LibGccType LGT = getLibGccType(D, Args);
  1068. if (LGT != LibGccType::SharedLibGcc)
  1069. CmdArgs.push_back("-lgcc");
  1070. AddUnwindLibrary(TC, D, CmdArgs, Args);
  1071. if (LGT == LibGccType::SharedLibGcc)
  1072. CmdArgs.push_back("-lgcc");
  1073. // According to Android ABI, we have to link with libdl if we are
  1074. // linking with non-static libgcc.
  1075. //
  1076. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  1077. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  1078. if (TC.getTriple().isAndroid() && LGT != LibGccType::StaticLibGcc)
  1079. CmdArgs.push_back("-ldl");
  1080. }
  1081. void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  1082. ArgStringList &CmdArgs, const ArgList &Args) {
  1083. // Make use of compiler-rt if --rtlib option is used
  1084. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  1085. switch (RLT) {
  1086. case ToolChain::RLT_CompilerRT:
  1087. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  1088. AddUnwindLibrary(TC, D, CmdArgs, Args);
  1089. break;
  1090. case ToolChain::RLT_Libgcc:
  1091. // Make sure libgcc is not used under MSVC environment by default
  1092. if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
  1093. // Issue error diagnostic if libgcc is explicitly specified
  1094. // through command line as --rtlib option argument.
  1095. if (Args.hasArg(options::OPT_rtlib_EQ)) {
  1096. TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  1097. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
  1098. }
  1099. } else
  1100. AddLibgcc(TC, D, CmdArgs, Args);
  1101. break;
  1102. }
  1103. }
  1104. /// Add HIP linker script arguments at the end of the argument list so that
  1105. /// the fat binary is built by embedding the device images into the host. The
  1106. /// linker script also defines a symbol required by the code generation so that
  1107. /// the image can be retrieved at runtime. This should be used only in tool
  1108. /// chains that support linker scripts.
  1109. void tools::AddHIPLinkerScript(const ToolChain &TC, Compilation &C,
  1110. const InputInfo &Output,
  1111. const InputInfoList &Inputs, const ArgList &Args,
  1112. ArgStringList &CmdArgs, const JobAction &JA,
  1113. const Tool &T) {
  1114. // If this is not a HIP host toolchain, we don't need to do anything.
  1115. if (!JA.isHostOffloading(Action::OFK_HIP))
  1116. return;
  1117. InputInfoList DeviceInputs;
  1118. for (const auto &II : Inputs) {
  1119. const Action *A = II.getAction();
  1120. // Is this a device linking action?
  1121. if (A && isa<LinkJobAction>(A) && A->isDeviceOffloading(Action::OFK_HIP)) {
  1122. DeviceInputs.push_back(II);
  1123. }
  1124. }
  1125. if (DeviceInputs.empty())
  1126. return;
  1127. // Create temporary linker script. Keep it if save-temps is enabled.
  1128. const char *LKS;
  1129. std::string Name = llvm::sys::path::filename(Output.getFilename());
  1130. if (C.getDriver().isSaveTempsEnabled()) {
  1131. LKS = C.getArgs().MakeArgString(Name + ".lk");
  1132. } else {
  1133. auto TmpName = C.getDriver().GetTemporaryPath(Name, "lk");
  1134. LKS = C.addTempFile(C.getArgs().MakeArgString(TmpName));
  1135. }
  1136. // Add linker script option to the command.
  1137. CmdArgs.push_back("-T");
  1138. CmdArgs.push_back(LKS);
  1139. // Create a buffer to write the contents of the linker script.
  1140. std::string LksBuffer;
  1141. llvm::raw_string_ostream LksStream(LksBuffer);
  1142. // Get the HIP offload tool chain.
  1143. auto *HIPTC = static_cast<const toolchains::CudaToolChain *>(
  1144. C.getSingleOffloadToolChain<Action::OFK_HIP>());
  1145. assert(HIPTC->getTriple().getArch() == llvm::Triple::amdgcn &&
  1146. "Wrong platform");
  1147. (void)HIPTC;
  1148. const char *BundleFile;
  1149. if (C.getDriver().isSaveTempsEnabled()) {
  1150. BundleFile = C.getArgs().MakeArgString(Name + ".hipfb");
  1151. } else {
  1152. auto TmpName = C.getDriver().GetTemporaryPath(Name, "hipfb");
  1153. BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpName));
  1154. }
  1155. AMDGCN::constructHIPFatbinCommand(C, JA, BundleFile, DeviceInputs, Args, T);
  1156. // Add commands to embed target binaries. We ensure that each section and
  1157. // image is 16-byte aligned. This is not mandatory, but increases the
  1158. // likelihood of data to be aligned with a cache block in several main host
  1159. // machines.
  1160. LksStream << "/*\n";
  1161. LksStream << " HIP Offload Linker Script\n";
  1162. LksStream << " *** Automatically generated by Clang ***\n";
  1163. LksStream << "*/\n";
  1164. LksStream << "TARGET(binary)\n";
  1165. LksStream << "INPUT(" << BundleFile << ")\n";
  1166. LksStream << "SECTIONS\n";
  1167. LksStream << "{\n";
  1168. LksStream << " .hip_fatbin :\n";
  1169. LksStream << " ALIGN(0x10)\n";
  1170. LksStream << " {\n";
  1171. LksStream << " PROVIDE_HIDDEN(__hip_fatbin = .);\n";
  1172. LksStream << " " << BundleFile << "\n";
  1173. LksStream << " }\n";
  1174. LksStream << " /DISCARD/ :\n";
  1175. LksStream << " {\n";
  1176. LksStream << " * ( __CLANG_OFFLOAD_BUNDLE__* )\n";
  1177. LksStream << " }\n";
  1178. LksStream << "}\n";
  1179. LksStream << "INSERT BEFORE .data\n";
  1180. LksStream.flush();
  1181. // Dump the contents of the linker script if the user requested that. We
  1182. // support this option to enable testing of behavior with -###.
  1183. if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
  1184. llvm::errs() << LksBuffer;
  1185. // If this is a dry run, do not create the linker script file.
  1186. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
  1187. return;
  1188. // Open script file and write the contents.
  1189. std::error_code EC;
  1190. llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::OF_None);
  1191. if (EC) {
  1192. C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  1193. return;
  1194. }
  1195. Lksf << LksBuffer;
  1196. }
  1197. SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
  1198. const InputInfo &Output,
  1199. const InputInfo &Input,
  1200. const Driver &D) {
  1201. const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
  1202. if (!A)
  1203. return {};
  1204. StringRef SaveStats = A->getValue();
  1205. SmallString<128> StatsFile;
  1206. if (SaveStats == "obj" && Output.isFilename()) {
  1207. StatsFile.assign(Output.getFilename());
  1208. llvm::sys::path::remove_filename(StatsFile);
  1209. } else if (SaveStats != "cwd") {
  1210. D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
  1211. return {};
  1212. }
  1213. StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
  1214. llvm::sys::path::append(StatsFile, BaseName);
  1215. llvm::sys::path::replace_extension(StatsFile, "stats");
  1216. return StatsFile;
  1217. }
  1218. void tools::addMultilibFlag(bool Enabled, const char *const Flag,
  1219. Multilib::flags_list &Flags) {
  1220. Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
  1221. }
  1222. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  1223. std::vector<StringRef> &Features) {
  1224. handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
  1225. }
  1226. void tools::getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  1227. const ArgList &Args, ArgStringList &CmdArgs, bool ForAS,
  1228. bool ForLTOPlugin) {
  1229. const Driver &D = TC.getDriver();
  1230. std::vector<StringRef> Features;
  1231. switch (Triple.getArch()) {
  1232. default:
  1233. break;
  1234. case llvm::Triple::mips:
  1235. case llvm::Triple::mipsel:
  1236. case llvm::Triple::mips64:
  1237. case llvm::Triple::mips64el:
  1238. mips::getMIPSTargetFeatures(D, Triple, Args, Features);
  1239. break;
  1240. case llvm::Triple::arm:
  1241. case llvm::Triple::armeb:
  1242. case llvm::Triple::thumb:
  1243. case llvm::Triple::thumbeb:
  1244. arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
  1245. break;
  1246. case llvm::Triple::ppc:
  1247. case llvm::Triple::ppc64:
  1248. case llvm::Triple::ppc64le:
  1249. ppc::getPPCTargetFeatures(D, Triple, Args, Features);
  1250. break;
  1251. case llvm::Triple::riscv32:
  1252. case llvm::Triple::riscv64:
  1253. riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
  1254. break;
  1255. case llvm::Triple::systemz:
  1256. systemz::getSystemZTargetFeatures(Args, Features);
  1257. break;
  1258. case llvm::Triple::aarch64:
  1259. case llvm::Triple::aarch64_be:
  1260. aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
  1261. break;
  1262. case llvm::Triple::x86:
  1263. case llvm::Triple::x86_64:
  1264. x86::getX86TargetFeatures(D, Triple, Args, Features);
  1265. break;
  1266. case llvm::Triple::hexagon:
  1267. hexagon::getHexagonTargetFeatures(D, Args, Features);
  1268. break;
  1269. case llvm::Triple::wasm32:
  1270. case llvm::Triple::wasm64:
  1271. getWebAssemblyTargetFeatures(Args, Features);
  1272. break;
  1273. case llvm::Triple::sparc:
  1274. case llvm::Triple::sparcel:
  1275. case llvm::Triple::sparcv9:
  1276. sparc::getSparcTargetFeatures(D, Args, Features);
  1277. break;
  1278. case llvm::Triple::r600:
  1279. case llvm::Triple::amdgcn:
  1280. amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
  1281. break;
  1282. case llvm::Triple::msp430:
  1283. msp430::getMSP430TargetFeatures(D, Args, Features);
  1284. }
  1285. // Find the last of each feature.
  1286. llvm::StringMap<unsigned> LastOpt;
  1287. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  1288. StringRef Name = Features[I];
  1289. assert(Name[0] == '-' || Name[0] == '+');
  1290. LastOpt[Name.drop_front(1)] = I;
  1291. }
  1292. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  1293. // If this feature was overridden, ignore it.
  1294. StringRef Name = Features[I];
  1295. llvm::StringMap<unsigned>::iterator LastI =
  1296. LastOpt.find(Name.drop_front(1));
  1297. assert(LastI != LastOpt.end());
  1298. unsigned Last = LastI->second;
  1299. if (Last != I)
  1300. continue;
  1301. if (!ForLTOPlugin) {
  1302. CmdArgs.push_back("-target-feature");
  1303. CmdArgs.push_back(Name.data());
  1304. } else {
  1305. CmdArgs.push_back(
  1306. Args.MakeArgString(Twine("-plugin-opt=-mattr=") + Name));
  1307. }
  1308. }
  1309. }
  1310. StringRef tools::getTargetABI(const ArgList &Args, const llvm::Triple &Triple) {
  1311. // TODO: Support the other target ABI
  1312. switch (Triple.getArch()) {
  1313. default:
  1314. break;
  1315. case llvm::Triple::riscv32:
  1316. case llvm::Triple::riscv64:
  1317. return tools::riscv::getRISCVABI(Args, Triple);
  1318. break;
  1319. }
  1320. return StringRef();
  1321. }