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