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