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