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