CommonArgs.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065
  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/M68k.h"
  12. #include "Arch/Mips.h"
  13. #include "Arch/PPC.h"
  14. #include "Arch/SystemZ.h"
  15. #include "Arch/VE.h"
  16. #include "Arch/X86.h"
  17. #include "HIPAMD.h"
  18. #include "Hexagon.h"
  19. #include "clang/Basic/CharInfo.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Basic/ObjCRuntime.h"
  22. #include "clang/Basic/Version.h"
  23. #include "clang/Config/config.h"
  24. #include "clang/Driver/Action.h"
  25. #include "clang/Driver/Compilation.h"
  26. #include "clang/Driver/Driver.h"
  27. #include "clang/Driver/DriverDiagnostic.h"
  28. #include "clang/Driver/InputInfo.h"
  29. #include "clang/Driver/Job.h"
  30. #include "clang/Driver/Options.h"
  31. #include "clang/Driver/SanitizerArgs.h"
  32. #include "clang/Driver/ToolChain.h"
  33. #include "clang/Driver/Util.h"
  34. #include "clang/Driver/XRayArgs.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/ADT/SmallSet.h"
  37. #include "llvm/ADT/SmallString.h"
  38. #include "llvm/ADT/StringExtras.h"
  39. #include "llvm/ADT/StringSwitch.h"
  40. #include "llvm/ADT/Twine.h"
  41. #include "llvm/Config/llvm-config.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/Threading.h"
  57. #include "llvm/Support/VirtualFileSystem.h"
  58. #include "llvm/Support/YAMLParser.h"
  59. using namespace clang::driver;
  60. using namespace clang::driver::tools;
  61. using namespace clang;
  62. using namespace llvm::opt;
  63. static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
  64. if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
  65. CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") +
  66. A->getValue()));
  67. if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
  68. CmdArgs.push_back(Args.MakeArgString(
  69. Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue()));
  70. if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
  71. CmdArgs.push_back(Args.MakeArgString(
  72. Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue()));
  73. }
  74. static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
  75. const llvm::Triple &Triple,
  76. const InputInfo &Input,
  77. const InputInfo &Output) {
  78. StringRef Format = "yaml";
  79. if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
  80. Format = A->getValue();
  81. SmallString<128> F;
  82. const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  83. if (A)
  84. F = A->getValue();
  85. else if (Output.isFilename())
  86. F = Output.getFilename();
  87. assert(!F.empty() && "Cannot determine remarks output name.");
  88. // Append "opt.ld.<format>" to the end of the file name.
  89. CmdArgs.push_back(
  90. Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F +
  91. Twine(".opt.ld.") + Format));
  92. if (const Arg *A =
  93. Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
  94. CmdArgs.push_back(Args.MakeArgString(
  95. Twine("--plugin-opt=opt-remarks-passes=") + A->getValue()));
  96. CmdArgs.push_back(Args.MakeArgString(
  97. Twine("--plugin-opt=opt-remarks-format=") + Format.data()));
  98. }
  99. static void renderRemarksHotnessOptions(const ArgList &Args,
  100. ArgStringList &CmdArgs) {
  101. if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
  102. options::OPT_fno_diagnostics_show_hotness, false))
  103. CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness");
  104. if (const Arg *A =
  105. Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
  106. CmdArgs.push_back(Args.MakeArgString(
  107. Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue()));
  108. }
  109. void tools::addPathIfExists(const Driver &D, const Twine &Path,
  110. ToolChain::path_list &Paths) {
  111. if (D.getVFS().exists(Path))
  112. Paths.push_back(Path.str());
  113. }
  114. void tools::handleTargetFeaturesGroup(const ArgList &Args,
  115. std::vector<StringRef> &Features,
  116. OptSpecifier Group) {
  117. for (const Arg *A : Args.filtered(Group)) {
  118. StringRef Name = A->getOption().getName();
  119. A->claim();
  120. // Skip over "-m".
  121. assert(Name.startswith("m") && "Invalid feature name.");
  122. Name = Name.substr(1);
  123. bool IsNegative = Name.startswith("no-");
  124. if (IsNegative)
  125. Name = Name.substr(3);
  126. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  127. }
  128. }
  129. std::vector<StringRef>
  130. tools::unifyTargetFeatures(const std::vector<StringRef> &Features) {
  131. std::vector<StringRef> UnifiedFeatures;
  132. // Find the last of each feature.
  133. llvm::StringMap<unsigned> LastOpt;
  134. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  135. StringRef Name = Features[I];
  136. assert(Name[0] == '-' || Name[0] == '+');
  137. LastOpt[Name.drop_front(1)] = I;
  138. }
  139. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  140. // If this feature was overridden, ignore it.
  141. StringRef Name = Features[I];
  142. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
  143. assert(LastI != LastOpt.end());
  144. unsigned Last = LastI->second;
  145. if (Last != I)
  146. continue;
  147. UnifiedFeatures.push_back(Name);
  148. }
  149. return UnifiedFeatures;
  150. }
  151. void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  152. const char *ArgName, const char *EnvVar) {
  153. const char *DirList = ::getenv(EnvVar);
  154. bool CombinedArg = false;
  155. if (!DirList)
  156. return; // Nothing to do.
  157. StringRef Name(ArgName);
  158. if (Name.equals("-I") || Name.equals("-L") || Name.empty())
  159. CombinedArg = true;
  160. StringRef Dirs(DirList);
  161. if (Dirs.empty()) // Empty string should not add '.'.
  162. return;
  163. StringRef::size_type Delim;
  164. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  165. if (Delim == 0) { // Leading colon.
  166. if (CombinedArg) {
  167. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  168. } else {
  169. CmdArgs.push_back(ArgName);
  170. CmdArgs.push_back(".");
  171. }
  172. } else {
  173. if (CombinedArg) {
  174. CmdArgs.push_back(
  175. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  176. } else {
  177. CmdArgs.push_back(ArgName);
  178. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  179. }
  180. }
  181. Dirs = Dirs.substr(Delim + 1);
  182. }
  183. if (Dirs.empty()) { // Trailing colon.
  184. if (CombinedArg) {
  185. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  186. } else {
  187. CmdArgs.push_back(ArgName);
  188. CmdArgs.push_back(".");
  189. }
  190. } else { // Add the last path.
  191. if (CombinedArg) {
  192. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  193. } else {
  194. CmdArgs.push_back(ArgName);
  195. CmdArgs.push_back(Args.MakeArgString(Dirs));
  196. }
  197. }
  198. }
  199. void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  200. const ArgList &Args, ArgStringList &CmdArgs,
  201. const JobAction &JA) {
  202. const Driver &D = TC.getDriver();
  203. // Add extra linker input arguments which are not treated as inputs
  204. // (constructed via -Xarch_).
  205. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  206. // LIBRARY_PATH are included before user inputs and only supported on native
  207. // toolchains.
  208. if (!TC.isCrossCompiling())
  209. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  210. for (const auto &II : Inputs) {
  211. // If the current tool chain refers to an OpenMP offloading host, we
  212. // should ignore inputs that refer to OpenMP offloading devices -
  213. // they will be embedded according to a proper linker script.
  214. if (auto *IA = II.getAction())
  215. if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
  216. IA->isDeviceOffloading(Action::OFK_OpenMP)))
  217. continue;
  218. if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
  219. // Don't try to pass LLVM inputs unless we have native support.
  220. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  221. // Add filenames immediately.
  222. if (II.isFilename()) {
  223. CmdArgs.push_back(II.getFilename());
  224. continue;
  225. }
  226. // Otherwise, this is a linker input argument.
  227. const Arg &A = II.getInputArg();
  228. // Handle reserved library options.
  229. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  230. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  231. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  232. TC.AddCCKextLibArgs(Args, CmdArgs);
  233. else if (A.getOption().matches(options::OPT_z)) {
  234. // Pass -z prefix for gcc linker compatibility.
  235. A.claim();
  236. A.render(Args, CmdArgs);
  237. } else if (A.getOption().matches(options::OPT_b)) {
  238. const llvm::Triple &T = TC.getTriple();
  239. if (!T.isOSAIX()) {
  240. TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  241. << A.getSpelling() << T.str();
  242. }
  243. // Pass -b prefix for AIX linker.
  244. A.claim();
  245. A.render(Args, CmdArgs);
  246. } else {
  247. A.renderAsInput(Args, CmdArgs);
  248. }
  249. }
  250. }
  251. void tools::addLinkerCompressDebugSectionsOption(
  252. const ToolChain &TC, const llvm::opt::ArgList &Args,
  253. llvm::opt::ArgStringList &CmdArgs) {
  254. // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
  255. // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore
  256. // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz
  257. // is not translated since ld --compress-debug-sections option requires an
  258. // argument.
  259. if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
  260. StringRef V = A->getValue();
  261. if (V == "none" || V == "zlib")
  262. CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
  263. else
  264. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  265. << A->getOption().getName() << V;
  266. }
  267. }
  268. void tools::AddTargetFeature(const ArgList &Args,
  269. std::vector<StringRef> &Features,
  270. OptSpecifier OnOpt, OptSpecifier OffOpt,
  271. StringRef FeatureName) {
  272. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  273. if (A->getOption().matches(OnOpt))
  274. Features.push_back(Args.MakeArgString("+" + FeatureName));
  275. else
  276. Features.push_back(Args.MakeArgString("-" + FeatureName));
  277. }
  278. }
  279. /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
  280. static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
  281. const ArgList &Args) {
  282. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  283. auto GPUName = getProcessorFromTargetID(T, A->getValue());
  284. return llvm::StringSwitch<std::string>(GPUName)
  285. .Cases("rv630", "rv635", "r600")
  286. .Cases("rv610", "rv620", "rs780", "rs880")
  287. .Case("rv740", "rv770")
  288. .Case("palm", "cedar")
  289. .Cases("sumo", "sumo2", "sumo")
  290. .Case("hemlock", "cypress")
  291. .Case("aruba", "cayman")
  292. .Default(GPUName.str());
  293. }
  294. return "";
  295. }
  296. static std::string getLanaiTargetCPU(const ArgList &Args) {
  297. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  298. return A->getValue();
  299. }
  300. return "";
  301. }
  302. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  303. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  304. // If we have -mcpu=, use that.
  305. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  306. StringRef CPU = A->getValue();
  307. #ifdef __wasm__
  308. // Handle "native" by examining the host. "native" isn't meaningful when
  309. // cross compiling, so only support this when the host is also WebAssembly.
  310. if (CPU == "native")
  311. return llvm::sys::getHostCPUName();
  312. #endif
  313. return CPU;
  314. }
  315. return "generic";
  316. }
  317. std::string tools::getCPUName(const Driver &D, const ArgList &Args,
  318. const llvm::Triple &T, bool FromAs) {
  319. Arg *A;
  320. switch (T.getArch()) {
  321. default:
  322. return "";
  323. case llvm::Triple::aarch64:
  324. case llvm::Triple::aarch64_32:
  325. case llvm::Triple::aarch64_be:
  326. return aarch64::getAArch64TargetCPU(Args, T, A);
  327. case llvm::Triple::arm:
  328. case llvm::Triple::armeb:
  329. case llvm::Triple::thumb:
  330. case llvm::Triple::thumbeb: {
  331. StringRef MArch, MCPU;
  332. arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  333. return arm::getARMTargetCPU(MCPU, MArch, T);
  334. }
  335. case llvm::Triple::avr:
  336. if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
  337. return A->getValue();
  338. return "";
  339. case llvm::Triple::m68k:
  340. return m68k::getM68kTargetCPU(Args);
  341. case llvm::Triple::mips:
  342. case llvm::Triple::mipsel:
  343. case llvm::Triple::mips64:
  344. case llvm::Triple::mips64el: {
  345. StringRef CPUName;
  346. StringRef ABIName;
  347. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  348. return std::string(CPUName);
  349. }
  350. case llvm::Triple::nvptx:
  351. case llvm::Triple::nvptx64:
  352. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  353. return A->getValue();
  354. return "";
  355. case llvm::Triple::ppc:
  356. case llvm::Triple::ppcle:
  357. case llvm::Triple::ppc64:
  358. case llvm::Triple::ppc64le: {
  359. std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
  360. // LLVM may default to generating code for the native CPU,
  361. // but, like gcc, we default to a more generic option for
  362. // each architecture. (except on AIX)
  363. if (!TargetCPUName.empty())
  364. return TargetCPUName;
  365. if (T.isOSAIX())
  366. TargetCPUName = "pwr7";
  367. else if (T.getArch() == llvm::Triple::ppc64le)
  368. TargetCPUName = "ppc64le";
  369. else if (T.getArch() == llvm::Triple::ppc64)
  370. TargetCPUName = "ppc64";
  371. else
  372. TargetCPUName = "ppc";
  373. return TargetCPUName;
  374. }
  375. case llvm::Triple::riscv32:
  376. case llvm::Triple::riscv64:
  377. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  378. return A->getValue();
  379. return "";
  380. case llvm::Triple::bpfel:
  381. case llvm::Triple::bpfeb:
  382. case llvm::Triple::sparc:
  383. case llvm::Triple::sparcel:
  384. case llvm::Triple::sparcv9:
  385. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  386. return A->getValue();
  387. if (T.getArch() == llvm::Triple::sparc && T.isOSSolaris())
  388. return "v9";
  389. return "";
  390. case llvm::Triple::x86:
  391. case llvm::Triple::x86_64:
  392. return x86::getX86TargetCPU(D, Args, T);
  393. case llvm::Triple::hexagon:
  394. return "hexagon" +
  395. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  396. case llvm::Triple::lanai:
  397. return getLanaiTargetCPU(Args);
  398. case llvm::Triple::systemz:
  399. return systemz::getSystemZTargetCPU(Args);
  400. case llvm::Triple::r600:
  401. case llvm::Triple::amdgcn:
  402. return getAMDGPUTargetGPU(T, Args);
  403. case llvm::Triple::wasm32:
  404. case llvm::Triple::wasm64:
  405. return std::string(getWebAssemblyTargetCPU(Args));
  406. }
  407. }
  408. llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
  409. Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
  410. if (!LtoJobsArg)
  411. return {};
  412. if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
  413. D.Diag(diag::err_drv_invalid_int_value)
  414. << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
  415. return LtoJobsArg->getValue();
  416. }
  417. // CloudABI uses -ffunction-sections and -fdata-sections by default.
  418. bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
  419. return Triple.getOS() == llvm::Triple::CloudABI;
  420. }
  421. void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
  422. ArgStringList &CmdArgs, const InputInfo &Output,
  423. const InputInfo &Input, bool IsThinLTO) {
  424. const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
  425. const Driver &D = ToolChain.getDriver();
  426. if (llvm::sys::path::filename(Linker) != "ld.lld" &&
  427. llvm::sys::path::stem(Linker) != "ld.lld") {
  428. // Tell the linker to load the plugin. This has to come before
  429. // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
  430. // that -Wl might forward.
  431. CmdArgs.push_back("-plugin");
  432. #if defined(_WIN32)
  433. const char *Suffix = ".dll";
  434. #elif defined(__APPLE__)
  435. const char *Suffix = ".dylib";
  436. #else
  437. const char *Suffix = ".so";
  438. #endif
  439. SmallString<1024> Plugin;
  440. llvm::sys::path::native(
  441. Twine("/var/empty/llvm-14.0.6-lib/lib" "/LLVMgold") + Suffix,
  442. Plugin);
  443. CmdArgs.push_back(Args.MakeArgString(Plugin));
  444. }
  445. // Try to pass driver level flags relevant to LTO code generation down to
  446. // the plugin.
  447. // Handle flags for selecting CPU variants.
  448. std::string CPU = getCPUName(D, Args, ToolChain.getTriple());
  449. if (!CPU.empty())
  450. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  451. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  452. // The optimization level matches
  453. // CompilerInvocation.cpp:getOptimizationLevel().
  454. StringRef OOpt;
  455. if (A->getOption().matches(options::OPT_O4) ||
  456. A->getOption().matches(options::OPT_Ofast))
  457. OOpt = "3";
  458. else if (A->getOption().matches(options::OPT_O)) {
  459. OOpt = A->getValue();
  460. if (OOpt == "g")
  461. OOpt = "1";
  462. else if (OOpt == "s" || OOpt == "z")
  463. OOpt = "2";
  464. } else if (A->getOption().matches(options::OPT_O0))
  465. OOpt = "0";
  466. if (!OOpt.empty())
  467. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  468. }
  469. if (Args.hasArg(options::OPT_gsplit_dwarf)) {
  470. CmdArgs.push_back(
  471. Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
  472. Output.getFilename() + "_dwo"));
  473. }
  474. if (IsThinLTO)
  475. CmdArgs.push_back("-plugin-opt=thinlto");
  476. StringRef Parallelism = getLTOParallelism(Args, D);
  477. if (!Parallelism.empty())
  478. CmdArgs.push_back(
  479. Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
  480. // If an explicit debugger tuning argument appeared, pass it along.
  481. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  482. options::OPT_ggdbN_Group)) {
  483. if (A->getOption().matches(options::OPT_glldb))
  484. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  485. else if (A->getOption().matches(options::OPT_gsce))
  486. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  487. else if (A->getOption().matches(options::OPT_gdbx))
  488. CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx");
  489. else
  490. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  491. }
  492. bool UseSeparateSections =
  493. isUseSeparateSections(ToolChain.getEffectiveTriple());
  494. if (Args.hasFlag(options::OPT_ffunction_sections,
  495. options::OPT_fno_function_sections, UseSeparateSections)) {
  496. CmdArgs.push_back("-plugin-opt=-function-sections");
  497. }
  498. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  499. UseSeparateSections)) {
  500. CmdArgs.push_back("-plugin-opt=-data-sections");
  501. }
  502. if (Arg *A = getLastProfileSampleUseArg(Args)) {
  503. StringRef FName = A->getValue();
  504. if (!llvm::sys::fs::exists(FName))
  505. D.Diag(diag::err_drv_no_such_file) << FName;
  506. else
  507. CmdArgs.push_back(
  508. Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
  509. }
  510. auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
  511. options::OPT_fcs_profile_generate_EQ,
  512. options::OPT_fno_profile_generate);
  513. if (CSPGOGenerateArg &&
  514. CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  515. CSPGOGenerateArg = nullptr;
  516. auto *ProfileUseArg = getLastProfileUseArg(Args);
  517. if (CSPGOGenerateArg) {
  518. CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
  519. if (CSPGOGenerateArg->getOption().matches(
  520. options::OPT_fcs_profile_generate_EQ)) {
  521. SmallString<128> Path(CSPGOGenerateArg->getValue());
  522. llvm::sys::path::append(Path, "default_%m.profraw");
  523. CmdArgs.push_back(
  524. Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
  525. } else
  526. CmdArgs.push_back(
  527. Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
  528. } else if (ProfileUseArg) {
  529. SmallString<128> Path(
  530. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  531. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  532. llvm::sys::path::append(Path, "default.profdata");
  533. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
  534. Path));
  535. }
  536. // Pass an option to enable/disable the new pass manager.
  537. if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager,
  538. options::OPT_fno_legacy_pass_manager)) {
  539. if (A->getOption().matches(options::OPT_flegacy_pass_manager))
  540. CmdArgs.push_back("-plugin-opt=legacy-pass-manager");
  541. else
  542. CmdArgs.push_back("-plugin-opt=new-pass-manager");
  543. }
  544. // Setup statistics file output.
  545. SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
  546. if (!StatsFile.empty())
  547. CmdArgs.push_back(
  548. Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
  549. addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
  550. // Handle remark diagnostics on screen options: '-Rpass-*'.
  551. renderRpassOptions(Args, CmdArgs);
  552. // Handle serialized remarks options: '-fsave-optimization-record'
  553. // and '-foptimization-record-*'.
  554. if (willEmitRemarks(Args))
  555. renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
  556. Output);
  557. // Handle remarks hotness/threshold related options.
  558. renderRemarksHotnessOptions(Args, CmdArgs);
  559. addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
  560. /*IsLTO=*/true);
  561. }
  562. void tools::addOpenMPRuntimeSpecificRPath(const ToolChain &TC,
  563. const ArgList &Args,
  564. ArgStringList &CmdArgs) {
  565. if (Args.hasFlag(options::OPT_fopenmp_implicit_rpath,
  566. options::OPT_fno_openmp_implicit_rpath, true)) {
  567. // Default to clang lib / lib64 folder, i.e. the same location as device
  568. // runtime
  569. SmallString<256> DefaultLibPath =
  570. llvm::sys::path::parent_path(TC.getDriver().Dir);
  571. llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
  572. CmdArgs.push_back("-rpath");
  573. CmdArgs.push_back(Args.MakeArgString(DefaultLibPath));
  574. }
  575. }
  576. void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,
  577. const ArgList &Args,
  578. ArgStringList &CmdArgs) {
  579. // Default to clang lib / lib64 folder, i.e. the same location as device
  580. // runtime.
  581. SmallString<256> DefaultLibPath =
  582. llvm::sys::path::parent_path(TC.getDriver().Dir);
  583. llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
  584. CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
  585. }
  586. void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
  587. ArgStringList &CmdArgs) {
  588. // Enable -frtlib-add-rpath by default for the case of VE.
  589. const bool IsVE = TC.getTriple().isVE();
  590. bool DefaultValue = IsVE;
  591. if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
  592. options::OPT_fno_rtlib_add_rpath, DefaultValue))
  593. return;
  594. std::string CandidateRPath = TC.getArchSpecificLibPath();
  595. if (TC.getVFS().exists(CandidateRPath)) {
  596. CmdArgs.push_back("-rpath");
  597. CmdArgs.push_back(Args.MakeArgString(CandidateRPath));
  598. }
  599. }
  600. bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  601. const ArgList &Args, bool ForceStaticHostRuntime,
  602. bool IsOffloadingHost, bool GompNeedsRT) {
  603. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  604. options::OPT_fno_openmp, false))
  605. return false;
  606. Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
  607. if (RTKind == Driver::OMPRT_Unknown)
  608. // Already diagnosed.
  609. return false;
  610. if (ForceStaticHostRuntime)
  611. CmdArgs.push_back("-Bstatic");
  612. switch (RTKind) {
  613. case Driver::OMPRT_OMP:
  614. CmdArgs.push_back("-lomp");
  615. break;
  616. case Driver::OMPRT_GOMP:
  617. CmdArgs.push_back("-lgomp");
  618. break;
  619. case Driver::OMPRT_IOMP5:
  620. CmdArgs.push_back("-liomp5");
  621. break;
  622. case Driver::OMPRT_Unknown:
  623. break;
  624. }
  625. if (ForceStaticHostRuntime)
  626. CmdArgs.push_back("-Bdynamic");
  627. if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
  628. CmdArgs.push_back("-lrt");
  629. if (IsOffloadingHost)
  630. CmdArgs.push_back("-lomptarget");
  631. addArchSpecificRPath(TC, Args, CmdArgs);
  632. if (RTKind == Driver::OMPRT_OMP)
  633. addOpenMPRuntimeSpecificRPath(TC, Args, CmdArgs);
  634. addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
  635. return true;
  636. }
  637. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  638. ArgStringList &CmdArgs, StringRef Sanitizer,
  639. bool IsShared, bool IsWhole) {
  640. // Wrap any static runtimes that must be forced into executable in
  641. // whole-archive.
  642. if (IsWhole) CmdArgs.push_back("--whole-archive");
  643. CmdArgs.push_back(TC.getCompilerRTArgString(
  644. Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
  645. if (IsWhole) CmdArgs.push_back("--no-whole-archive");
  646. if (IsShared) {
  647. addArchSpecificRPath(TC, Args, CmdArgs);
  648. }
  649. }
  650. // Tries to use a file with the list of dynamic symbols that need to be exported
  651. // from the runtime library. Returns true if the file was found.
  652. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  653. ArgStringList &CmdArgs,
  654. StringRef Sanitizer) {
  655. // Solaris ld defaults to --export-dynamic behaviour but doesn't support
  656. // the option, so don't try to pass it.
  657. if (TC.getTriple().getOS() == llvm::Triple::Solaris)
  658. return true;
  659. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  660. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  661. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  662. return true;
  663. }
  664. return false;
  665. }
  666. const char *tools::getAsNeededOption(const ToolChain &TC, bool as_needed) {
  667. assert(!TC.getTriple().isOSAIX() &&
  668. "AIX linker does not support any form of --as-needed option yet.");
  669. // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
  670. // for the native forms -z ignore/-z record, they are missing in Illumos,
  671. // so always use the native form.
  672. if (TC.getTriple().isOSSolaris())
  673. return as_needed ? "-zignore" : "-zrecord";
  674. else
  675. return as_needed ? "--as-needed" : "--no-as-needed";
  676. }
  677. void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
  678. ArgStringList &CmdArgs) {
  679. // Fuchsia never needs these. Any sanitizer runtimes with system
  680. // dependencies use the `.deplibs` feature instead.
  681. if (TC.getTriple().isOSFuchsia())
  682. return;
  683. // Force linking against the system libraries sanitizers depends on
  684. // (see PR15823 why this is necessary).
  685. CmdArgs.push_back(getAsNeededOption(TC, false));
  686. // There's no libpthread or librt on RTEMS & Android.
  687. if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
  688. !TC.getTriple().isAndroid()) {
  689. CmdArgs.push_back("-lpthread");
  690. if (!TC.getTriple().isOSOpenBSD())
  691. CmdArgs.push_back("-lrt");
  692. }
  693. CmdArgs.push_back("-lm");
  694. // There's no libdl on all OSes.
  695. if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
  696. !TC.getTriple().isOSOpenBSD() &&
  697. TC.getTriple().getOS() != llvm::Triple::RTEMS)
  698. CmdArgs.push_back("-ldl");
  699. // Required for backtrace on some OSes
  700. if (TC.getTriple().isOSFreeBSD() ||
  701. TC.getTriple().isOSNetBSD() ||
  702. TC.getTriple().isOSOpenBSD())
  703. CmdArgs.push_back("-lexecinfo");
  704. }
  705. static void
  706. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  707. SmallVectorImpl<StringRef> &SharedRuntimes,
  708. SmallVectorImpl<StringRef> &StaticRuntimes,
  709. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  710. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  711. SmallVectorImpl<StringRef> &RequiredSymbols) {
  712. const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
  713. // Collect shared runtimes.
  714. if (SanArgs.needsSharedRt()) {
  715. if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
  716. SharedRuntimes.push_back("asan");
  717. if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
  718. HelperStaticRuntimes.push_back("asan-preinit");
  719. }
  720. if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
  721. SharedRuntimes.push_back("memprof");
  722. if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
  723. HelperStaticRuntimes.push_back("memprof-preinit");
  724. }
  725. if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
  726. if (SanArgs.requiresMinimalRuntime())
  727. SharedRuntimes.push_back("ubsan_minimal");
  728. else
  729. SharedRuntimes.push_back("ubsan_standalone");
  730. }
  731. if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
  732. if (SanArgs.requiresMinimalRuntime())
  733. SharedRuntimes.push_back("scudo_minimal");
  734. else
  735. SharedRuntimes.push_back("scudo");
  736. }
  737. if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
  738. SharedRuntimes.push_back("tsan");
  739. if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
  740. if (SanArgs.needsHwasanAliasesRt())
  741. SharedRuntimes.push_back("hwasan_aliases");
  742. else
  743. SharedRuntimes.push_back("hwasan");
  744. }
  745. }
  746. // The stats_client library is also statically linked into DSOs.
  747. if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
  748. StaticRuntimes.push_back("stats_client");
  749. // Always link the static runtime regardless of DSO or executable.
  750. if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes())
  751. HelperStaticRuntimes.push_back("asan_static");
  752. // Collect static runtimes.
  753. if (Args.hasArg(options::OPT_shared)) {
  754. // Don't link static runtimes into DSOs.
  755. return;
  756. }
  757. // Each static runtime that has a DSO counterpart above is excluded below,
  758. // but runtimes that exist only as static are not affected by needsSharedRt.
  759. if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
  760. StaticRuntimes.push_back("asan");
  761. if (SanArgs.linkCXXRuntimes())
  762. StaticRuntimes.push_back("asan_cxx");
  763. }
  764. if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
  765. SanArgs.linkRuntimes()) {
  766. StaticRuntimes.push_back("memprof");
  767. if (SanArgs.linkCXXRuntimes())
  768. StaticRuntimes.push_back("memprof_cxx");
  769. }
  770. if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
  771. if (SanArgs.needsHwasanAliasesRt()) {
  772. StaticRuntimes.push_back("hwasan_aliases");
  773. if (SanArgs.linkCXXRuntimes())
  774. StaticRuntimes.push_back("hwasan_aliases_cxx");
  775. } else {
  776. StaticRuntimes.push_back("hwasan");
  777. if (SanArgs.linkCXXRuntimes())
  778. StaticRuntimes.push_back("hwasan_cxx");
  779. }
  780. }
  781. if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
  782. StaticRuntimes.push_back("dfsan");
  783. if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
  784. StaticRuntimes.push_back("lsan");
  785. if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
  786. StaticRuntimes.push_back("msan");
  787. if (SanArgs.linkCXXRuntimes())
  788. StaticRuntimes.push_back("msan_cxx");
  789. }
  790. if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
  791. SanArgs.linkRuntimes()) {
  792. StaticRuntimes.push_back("tsan");
  793. if (SanArgs.linkCXXRuntimes())
  794. StaticRuntimes.push_back("tsan_cxx");
  795. }
  796. if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
  797. if (SanArgs.requiresMinimalRuntime()) {
  798. StaticRuntimes.push_back("ubsan_minimal");
  799. } else {
  800. StaticRuntimes.push_back("ubsan_standalone");
  801. if (SanArgs.linkCXXRuntimes())
  802. StaticRuntimes.push_back("ubsan_standalone_cxx");
  803. }
  804. }
  805. if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
  806. NonWholeStaticRuntimes.push_back("safestack");
  807. RequiredSymbols.push_back("__safestack_init");
  808. }
  809. if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
  810. if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
  811. StaticRuntimes.push_back("cfi");
  812. if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
  813. StaticRuntimes.push_back("cfi_diag");
  814. if (SanArgs.linkCXXRuntimes())
  815. StaticRuntimes.push_back("ubsan_standalone_cxx");
  816. }
  817. }
  818. if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
  819. NonWholeStaticRuntimes.push_back("stats");
  820. RequiredSymbols.push_back("__sanitizer_stats_register");
  821. }
  822. if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
  823. if (SanArgs.requiresMinimalRuntime()) {
  824. StaticRuntimes.push_back("scudo_minimal");
  825. if (SanArgs.linkCXXRuntimes())
  826. StaticRuntimes.push_back("scudo_cxx_minimal");
  827. } else {
  828. StaticRuntimes.push_back("scudo");
  829. if (SanArgs.linkCXXRuntimes())
  830. StaticRuntimes.push_back("scudo_cxx");
  831. }
  832. }
  833. }
  834. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  835. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  836. bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  837. ArgStringList &CmdArgs) {
  838. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  839. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  840. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  841. NonWholeStaticRuntimes, HelperStaticRuntimes,
  842. RequiredSymbols);
  843. const SanitizerArgs &SanArgs = TC.getSanitizerArgs(Args);
  844. // Inject libfuzzer dependencies.
  845. if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
  846. !Args.hasArg(options::OPT_shared)) {
  847. addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
  848. if (SanArgs.needsFuzzerInterceptors())
  849. addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
  850. true);
  851. if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
  852. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  853. !Args.hasArg(options::OPT_static);
  854. if (OnlyLibstdcxxStatic)
  855. CmdArgs.push_back("-Bstatic");
  856. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  857. if (OnlyLibstdcxxStatic)
  858. CmdArgs.push_back("-Bdynamic");
  859. }
  860. }
  861. for (auto RT : SharedRuntimes)
  862. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  863. for (auto RT : HelperStaticRuntimes)
  864. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  865. bool AddExportDynamic = false;
  866. for (auto RT : StaticRuntimes) {
  867. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  868. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  869. }
  870. for (auto RT : NonWholeStaticRuntimes) {
  871. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  872. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  873. }
  874. for (auto S : RequiredSymbols) {
  875. CmdArgs.push_back("-u");
  876. CmdArgs.push_back(Args.MakeArgString(S));
  877. }
  878. // If there is a static runtime with no dynamic list, force all the symbols
  879. // to be dynamic to be sure we export sanitizer interface functions.
  880. if (AddExportDynamic)
  881. CmdArgs.push_back("--export-dynamic");
  882. if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
  883. CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
  884. return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
  885. }
  886. bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
  887. if (Args.hasArg(options::OPT_shared))
  888. return false;
  889. if (TC.getXRayArgs().needsXRayRt()) {
  890. CmdArgs.push_back("-whole-archive");
  891. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
  892. for (const auto &Mode : TC.getXRayArgs().modeList())
  893. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
  894. CmdArgs.push_back("-no-whole-archive");
  895. return true;
  896. }
  897. return false;
  898. }
  899. void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
  900. CmdArgs.push_back(getAsNeededOption(TC, false));
  901. CmdArgs.push_back("-lpthread");
  902. if (!TC.getTriple().isOSOpenBSD())
  903. CmdArgs.push_back("-lrt");
  904. CmdArgs.push_back("-lm");
  905. if (!TC.getTriple().isOSFreeBSD() &&
  906. !TC.getTriple().isOSNetBSD() &&
  907. !TC.getTriple().isOSOpenBSD())
  908. CmdArgs.push_back("-ldl");
  909. }
  910. bool tools::areOptimizationsEnabled(const ArgList &Args) {
  911. // Find the last -O arg and see if it is non-zero.
  912. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  913. return !A->getOption().matches(options::OPT_O0);
  914. // Defaults to -O0.
  915. return false;
  916. }
  917. const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
  918. const InputInfo &Input,
  919. const InputInfo &Output) {
  920. auto AddPostfix = [JA](auto &F) {
  921. if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
  922. F += (Twine("_") + JA.getOffloadingArch()).str();
  923. F += ".dwo";
  924. };
  925. if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
  926. if (StringRef(A->getValue()) == "single")
  927. return Args.MakeArgString(Output.getFilename());
  928. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  929. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  930. SmallString<128> T(FinalOutput->getValue());
  931. llvm::sys::path::remove_filename(T);
  932. llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
  933. AddPostfix(T);
  934. return Args.MakeArgString(T);
  935. } else {
  936. // Use the compilation dir.
  937. Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
  938. options::OPT_fdebug_compilation_dir_EQ);
  939. SmallString<128> T(A ? A->getValue() : "");
  940. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  941. AddPostfix(F);
  942. T += F;
  943. return Args.MakeArgString(T);
  944. }
  945. }
  946. void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  947. const JobAction &JA, const ArgList &Args,
  948. const InputInfo &Output, const char *OutFile) {
  949. ArgStringList ExtractArgs;
  950. ExtractArgs.push_back("--extract-dwo");
  951. ArgStringList StripArgs;
  952. StripArgs.push_back("--strip-dwo");
  953. // Grabbing the output of the earlier compile step.
  954. StripArgs.push_back(Output.getFilename());
  955. ExtractArgs.push_back(Output.getFilename());
  956. ExtractArgs.push_back(OutFile);
  957. const char *Exec =
  958. Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
  959. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  960. // First extract the dwo sections.
  961. C.addCommand(std::make_unique<Command>(JA, T,
  962. ResponseFileSupport::AtFileCurCP(),
  963. Exec, ExtractArgs, II, Output));
  964. // Then remove them from the original .o file.
  965. C.addCommand(std::make_unique<Command>(
  966. JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
  967. }
  968. // Claim options we don't want to warn if they are unused. We do this for
  969. // options that build systems might add but are unused when assembling or only
  970. // running the preprocessor for example.
  971. void tools::claimNoWarnArgs(const ArgList &Args) {
  972. // Don't warn about unused -f(no-)?lto. This can happen when we're
  973. // preprocessing, precompiling or assembling.
  974. Args.ClaimAllArgs(options::OPT_flto_EQ);
  975. Args.ClaimAllArgs(options::OPT_flto);
  976. Args.ClaimAllArgs(options::OPT_fno_lto);
  977. }
  978. Arg *tools::getLastProfileUseArg(const ArgList &Args) {
  979. auto *ProfileUseArg = Args.getLastArg(
  980. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  981. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  982. options::OPT_fno_profile_instr_use);
  983. if (ProfileUseArg &&
  984. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  985. ProfileUseArg = nullptr;
  986. return ProfileUseArg;
  987. }
  988. Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
  989. auto *ProfileSampleUseArg = Args.getLastArg(
  990. options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
  991. options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
  992. options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
  993. if (ProfileSampleUseArg &&
  994. (ProfileSampleUseArg->getOption().matches(
  995. options::OPT_fno_profile_sample_use) ||
  996. ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
  997. return nullptr;
  998. return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
  999. options::OPT_fauto_profile_EQ);
  1000. }
  1001. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  1002. /// smooshes them together with platform defaults, to decide whether
  1003. /// this compile should be using PIC mode or not. Returns a tuple of
  1004. /// (RelocationModel, PICLevel, IsPIE).
  1005. std::tuple<llvm::Reloc::Model, unsigned, bool>
  1006. tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
  1007. const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
  1008. const llvm::Triple &Triple = ToolChain.getTriple();
  1009. bool PIE = ToolChain.isPIEDefault(Args);
  1010. bool PIC = PIE || ToolChain.isPICDefault();
  1011. // The Darwin/MachO default to use PIC does not apply when using -static.
  1012. if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
  1013. PIE = PIC = false;
  1014. bool IsPICLevelTwo = PIC;
  1015. bool KernelOrKext =
  1016. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  1017. // Android-specific defaults for PIC/PIE
  1018. if (Triple.isAndroid()) {
  1019. switch (Triple.getArch()) {
  1020. case llvm::Triple::arm:
  1021. case llvm::Triple::armeb:
  1022. case llvm::Triple::thumb:
  1023. case llvm::Triple::thumbeb:
  1024. case llvm::Triple::aarch64:
  1025. case llvm::Triple::mips:
  1026. case llvm::Triple::mipsel:
  1027. case llvm::Triple::mips64:
  1028. case llvm::Triple::mips64el:
  1029. PIC = true; // "-fpic"
  1030. break;
  1031. case llvm::Triple::x86:
  1032. case llvm::Triple::x86_64:
  1033. PIC = true; // "-fPIC"
  1034. IsPICLevelTwo = true;
  1035. break;
  1036. default:
  1037. break;
  1038. }
  1039. }
  1040. // OpenBSD-specific defaults for PIE
  1041. if (Triple.isOSOpenBSD()) {
  1042. switch (ToolChain.getArch()) {
  1043. case llvm::Triple::arm:
  1044. case llvm::Triple::aarch64:
  1045. case llvm::Triple::mips64:
  1046. case llvm::Triple::mips64el:
  1047. case llvm::Triple::x86:
  1048. case llvm::Triple::x86_64:
  1049. IsPICLevelTwo = false; // "-fpie"
  1050. break;
  1051. case llvm::Triple::ppc:
  1052. case llvm::Triple::sparcv9:
  1053. IsPICLevelTwo = true; // "-fPIE"
  1054. break;
  1055. default:
  1056. break;
  1057. }
  1058. }
  1059. // AMDGPU-specific defaults for PIC.
  1060. if (Triple.getArch() == llvm::Triple::amdgcn)
  1061. PIC = true;
  1062. // The last argument relating to either PIC or PIE wins, and no
  1063. // other argument is used. If the last argument is any flavor of the
  1064. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  1065. // option implicitly enables PIC at the same level.
  1066. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  1067. options::OPT_fpic, options::OPT_fno_pic,
  1068. options::OPT_fPIE, options::OPT_fno_PIE,
  1069. options::OPT_fpie, options::OPT_fno_pie);
  1070. if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg &&
  1071. LastPICArg == Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
  1072. options::OPT_fPIE, options::OPT_fpie)) {
  1073. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  1074. << LastPICArg->getSpelling() << Triple.str();
  1075. if (Triple.getArch() == llvm::Triple::x86_64)
  1076. return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
  1077. return std::make_tuple(llvm::Reloc::Static, 0U, false);
  1078. }
  1079. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  1080. // is forced, then neither PIC nor PIE flags will have no effect.
  1081. if (!ToolChain.isPICDefaultForced()) {
  1082. if (LastPICArg) {
  1083. Option O = LastPICArg->getOption();
  1084. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  1085. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  1086. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  1087. PIC =
  1088. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  1089. IsPICLevelTwo =
  1090. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  1091. } else {
  1092. PIE = PIC = false;
  1093. if (EffectiveTriple.isPS4CPU()) {
  1094. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  1095. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  1096. if (Model != "kernel") {
  1097. PIC = true;
  1098. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  1099. << LastPICArg->getSpelling();
  1100. }
  1101. }
  1102. }
  1103. }
  1104. }
  1105. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  1106. // PIC level would've been set to level 1, force it back to level 2 PIC
  1107. // instead.
  1108. if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
  1109. IsPICLevelTwo |= ToolChain.isPICDefault();
  1110. // This kernel flags are a trump-card: they will disable PIC/PIE
  1111. // generation, independent of the argument order.
  1112. if (KernelOrKext &&
  1113. ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
  1114. !EffectiveTriple.isWatchOS()))
  1115. PIC = PIE = false;
  1116. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  1117. // This is a very special mode. It trumps the other modes, almost no one
  1118. // uses it, and it isn't even valid on any OS but Darwin.
  1119. if (!Triple.isOSDarwin())
  1120. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  1121. << A->getSpelling() << Triple.str();
  1122. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  1123. // Only a forced PIC mode can cause the actual compile to have PIC defines
  1124. // etc., no flags are sufficient. This behavior was selected to closely
  1125. // match that of llvm-gcc and Apple GCC before that.
  1126. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  1127. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
  1128. }
  1129. bool EmbeddedPISupported;
  1130. switch (Triple.getArch()) {
  1131. case llvm::Triple::arm:
  1132. case llvm::Triple::armeb:
  1133. case llvm::Triple::thumb:
  1134. case llvm::Triple::thumbeb:
  1135. EmbeddedPISupported = true;
  1136. break;
  1137. default:
  1138. EmbeddedPISupported = false;
  1139. break;
  1140. }
  1141. bool ROPI = false, RWPI = false;
  1142. Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
  1143. if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
  1144. if (!EmbeddedPISupported)
  1145. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  1146. << LastROPIArg->getSpelling() << Triple.str();
  1147. ROPI = true;
  1148. }
  1149. Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
  1150. if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
  1151. if (!EmbeddedPISupported)
  1152. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  1153. << LastRWPIArg->getSpelling() << Triple.str();
  1154. RWPI = true;
  1155. }
  1156. // ROPI and RWPI are not compatible with PIC or PIE.
  1157. if ((ROPI || RWPI) && (PIC || PIE))
  1158. ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
  1159. if (Triple.isMIPS()) {
  1160. StringRef CPUName;
  1161. StringRef ABIName;
  1162. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1163. // When targeting the N64 ABI, PIC is the default, except in the case
  1164. // when the -mno-abicalls option is used. In that case we exit
  1165. // at next check regardless of PIC being set below.
  1166. if (ABIName == "n64")
  1167. PIC = true;
  1168. // When targettng MIPS with -mno-abicalls, it's always static.
  1169. if(Args.hasArg(options::OPT_mno_abicalls))
  1170. return std::make_tuple(llvm::Reloc::Static, 0U, false);
  1171. // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
  1172. // does not use PIC level 2 for historical reasons.
  1173. IsPICLevelTwo = false;
  1174. }
  1175. if (PIC)
  1176. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
  1177. llvm::Reloc::Model RelocM = llvm::Reloc::Static;
  1178. if (ROPI && RWPI)
  1179. RelocM = llvm::Reloc::ROPI_RWPI;
  1180. else if (ROPI)
  1181. RelocM = llvm::Reloc::ROPI;
  1182. else if (RWPI)
  1183. RelocM = llvm::Reloc::RWPI;
  1184. return std::make_tuple(RelocM, 0U, false);
  1185. }
  1186. // `-falign-functions` indicates that the functions should be aligned to a
  1187. // 16-byte boundary.
  1188. //
  1189. // `-falign-functions=1` is the same as `-fno-align-functions`.
  1190. //
  1191. // The scalar `n` in `-falign-functions=n` must be an integral value between
  1192. // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
  1193. // the nearest power-of-two.
  1194. //
  1195. // If we return `0`, the frontend will default to the backend's preferred
  1196. // alignment.
  1197. //
  1198. // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
  1199. // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
  1200. // alignment. For unaligned functions, we default to the backend's preferred
  1201. // alignment.
  1202. unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
  1203. const ArgList &Args) {
  1204. const Arg *A = Args.getLastArg(options::OPT_falign_functions,
  1205. options::OPT_falign_functions_EQ,
  1206. options::OPT_fno_align_functions);
  1207. if (!A || A->getOption().matches(options::OPT_fno_align_functions))
  1208. return 0;
  1209. if (A->getOption().matches(options::OPT_falign_functions))
  1210. return 0;
  1211. unsigned Value = 0;
  1212. if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
  1213. TC.getDriver().Diag(diag::err_drv_invalid_int_value)
  1214. << A->getAsString(Args) << A->getValue();
  1215. return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
  1216. }
  1217. unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
  1218. const ArgList &Args) {
  1219. const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
  1220. if (!A)
  1221. return 0;
  1222. unsigned Value = 0;
  1223. if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
  1224. Value < 2)
  1225. TC.getDriver().Diag(diag::err_drv_invalid_int_value)
  1226. << A->getAsString(Args) << A->getValue();
  1227. return Value;
  1228. }
  1229. void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  1230. ArgStringList &CmdArgs) {
  1231. llvm::Reloc::Model RelocationModel;
  1232. unsigned PICLevel;
  1233. bool IsPIE;
  1234. std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
  1235. if (RelocationModel != llvm::Reloc::Static)
  1236. CmdArgs.push_back("-KPIC");
  1237. }
  1238. /// Determine whether Objective-C automated reference counting is
  1239. /// enabled.
  1240. bool tools::isObjCAutoRefCount(const ArgList &Args) {
  1241. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  1242. }
  1243. enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
  1244. static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
  1245. const ArgList &Args) {
  1246. if (Args.hasArg(options::OPT_static_libgcc) ||
  1247. Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
  1248. return LibGccType::StaticLibGcc;
  1249. if (Args.hasArg(options::OPT_shared_libgcc))
  1250. return LibGccType::SharedLibGcc;
  1251. // The Android NDK only provides libunwind.a, not libunwind.so.
  1252. if (TC.getTriple().isAndroid())
  1253. return LibGccType::StaticLibGcc;
  1254. // For MinGW, don't imply a shared libgcc here, we only want to return
  1255. // SharedLibGcc if that was explicitly requested.
  1256. if (D.CCCIsCXX() && !TC.getTriple().isOSCygMing())
  1257. return LibGccType::SharedLibGcc;
  1258. return LibGccType::UnspecifiedLibGcc;
  1259. }
  1260. // Gcc adds libgcc arguments in various ways:
  1261. //
  1262. // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
  1263. // g++ <none>: -lgcc_s -lgcc
  1264. // gcc shared: -lgcc_s -lgcc
  1265. // g++ shared: -lgcc_s -lgcc
  1266. // gcc static: -lgcc -lgcc_eh
  1267. // g++ static: -lgcc -lgcc_eh
  1268. // gcc static-pie: -lgcc -lgcc_eh
  1269. // g++ static-pie: -lgcc -lgcc_eh
  1270. //
  1271. // Also, certain targets need additional adjustments.
  1272. static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
  1273. ArgStringList &CmdArgs, const ArgList &Args) {
  1274. ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
  1275. // Targets that don't use unwind libraries.
  1276. if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
  1277. TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
  1278. UNW == ToolChain::UNW_None)
  1279. return;
  1280. LibGccType LGT = getLibGccType(TC, D, Args);
  1281. bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
  1282. !TC.getTriple().isAndroid() &&
  1283. !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
  1284. if (AsNeeded)
  1285. CmdArgs.push_back(getAsNeededOption(TC, true));
  1286. switch (UNW) {
  1287. case ToolChain::UNW_None:
  1288. return;
  1289. case ToolChain::UNW_Libgcc: {
  1290. if (LGT == LibGccType::StaticLibGcc)
  1291. CmdArgs.push_back("-lgcc_eh");
  1292. else
  1293. CmdArgs.push_back("-lgcc_s");
  1294. break;
  1295. }
  1296. case ToolChain::UNW_CompilerRT:
  1297. if (TC.getTriple().isOSAIX()) {
  1298. // AIX only has libunwind as a shared library. So do not pass
  1299. // anything in if -static is specified.
  1300. if (LGT != LibGccType::StaticLibGcc)
  1301. CmdArgs.push_back("-lunwind");
  1302. } else if (LGT == LibGccType::StaticLibGcc) {
  1303. CmdArgs.push_back("-l:libunwind.a");
  1304. } else if (TC.getTriple().isOSCygMing()) {
  1305. if (LGT == LibGccType::SharedLibGcc)
  1306. CmdArgs.push_back("-l:libunwind.dll.a");
  1307. else
  1308. // Let the linker choose between libunwind.dll.a and libunwind.a
  1309. // depending on what's available, and depending on the -static flag
  1310. CmdArgs.push_back("-lunwind");
  1311. } else {
  1312. CmdArgs.push_back("-l:libunwind.so");
  1313. }
  1314. break;
  1315. }
  1316. if (AsNeeded)
  1317. CmdArgs.push_back(getAsNeededOption(TC, false));
  1318. }
  1319. static void AddLibgcc(const ToolChain &TC, const Driver &D,
  1320. ArgStringList &CmdArgs, const ArgList &Args) {
  1321. LibGccType LGT = getLibGccType(TC, D, Args);
  1322. if (LGT != LibGccType::SharedLibGcc)
  1323. CmdArgs.push_back("-lgcc");
  1324. AddUnwindLibrary(TC, D, CmdArgs, Args);
  1325. if (LGT == LibGccType::SharedLibGcc)
  1326. CmdArgs.push_back("-lgcc");
  1327. }
  1328. void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  1329. ArgStringList &CmdArgs, const ArgList &Args) {
  1330. // Make use of compiler-rt if --rtlib option is used
  1331. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  1332. switch (RLT) {
  1333. case ToolChain::RLT_CompilerRT:
  1334. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  1335. AddUnwindLibrary(TC, D, CmdArgs, Args);
  1336. break;
  1337. case ToolChain::RLT_Libgcc:
  1338. // Make sure libgcc is not used under MSVC environment by default
  1339. if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
  1340. // Issue error diagnostic if libgcc is explicitly specified
  1341. // through command line as --rtlib option argument.
  1342. if (Args.hasArg(options::OPT_rtlib_EQ)) {
  1343. TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  1344. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
  1345. }
  1346. } else
  1347. AddLibgcc(TC, D, CmdArgs, Args);
  1348. break;
  1349. }
  1350. // On Android, the unwinder uses dl_iterate_phdr (or one of
  1351. // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
  1352. // statically-linked executables, these functions come from libc.a instead.
  1353. if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
  1354. !Args.hasArg(options::OPT_static_pie))
  1355. CmdArgs.push_back("-ldl");
  1356. }
  1357. SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
  1358. const InputInfo &Output,
  1359. const InputInfo &Input,
  1360. const Driver &D) {
  1361. const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
  1362. if (!A)
  1363. return {};
  1364. StringRef SaveStats = A->getValue();
  1365. SmallString<128> StatsFile;
  1366. if (SaveStats == "obj" && Output.isFilename()) {
  1367. StatsFile.assign(Output.getFilename());
  1368. llvm::sys::path::remove_filename(StatsFile);
  1369. } else if (SaveStats != "cwd") {
  1370. D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
  1371. return {};
  1372. }
  1373. StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
  1374. llvm::sys::path::append(StatsFile, BaseName);
  1375. llvm::sys::path::replace_extension(StatsFile, "stats");
  1376. return StatsFile;
  1377. }
  1378. void tools::addMultilibFlag(bool Enabled, const char *const Flag,
  1379. Multilib::flags_list &Flags) {
  1380. Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
  1381. }
  1382. void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
  1383. ArgStringList &CmdArgs, bool IsLTO) {
  1384. auto addArg = [&, IsLTO](const Twine &Arg) {
  1385. if (IsLTO) {
  1386. CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
  1387. } else {
  1388. CmdArgs.push_back("-mllvm");
  1389. CmdArgs.push_back(Args.MakeArgString(Arg));
  1390. }
  1391. };
  1392. if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
  1393. addArg(Twine("-x86-branches-within-32B-boundaries"));
  1394. }
  1395. if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
  1396. StringRef Value = A->getValue();
  1397. unsigned Boundary;
  1398. if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
  1399. !llvm::isPowerOf2_64(Boundary)) {
  1400. D.Diag(diag::err_drv_invalid_argument_to_option)
  1401. << Value << A->getOption().getName();
  1402. } else {
  1403. addArg("-x86-align-branch-boundary=" + Twine(Boundary));
  1404. }
  1405. }
  1406. if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
  1407. std::string AlignBranch;
  1408. for (StringRef T : A->getValues()) {
  1409. if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
  1410. T != "ret" && T != "indirect")
  1411. D.Diag(diag::err_drv_invalid_malign_branch_EQ)
  1412. << T << "fused, jcc, jmp, call, ret, indirect";
  1413. if (!AlignBranch.empty())
  1414. AlignBranch += '+';
  1415. AlignBranch += T;
  1416. }
  1417. addArg("-x86-align-branch=" + Twine(AlignBranch));
  1418. }
  1419. if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
  1420. StringRef Value = A->getValue();
  1421. unsigned PrefixSize;
  1422. if (Value.getAsInteger(10, PrefixSize)) {
  1423. D.Diag(diag::err_drv_invalid_argument_to_option)
  1424. << Value << A->getOption().getName();
  1425. } else {
  1426. addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
  1427. }
  1428. }
  1429. }
  1430. /// SDLSearch: Search for Static Device Library
  1431. /// The search for SDL bitcode files is consistent with how static host
  1432. /// libraries are discovered. That is, the -l option triggers a search for
  1433. /// files in a set of directories called the LINKPATH. The host library search
  1434. /// procedure looks for a specific filename in the LINKPATH. The filename for
  1435. /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an
  1436. /// ordered-set of filenames that are searched. We call this ordered-set of
  1437. /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific,
  1438. /// architecture specific, or generic across all architectures, a naming
  1439. /// convention and search order is used where the file name embeds the
  1440. /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type
  1441. /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of
  1442. /// device-independent SDLs. To reduce congestion in host library directories,
  1443. /// the search first looks for files in the “libdevice” subdirectory. SDLs that
  1444. /// are bc files begin with the prefix “lib”.
  1445. ///
  1446. /// Machine-code SDLs can also be managed as an archive (*.a file). The
  1447. /// convention has been to use the prefix “lib”. To avoid confusion with host
  1448. /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives.
  1449. ///
  1450. bool tools::SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs,
  1451. llvm::opt::ArgStringList &CC1Args,
  1452. SmallVector<std::string, 8> LibraryPaths, std::string Lib,
  1453. StringRef Arch, StringRef Target, bool isBitCodeSDL,
  1454. bool postClangLink) {
  1455. SmallVector<std::string, 12> SDLs;
  1456. std::string LibDeviceLoc = "/libdevice";
  1457. std::string LibBcPrefix = "/libbc-";
  1458. std::string LibPrefix = "/lib";
  1459. if (isBitCodeSDL) {
  1460. // SEARCH-ORDER for Bitcode SDLs:
  1461. // libdevice/libbc-<libname>-<arch-name>-<device-type>.a
  1462. // libbc-<libname>-<arch-name>-<device-type>.a
  1463. // libdevice/libbc-<libname>-<arch-name>.a
  1464. // libbc-<libname>-<arch-name>.a
  1465. // libdevice/libbc-<libname>.a
  1466. // libbc-<libname>.a
  1467. // libdevice/lib<libname>-<arch-name>-<device-type>.bc
  1468. // lib<libname>-<arch-name>-<device-type>.bc
  1469. // libdevice/lib<libname>-<arch-name>.bc
  1470. // lib<libname>-<arch-name>.bc
  1471. // libdevice/lib<libname>.bc
  1472. // lib<libname>.bc
  1473. for (StringRef Base : {LibBcPrefix, LibPrefix}) {
  1474. const auto *Ext = Base.contains(LibBcPrefix) ? ".a" : ".bc";
  1475. for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
  1476. Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) {
  1477. SDLs.push_back(Twine(LibDeviceLoc + Base + Suffix + Ext).str());
  1478. SDLs.push_back(Twine(Base + Suffix + Ext).str());
  1479. }
  1480. }
  1481. } else {
  1482. // SEARCH-ORDER for Machine-code SDLs:
  1483. // libdevice/lib<libname>-<arch-name>-<device-type>.a
  1484. // lib<libname>-<arch-name>-<device-type>.a
  1485. // libdevice/lib<libname>-<arch-name>.a
  1486. // lib<libname>-<arch-name>.a
  1487. const auto *Ext = ".a";
  1488. for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(),
  1489. Twine(Lib + "-" + Arch).str()}) {
  1490. SDLs.push_back(Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str());
  1491. SDLs.push_back(Twine(LibPrefix + Suffix + Ext).str());
  1492. }
  1493. }
  1494. // The CUDA toolchain does not use a global device llvm-link before the LLVM
  1495. // backend generates ptx. So currently, the use of bitcode SDL for nvptx is
  1496. // only possible with post-clang-cc1 linking. Clang cc1 has a feature that
  1497. // will link libraries after clang compilation while the LLVM IR is still in
  1498. // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”.
  1499. // This is a clang -cc1 option that is generated by the clang driver. The
  1500. // option value must a full path to an existing file.
  1501. bool FoundSDL = false;
  1502. for (auto LPath : LibraryPaths) {
  1503. for (auto SDL : SDLs) {
  1504. auto FullName = Twine(LPath + SDL).str();
  1505. if (llvm::sys::fs::exists(FullName)) {
  1506. if (postClangLink)
  1507. CC1Args.push_back("-mlink-builtin-bitcode");
  1508. CC1Args.push_back(DriverArgs.MakeArgString(FullName));
  1509. FoundSDL = true;
  1510. break;
  1511. }
  1512. }
  1513. if (FoundSDL)
  1514. break;
  1515. }
  1516. return FoundSDL;
  1517. }
  1518. /// Search if a user provided archive file lib<libname>.a exists in any of
  1519. /// the library paths. If so, add a new command to clang-offload-bundler to
  1520. /// unbundle this archive and create a temporary device specific archive. Name
  1521. /// of this SDL is passed to the llvm-link (for amdgcn) or to the
  1522. /// clang-nvlink-wrapper (for nvptx) commands by the driver.
  1523. bool tools::GetSDLFromOffloadArchive(
  1524. Compilation &C, const Driver &D, const Tool &T, const JobAction &JA,
  1525. const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs,
  1526. llvm::opt::ArgStringList &CC1Args, SmallVector<std::string, 8> LibraryPaths,
  1527. StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
  1528. bool postClangLink) {
  1529. // We don't support bitcode archive bundles for nvptx
  1530. if (isBitCodeSDL && Arch.contains("nvptx"))
  1531. return false;
  1532. bool FoundAOB = false;
  1533. SmallVector<std::string, 2> AOBFileNames;
  1534. std::string ArchiveOfBundles;
  1535. for (auto LPath : LibraryPaths) {
  1536. ArchiveOfBundles.clear();
  1537. AOBFileNames.push_back(Twine(LPath + "/libdevice/lib" + Lib + ".a").str());
  1538. AOBFileNames.push_back(Twine(LPath + "/lib" + Lib + ".a").str());
  1539. for (auto AOB : AOBFileNames) {
  1540. if (llvm::sys::fs::exists(AOB)) {
  1541. ArchiveOfBundles = AOB;
  1542. FoundAOB = true;
  1543. break;
  1544. }
  1545. }
  1546. if (!FoundAOB)
  1547. continue;
  1548. StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib";
  1549. std::string OutputLib = D.GetTemporaryPath(
  1550. Twine(Prefix + Lib + "-" + Arch + "-" + Target).str(), "a");
  1551. C.addTempFile(C.getArgs().MakeArgString(OutputLib));
  1552. ArgStringList CmdArgs;
  1553. SmallString<128> DeviceTriple;
  1554. DeviceTriple += Action::GetOffloadKindName(JA.getOffloadingDeviceKind());
  1555. DeviceTriple += '-';
  1556. std::string NormalizedTriple = T.getToolChain().getTriple().normalize();
  1557. DeviceTriple += NormalizedTriple;
  1558. if (!Target.empty()) {
  1559. DeviceTriple += '-';
  1560. DeviceTriple += Target;
  1561. }
  1562. std::string UnbundleArg("-unbundle");
  1563. std::string TypeArg("-type=a");
  1564. std::string InputArg("-inputs=" + ArchiveOfBundles);
  1565. std::string OffloadArg("-targets=" + std::string(DeviceTriple));
  1566. std::string OutputArg("-outputs=" + OutputLib);
  1567. const char *UBProgram = DriverArgs.MakeArgString(
  1568. T.getToolChain().GetProgramPath("clang-offload-bundler"));
  1569. ArgStringList UBArgs;
  1570. UBArgs.push_back(C.getArgs().MakeArgString(UnbundleArg));
  1571. UBArgs.push_back(C.getArgs().MakeArgString(TypeArg));
  1572. UBArgs.push_back(C.getArgs().MakeArgString(InputArg));
  1573. UBArgs.push_back(C.getArgs().MakeArgString(OffloadArg));
  1574. UBArgs.push_back(C.getArgs().MakeArgString(OutputArg));
  1575. // Add this flag to not exit from clang-offload-bundler if no compatible
  1576. // code object is found in heterogenous archive library.
  1577. std::string AdditionalArgs("-allow-missing-bundles");
  1578. UBArgs.push_back(C.getArgs().MakeArgString(AdditionalArgs));
  1579. C.addCommand(std::make_unique<Command>(
  1580. JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
  1581. InputInfo(&JA, C.getArgs().MakeArgString(OutputLib))));
  1582. if (postClangLink)
  1583. CC1Args.push_back("-mlink-builtin-bitcode");
  1584. CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
  1585. break;
  1586. }
  1587. return FoundAOB;
  1588. }
  1589. // Wrapper function used by driver for adding SDLs during link phase.
  1590. void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T,
  1591. const JobAction &JA,
  1592. const InputInfoList &Inputs,
  1593. const llvm::opt::ArgList &DriverArgs,
  1594. llvm::opt::ArgStringList &CC1Args,
  1595. StringRef Arch, StringRef Target,
  1596. bool isBitCodeSDL, bool postClangLink) {
  1597. AddStaticDeviceLibs(&C, &T, &JA, &Inputs, C.getDriver(), DriverArgs, CC1Args,
  1598. Arch, Target, isBitCodeSDL, postClangLink);
  1599. }
  1600. // Wrapper function used for post clang linking of bitcode SDLS for nvptx by
  1601. // the CUDA toolchain.
  1602. void tools::AddStaticDeviceLibsPostLinking(const Driver &D,
  1603. const llvm::opt::ArgList &DriverArgs,
  1604. llvm::opt::ArgStringList &CC1Args,
  1605. StringRef Arch, StringRef Target,
  1606. bool isBitCodeSDL, bool postClangLink) {
  1607. AddStaticDeviceLibs(nullptr, nullptr, nullptr, nullptr, D, DriverArgs,
  1608. CC1Args, Arch, Target, isBitCodeSDL, postClangLink);
  1609. }
  1610. // User defined Static Device Libraries(SDLs) can be passed to clang for
  1611. // offloading GPU compilers. Like static host libraries, the use of a SDL is
  1612. // specified with the -l command line option. The primary difference between
  1613. // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs
  1614. // and SEARCH-ORDER for Machine-code SDLs for the naming convention).
  1615. // SDLs are of following types:
  1616. //
  1617. // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files.
  1618. // For NVPTX, these libraries are post-clang linked following each
  1619. // compilation. For AMDGPU, these libraries are linked one time
  1620. // during the application link phase.
  1621. //
  1622. // * Machine-code SDLs: They are archive files. For NVPTX, the archive members
  1623. // contain cubin for Nvidia GPUs and are linked one time during the
  1624. // link phase by the CUDA SDK linker called nvlink. For AMDGPU, the
  1625. // process for machine code SDLs is still in development. But they
  1626. // will be linked by the LLVM tool lld.
  1627. //
  1628. // * Bundled objects that contain both host and device codes: Bundled objects
  1629. // may also contain library code compiled from source. For NVPTX, the
  1630. // bundle contains cubin. For AMDGPU, the bundle contains bitcode.
  1631. //
  1632. // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the
  1633. // inclusion of specific SDLs such as math libraries and the OpenMP device
  1634. // library libomptarget.
  1635. void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T,
  1636. const JobAction *JA,
  1637. const InputInfoList *Inputs, const Driver &D,
  1638. const llvm::opt::ArgList &DriverArgs,
  1639. llvm::opt::ArgStringList &CC1Args,
  1640. StringRef Arch, StringRef Target,
  1641. bool isBitCodeSDL, bool postClangLink) {
  1642. SmallVector<std::string, 8> LibraryPaths;
  1643. // Add search directories from LIBRARY_PATH env variable
  1644. llvm::Optional<std::string> LibPath =
  1645. llvm::sys::Process::GetEnv("LIBRARY_PATH");
  1646. if (LibPath) {
  1647. SmallVector<StringRef, 8> Frags;
  1648. const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
  1649. llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
  1650. for (StringRef Path : Frags)
  1651. LibraryPaths.emplace_back(Path.trim());
  1652. }
  1653. // Add directories from user-specified -L options
  1654. for (std::string Search_Dir : DriverArgs.getAllArgValues(options::OPT_L))
  1655. LibraryPaths.emplace_back(Search_Dir);
  1656. // Add path to lib-debug folders
  1657. SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
  1658. llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
  1659. LibraryPaths.emplace_back(DefaultLibPath.c_str());
  1660. // Build list of Static Device Libraries SDLs specified by -l option
  1661. llvm::SmallSet<std::string, 16> SDLNames;
  1662. static const StringRef HostOnlyArchives[] = {
  1663. "omp", "cudart", "m", "gcc", "gcc_s", "pthread", "hip_hcc"};
  1664. for (auto SDLName : DriverArgs.getAllArgValues(options::OPT_l)) {
  1665. if (!HostOnlyArchives->contains(SDLName)) {
  1666. SDLNames.insert(SDLName);
  1667. }
  1668. }
  1669. // The search stops as soon as an SDL file is found. The driver then provides
  1670. // the full filename of the SDL to the llvm-link or clang-nvlink-wrapper
  1671. // command. If no SDL is found after searching each LINKPATH with
  1672. // SEARCH-ORDER, it is possible that an archive file lib<libname>.a exists
  1673. // and may contain bundled object files.
  1674. for (auto SDLName : SDLNames) {
  1675. // This is the only call to SDLSearch
  1676. if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
  1677. isBitCodeSDL, postClangLink)) {
  1678. GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
  1679. LibraryPaths, SDLName, Arch, Target,
  1680. isBitCodeSDL, postClangLink);
  1681. }
  1682. }
  1683. }
  1684. static llvm::opt::Arg *
  1685. getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
  1686. // The last of -mcode-object-v3, -mno-code-object-v3 and
  1687. // -mcode-object-version=<version> wins.
  1688. return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
  1689. options::OPT_mno_code_object_v3_legacy,
  1690. options::OPT_mcode_object_version_EQ);
  1691. }
  1692. void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
  1693. const llvm::opt::ArgList &Args) {
  1694. const unsigned MinCodeObjVer = 2;
  1695. const unsigned MaxCodeObjVer = 4;
  1696. // Emit warnings for legacy options even if they are overridden.
  1697. if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
  1698. D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
  1699. << "-mcode-object-version=2";
  1700. if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
  1701. D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
  1702. << "-mcode-object-version=3";
  1703. if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
  1704. if (CodeObjArg->getOption().getID() ==
  1705. options::OPT_mcode_object_version_EQ) {
  1706. unsigned CodeObjVer = MaxCodeObjVer;
  1707. auto Remnant =
  1708. StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
  1709. if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
  1710. D.Diag(diag::err_drv_invalid_int_value)
  1711. << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
  1712. }
  1713. }
  1714. }
  1715. unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
  1716. const llvm::opt::ArgList &Args) {
  1717. unsigned CodeObjVer = 4; // default
  1718. if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
  1719. if (CodeObjArg->getOption().getID() ==
  1720. options::OPT_mno_code_object_v3_legacy) {
  1721. CodeObjVer = 2;
  1722. } else if (CodeObjArg->getOption().getID() ==
  1723. options::OPT_mcode_object_v3_legacy) {
  1724. CodeObjVer = 3;
  1725. } else {
  1726. StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
  1727. }
  1728. }
  1729. return CodeObjVer;
  1730. }
  1731. bool tools::haveAMDGPUCodeObjectVersionArgument(
  1732. const Driver &D, const llvm::opt::ArgList &Args) {
  1733. return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
  1734. }
  1735. void tools::addMachineOutlinerArgs(const Driver &D,
  1736. const llvm::opt::ArgList &Args,
  1737. llvm::opt::ArgStringList &CmdArgs,
  1738. const llvm::Triple &Triple, bool IsLTO) {
  1739. auto addArg = [&, IsLTO](const Twine &Arg) {
  1740. if (IsLTO) {
  1741. CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
  1742. } else {
  1743. CmdArgs.push_back("-mllvm");
  1744. CmdArgs.push_back(Args.MakeArgString(Arg));
  1745. }
  1746. };
  1747. if (Arg *A = Args.getLastArg(options::OPT_moutline,
  1748. options::OPT_mno_outline)) {
  1749. if (A->getOption().matches(options::OPT_moutline)) {
  1750. // We only support -moutline in AArch64 and ARM targets right now. If
  1751. // we're not compiling for these, emit a warning and ignore the flag.
  1752. // Otherwise, add the proper mllvm flags.
  1753. if (!(Triple.isARM() || Triple.isThumb() ||
  1754. Triple.getArch() == llvm::Triple::aarch64 ||
  1755. Triple.getArch() == llvm::Triple::aarch64_32)) {
  1756. D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
  1757. } else {
  1758. addArg(Twine("-enable-machine-outliner"));
  1759. }
  1760. } else {
  1761. // Disable all outlining behaviour.
  1762. addArg(Twine("-enable-machine-outliner=never"));
  1763. }
  1764. }
  1765. }
  1766. void tools::addOpenMPDeviceRTL(const Driver &D,
  1767. const llvm::opt::ArgList &DriverArgs,
  1768. llvm::opt::ArgStringList &CC1Args,
  1769. StringRef BitcodeSuffix,
  1770. const llvm::Triple &Triple) {
  1771. SmallVector<StringRef, 8> LibraryPaths;
  1772. // Add path to clang lib / lib64 folder.
  1773. SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
  1774. llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
  1775. LibraryPaths.emplace_back(DefaultLibPath.c_str());
  1776. // Add user defined library paths from LIBRARY_PATH.
  1777. llvm::Optional<std::string> LibPath =
  1778. llvm::sys::Process::GetEnv("LIBRARY_PATH");
  1779. if (LibPath) {
  1780. SmallVector<StringRef, 8> Frags;
  1781. const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
  1782. llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
  1783. for (StringRef Path : Frags)
  1784. LibraryPaths.emplace_back(Path.trim());
  1785. }
  1786. OptSpecifier LibomptargetBCPathOpt =
  1787. Triple.isAMDGCN() ? options::OPT_libomptarget_amdgcn_bc_path_EQ
  1788. : options::OPT_libomptarget_nvptx_bc_path_EQ;
  1789. StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgcn" : "nvptx";
  1790. std::string LibOmpTargetName = "libomptarget-" + BitcodeSuffix.str() + ".bc";
  1791. // First check whether user specifies bc library
  1792. if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
  1793. SmallString<128> LibOmpTargetFile(A->getValue());
  1794. if (llvm::sys::fs::exists(LibOmpTargetFile) &&
  1795. llvm::sys::fs::is_directory(LibOmpTargetFile)) {
  1796. llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
  1797. }
  1798. if (llvm::sys::fs::exists(LibOmpTargetFile)) {
  1799. CC1Args.push_back("-mlink-builtin-bitcode");
  1800. CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
  1801. } else {
  1802. D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
  1803. << LibOmpTargetFile;
  1804. }
  1805. } else {
  1806. bool FoundBCLibrary = false;
  1807. for (StringRef LibraryPath : LibraryPaths) {
  1808. SmallString<128> LibOmpTargetFile(LibraryPath);
  1809. llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
  1810. if (llvm::sys::fs::exists(LibOmpTargetFile)) {
  1811. CC1Args.push_back("-mlink-builtin-bitcode");
  1812. CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
  1813. FoundBCLibrary = true;
  1814. break;
  1815. }
  1816. }
  1817. if (!FoundBCLibrary)
  1818. D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
  1819. << LibOmpTargetName << ArchPrefix;
  1820. }
  1821. }