gold-plugin.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
  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. //
  9. // This is a gold plugin for LLVM. It provides an LLVM implementation of the
  10. // interface described in http://gcc.gnu.org/wiki/whopr/driver .
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/Bitcode/BitcodeReader.h"
  15. #include "llvm/Bitcode/BitcodeWriter.h"
  16. #include "llvm/CodeGen/CommandFlags.h"
  17. #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
  18. #include "llvm/Config/llvm-config.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DiagnosticPrinter.h"
  21. #include "llvm/LTO/LTO.h"
  22. #include "llvm/Object/Error.h"
  23. #include "llvm/Remarks/HotnessThresholdParser.h"
  24. #include "llvm/Support/CachePruning.h"
  25. #include "llvm/Support/Caching.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/FileSystem.h"
  28. #include "llvm/Support/Host.h"
  29. #include "llvm/Support/ManagedStatic.h"
  30. #include "llvm/Support/MemoryBuffer.h"
  31. #include "llvm/Support/Path.h"
  32. #include "llvm/Support/TargetSelect.h"
  33. #include "llvm/Support/Threading.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <list>
  36. #include <map>
  37. #include <plugin-api.h>
  38. #include <string>
  39. #include <system_error>
  40. #include <utility>
  41. #include <vector>
  42. // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
  43. // Precise and Debian Wheezy (binutils 2.23 is required)
  44. #define LDPO_PIE 3
  45. #define LDPT_GET_SYMBOLS_V3 28
  46. // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
  47. // required version.
  48. #define LDPT_GET_WRAP_SYMBOLS 32
  49. using namespace llvm;
  50. using namespace lto;
  51. static codegen::RegisterCodeGenFlags CodeGenFlags;
  52. // FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
  53. // required version.
  54. typedef enum ld_plugin_status (*ld_plugin_get_wrap_symbols)(
  55. uint64_t *num_symbols, const char ***wrap_symbol_list);
  56. static ld_plugin_status discard_message(int level, const char *format, ...) {
  57. // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
  58. // callback in the transfer vector. This should never be called.
  59. abort();
  60. }
  61. static ld_plugin_release_input_file release_input_file = nullptr;
  62. static ld_plugin_get_input_file get_input_file = nullptr;
  63. static ld_plugin_message message = discard_message;
  64. static ld_plugin_get_wrap_symbols get_wrap_symbols = nullptr;
  65. namespace {
  66. struct claimed_file {
  67. void *handle;
  68. void *leader_handle;
  69. std::vector<ld_plugin_symbol> syms;
  70. off_t filesize;
  71. std::string name;
  72. };
  73. /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
  74. struct PluginInputFile {
  75. void *Handle;
  76. std::unique_ptr<ld_plugin_input_file> File;
  77. PluginInputFile(void *Handle) : Handle(Handle) {
  78. File = std::make_unique<ld_plugin_input_file>();
  79. if (get_input_file(Handle, File.get()) != LDPS_OK)
  80. message(LDPL_FATAL, "Failed to get file information");
  81. }
  82. ~PluginInputFile() {
  83. // File would have been reset to nullptr if we moved this object
  84. // to a new owner.
  85. if (File)
  86. if (release_input_file(Handle) != LDPS_OK)
  87. message(LDPL_FATAL, "Failed to release file information");
  88. }
  89. ld_plugin_input_file &file() { return *File; }
  90. PluginInputFile(PluginInputFile &&RHS) = default;
  91. PluginInputFile &operator=(PluginInputFile &&RHS) = default;
  92. };
  93. struct ResolutionInfo {
  94. bool CanOmitFromDynSym = true;
  95. bool DefaultVisibility = true;
  96. bool CanInline = true;
  97. bool IsUsedInRegularObj = false;
  98. };
  99. }
  100. static ld_plugin_add_symbols add_symbols = nullptr;
  101. static ld_plugin_get_symbols get_symbols = nullptr;
  102. static ld_plugin_add_input_file add_input_file = nullptr;
  103. static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
  104. static ld_plugin_get_view get_view = nullptr;
  105. static bool IsExecutable = false;
  106. static bool SplitSections = true;
  107. static std::optional<Reloc::Model> RelocationModel;
  108. static std::string output_name = "";
  109. static std::list<claimed_file> Modules;
  110. static DenseMap<int, void *> FDToLeaderHandle;
  111. static StringMap<ResolutionInfo> ResInfo;
  112. static std::vector<std::string> Cleanup;
  113. namespace options {
  114. enum OutputType {
  115. OT_NORMAL,
  116. OT_DISABLE,
  117. OT_BC_ONLY,
  118. OT_ASM_ONLY,
  119. OT_SAVE_TEMPS
  120. };
  121. static OutputType TheOutputType = OT_NORMAL;
  122. static unsigned OptLevel = 2;
  123. // Currently only affects ThinLTO, where the default is the max cores in the
  124. // system. See llvm::get_threadpool_strategy() for acceptable values.
  125. static std::string Parallelism;
  126. // Default regular LTO codegen parallelism (number of partitions).
  127. static unsigned ParallelCodeGenParallelismLevel = 1;
  128. #ifdef NDEBUG
  129. static bool DisableVerify = true;
  130. #else
  131. static bool DisableVerify = false;
  132. #endif
  133. static std::string obj_path;
  134. static std::string extra_library_path;
  135. static std::string triple;
  136. static std::string mcpu;
  137. // When the thinlto plugin option is specified, only read the function
  138. // the information from intermediate files and write a combined
  139. // global index for the ThinLTO backends.
  140. static bool thinlto = false;
  141. // If false, all ThinLTO backend compilations through code gen are performed
  142. // using multiple threads in the gold-plugin, before handing control back to
  143. // gold. If true, write individual backend index files which reflect
  144. // the import decisions, and exit afterwards. The assumption is
  145. // that the build system will launch the backend processes.
  146. static bool thinlto_index_only = false;
  147. // If non-empty, holds the name of a file in which to write the list of
  148. // oject files gold selected for inclusion in the link after symbol
  149. // resolution (i.e. they had selected symbols). This will only be non-empty
  150. // in the thinlto_index_only case. It is used to identify files, which may
  151. // have originally been within archive libraries specified via
  152. // --start-lib/--end-lib pairs, that should be included in the final
  153. // native link process (since intervening function importing and inlining
  154. // may change the symbol resolution detected in the final link and which
  155. // files to include out of --start-lib/--end-lib libraries as a result).
  156. static std::string thinlto_linked_objects_file;
  157. // If true, when generating individual index files for distributed backends,
  158. // also generate a "${bitcodefile}.imports" file at the same location for each
  159. // bitcode file, listing the files it imports from in plain text. This is to
  160. // support distributed build file staging.
  161. static bool thinlto_emit_imports_files = false;
  162. // Option to control where files for a distributed backend (the individual
  163. // index files and optional imports files) are created.
  164. // If specified, expects a string of the form "oldprefix:newprefix", and
  165. // instead of generating these files in the same directory path as the
  166. // corresponding bitcode file, will use a path formed by replacing the
  167. // bitcode file's path prefix matching oldprefix with newprefix.
  168. static std::string thinlto_prefix_replace;
  169. // Option to control the name of modules encoded in the individual index
  170. // files for a distributed backend. This enables the use of minimized
  171. // bitcode files for the thin link, assuming the name of the full bitcode
  172. // file used in the backend differs just in some part of the file suffix.
  173. // If specified, expects a string of the form "oldsuffix:newsuffix".
  174. static std::string thinlto_object_suffix_replace;
  175. // Optional path to a directory for caching ThinLTO objects.
  176. static std::string cache_dir;
  177. // Optional pruning policy for ThinLTO caches.
  178. static std::string cache_policy;
  179. // Additional options to pass into the code generator.
  180. // Note: This array will contain all plugin options which are not claimed
  181. // as plugin exclusive to pass to the code generator.
  182. static std::vector<const char *> extra;
  183. // Sample profile file path
  184. static std::string sample_profile;
  185. // Debug new pass manager
  186. static bool debug_pass_manager = false;
  187. // Directory to store the .dwo files.
  188. static std::string dwo_dir;
  189. /// Statistics output filename.
  190. static std::string stats_file;
  191. // Asserts that LTO link has whole program visibility
  192. static bool whole_program_visibility = false;
  193. // Use opaque pointer types.
  194. static bool opaque_pointers = true;
  195. // Optimization remarks filename, accepted passes and hotness options
  196. static std::string RemarksFilename;
  197. static std::string RemarksPasses;
  198. static bool RemarksWithHotness = false;
  199. static std::optional<uint64_t> RemarksHotnessThreshold = 0;
  200. static std::string RemarksFormat;
  201. // Context sensitive PGO options.
  202. static std::string cs_profile_path;
  203. static bool cs_pgo_gen = false;
  204. static void process_plugin_option(const char *opt_)
  205. {
  206. if (opt_ == nullptr)
  207. return;
  208. llvm::StringRef opt = opt_;
  209. if (opt.consume_front("mcpu=")) {
  210. mcpu = std::string(opt);
  211. } else if (opt.consume_front("extra-library-path=")) {
  212. extra_library_path = std::string(opt);
  213. } else if (opt.consume_front("mtriple=")) {
  214. triple = std::string(opt);
  215. } else if (opt.consume_front("obj-path=")) {
  216. obj_path = std::string(opt);
  217. } else if (opt == "emit-llvm") {
  218. TheOutputType = OT_BC_ONLY;
  219. } else if (opt == "save-temps") {
  220. TheOutputType = OT_SAVE_TEMPS;
  221. } else if (opt == "disable-output") {
  222. TheOutputType = OT_DISABLE;
  223. } else if (opt == "emit-asm") {
  224. TheOutputType = OT_ASM_ONLY;
  225. } else if (opt == "thinlto") {
  226. thinlto = true;
  227. } else if (opt == "thinlto-index-only") {
  228. thinlto_index_only = true;
  229. } else if (opt.consume_front("thinlto-index-only=")) {
  230. thinlto_index_only = true;
  231. thinlto_linked_objects_file = std::string(opt);
  232. } else if (opt == "thinlto-emit-imports-files") {
  233. thinlto_emit_imports_files = true;
  234. } else if (opt.consume_front("thinlto-prefix-replace=")) {
  235. thinlto_prefix_replace = std::string(opt);
  236. if (thinlto_prefix_replace.find(';') == std::string::npos)
  237. message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
  238. } else if (opt.consume_front("thinlto-object-suffix-replace=")) {
  239. thinlto_object_suffix_replace = std::string(opt);
  240. if (thinlto_object_suffix_replace.find(';') == std::string::npos)
  241. message(LDPL_FATAL,
  242. "thinlto-object-suffix-replace expects 'old;new' format");
  243. } else if (opt.consume_front("cache-dir=")) {
  244. cache_dir = std::string(opt);
  245. } else if (opt.consume_front("cache-policy=")) {
  246. cache_policy = std::string(opt);
  247. } else if (opt.size() == 2 && opt[0] == 'O') {
  248. if (opt[1] < '0' || opt[1] > '3')
  249. message(LDPL_FATAL, "Optimization level must be between 0 and 3");
  250. OptLevel = opt[1] - '0';
  251. } else if (opt.consume_front("jobs=")) {
  252. Parallelism = std::string(opt);
  253. if (!get_threadpool_strategy(opt))
  254. message(LDPL_FATAL, "Invalid parallelism level: %s",
  255. Parallelism.c_str());
  256. } else if (opt.consume_front("lto-partitions=")) {
  257. if (opt.getAsInteger(10, ParallelCodeGenParallelismLevel))
  258. message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
  259. } else if (opt == "disable-verify") {
  260. DisableVerify = true;
  261. } else if (opt.consume_front("sample-profile=")) {
  262. sample_profile = std::string(opt);
  263. } else if (opt == "cs-profile-generate") {
  264. cs_pgo_gen = true;
  265. } else if (opt.consume_front("cs-profile-path=")) {
  266. cs_profile_path = std::string(opt);
  267. } else if (opt == "new-pass-manager") {
  268. // We always use the new pass manager.
  269. } else if (opt == "debug-pass-manager") {
  270. debug_pass_manager = true;
  271. } else if (opt == "whole-program-visibility") {
  272. whole_program_visibility = true;
  273. } else if (opt.consume_front("dwo_dir=")) {
  274. dwo_dir = std::string(opt);
  275. } else if (opt.consume_front("opt-remarks-filename=")) {
  276. RemarksFilename = std::string(opt);
  277. } else if (opt.consume_front("opt-remarks-passes=")) {
  278. RemarksPasses = std::string(opt);
  279. } else if (opt == "opt-remarks-with-hotness") {
  280. RemarksWithHotness = true;
  281. } else if (opt.consume_front("opt-remarks-hotness-threshold=")) {
  282. auto ResultOrErr = remarks::parseHotnessThresholdOption(opt);
  283. if (!ResultOrErr)
  284. message(LDPL_FATAL, "Invalid remarks hotness threshold: %s", opt);
  285. else
  286. RemarksHotnessThreshold = *ResultOrErr;
  287. } else if (opt.consume_front("opt-remarks-format=")) {
  288. RemarksFormat = std::string(opt);
  289. } else if (opt.consume_front("stats-file=")) {
  290. stats_file = std::string(opt);
  291. } else if (opt == "opaque-pointers") {
  292. opaque_pointers = true;
  293. } else if (opt == "no-opaque-pointers") {
  294. opaque_pointers = false;
  295. } else {
  296. // Save this option to pass to the code generator.
  297. // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
  298. // add that.
  299. if (extra.empty())
  300. extra.push_back("LLVMgold");
  301. extra.push_back(opt_);
  302. }
  303. }
  304. }
  305. static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
  306. int *claimed);
  307. static ld_plugin_status all_symbols_read_hook(void);
  308. static ld_plugin_status cleanup_hook(void);
  309. extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
  310. ld_plugin_status onload(ld_plugin_tv *tv) {
  311. InitializeAllTargetInfos();
  312. InitializeAllTargets();
  313. InitializeAllTargetMCs();
  314. InitializeAllAsmParsers();
  315. InitializeAllAsmPrinters();
  316. // We're given a pointer to the first transfer vector. We read through them
  317. // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
  318. // contain pointers to functions that we need to call to register our own
  319. // hooks. The others are addresses of functions we can use to call into gold
  320. // for services.
  321. bool registeredClaimFile = false;
  322. bool RegisteredAllSymbolsRead = false;
  323. for (; tv->tv_tag != LDPT_NULL; ++tv) {
  324. // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
  325. // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
  326. // header.
  327. switch (static_cast<int>(tv->tv_tag)) {
  328. case LDPT_OUTPUT_NAME:
  329. output_name = tv->tv_u.tv_string;
  330. break;
  331. case LDPT_LINKER_OUTPUT:
  332. switch (tv->tv_u.tv_val) {
  333. case LDPO_REL: // .o
  334. IsExecutable = false;
  335. SplitSections = false;
  336. break;
  337. case LDPO_DYN: // .so
  338. IsExecutable = false;
  339. RelocationModel = Reloc::PIC_;
  340. break;
  341. case LDPO_PIE: // position independent executable
  342. IsExecutable = true;
  343. RelocationModel = Reloc::PIC_;
  344. break;
  345. case LDPO_EXEC: // .exe
  346. IsExecutable = true;
  347. RelocationModel = Reloc::Static;
  348. break;
  349. default:
  350. message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
  351. return LDPS_ERR;
  352. }
  353. break;
  354. case LDPT_OPTION:
  355. options::process_plugin_option(tv->tv_u.tv_string);
  356. break;
  357. case LDPT_REGISTER_CLAIM_FILE_HOOK: {
  358. ld_plugin_register_claim_file callback;
  359. callback = tv->tv_u.tv_register_claim_file;
  360. if (callback(claim_file_hook) != LDPS_OK)
  361. return LDPS_ERR;
  362. registeredClaimFile = true;
  363. } break;
  364. case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
  365. ld_plugin_register_all_symbols_read callback;
  366. callback = tv->tv_u.tv_register_all_symbols_read;
  367. if (callback(all_symbols_read_hook) != LDPS_OK)
  368. return LDPS_ERR;
  369. RegisteredAllSymbolsRead = true;
  370. } break;
  371. case LDPT_REGISTER_CLEANUP_HOOK: {
  372. ld_plugin_register_cleanup callback;
  373. callback = tv->tv_u.tv_register_cleanup;
  374. if (callback(cleanup_hook) != LDPS_OK)
  375. return LDPS_ERR;
  376. } break;
  377. case LDPT_GET_INPUT_FILE:
  378. get_input_file = tv->tv_u.tv_get_input_file;
  379. break;
  380. case LDPT_RELEASE_INPUT_FILE:
  381. release_input_file = tv->tv_u.tv_release_input_file;
  382. break;
  383. case LDPT_ADD_SYMBOLS:
  384. add_symbols = tv->tv_u.tv_add_symbols;
  385. break;
  386. case LDPT_GET_SYMBOLS_V2:
  387. // Do not override get_symbols_v3 with get_symbols_v2.
  388. if (!get_symbols)
  389. get_symbols = tv->tv_u.tv_get_symbols;
  390. break;
  391. case LDPT_GET_SYMBOLS_V3:
  392. get_symbols = tv->tv_u.tv_get_symbols;
  393. break;
  394. case LDPT_ADD_INPUT_FILE:
  395. add_input_file = tv->tv_u.tv_add_input_file;
  396. break;
  397. case LDPT_SET_EXTRA_LIBRARY_PATH:
  398. set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
  399. break;
  400. case LDPT_GET_VIEW:
  401. get_view = tv->tv_u.tv_get_view;
  402. break;
  403. case LDPT_MESSAGE:
  404. message = tv->tv_u.tv_message;
  405. break;
  406. case LDPT_GET_WRAP_SYMBOLS:
  407. // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
  408. // required version, this should be changed to:
  409. // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
  410. get_wrap_symbols =
  411. (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
  412. break;
  413. default:
  414. break;
  415. }
  416. }
  417. if (!registeredClaimFile) {
  418. message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
  419. return LDPS_ERR;
  420. }
  421. if (!add_symbols) {
  422. message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
  423. return LDPS_ERR;
  424. }
  425. if (!RegisteredAllSymbolsRead)
  426. return LDPS_OK;
  427. if (!get_input_file) {
  428. message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
  429. return LDPS_ERR;
  430. }
  431. if (!release_input_file) {
  432. message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
  433. return LDPS_ERR;
  434. }
  435. return LDPS_OK;
  436. }
  437. static void diagnosticHandler(const DiagnosticInfo &DI) {
  438. std::string ErrStorage;
  439. {
  440. raw_string_ostream OS(ErrStorage);
  441. DiagnosticPrinterRawOStream DP(OS);
  442. DI.print(DP);
  443. }
  444. ld_plugin_level Level;
  445. switch (DI.getSeverity()) {
  446. case DS_Error:
  447. Level = LDPL_FATAL;
  448. break;
  449. case DS_Warning:
  450. Level = LDPL_WARNING;
  451. break;
  452. case DS_Note:
  453. case DS_Remark:
  454. Level = LDPL_INFO;
  455. break;
  456. }
  457. message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
  458. }
  459. static void check(Error E, std::string Msg = "LLVM gold plugin") {
  460. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
  461. message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
  462. return Error::success();
  463. });
  464. }
  465. template <typename T> static T check(Expected<T> E) {
  466. if (E)
  467. return std::move(*E);
  468. check(E.takeError());
  469. return T();
  470. }
  471. /// Called by gold to see whether this file is one that our plugin can handle.
  472. /// We'll try to open it and register all the symbols with add_symbol if
  473. /// possible.
  474. static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
  475. int *claimed) {
  476. MemoryBufferRef BufferRef;
  477. std::unique_ptr<MemoryBuffer> Buffer;
  478. if (get_view) {
  479. const void *view;
  480. if (get_view(file->handle, &view) != LDPS_OK) {
  481. message(LDPL_ERROR, "Failed to get a view of %s", file->name);
  482. return LDPS_ERR;
  483. }
  484. BufferRef =
  485. MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
  486. } else {
  487. int64_t offset = 0;
  488. // Gold has found what might be IR part-way inside of a file, such as
  489. // an .a archive.
  490. if (file->offset) {
  491. offset = file->offset;
  492. }
  493. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
  494. MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(file->fd),
  495. file->name, file->filesize, offset);
  496. if (std::error_code EC = BufferOrErr.getError()) {
  497. message(LDPL_ERROR, EC.message().c_str());
  498. return LDPS_ERR;
  499. }
  500. Buffer = std::move(BufferOrErr.get());
  501. BufferRef = Buffer->getMemBufferRef();
  502. }
  503. // Only use bitcode files for LTO. InputFile::create() will load bitcode
  504. // from the .llvmbc section within a binary object, this bitcode is typically
  505. // generated by -fembed-bitcode and is not to be used by LLVMgold.so for LTO.
  506. if (identify_magic(BufferRef.getBuffer()) != file_magic::bitcode) {
  507. *claimed = 0;
  508. return LDPS_OK;
  509. }
  510. *claimed = 1;
  511. Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
  512. if (!ObjOrErr) {
  513. handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
  514. std::error_code EC = EI.convertToErrorCode();
  515. if (EC == object::object_error::invalid_file_type ||
  516. EC == object::object_error::bitcode_section_not_found)
  517. *claimed = 0;
  518. else
  519. message(LDPL_FATAL,
  520. "LLVM gold plugin has failed to create LTO module: %s",
  521. EI.message().c_str());
  522. });
  523. return *claimed ? LDPS_ERR : LDPS_OK;
  524. }
  525. std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
  526. Modules.emplace_back();
  527. claimed_file &cf = Modules.back();
  528. cf.handle = file->handle;
  529. // Keep track of the first handle for each file descriptor, since there are
  530. // multiple in the case of an archive. This is used later in the case of
  531. // ThinLTO parallel backends to ensure that each file is only opened and
  532. // released once.
  533. auto LeaderHandle =
  534. FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
  535. cf.leader_handle = LeaderHandle->second;
  536. // Save the filesize since for parallel ThinLTO backends we can only
  537. // invoke get_input_file once per archive (only for the leader handle).
  538. cf.filesize = file->filesize;
  539. // In the case of an archive library, all but the first member must have a
  540. // non-zero offset, which we can append to the file name to obtain a
  541. // unique name.
  542. cf.name = file->name;
  543. if (file->offset)
  544. cf.name += ".llvm." + std::to_string(file->offset) + "." +
  545. sys::path::filename(Obj->getSourceFileName()).str();
  546. for (auto &Sym : Obj->symbols()) {
  547. cf.syms.push_back(ld_plugin_symbol());
  548. ld_plugin_symbol &sym = cf.syms.back();
  549. sym.version = nullptr;
  550. StringRef Name = Sym.getName();
  551. sym.name = strdup(Name.str().c_str());
  552. ResolutionInfo &Res = ResInfo[Name];
  553. Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
  554. sym.visibility = LDPV_DEFAULT;
  555. GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
  556. if (Vis != GlobalValue::DefaultVisibility)
  557. Res.DefaultVisibility = false;
  558. switch (Vis) {
  559. case GlobalValue::DefaultVisibility:
  560. break;
  561. case GlobalValue::HiddenVisibility:
  562. sym.visibility = LDPV_HIDDEN;
  563. break;
  564. case GlobalValue::ProtectedVisibility:
  565. sym.visibility = LDPV_PROTECTED;
  566. break;
  567. }
  568. if (Sym.isUndefined()) {
  569. sym.def = LDPK_UNDEF;
  570. if (Sym.isWeak())
  571. sym.def = LDPK_WEAKUNDEF;
  572. } else if (Sym.isCommon())
  573. sym.def = LDPK_COMMON;
  574. else if (Sym.isWeak())
  575. sym.def = LDPK_WEAKDEF;
  576. else
  577. sym.def = LDPK_DEF;
  578. sym.size = 0;
  579. sym.comdat_key = nullptr;
  580. int CI = Sym.getComdatIndex();
  581. if (CI != -1) {
  582. // Not setting comdat_key for nodeduplicate ensuress we don't deduplicate.
  583. std::pair<StringRef, Comdat::SelectionKind> C = Obj->getComdatTable()[CI];
  584. if (C.second != Comdat::NoDeduplicate)
  585. sym.comdat_key = strdup(C.first.str().c_str());
  586. }
  587. sym.resolution = LDPR_UNKNOWN;
  588. }
  589. if (!cf.syms.empty()) {
  590. if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
  591. message(LDPL_ERROR, "Unable to add symbols!");
  592. return LDPS_ERR;
  593. }
  594. }
  595. // Handle any --wrap options passed to gold, which are than passed
  596. // along to the plugin.
  597. if (get_wrap_symbols) {
  598. const char **wrap_symbols;
  599. uint64_t count = 0;
  600. if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
  601. message(LDPL_ERROR, "Unable to get wrap symbols!");
  602. return LDPS_ERR;
  603. }
  604. for (uint64_t i = 0; i < count; i++) {
  605. StringRef Name = wrap_symbols[i];
  606. ResolutionInfo &Res = ResInfo[Name];
  607. ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
  608. ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
  609. // Tell LTO not to inline symbols that will be overwritten.
  610. Res.CanInline = false;
  611. RealRes.CanInline = false;
  612. // Tell LTO not to eliminate symbols that will be used after renaming.
  613. Res.IsUsedInRegularObj = true;
  614. WrapRes.IsUsedInRegularObj = true;
  615. }
  616. }
  617. return LDPS_OK;
  618. }
  619. static void freeSymName(ld_plugin_symbol &Sym) {
  620. free(Sym.name);
  621. free(Sym.comdat_key);
  622. Sym.name = nullptr;
  623. Sym.comdat_key = nullptr;
  624. }
  625. /// Helper to get a file's symbols and a view into it via gold callbacks.
  626. static const void *getSymbolsAndView(claimed_file &F) {
  627. ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
  628. if (status == LDPS_NO_SYMS)
  629. return nullptr;
  630. if (status != LDPS_OK)
  631. message(LDPL_FATAL, "Failed to get symbol information");
  632. const void *View;
  633. if (get_view(F.handle, &View) != LDPS_OK)
  634. message(LDPL_FATAL, "Failed to get a view of file");
  635. return View;
  636. }
  637. /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
  638. /// \p NewSuffix strings, if it was specified.
  639. static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
  640. std::string &NewSuffix) {
  641. assert(options::thinlto_object_suffix_replace.empty() ||
  642. options::thinlto_object_suffix_replace.find(';') != StringRef::npos);
  643. StringRef SuffixReplace = options::thinlto_object_suffix_replace;
  644. auto Split = SuffixReplace.split(';');
  645. OldSuffix = std::string(Split.first);
  646. NewSuffix = std::string(Split.second);
  647. }
  648. /// Given the original \p Path to an output file, replace any filename
  649. /// suffix matching \p OldSuffix with \p NewSuffix.
  650. static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
  651. StringRef NewSuffix) {
  652. if (Path.consume_back(OldSuffix))
  653. return (Path + NewSuffix).str();
  654. return std::string(Path);
  655. }
  656. // Returns true if S is valid as a C language identifier.
  657. static bool isValidCIdentifier(StringRef S) {
  658. return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
  659. llvm::all_of(llvm::drop_begin(S),
  660. [](char C) { return C == '_' || isAlnum(C); });
  661. }
  662. static bool isUndefined(ld_plugin_symbol &Sym) {
  663. return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
  664. }
  665. static void addModule(LTO &Lto, claimed_file &F, const void *View,
  666. StringRef Filename) {
  667. MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
  668. Filename);
  669. Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
  670. if (!ObjOrErr)
  671. message(LDPL_FATAL, "Could not read bitcode from file : %s",
  672. toString(ObjOrErr.takeError()).c_str());
  673. unsigned SymNum = 0;
  674. std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
  675. auto InputFileSyms = Input->symbols();
  676. assert(InputFileSyms.size() == F.syms.size());
  677. std::vector<SymbolResolution> Resols(F.syms.size());
  678. for (ld_plugin_symbol &Sym : F.syms) {
  679. const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
  680. SymbolResolution &R = Resols[SymNum++];
  681. ld_plugin_symbol_resolution Resolution =
  682. (ld_plugin_symbol_resolution)Sym.resolution;
  683. ResolutionInfo &Res = ResInfo[Sym.name];
  684. switch (Resolution) {
  685. case LDPR_UNKNOWN:
  686. llvm_unreachable("Unexpected resolution");
  687. case LDPR_RESOLVED_IR:
  688. case LDPR_RESOLVED_EXEC:
  689. case LDPR_PREEMPTED_IR:
  690. case LDPR_PREEMPTED_REG:
  691. case LDPR_UNDEF:
  692. break;
  693. case LDPR_RESOLVED_DYN:
  694. R.ExportDynamic = true;
  695. break;
  696. case LDPR_PREVAILING_DEF_IRONLY:
  697. R.Prevailing = !isUndefined(Sym);
  698. break;
  699. case LDPR_PREVAILING_DEF:
  700. R.Prevailing = !isUndefined(Sym);
  701. R.VisibleToRegularObj = true;
  702. break;
  703. case LDPR_PREVAILING_DEF_IRONLY_EXP:
  704. R.Prevailing = !isUndefined(Sym);
  705. // Identify symbols exported dynamically, and that therefore could be
  706. // referenced by a shared library not visible to the linker.
  707. R.ExportDynamic = true;
  708. if (!Res.CanOmitFromDynSym)
  709. R.VisibleToRegularObj = true;
  710. break;
  711. }
  712. // If the symbol has a C identifier section name, we need to mark
  713. // it as visible to a regular object so that LTO will keep it around
  714. // to ensure the linker generates special __start_<secname> and
  715. // __stop_<secname> symbols which may be used elsewhere.
  716. if (isValidCIdentifier(InpSym.getSectionName()))
  717. R.VisibleToRegularObj = true;
  718. if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
  719. (IsExecutable || !Res.DefaultVisibility))
  720. R.FinalDefinitionInLinkageUnit = true;
  721. if (!Res.CanInline)
  722. R.LinkerRedefined = true;
  723. if (Res.IsUsedInRegularObj)
  724. R.VisibleToRegularObj = true;
  725. freeSymName(Sym);
  726. }
  727. check(Lto.add(std::move(Input), Resols),
  728. std::string("Failed to link module ") + F.name);
  729. }
  730. static void recordFile(const std::string &Filename, bool TempOutFile) {
  731. if (add_input_file(Filename.c_str()) != LDPS_OK)
  732. message(LDPL_FATAL,
  733. "Unable to add .o file to the link. File left behind in: %s",
  734. Filename.c_str());
  735. if (TempOutFile)
  736. Cleanup.push_back(Filename);
  737. }
  738. /// Return the desired output filename given a base input name, a flag
  739. /// indicating whether a temp file should be generated, and an optional task id.
  740. /// The new filename generated is returned in \p NewFilename.
  741. static int getOutputFileName(StringRef InFilename, bool TempOutFile,
  742. SmallString<128> &NewFilename, int TaskID) {
  743. int FD = -1;
  744. if (TempOutFile) {
  745. std::error_code EC =
  746. sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
  747. if (EC)
  748. message(LDPL_FATAL, "Could not create temporary file: %s",
  749. EC.message().c_str());
  750. } else {
  751. NewFilename = InFilename;
  752. if (TaskID > 0)
  753. NewFilename += utostr(TaskID);
  754. std::error_code EC =
  755. sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);
  756. if (EC)
  757. message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
  758. EC.message().c_str());
  759. }
  760. return FD;
  761. }
  762. /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
  763. /// \p NewPrefix strings, if it was specified.
  764. static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
  765. std::string &NewPrefix) {
  766. StringRef PrefixReplace = options::thinlto_prefix_replace;
  767. assert(PrefixReplace.empty() || PrefixReplace.find(';') != StringRef::npos);
  768. auto Split = PrefixReplace.split(';');
  769. OldPrefix = std::string(Split.first);
  770. NewPrefix = std::string(Split.second);
  771. }
  772. /// Creates instance of LTO.
  773. /// OnIndexWrite is callback to let caller know when LTO writes index files.
  774. /// LinkedObjectsFile is an output stream to write the list of object files for
  775. /// the final ThinLTO linking. Can be nullptr.
  776. static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
  777. raw_fd_ostream *LinkedObjectsFile) {
  778. Config Conf;
  779. ThinBackend Backend;
  780. Conf.CPU = options::mcpu;
  781. Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  782. // Disable the new X86 relax relocations since gold might not support them.
  783. // FIXME: Check the gold version or add a new option to enable them.
  784. Conf.Options.RelaxELFRelocations = false;
  785. // Toggle function/data sections.
  786. if (!codegen::getExplicitFunctionSections())
  787. Conf.Options.FunctionSections = SplitSections;
  788. if (!codegen::getExplicitDataSections())
  789. Conf.Options.DataSections = SplitSections;
  790. Conf.MAttrs = codegen::getMAttrs();
  791. Conf.RelocModel = RelocationModel;
  792. Conf.CodeModel = codegen::getExplicitCodeModel();
  793. std::optional<CodeGenOpt::Level> CGOptLevelOrNone =
  794. CodeGenOpt::getLevel(options::OptLevel);
  795. assert(CGOptLevelOrNone && "Invalid optimization level");
  796. Conf.CGOptLevel = *CGOptLevelOrNone;
  797. Conf.DisableVerify = options::DisableVerify;
  798. Conf.OptLevel = options::OptLevel;
  799. Conf.PTO.LoopVectorization = options::OptLevel > 1;
  800. Conf.PTO.SLPVectorization = options::OptLevel > 1;
  801. Conf.AlwaysEmitRegularLTOObj = !options::obj_path.empty();
  802. if (options::thinlto_index_only) {
  803. std::string OldPrefix, NewPrefix;
  804. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  805. Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
  806. options::thinlto_emit_imports_files,
  807. LinkedObjectsFile, OnIndexWrite);
  808. } else {
  809. Backend = createInProcessThinBackend(
  810. llvm::heavyweight_hardware_concurrency(options::Parallelism));
  811. }
  812. Conf.OverrideTriple = options::triple;
  813. Conf.DefaultTriple = sys::getDefaultTargetTriple();
  814. Conf.DiagHandler = diagnosticHandler;
  815. switch (options::TheOutputType) {
  816. case options::OT_NORMAL:
  817. break;
  818. case options::OT_DISABLE:
  819. Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
  820. break;
  821. case options::OT_BC_ONLY:
  822. Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
  823. std::error_code EC;
  824. SmallString<128> TaskFilename;
  825. getOutputFileName(output_name, /* TempOutFile */ false, TaskFilename,
  826. Task);
  827. raw_fd_ostream OS(TaskFilename, EC, sys::fs::OpenFlags::OF_None);
  828. if (EC)
  829. message(LDPL_FATAL, "Failed to write the output file.");
  830. WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
  831. return false;
  832. };
  833. break;
  834. case options::OT_SAVE_TEMPS:
  835. check(Conf.addSaveTemps(output_name + ".",
  836. /* UseInputModulePath */ true));
  837. break;
  838. case options::OT_ASM_ONLY:
  839. Conf.CGFileType = CGFT_AssemblyFile;
  840. break;
  841. }
  842. if (!options::sample_profile.empty())
  843. Conf.SampleProfile = options::sample_profile;
  844. if (!options::cs_profile_path.empty())
  845. Conf.CSIRProfile = options::cs_profile_path;
  846. Conf.RunCSIRInstr = options::cs_pgo_gen;
  847. Conf.DwoDir = options::dwo_dir;
  848. // Set up optimization remarks handling.
  849. Conf.RemarksFilename = options::RemarksFilename;
  850. Conf.RemarksPasses = options::RemarksPasses;
  851. Conf.RemarksWithHotness = options::RemarksWithHotness;
  852. Conf.RemarksHotnessThreshold = options::RemarksHotnessThreshold;
  853. Conf.RemarksFormat = options::RemarksFormat;
  854. // Debug new pass manager if requested
  855. Conf.DebugPassManager = options::debug_pass_manager;
  856. Conf.HasWholeProgramVisibility = options::whole_program_visibility;
  857. Conf.OpaquePointers = options::opaque_pointers;
  858. Conf.StatsFile = options::stats_file;
  859. return std::make_unique<LTO>(std::move(Conf), Backend,
  860. options::ParallelCodeGenParallelismLevel);
  861. }
  862. // Write empty files that may be expected by a distributed build
  863. // system when invoked with thinlto_index_only. This is invoked when
  864. // the linker has decided not to include the given module in the
  865. // final link. Frequently the distributed build system will want to
  866. // confirm that all expected outputs are created based on all of the
  867. // modules provided to the linker.
  868. // If SkipModule is true then .thinlto.bc should contain just
  869. // SkipModuleByDistributedBackend flag which requests distributed backend
  870. // to skip the compilation of the corresponding module and produce an empty
  871. // object file.
  872. static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
  873. const std::string &OldPrefix,
  874. const std::string &NewPrefix,
  875. bool SkipModule) {
  876. std::string NewModulePath =
  877. getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
  878. std::error_code EC;
  879. {
  880. raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
  881. sys::fs::OpenFlags::OF_None);
  882. if (EC)
  883. message(LDPL_FATAL, "Failed to write '%s': %s",
  884. (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
  885. if (SkipModule) {
  886. ModuleSummaryIndex Index(/*HaveGVs*/ false);
  887. Index.setSkipModuleByDistributedBackend();
  888. writeIndexToFile(Index, OS, nullptr);
  889. }
  890. }
  891. if (options::thinlto_emit_imports_files) {
  892. raw_fd_ostream OS(NewModulePath + ".imports", EC,
  893. sys::fs::OpenFlags::OF_None);
  894. if (EC)
  895. message(LDPL_FATAL, "Failed to write '%s': %s",
  896. (NewModulePath + ".imports").c_str(), EC.message().c_str());
  897. }
  898. }
  899. // Creates and returns output stream with a list of object files for final
  900. // linking of distributed ThinLTO.
  901. static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
  902. if (options::thinlto_linked_objects_file.empty())
  903. return nullptr;
  904. assert(options::thinlto_index_only);
  905. std::error_code EC;
  906. auto LinkedObjectsFile = std::make_unique<raw_fd_ostream>(
  907. options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::OF_None);
  908. if (EC)
  909. message(LDPL_FATAL, "Failed to create '%s': %s",
  910. options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
  911. return LinkedObjectsFile;
  912. }
  913. /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
  914. static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
  915. // Map to own RAII objects that manage the file opening and releasing
  916. // interfaces with gold. This is needed only for ThinLTO mode, since
  917. // unlike regular LTO, where addModule will result in the opened file
  918. // being merged into a new combined module, we need to keep these files open
  919. // through Lto->run().
  920. DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
  921. // Owns string objects and tells if index file was already created.
  922. StringMap<bool> ObjectToIndexFileState;
  923. std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
  924. std::unique_ptr<LTO> Lto = createLTO(
  925. [&ObjectToIndexFileState](const std::string &Identifier) {
  926. ObjectToIndexFileState[Identifier] = true;
  927. },
  928. LinkedObjects.get());
  929. std::string OldPrefix, NewPrefix;
  930. if (options::thinlto_index_only)
  931. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  932. std::string OldSuffix, NewSuffix;
  933. getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
  934. for (claimed_file &F : Modules) {
  935. if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
  936. HandleToInputFile.insert(std::make_pair(
  937. F.leader_handle, std::make_unique<PluginInputFile>(F.handle)));
  938. // In case we are thin linking with a minimized bitcode file, ensure
  939. // the module paths encoded in the index reflect where the backends
  940. // will locate the full bitcode files for compiling/importing.
  941. std::string Identifier =
  942. getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
  943. auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
  944. assert(ObjFilename.second);
  945. if (const void *View = getSymbolsAndView(F))
  946. addModule(*Lto, F, View, ObjFilename.first->first());
  947. else if (options::thinlto_index_only) {
  948. ObjFilename.first->second = true;
  949. writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
  950. /* SkipModule */ true);
  951. }
  952. }
  953. SmallString<128> Filename;
  954. // Note that getOutputFileName will append a unique ID for each task
  955. if (!options::obj_path.empty())
  956. Filename = options::obj_path;
  957. else if (options::TheOutputType == options::OT_SAVE_TEMPS)
  958. Filename = output_name + ".lto.o";
  959. else if (options::TheOutputType == options::OT_ASM_ONLY)
  960. Filename = output_name;
  961. bool SaveTemps = !Filename.empty();
  962. size_t MaxTasks = Lto->getMaxTasks();
  963. std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
  964. auto AddStream =
  965. [&](size_t Task,
  966. const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
  967. Files[Task].second = !SaveTemps;
  968. int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
  969. Files[Task].first, Task);
  970. return std::make_unique<CachedFileStream>(
  971. std::make_unique<llvm::raw_fd_ostream>(FD, true));
  972. };
  973. auto AddBuffer = [&](size_t Task, const Twine &moduleName,
  974. std::unique_ptr<MemoryBuffer> MB) {
  975. *AddStream(Task, moduleName)->OS << MB->getBuffer();
  976. };
  977. FileCache Cache;
  978. if (!options::cache_dir.empty())
  979. Cache = check(localCache("ThinLTO", "Thin", options::cache_dir, AddBuffer));
  980. check(Lto->run(AddStream, Cache));
  981. // Write empty output files that may be expected by the distributed build
  982. // system.
  983. if (options::thinlto_index_only)
  984. for (auto &Identifier : ObjectToIndexFileState)
  985. if (!Identifier.getValue())
  986. writeEmptyDistributedBuildOutputs(std::string(Identifier.getKey()),
  987. OldPrefix, NewPrefix,
  988. /* SkipModule */ false);
  989. return Files;
  990. }
  991. /// gold informs us that all symbols have been read. At this point, we use
  992. /// get_symbols to see if any of our definitions have been overridden by a
  993. /// native object file. Then, perform optimization and codegen.
  994. static ld_plugin_status allSymbolsReadHook() {
  995. if (Modules.empty())
  996. return LDPS_OK;
  997. if (unsigned NumOpts = options::extra.size())
  998. cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
  999. std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
  1000. if (options::TheOutputType == options::OT_DISABLE ||
  1001. options::TheOutputType == options::OT_BC_ONLY ||
  1002. options::TheOutputType == options::OT_ASM_ONLY)
  1003. return LDPS_OK;
  1004. if (options::thinlto_index_only) {
  1005. llvm_shutdown();
  1006. cleanup_hook();
  1007. exit(0);
  1008. }
  1009. for (const auto &F : Files)
  1010. if (!F.first.empty())
  1011. recordFile(std::string(F.first.str()), F.second);
  1012. if (!options::extra_library_path.empty() &&
  1013. set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
  1014. message(LDPL_FATAL, "Unable to set the extra library path.");
  1015. return LDPS_OK;
  1016. }
  1017. static ld_plugin_status all_symbols_read_hook(void) {
  1018. ld_plugin_status Ret = allSymbolsReadHook();
  1019. llvm_shutdown();
  1020. if (options::TheOutputType == options::OT_BC_ONLY ||
  1021. options::TheOutputType == options::OT_ASM_ONLY ||
  1022. options::TheOutputType == options::OT_DISABLE) {
  1023. if (options::TheOutputType == options::OT_DISABLE) {
  1024. // Remove the output file here since ld.bfd creates the output file
  1025. // early.
  1026. std::error_code EC = sys::fs::remove(output_name);
  1027. if (EC)
  1028. message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
  1029. EC.message().c_str());
  1030. }
  1031. exit(0);
  1032. }
  1033. return Ret;
  1034. }
  1035. static ld_plugin_status cleanup_hook(void) {
  1036. for (std::string &Name : Cleanup) {
  1037. std::error_code EC = sys::fs::remove(Name);
  1038. if (EC)
  1039. message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
  1040. EC.message().c_str());
  1041. }
  1042. // Prune cache
  1043. if (!options::cache_dir.empty()) {
  1044. CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
  1045. pruneCache(options::cache_dir, policy);
  1046. }
  1047. return LDPS_OK;
  1048. }