gold-plugin.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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 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. // Not setting comdat_key for nodeduplicate ensuress we don't deduplicate.
  574. std::pair<StringRef, Comdat::SelectionKind> C = Obj->getComdatTable()[CI];
  575. if (C.second != Comdat::NoDeduplicate)
  576. sym.comdat_key = strdup(C.first.str().c_str());
  577. }
  578. sym.resolution = LDPR_UNKNOWN;
  579. }
  580. if (!cf.syms.empty()) {
  581. if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
  582. message(LDPL_ERROR, "Unable to add symbols!");
  583. return LDPS_ERR;
  584. }
  585. }
  586. // Handle any --wrap options passed to gold, which are than passed
  587. // along to the plugin.
  588. if (get_wrap_symbols) {
  589. const char **wrap_symbols;
  590. uint64_t count = 0;
  591. if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
  592. message(LDPL_ERROR, "Unable to get wrap symbols!");
  593. return LDPS_ERR;
  594. }
  595. for (uint64_t i = 0; i < count; i++) {
  596. StringRef Name = wrap_symbols[i];
  597. ResolutionInfo &Res = ResInfo[Name];
  598. ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
  599. ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
  600. // Tell LTO not to inline symbols that will be overwritten.
  601. Res.CanInline = false;
  602. RealRes.CanInline = false;
  603. // Tell LTO not to eliminate symbols that will be used after renaming.
  604. Res.IsUsedInRegularObj = true;
  605. WrapRes.IsUsedInRegularObj = true;
  606. }
  607. }
  608. return LDPS_OK;
  609. }
  610. static void freeSymName(ld_plugin_symbol &Sym) {
  611. free(Sym.name);
  612. free(Sym.comdat_key);
  613. Sym.name = nullptr;
  614. Sym.comdat_key = nullptr;
  615. }
  616. /// Helper to get a file's symbols and a view into it via gold callbacks.
  617. static const void *getSymbolsAndView(claimed_file &F) {
  618. ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
  619. if (status == LDPS_NO_SYMS)
  620. return nullptr;
  621. if (status != LDPS_OK)
  622. message(LDPL_FATAL, "Failed to get symbol information");
  623. const void *View;
  624. if (get_view(F.handle, &View) != LDPS_OK)
  625. message(LDPL_FATAL, "Failed to get a view of file");
  626. return View;
  627. }
  628. /// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
  629. /// \p NewSuffix strings, if it was specified.
  630. static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
  631. std::string &NewSuffix) {
  632. assert(options::thinlto_object_suffix_replace.empty() ||
  633. options::thinlto_object_suffix_replace.find(';') != StringRef::npos);
  634. StringRef SuffixReplace = options::thinlto_object_suffix_replace;
  635. auto Split = SuffixReplace.split(';');
  636. OldSuffix = std::string(Split.first);
  637. NewSuffix = std::string(Split.second);
  638. }
  639. /// Given the original \p Path to an output file, replace any filename
  640. /// suffix matching \p OldSuffix with \p NewSuffix.
  641. static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
  642. StringRef NewSuffix) {
  643. if (Path.consume_back(OldSuffix))
  644. return (Path + NewSuffix).str();
  645. return std::string(Path);
  646. }
  647. // Returns true if S is valid as a C language identifier.
  648. static bool isValidCIdentifier(StringRef S) {
  649. return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
  650. std::all_of(S.begin() + 1, S.end(),
  651. [](char C) { return C == '_' || isAlnum(C); });
  652. }
  653. static bool isUndefined(ld_plugin_symbol &Sym) {
  654. return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
  655. }
  656. static void addModule(LTO &Lto, claimed_file &F, const void *View,
  657. StringRef Filename) {
  658. MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
  659. Filename);
  660. Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
  661. if (!ObjOrErr)
  662. message(LDPL_FATAL, "Could not read bitcode from file : %s",
  663. toString(ObjOrErr.takeError()).c_str());
  664. unsigned SymNum = 0;
  665. std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
  666. auto InputFileSyms = Input->symbols();
  667. assert(InputFileSyms.size() == F.syms.size());
  668. std::vector<SymbolResolution> Resols(F.syms.size());
  669. for (ld_plugin_symbol &Sym : F.syms) {
  670. const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
  671. SymbolResolution &R = Resols[SymNum++];
  672. ld_plugin_symbol_resolution Resolution =
  673. (ld_plugin_symbol_resolution)Sym.resolution;
  674. ResolutionInfo &Res = ResInfo[Sym.name];
  675. switch (Resolution) {
  676. case LDPR_UNKNOWN:
  677. llvm_unreachable("Unexpected resolution");
  678. case LDPR_RESOLVED_IR:
  679. case LDPR_RESOLVED_EXEC:
  680. case LDPR_PREEMPTED_IR:
  681. case LDPR_PREEMPTED_REG:
  682. case LDPR_UNDEF:
  683. break;
  684. case LDPR_RESOLVED_DYN:
  685. R.ExportDynamic = true;
  686. break;
  687. case LDPR_PREVAILING_DEF_IRONLY:
  688. R.Prevailing = !isUndefined(Sym);
  689. break;
  690. case LDPR_PREVAILING_DEF:
  691. R.Prevailing = !isUndefined(Sym);
  692. R.VisibleToRegularObj = true;
  693. break;
  694. case LDPR_PREVAILING_DEF_IRONLY_EXP:
  695. R.Prevailing = !isUndefined(Sym);
  696. // Identify symbols exported dynamically, and that therefore could be
  697. // referenced by a shared library not visible to the linker.
  698. R.ExportDynamic = true;
  699. if (!Res.CanOmitFromDynSym)
  700. R.VisibleToRegularObj = true;
  701. break;
  702. }
  703. // If the symbol has a C identifier section name, we need to mark
  704. // it as visible to a regular object so that LTO will keep it around
  705. // to ensure the linker generates special __start_<secname> and
  706. // __stop_<secname> symbols which may be used elsewhere.
  707. if (isValidCIdentifier(InpSym.getSectionName()))
  708. R.VisibleToRegularObj = true;
  709. if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
  710. (IsExecutable || !Res.DefaultVisibility))
  711. R.FinalDefinitionInLinkageUnit = true;
  712. if (!Res.CanInline)
  713. R.LinkerRedefined = true;
  714. if (Res.IsUsedInRegularObj)
  715. R.VisibleToRegularObj = true;
  716. freeSymName(Sym);
  717. }
  718. check(Lto.add(std::move(Input), Resols),
  719. std::string("Failed to link module ") + F.name);
  720. }
  721. static void recordFile(const std::string &Filename, bool TempOutFile) {
  722. if (add_input_file(Filename.c_str()) != LDPS_OK)
  723. message(LDPL_FATAL,
  724. "Unable to add .o file to the link. File left behind in: %s",
  725. Filename.c_str());
  726. if (TempOutFile)
  727. Cleanup.push_back(Filename);
  728. }
  729. /// Return the desired output filename given a base input name, a flag
  730. /// indicating whether a temp file should be generated, and an optional task id.
  731. /// The new filename generated is returned in \p NewFilename.
  732. static int getOutputFileName(StringRef InFilename, bool TempOutFile,
  733. SmallString<128> &NewFilename, int TaskID) {
  734. int FD = -1;
  735. if (TempOutFile) {
  736. std::error_code EC =
  737. sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
  738. if (EC)
  739. message(LDPL_FATAL, "Could not create temporary file: %s",
  740. EC.message().c_str());
  741. } else {
  742. NewFilename = InFilename;
  743. if (TaskID > 0)
  744. NewFilename += utostr(TaskID);
  745. std::error_code EC =
  746. sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);
  747. if (EC)
  748. message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
  749. EC.message().c_str());
  750. }
  751. return FD;
  752. }
  753. static CodeGenOpt::Level getCGOptLevel() {
  754. switch (options::OptLevel) {
  755. case 0:
  756. return CodeGenOpt::None;
  757. case 1:
  758. return CodeGenOpt::Less;
  759. case 2:
  760. return CodeGenOpt::Default;
  761. case 3:
  762. return CodeGenOpt::Aggressive;
  763. }
  764. llvm_unreachable("Invalid optimization level");
  765. }
  766. /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
  767. /// \p NewPrefix strings, if it was specified.
  768. static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
  769. std::string &NewPrefix) {
  770. StringRef PrefixReplace = options::thinlto_prefix_replace;
  771. assert(PrefixReplace.empty() || PrefixReplace.find(';') != StringRef::npos);
  772. auto Split = PrefixReplace.split(';');
  773. OldPrefix = std::string(Split.first);
  774. NewPrefix = std::string(Split.second);
  775. }
  776. /// Creates instance of LTO.
  777. /// OnIndexWrite is callback to let caller know when LTO writes index files.
  778. /// LinkedObjectsFile is an output stream to write the list of object files for
  779. /// the final ThinLTO linking. Can be nullptr.
  780. static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
  781. raw_fd_ostream *LinkedObjectsFile) {
  782. Config Conf;
  783. ThinBackend Backend;
  784. Conf.CPU = options::mcpu;
  785. Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple());
  786. // Disable the new X86 relax relocations since gold might not support them.
  787. // FIXME: Check the gold version or add a new option to enable them.
  788. Conf.Options.RelaxELFRelocations = false;
  789. // Toggle function/data sections.
  790. if (!codegen::getExplicitFunctionSections())
  791. Conf.Options.FunctionSections = SplitSections;
  792. if (!codegen::getExplicitDataSections())
  793. Conf.Options.DataSections = SplitSections;
  794. Conf.MAttrs = codegen::getMAttrs();
  795. Conf.RelocModel = RelocationModel;
  796. Conf.CodeModel = codegen::getExplicitCodeModel();
  797. Conf.CGOptLevel = getCGOptLevel();
  798. Conf.DisableVerify = options::DisableVerify;
  799. Conf.OptLevel = options::OptLevel;
  800. Conf.PTO.LoopVectorization = options::OptLevel > 1;
  801. Conf.PTO.SLPVectorization = options::OptLevel > 1;
  802. Conf.AlwaysEmitRegularLTOObj = !options::obj_path.empty();
  803. if (options::thinlto_index_only) {
  804. std::string OldPrefix, NewPrefix;
  805. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  806. Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
  807. options::thinlto_emit_imports_files,
  808. LinkedObjectsFile, OnIndexWrite);
  809. } else {
  810. Backend = createInProcessThinBackend(
  811. llvm::heavyweight_hardware_concurrency(options::Parallelism));
  812. }
  813. Conf.OverrideTriple = options::triple;
  814. Conf.DefaultTriple = sys::getDefaultTargetTriple();
  815. Conf.DiagHandler = diagnosticHandler;
  816. switch (options::TheOutputType) {
  817. case options::OT_NORMAL:
  818. break;
  819. case options::OT_DISABLE:
  820. Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
  821. break;
  822. case options::OT_BC_ONLY:
  823. Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
  824. std::error_code EC;
  825. SmallString<128> TaskFilename;
  826. getOutputFileName(output_name, /* TempOutFile */ false, TaskFilename,
  827. Task);
  828. raw_fd_ostream OS(TaskFilename, EC, sys::fs::OpenFlags::OF_None);
  829. if (EC)
  830. message(LDPL_FATAL, "Failed to write the output file.");
  831. WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
  832. return false;
  833. };
  834. break;
  835. case options::OT_SAVE_TEMPS:
  836. check(Conf.addSaveTemps(output_name + ".",
  837. /* UseInputModulePath */ true));
  838. break;
  839. case options::OT_ASM_ONLY:
  840. Conf.CGFileType = CGFT_AssemblyFile;
  841. break;
  842. }
  843. if (!options::sample_profile.empty())
  844. Conf.SampleProfile = options::sample_profile;
  845. if (!options::cs_profile_path.empty())
  846. Conf.CSIRProfile = options::cs_profile_path;
  847. Conf.RunCSIRInstr = options::cs_pgo_gen;
  848. Conf.DwoDir = options::dwo_dir;
  849. // Set up optimization remarks handling.
  850. Conf.RemarksFilename = options::RemarksFilename;
  851. Conf.RemarksPasses = options::RemarksPasses;
  852. Conf.RemarksWithHotness = options::RemarksWithHotness;
  853. Conf.RemarksHotnessThreshold = options::RemarksHotnessThreshold;
  854. Conf.RemarksFormat = options::RemarksFormat;
  855. // Use new pass manager if set in driver
  856. Conf.UseNewPM = options::new_pass_manager;
  857. // Debug new pass manager if requested
  858. Conf.DebugPassManager = options::debug_pass_manager;
  859. Conf.HasWholeProgramVisibility = options::whole_program_visibility;
  860. Conf.StatsFile = options::stats_file;
  861. return std::make_unique<LTO>(std::move(Conf), Backend,
  862. options::ParallelCodeGenParallelismLevel);
  863. }
  864. // Write empty files that may be expected by a distributed build
  865. // system when invoked with thinlto_index_only. This is invoked when
  866. // the linker has decided not to include the given module in the
  867. // final link. Frequently the distributed build system will want to
  868. // confirm that all expected outputs are created based on all of the
  869. // modules provided to the linker.
  870. // If SkipModule is true then .thinlto.bc should contain just
  871. // SkipModuleByDistributedBackend flag which requests distributed backend
  872. // to skip the compilation of the corresponding module and produce an empty
  873. // object file.
  874. static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
  875. const std::string &OldPrefix,
  876. const std::string &NewPrefix,
  877. bool SkipModule) {
  878. std::string NewModulePath =
  879. getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
  880. std::error_code EC;
  881. {
  882. raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
  883. sys::fs::OpenFlags::OF_None);
  884. if (EC)
  885. message(LDPL_FATAL, "Failed to write '%s': %s",
  886. (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
  887. if (SkipModule) {
  888. ModuleSummaryIndex Index(/*HaveGVs*/ false);
  889. Index.setSkipModuleByDistributedBackend();
  890. writeIndexToFile(Index, OS, nullptr);
  891. }
  892. }
  893. if (options::thinlto_emit_imports_files) {
  894. raw_fd_ostream OS(NewModulePath + ".imports", EC,
  895. sys::fs::OpenFlags::OF_None);
  896. if (EC)
  897. message(LDPL_FATAL, "Failed to write '%s': %s",
  898. (NewModulePath + ".imports").c_str(), EC.message().c_str());
  899. }
  900. }
  901. // Creates and returns output stream with a list of object files for final
  902. // linking of distributed ThinLTO.
  903. static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
  904. if (options::thinlto_linked_objects_file.empty())
  905. return nullptr;
  906. assert(options::thinlto_index_only);
  907. std::error_code EC;
  908. auto LinkedObjectsFile = std::make_unique<raw_fd_ostream>(
  909. options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::OF_None);
  910. if (EC)
  911. message(LDPL_FATAL, "Failed to create '%s': %s",
  912. options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
  913. return LinkedObjectsFile;
  914. }
  915. /// Runs LTO and return a list of pairs <FileName, IsTemporary>.
  916. static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
  917. // Map to own RAII objects that manage the file opening and releasing
  918. // interfaces with gold. This is needed only for ThinLTO mode, since
  919. // unlike regular LTO, where addModule will result in the opened file
  920. // being merged into a new combined module, we need to keep these files open
  921. // through Lto->run().
  922. DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
  923. // Owns string objects and tells if index file was already created.
  924. StringMap<bool> ObjectToIndexFileState;
  925. std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
  926. std::unique_ptr<LTO> Lto = createLTO(
  927. [&ObjectToIndexFileState](const std::string &Identifier) {
  928. ObjectToIndexFileState[Identifier] = true;
  929. },
  930. LinkedObjects.get());
  931. std::string OldPrefix, NewPrefix;
  932. if (options::thinlto_index_only)
  933. getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
  934. std::string OldSuffix, NewSuffix;
  935. getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
  936. for (claimed_file &F : Modules) {
  937. if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
  938. HandleToInputFile.insert(std::make_pair(
  939. F.leader_handle, std::make_unique<PluginInputFile>(F.handle)));
  940. // In case we are thin linking with a minimized bitcode file, ensure
  941. // the module paths encoded in the index reflect where the backends
  942. // will locate the full bitcode files for compiling/importing.
  943. std::string Identifier =
  944. getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
  945. auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
  946. assert(ObjFilename.second);
  947. if (const void *View = getSymbolsAndView(F))
  948. addModule(*Lto, F, View, ObjFilename.first->first());
  949. else if (options::thinlto_index_only) {
  950. ObjFilename.first->second = true;
  951. writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
  952. /* SkipModule */ true);
  953. }
  954. }
  955. SmallString<128> Filename;
  956. // Note that getOutputFileName will append a unique ID for each task
  957. if (!options::obj_path.empty())
  958. Filename = options::obj_path;
  959. else if (options::TheOutputType == options::OT_SAVE_TEMPS)
  960. Filename = output_name + ".lto.o";
  961. else if (options::TheOutputType == options::OT_ASM_ONLY)
  962. Filename = output_name;
  963. bool SaveTemps = !Filename.empty();
  964. size_t MaxTasks = Lto->getMaxTasks();
  965. std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
  966. auto AddStream = [&](size_t Task) -> 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, std::unique_ptr<MemoryBuffer> MB) {
  974. *AddStream(Task)->OS << MB->getBuffer();
  975. };
  976. FileCache Cache;
  977. if (!options::cache_dir.empty())
  978. Cache = check(localCache("ThinLTO", "Thin", options::cache_dir, AddBuffer));
  979. check(Lto->run(AddStream, Cache));
  980. // Write empty output files that may be expected by the distributed build
  981. // system.
  982. if (options::thinlto_index_only)
  983. for (auto &Identifier : ObjectToIndexFileState)
  984. if (!Identifier.getValue())
  985. writeEmptyDistributedBuildOutputs(std::string(Identifier.getKey()),
  986. OldPrefix, NewPrefix,
  987. /* SkipModule */ false);
  988. return Files;
  989. }
  990. /// gold informs us that all symbols have been read. At this point, we use
  991. /// get_symbols to see if any of our definitions have been overridden by a
  992. /// native object file. Then, perform optimization and codegen.
  993. static ld_plugin_status allSymbolsReadHook() {
  994. if (Modules.empty())
  995. return LDPS_OK;
  996. if (unsigned NumOpts = options::extra.size())
  997. cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
  998. std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
  999. if (options::TheOutputType == options::OT_DISABLE ||
  1000. options::TheOutputType == options::OT_BC_ONLY ||
  1001. options::TheOutputType == options::OT_ASM_ONLY)
  1002. return LDPS_OK;
  1003. if (options::thinlto_index_only) {
  1004. llvm_shutdown();
  1005. cleanup_hook();
  1006. exit(0);
  1007. }
  1008. for (const auto &F : Files)
  1009. if (!F.first.empty())
  1010. recordFile(std::string(F.first.str()), F.second);
  1011. if (!options::extra_library_path.empty() &&
  1012. set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
  1013. message(LDPL_FATAL, "Unable to set the extra library path.");
  1014. return LDPS_OK;
  1015. }
  1016. static ld_plugin_status all_symbols_read_hook(void) {
  1017. ld_plugin_status Ret = allSymbolsReadHook();
  1018. llvm_shutdown();
  1019. if (options::TheOutputType == options::OT_BC_ONLY ||
  1020. options::TheOutputType == options::OT_ASM_ONLY ||
  1021. options::TheOutputType == options::OT_DISABLE) {
  1022. if (options::TheOutputType == options::OT_DISABLE) {
  1023. // Remove the output file here since ld.bfd creates the output file
  1024. // early.
  1025. std::error_code EC = sys::fs::remove(output_name);
  1026. if (EC)
  1027. message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
  1028. EC.message().c_str());
  1029. }
  1030. exit(0);
  1031. }
  1032. return Ret;
  1033. }
  1034. static ld_plugin_status cleanup_hook(void) {
  1035. for (std::string &Name : Cleanup) {
  1036. std::error_code EC = sys::fs::remove(Name);
  1037. if (EC)
  1038. message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
  1039. EC.message().c_str());
  1040. }
  1041. // Prune cache
  1042. if (!options::cache_dir.empty()) {
  1043. CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
  1044. pruneCache(options::cache_dir, policy);
  1045. }
  1046. return LDPS_OK;
  1047. }