gold-plugin.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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/Caching.h"
  22. #include "llvm/LTO/LTO.h"
  23. #include "llvm/Object/Error.h"
  24. #include "llvm/Remarks/HotnessThresholdParser.h"
  25. #include "llvm/Support/CachePruning.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 Optional<Reloc::Model> RelocationModel = None;
  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. // New pass manager
  186. static bool new_pass_manager = LLVM_ENABLE_NEW_PASS_MANAGER;
  187. // Debug new pass manager
  188. static bool debug_pass_manager = false;
  189. // Directory to store the .dwo files.
  190. static std::string dwo_dir;
  191. /// Statistics output filename.
  192. static std::string stats_file;
  193. // Asserts that LTO link has whole program visibility
  194. static bool whole_program_visibility = false;
  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 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. new_pass_manager = true;
  269. } else if (opt == "legacy-pass-manager") {
  270. new_pass_manager = false;
  271. } else if (opt == "debug-pass-manager") {
  272. debug_pass_manager = true;
  273. } else if (opt == "whole-program-visibility") {
  274. whole_program_visibility = true;
  275. } else if (opt.consume_front("dwo_dir=")) {
  276. dwo_dir = std::string(opt);
  277. } else if (opt.consume_front("opt-remarks-filename=")) {
  278. RemarksFilename = std::string(opt);
  279. } else if (opt.consume_front("opt-remarks-passes=")) {
  280. RemarksPasses = std::string(opt);
  281. } else if (opt == "opt-remarks-with-hotness") {
  282. RemarksWithHotness = true;
  283. } else if (opt.consume_front("opt-remarks-hotness-threshold=")) {
  284. auto ResultOrErr = remarks::parseHotnessThresholdOption(opt);
  285. if (!ResultOrErr)
  286. message(LDPL_FATAL, "Invalid remarks hotness threshold: %s", opt);
  287. else
  288. RemarksHotnessThreshold = *ResultOrErr;
  289. } else if (opt.consume_front("opt-remarks-format=")) {
  290. RemarksFormat = std::string(opt);
  291. } else if (opt.consume_front("stats-file=")) {
  292. stats_file = std::string(opt);
  293. } else {
  294. // Save this option to pass to the code generator.
  295. // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
  296. // add that.
  297. if (extra.empty())
  298. extra.push_back("LLVMgold");
  299. extra.push_back(opt_);
  300. }
  301. }
  302. }
  303. static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
  304. int *claimed);
  305. static ld_plugin_status all_symbols_read_hook(void);
  306. static ld_plugin_status cleanup_hook(void);
  307. extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
  308. ld_plugin_status onload(ld_plugin_tv *tv) {
  309. InitializeAllTargetInfos();
  310. InitializeAllTargets();
  311. InitializeAllTargetMCs();
  312. InitializeAllAsmParsers();
  313. InitializeAllAsmPrinters();
  314. // We're given a pointer to the first transfer vector. We read through them
  315. // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
  316. // contain pointers to functions that we need to call to register our own
  317. // hooks. The others are addresses of functions we can use to call into gold
  318. // for services.
  319. bool registeredClaimFile = false;
  320. bool RegisteredAllSymbolsRead = false;
  321. for (; tv->tv_tag != LDPT_NULL; ++tv) {
  322. // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
  323. // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
  324. // header.
  325. switch (static_cast<int>(tv->tv_tag)) {
  326. case LDPT_OUTPUT_NAME:
  327. output_name = tv->tv_u.tv_string;
  328. break;
  329. case LDPT_LINKER_OUTPUT:
  330. switch (tv->tv_u.tv_val) {
  331. case LDPO_REL: // .o
  332. IsExecutable = false;
  333. SplitSections = false;
  334. break;
  335. case LDPO_DYN: // .so
  336. IsExecutable = false;
  337. RelocationModel = Reloc::PIC_;
  338. break;
  339. case LDPO_PIE: // position independent executable
  340. IsExecutable = true;
  341. RelocationModel = Reloc::PIC_;
  342. break;
  343. case LDPO_EXEC: // .exe
  344. IsExecutable = true;
  345. RelocationModel = Reloc::Static;
  346. break;
  347. default:
  348. message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
  349. return LDPS_ERR;
  350. }
  351. break;
  352. case LDPT_OPTION:
  353. options::process_plugin_option(tv->tv_u.tv_string);
  354. break;
  355. case LDPT_REGISTER_CLAIM_FILE_HOOK: {
  356. ld_plugin_register_claim_file callback;
  357. callback = tv->tv_u.tv_register_claim_file;
  358. if (callback(claim_file_hook) != LDPS_OK)
  359. return LDPS_ERR;
  360. registeredClaimFile = true;
  361. } break;
  362. case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
  363. ld_plugin_register_all_symbols_read callback;
  364. callback = tv->tv_u.tv_register_all_symbols_read;
  365. if (callback(all_symbols_read_hook) != LDPS_OK)
  366. return LDPS_ERR;
  367. RegisteredAllSymbolsRead = true;
  368. } break;
  369. case LDPT_REGISTER_CLEANUP_HOOK: {
  370. ld_plugin_register_cleanup callback;
  371. callback = tv->tv_u.tv_register_cleanup;
  372. if (callback(cleanup_hook) != LDPS_OK)
  373. return LDPS_ERR;
  374. } break;
  375. case LDPT_GET_INPUT_FILE:
  376. get_input_file = tv->tv_u.tv_get_input_file;
  377. break;
  378. case LDPT_RELEASE_INPUT_FILE:
  379. release_input_file = tv->tv_u.tv_release_input_file;
  380. break;
  381. case LDPT_ADD_SYMBOLS:
  382. add_symbols = tv->tv_u.tv_add_symbols;
  383. break;
  384. case LDPT_GET_SYMBOLS_V2:
  385. // Do not override get_symbols_v3 with get_symbols_v2.
  386. if (!get_symbols)
  387. get_symbols = tv->tv_u.tv_get_symbols;
  388. break;
  389. case LDPT_GET_SYMBOLS_V3:
  390. get_symbols = tv->tv_u.tv_get_symbols;
  391. break;
  392. case LDPT_ADD_INPUT_FILE:
  393. add_input_file = tv->tv_u.tv_add_input_file;
  394. break;
  395. case LDPT_SET_EXTRA_LIBRARY_PATH:
  396. set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
  397. break;
  398. case LDPT_GET_VIEW:
  399. get_view = tv->tv_u.tv_get_view;
  400. break;
  401. case LDPT_MESSAGE:
  402. message = tv->tv_u.tv_message;
  403. break;
  404. case LDPT_GET_WRAP_SYMBOLS:
  405. // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
  406. // required version, this should be changed to:
  407. // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
  408. get_wrap_symbols =
  409. (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
  410. break;
  411. default:
  412. break;
  413. }
  414. }
  415. if (!registeredClaimFile) {
  416. message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
  417. return LDPS_ERR;
  418. }
  419. if (!add_symbols) {
  420. message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
  421. return LDPS_ERR;
  422. }
  423. if (!RegisteredAllSymbolsRead)
  424. return LDPS_OK;
  425. if (!get_input_file) {
  426. message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
  427. return LDPS_ERR;
  428. }
  429. if (!release_input_file) {
  430. message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
  431. return LDPS_ERR;
  432. }
  433. return LDPS_OK;
  434. }
  435. static void diagnosticHandler(const DiagnosticInfo &DI) {
  436. std::string ErrStorage;
  437. {
  438. raw_string_ostream OS(ErrStorage);
  439. DiagnosticPrinterRawOStream DP(OS);
  440. DI.print(DP);
  441. }
  442. ld_plugin_level Level;
  443. switch (DI.getSeverity()) {
  444. case DS_Error:
  445. Level = LDPL_FATAL;
  446. break;
  447. case DS_Warning:
  448. Level = LDPL_WARNING;
  449. break;
  450. case DS_Note:
  451. case DS_Remark:
  452. Level = LDPL_INFO;
  453. break;
  454. }
  455. message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
  456. }
  457. static void check(Error E, std::string Msg = "LLVM gold plugin") {
  458. handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
  459. message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
  460. return Error::success();
  461. });
  462. }
  463. template <typename T> static T check(Expected<T> E) {
  464. if (E)
  465. return std::move(*E);
  466. check(E.takeError());
  467. return T();
  468. }
  469. /// Called by gold to see whether this file is one that our plugin can handle.
  470. /// We'll try to open it and register all the symbols with add_symbol if
  471. /// possible.
  472. static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
  473. int *claimed) {
  474. MemoryBufferRef BufferRef;
  475. std::unique_ptr<MemoryBuffer> Buffer;
  476. if (get_view) {
  477. const void *view;
  478. if (get_view(file->handle, &view) != LDPS_OK) {
  479. message(LDPL_ERROR, "Failed to get a view of %s", file->name);
  480. return LDPS_ERR;
  481. }
  482. BufferRef =
  483. MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
  484. } else {
  485. int64_t offset = 0;
  486. // Gold has found what might be IR part-way inside of a file, such as
  487. // an .a archive.
  488. if (file->offset) {
  489. offset = file->offset;
  490. }
  491. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
  492. MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(file->fd),
  493. file->name, file->filesize, offset);
  494. if (std::error_code EC = BufferOrErr.getError()) {
  495. message(LDPL_ERROR, EC.message().c_str());
  496. return LDPS_ERR;
  497. }
  498. Buffer = std::move(BufferOrErr.get());
  499. BufferRef = Buffer->getMemBufferRef();
  500. }
  501. *claimed = 1;
  502. Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
  503. if (!ObjOrErr) {
  504. handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
  505. std::error_code EC = EI.convertToErrorCode();
  506. if (EC == object::object_error::invalid_file_type ||
  507. EC == object::object_error::bitcode_section_not_found)
  508. *claimed = 0;
  509. else
  510. message(LDPL_FATAL,
  511. "LLVM gold plugin has failed to create LTO module: %s",
  512. EI.message().c_str());
  513. });
  514. return *claimed ? LDPS_ERR : LDPS_OK;
  515. }
  516. std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
  517. Modules.emplace_back();
  518. claimed_file &cf = Modules.back();
  519. cf.handle = file->handle;
  520. // Keep track of the first handle for each file descriptor, since there are
  521. // multiple in the case of an archive. This is used later in the case of
  522. // ThinLTO parallel backends to ensure that each file is only opened and
  523. // released once.
  524. auto LeaderHandle =
  525. FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
  526. cf.leader_handle = LeaderHandle->second;
  527. // Save the filesize since for parallel ThinLTO backends we can only
  528. // invoke get_input_file once per archive (only for the leader handle).
  529. cf.filesize = file->filesize;
  530. // In the case of an archive library, all but the first member must have a
  531. // non-zero offset, which we can append to the file name to obtain a
  532. // unique name.
  533. cf.name = file->name;
  534. if (file->offset)
  535. cf.name += ".llvm." + std::to_string(file->offset) + "." +
  536. sys::path::filename(Obj->getSourceFileName()).str();
  537. for (auto &Sym : Obj->symbols()) {
  538. cf.syms.push_back(ld_plugin_symbol());
  539. ld_plugin_symbol &sym = cf.syms.back();
  540. sym.version = nullptr;
  541. StringRef Name = Sym.getName();
  542. sym.name = strdup(Name.str().c_str());
  543. ResolutionInfo &Res = ResInfo[Name];
  544. Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
  545. sym.visibility = LDPV_DEFAULT;
  546. GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
  547. if (Vis != GlobalValue::DefaultVisibility)
  548. Res.DefaultVisibility = false;
  549. switch (Vis) {
  550. case GlobalValue::DefaultVisibility:
  551. break;
  552. case GlobalValue::HiddenVisibility:
  553. sym.visibility = LDPV_HIDDEN;
  554. break;
  555. case GlobalValue::ProtectedVisibility:
  556. sym.visibility = LDPV_PROTECTED;
  557. break;
  558. }
  559. if (Sym.isUndefined()) {
  560. sym.def = LDPK_UNDEF;
  561. if (Sym.isWeak())
  562. sym.def = LDPK_WEAKUNDEF;
  563. } else if (Sym.isCommon())
  564. sym.def = LDPK_COMMON;
  565. else if (Sym.isWeak())
  566. sym.def = LDPK_WEAKDEF;
  567. else
  568. sym.def = LDPK_DEF;
  569. sym.size = 0;
  570. sym.comdat_key = nullptr;
  571. int CI = Sym.getComdatIndex();
  572. if (CI != -1) {
  573. StringRef C = Obj->getComdatTable()[CI];
  574. sym.comdat_key = strdup(C.str().c_str());
  575. }
  576. sym.resolution = LDPR_UNKNOWN;
  577. }
  578. if (!cf.syms.empty()) {
  579. if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
  580. message(LDPL_ERROR, "Unable to add symbols!");
  581. return LDPS_ERR;
  582. }
  583. }
  584. // Handle any --wrap options passed to gold, which are than passed
  585. // along to the plugin.
  586. if (get_wrap_symbols) {
  587. const char **wrap_symbols;
  588. uint64_t count = 0;
  589. if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
  590. message(LDPL_ERROR, "Unable to get wrap symbols!");
  591. return LDPS_ERR;
  592. }
  593. for (uint64_t i = 0; i < count; i++) {
  594. StringRef Name = wrap_symbols[i];
  595. ResolutionInfo &Res = ResInfo[Name];
  596. ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
  597. ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
  598. // Tell LTO not to inline symbols that will be overwritten.
  599. Res.CanInline = false;
  600. RealRes.CanInline = false;
  601. // Tell LTO not to eliminate symbols that will be used after renaming.
  602. Res.IsUsedInRegularObj = true;
  603. WrapRes.IsUsedInRegularObj = true;
  604. }
  605. }
  606. return LDPS_OK;
  607. }
  608. static void freeSymName(ld_plugin_symbol &Sym) {
  609. free(Sym.name);
  610. free(Sym.comdat_key);
  611. Sym.name = nullptr;
  612. Sym.comdat_key = nullptr;
  613. }
  614. /// Helper to get a file's symbols and a view into it via gold callbacks.
  615. static const void *getSymbolsAndView(claimed_file &F) {
  616. ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
  617. if (status == LDPS_NO_SYMS)
  618. return nullptr;
  619. if (status != LDPS_OK)
  620. message(LDPL_FATAL, "Failed to get symbol information");
  621. const void *View;
  622. if (get_view(F.handle, &View) != LDPS_OK)
  623. message(LDPL_FATAL, "Failed to get a view of file");
  624. return View;
  625. }
  626. /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
  627. /// \p NewSuffix strings, if it was specified.
  628. static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
  629. std::string &NewSuffix) {
  630. assert(options::thinlto_object_suffix_replace.empty() ||
  631. options::thinlto_object_suffix_replace.find(';') != StringRef::npos);
  632. StringRef SuffixReplace = options::thinlto_object_suffix_replace;
  633. auto Split = SuffixReplace.split(';');
  634. OldSuffix = std::string(Split.first);
  635. NewSuffix = std::string(Split.second);
  636. }
  637. /// Given the original \p Path to an output file, replace any filename
  638. /// suffix matching \p OldSuffix with \p NewSuffix.
  639. static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
  640. StringRef NewSuffix) {
  641. if (Path.consume_back(OldSuffix))
  642. return (Path + NewSuffix).str();
  643. return std::string(Path);
  644. }
  645. // Returns true if S is valid as a C language identifier.
  646. static bool isValidCIdentifier(StringRef S) {
  647. return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
  648. std::all_of(S.begin() + 1, S.end(),
  649. [](char C) { return C == '_' || isAlnum(C); });
  650. }
  651. static bool isUndefined(ld_plugin_symbol &Sym) {
  652. return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
  653. }
  654. static void addModule(LTO &Lto, claimed_file &F, const void *View,
  655. StringRef Filename) {
  656. MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
  657. Filename);
  658. Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
  659. if (!ObjOrErr)
  660. message(LDPL_FATAL, "Could not read bitcode from file : %s",
  661. toString(ObjOrErr.takeError()).c_str());
  662. unsigned SymNum = 0;
  663. std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
  664. auto InputFileSyms = Input->symbols();
  665. assert(InputFileSyms.size() == F.syms.size());
  666. std::vector<SymbolResolution> Resols(F.syms.size());
  667. for (ld_plugin_symbol &Sym : F.syms) {
  668. const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
  669. SymbolResolution &R = Resols[SymNum++];
  670. ld_plugin_symbol_resolution Resolution =
  671. (ld_plugin_symbol_resolution)Sym.resolution;
  672. ResolutionInfo &Res = ResInfo[Sym.name];
  673. switch (Resolution) {
  674. case LDPR_UNKNOWN:
  675. llvm_unreachable("Unexpected resolution");
  676. case LDPR_RESOLVED_IR:
  677. case LDPR_RESOLVED_EXEC:
  678. case LDPR_RESOLVED_DYN:
  679. case LDPR_PREEMPTED_IR:
  680. case LDPR_PREEMPTED_REG:
  681. case LDPR_UNDEF:
  682. break;
  683. case LDPR_PREVAILING_DEF_IRONLY:
  684. R.Prevailing = !isUndefined(Sym);
  685. break;
  686. case LDPR_PREVAILING_DEF:
  687. R.Prevailing = !isUndefined(Sym);
  688. R.VisibleToRegularObj = true;
  689. break;
  690. case LDPR_PREVAILING_DEF_IRONLY_EXP:
  691. R.Prevailing = !isUndefined(Sym);
  692. if (!Res.CanOmitFromDynSym)
  693. R.VisibleToRegularObj = true;
  694. break;
  695. }
  696. // If the symbol has a C identifier section name, we need to mark
  697. // it as visible to a regular object so that LTO will keep it around
  698. // to ensure the linker generates special __start_<secname> and
  699. // __stop_<secname> symbols which may be used elsewhere.
  700. if (isValidCIdentifier(InpSym.getSectionName()))
  701. R.VisibleToRegularObj = true;
  702. if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
  703. (IsExecutable || !Res.DefaultVisibility))
  704. R.FinalDefinitionInLinkageUnit = true;
  705. if (!Res.CanInline)
  706. R.LinkerRedefined = true;
  707. if (Res.IsUsedInRegularObj)
  708. R.VisibleToRegularObj = true;
  709. freeSymName(Sym);
  710. }
  711. check(Lto.add(std::move(Input), Resols),
  712. std::string("Failed to link module ") + F.name);
  713. }
  714. static void recordFile(const std::string &Filename, bool TempOutFile) {
  715. if (add_input_file(Filename.c_str()) != LDPS_OK)
  716. message(LDPL_FATAL,
  717. "Unable to add .o file to the link. File left behind in: %s",
  718. Filename.c_str());
  719. if (TempOutFile)
  720. Cleanup.push_back(Filename);
  721. }
  722. /// Return the desired output filename given a base input name, a flag
  723. /// indicating whether a temp file should be generated, and an optional task id.
  724. /// The new filename generated is returned in \p NewFilename.
  725. static int getOutputFileName(StringRef InFilename, bool TempOutFile,
  726. SmallString<128> &NewFilename, int TaskID) {
  727. int FD = -1;
  728. if (TempOutFile) {
  729. std::error_code EC =
  730. sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
  731. if (EC)
  732. message(LDPL_FATAL, "Could not create temporary file: %s",
  733. EC.message().c_str());
  734. } else {
  735. NewFilename = InFilename;
  736. if (TaskID > 0)
  737. NewFilename += utostr(TaskID);
  738. std::error_code EC =
  739. sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);
  740. if (EC)
  741. message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
  742. EC.message().c_str());
  743. }
  744. return FD;
  745. }
  746. static CodeGenOpt::Level getCGOptLevel() {
  747. switch (options::OptLevel) {
  748. case 0:
  749. return CodeGenOpt::None;
  750. case 1:
  751. return CodeGenOpt::Less;
  752. case 2:
  753. return CodeGenOpt::Default;
  754. case 3:
  755. return CodeGenOpt::Aggressive;
  756. }
  757. llvm_unreachable("Invalid optimization level");
  758. }
  759. /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
  760. /// \p NewPrefix strings, if it was specified.
  761. static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
  762. std::string &NewPrefix) {
  763. StringRef PrefixReplace = options::thinlto_prefix_replace;
  764. assert(PrefixReplace.empty() || PrefixReplace.find(';') != StringRef::npos);
  765. auto Split = PrefixReplace.split(';');
  766. OldPrefix = std::string(Split.first);
  767. NewPrefix = std::string(Split.second);
  768. }
  769. /// Creates instance of LTO.
  770. /// OnIndexWrite is callback to let caller know when LTO writes index files.
  771. /// LinkedObjectsFile is an output stream to write the list of object files for
  772. /// the final ThinLTO linking. Can be nullptr.
  773. static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
  774. raw_fd_ostream *LinkedObjectsFile) {
  775. Config Conf;
  776. ThinBackend Backend;
  777. Conf.CPU = options::mcpu;
  778. Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  779. // Disable the new X86 relax relocations since gold might not support them.
  780. // FIXME: Check the gold version or add a new option to enable them.
  781. Conf.Options.RelaxELFRelocations = false;
  782. // Toggle function/data sections.
  783. if (!codegen::getExplicitFunctionSections())
  784. Conf.Options.FunctionSections = SplitSections;
  785. if (!codegen::getExplicitDataSections())
  786. Conf.Options.DataSections = SplitSections;
  787. Conf.MAttrs = codegen::getMAttrs();
  788. Conf.RelocModel = RelocationModel;
  789. Conf.CodeModel = codegen::getExplicitCodeModel();
  790. Conf.CGOptLevel = getCGOptLevel();
  791. Conf.DisableVerify = options::DisableVerify;
  792. Conf.OptLevel = options::OptLevel;
  793. Conf.PTO.LoopVectorization = options::OptLevel > 1;
  794. Conf.PTO.SLPVectorization = options::OptLevel > 1;
  795. Conf.AlwaysEmitRegularLTOObj = !options::obj_path.empty();
  796. if (options::thinlto_index_only) {
  797. std::string OldPrefix, NewPrefix;
  798. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  799. Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
  800. options::thinlto_emit_imports_files,
  801. LinkedObjectsFile, OnIndexWrite);
  802. } else {
  803. Backend = createInProcessThinBackend(
  804. llvm::heavyweight_hardware_concurrency(options::Parallelism));
  805. }
  806. Conf.OverrideTriple = options::triple;
  807. Conf.DefaultTriple = sys::getDefaultTargetTriple();
  808. Conf.DiagHandler = diagnosticHandler;
  809. switch (options::TheOutputType) {
  810. case options::OT_NORMAL:
  811. break;
  812. case options::OT_DISABLE:
  813. Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
  814. break;
  815. case options::OT_BC_ONLY:
  816. Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
  817. std::error_code EC;
  818. raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::OF_None);
  819. if (EC)
  820. message(LDPL_FATAL, "Failed to write the output file.");
  821. WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
  822. return false;
  823. };
  824. break;
  825. case options::OT_SAVE_TEMPS:
  826. check(Conf.addSaveTemps(output_name + ".",
  827. /* UseInputModulePath */ true));
  828. break;
  829. case options::OT_ASM_ONLY:
  830. Conf.CGFileType = CGFT_AssemblyFile;
  831. break;
  832. }
  833. if (!options::sample_profile.empty())
  834. Conf.SampleProfile = options::sample_profile;
  835. if (!options::cs_profile_path.empty())
  836. Conf.CSIRProfile = options::cs_profile_path;
  837. Conf.RunCSIRInstr = options::cs_pgo_gen;
  838. Conf.DwoDir = options::dwo_dir;
  839. // Set up optimization remarks handling.
  840. Conf.RemarksFilename = options::RemarksFilename;
  841. Conf.RemarksPasses = options::RemarksPasses;
  842. Conf.RemarksWithHotness = options::RemarksWithHotness;
  843. Conf.RemarksHotnessThreshold = options::RemarksHotnessThreshold;
  844. Conf.RemarksFormat = options::RemarksFormat;
  845. // Use new pass manager if set in driver
  846. Conf.UseNewPM = options::new_pass_manager;
  847. // Debug new pass manager if requested
  848. Conf.DebugPassManager = options::debug_pass_manager;
  849. Conf.HasWholeProgramVisibility = options::whole_program_visibility;
  850. Conf.StatsFile = options::stats_file;
  851. return std::make_unique<LTO>(std::move(Conf), Backend,
  852. options::ParallelCodeGenParallelismLevel);
  853. }
  854. // Write empty files that may be expected by a distributed build
  855. // system when invoked with thinlto_index_only. This is invoked when
  856. // the linker has decided not to include the given module in the
  857. // final link. Frequently the distributed build system will want to
  858. // confirm that all expected outputs are created based on all of the
  859. // modules provided to the linker.
  860. // If SkipModule is true then .thinlto.bc should contain just
  861. // SkipModuleByDistributedBackend flag which requests distributed backend
  862. // to skip the compilation of the corresponding module and produce an empty
  863. // object file.
  864. static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
  865. const std::string &OldPrefix,
  866. const std::string &NewPrefix,
  867. bool SkipModule) {
  868. std::string NewModulePath =
  869. getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
  870. std::error_code EC;
  871. {
  872. raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
  873. sys::fs::OpenFlags::OF_None);
  874. if (EC)
  875. message(LDPL_FATAL, "Failed to write '%s': %s",
  876. (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
  877. if (SkipModule) {
  878. ModuleSummaryIndex Index(/*HaveGVs*/ false);
  879. Index.setSkipModuleByDistributedBackend();
  880. WriteIndexToFile(Index, OS, nullptr);
  881. }
  882. }
  883. if (options::thinlto_emit_imports_files) {
  884. raw_fd_ostream OS(NewModulePath + ".imports", EC,
  885. sys::fs::OpenFlags::OF_None);
  886. if (EC)
  887. message(LDPL_FATAL, "Failed to write '%s': %s",
  888. (NewModulePath + ".imports").c_str(), EC.message().c_str());
  889. }
  890. }
  891. // Creates and returns output stream with a list of object files for final
  892. // linking of distributed ThinLTO.
  893. static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
  894. if (options::thinlto_linked_objects_file.empty())
  895. return nullptr;
  896. assert(options::thinlto_index_only);
  897. std::error_code EC;
  898. auto LinkedObjectsFile = std::make_unique<raw_fd_ostream>(
  899. options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::OF_None);
  900. if (EC)
  901. message(LDPL_FATAL, "Failed to create '%s': %s",
  902. options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
  903. return LinkedObjectsFile;
  904. }
  905. /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
  906. static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
  907. // Map to own RAII objects that manage the file opening and releasing
  908. // interfaces with gold. This is needed only for ThinLTO mode, since
  909. // unlike regular LTO, where addModule will result in the opened file
  910. // being merged into a new combined module, we need to keep these files open
  911. // through Lto->run().
  912. DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
  913. // Owns string objects and tells if index file was already created.
  914. StringMap<bool> ObjectToIndexFileState;
  915. std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
  916. std::unique_ptr<LTO> Lto = createLTO(
  917. [&ObjectToIndexFileState](const std::string &Identifier) {
  918. ObjectToIndexFileState[Identifier] = true;
  919. },
  920. LinkedObjects.get());
  921. std::string OldPrefix, NewPrefix;
  922. if (options::thinlto_index_only)
  923. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  924. std::string OldSuffix, NewSuffix;
  925. getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
  926. for (claimed_file &F : Modules) {
  927. if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
  928. HandleToInputFile.insert(std::make_pair(
  929. F.leader_handle, std::make_unique<PluginInputFile>(F.handle)));
  930. // In case we are thin linking with a minimized bitcode file, ensure
  931. // the module paths encoded in the index reflect where the backends
  932. // will locate the full bitcode files for compiling/importing.
  933. std::string Identifier =
  934. getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
  935. auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
  936. assert(ObjFilename.second);
  937. if (const void *View = getSymbolsAndView(F))
  938. addModule(*Lto, F, View, ObjFilename.first->first());
  939. else if (options::thinlto_index_only) {
  940. ObjFilename.first->second = true;
  941. writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
  942. /* SkipModule */ true);
  943. }
  944. }
  945. SmallString<128> Filename;
  946. // Note that getOutputFileName will append a unique ID for each task
  947. if (!options::obj_path.empty())
  948. Filename = options::obj_path;
  949. else if (options::TheOutputType == options::OT_SAVE_TEMPS)
  950. Filename = output_name + ".lto.o";
  951. else if (options::TheOutputType == options::OT_ASM_ONLY)
  952. Filename = output_name;
  953. bool SaveTemps = !Filename.empty();
  954. size_t MaxTasks = Lto->getMaxTasks();
  955. std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
  956. auto AddStream =
  957. [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
  958. Files[Task].second = !SaveTemps;
  959. int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
  960. Files[Task].first, Task);
  961. return std::make_unique<lto::NativeObjectStream>(
  962. std::make_unique<llvm::raw_fd_ostream>(FD, true));
  963. };
  964. auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
  965. *AddStream(Task)->OS << MB->getBuffer();
  966. };
  967. NativeObjectCache Cache;
  968. if (!options::cache_dir.empty())
  969. Cache = check(localCache(options::cache_dir, AddBuffer));
  970. check(Lto->run(AddStream, Cache));
  971. // Write empty output files that may be expected by the distributed build
  972. // system.
  973. if (options::thinlto_index_only)
  974. for (auto &Identifier : ObjectToIndexFileState)
  975. if (!Identifier.getValue())
  976. writeEmptyDistributedBuildOutputs(std::string(Identifier.getKey()),
  977. OldPrefix, NewPrefix,
  978. /* SkipModule */ false);
  979. return Files;
  980. }
  981. /// gold informs us that all symbols have been read. At this point, we use
  982. /// get_symbols to see if any of our definitions have been overridden by a
  983. /// native object file. Then, perform optimization and codegen.
  984. static ld_plugin_status allSymbolsReadHook() {
  985. if (Modules.empty())
  986. return LDPS_OK;
  987. if (unsigned NumOpts = options::extra.size())
  988. cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
  989. std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
  990. if (options::TheOutputType == options::OT_DISABLE ||
  991. options::TheOutputType == options::OT_BC_ONLY ||
  992. options::TheOutputType == options::OT_ASM_ONLY)
  993. return LDPS_OK;
  994. if (options::thinlto_index_only) {
  995. llvm_shutdown();
  996. cleanup_hook();
  997. exit(0);
  998. }
  999. for (const auto &F : Files)
  1000. if (!F.first.empty())
  1001. recordFile(std::string(F.first.str()), F.second);
  1002. if (!options::extra_library_path.empty() &&
  1003. set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
  1004. message(LDPL_FATAL, "Unable to set the extra library path.");
  1005. return LDPS_OK;
  1006. }
  1007. static ld_plugin_status all_symbols_read_hook(void) {
  1008. ld_plugin_status Ret = allSymbolsReadHook();
  1009. llvm_shutdown();
  1010. if (options::TheOutputType == options::OT_BC_ONLY ||
  1011. options::TheOutputType == options::OT_ASM_ONLY ||
  1012. options::TheOutputType == options::OT_DISABLE) {
  1013. if (options::TheOutputType == options::OT_DISABLE) {
  1014. // Remove the output file here since ld.bfd creates the output file
  1015. // early.
  1016. std::error_code EC = sys::fs::remove(output_name);
  1017. if (EC)
  1018. message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
  1019. EC.message().c_str());
  1020. }
  1021. exit(0);
  1022. }
  1023. return Ret;
  1024. }
  1025. static ld_plugin_status cleanup_hook(void) {
  1026. for (std::string &Name : Cleanup) {
  1027. std::error_code EC = sys::fs::remove(Name);
  1028. if (EC)
  1029. message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
  1030. EC.message().c_str());
  1031. }
  1032. // Prune cache
  1033. if (!options::cache_dir.empty()) {
  1034. CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
  1035. pruneCache(options::cache_dir, policy);
  1036. }
  1037. return LDPS_OK;
  1038. }