blob: 239460d972d4c22999a1af4c2a8d19e8d9f556ac [file] [log] [blame]
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001//===-- 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
Teresa Johnson95597ae2017-02-02 17:33:53 +000015#include "llvm/ADT/Statistic.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000016#include "llvm/Bitcode/BitcodeReader.h"
17#include "llvm/Bitcode/BitcodeWriter.h"
David Blaikie4333f972018-04-11 18:49:37 +000018#include "llvm/CodeGen/CommandFlags.inc"
Mehdi Aminib550cb12016-04-18 09:17:29 +000019#include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
Rafael Espindola890db272014-09-09 20:08:22 +000020#include "llvm/IR/Constants.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000021#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson57891a52016-08-24 15:11:47 +000022#include "llvm/LTO/Caching.h"
Teresa Johnson683abe72016-05-26 01:46:41 +000023#include "llvm/LTO/LTO.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000024#include "llvm/Object/Error.h"
Yi Kongbb4b4ee2017-09-18 23:24:55 +000025#include "llvm/Support/CachePruning.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000026#include "llvm/Support/CommandLine.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000027#include "llvm/Support/FileSystem.h"
Rafael Espindola947bdb62014-11-25 20:52:49 +000028#include "llvm/Support/ManagedStatic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000029#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000030#include "llvm/Support/Path.h"
Rafael Espindola6b244b12014-06-19 21:14:13 +000031#include "llvm/Support/TargetSelect.h"
Teresa Johnsonb13dbd62015-12-09 19:45:55 +000032#include "llvm/Support/raw_ostream.h"
Nick Lewyckyfb643e42009-02-03 07:13:24 +000033#include <list>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000034#include <map>
Chandler Carruth07baed52014-01-13 08:04:33 +000035#include <plugin-api.h>
Teresa Johnson9ba95f92016-08-11 14:58:12 +000036#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000037#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000038#include <utility>
Nick Lewyckyfb643e42009-02-03 07:13:24 +000039#include <vector>
40
Sylvestre Ledru53999792014-02-11 17:30:18 +000041// FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
42// Precise and Debian Wheezy (binutils 2.23 is required)
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +000043#define LDPO_PIE 3
44
45#define LDPT_GET_SYMBOLS_V3 28
Sylvestre Ledru53999792014-02-11 17:30:18 +000046
Teresa Johnson8883af62018-03-14 13:26:18 +000047// FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
48// required version.
49#define LDPT_GET_WRAP_SYMBOLS 32
50
Nick Lewyckyfb643e42009-02-03 07:13:24 +000051using namespace llvm;
Teresa Johnson9ba95f92016-08-11 14:58:12 +000052using namespace lto;
Nick Lewyckyfb643e42009-02-03 07:13:24 +000053
Teresa Johnson8883af62018-03-14 13:26:18 +000054// FIXME: Remove when binutils 2.31 (containing gold 1.16) is the minimum
55// required version.
56typedef enum ld_plugin_status (*ld_plugin_get_wrap_symbols)(
57 uint64_t *num_symbols, const char ***wrap_symbol_list);
58
Teresa Johnsoncb15b732015-12-16 16:34:06 +000059static 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
65static ld_plugin_release_input_file release_input_file = nullptr;
66static ld_plugin_get_input_file get_input_file = nullptr;
67static ld_plugin_message message = discard_message;
Teresa Johnson8883af62018-03-14 13:26:18 +000068static ld_plugin_get_wrap_symbols get_wrap_symbols = nullptr;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000069
Nick Lewyckyfb643e42009-02-03 07:13:24 +000070namespace {
Rafael Espindolabfb8b912014-06-20 01:37:35 +000071struct claimed_file {
72 void *handle;
Teresa Johnson683abe72016-05-26 01:46:41 +000073 void *leader_handle;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000074 std::vector<ld_plugin_symbol> syms;
Teresa Johnson683abe72016-05-26 01:46:41 +000075 off_t filesize;
76 std::string name;
Rafael Espindolabfb8b912014-06-20 01:37:35 +000077};
Rafael Espindolacaabe222015-12-10 14:19:35 +000078
Teresa Johnsoncb15b732015-12-16 16:34:06 +000079/// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
80struct PluginInputFile {
Teresa Johnson031bed22015-12-16 21:37:48 +000081 void *Handle;
Teresa Johnson7cffaf32016-03-04 17:06:02 +000082 std::unique_ptr<ld_plugin_input_file> File;
Teresa Johnsoncb15b732015-12-16 16:34:06 +000083
Teresa Johnson031bed22015-12-16 21:37:48 +000084 PluginInputFile(void *Handle) : Handle(Handle) {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000085 File = llvm::make_unique<ld_plugin_input_file>();
86 if (get_input_file(Handle, File.get()) != LDPS_OK)
Teresa Johnsoncb15b732015-12-16 16:34:06 +000087 message(LDPL_FATAL, "Failed to get file information");
88 }
89 ~PluginInputFile() {
Teresa Johnson7cffaf32016-03-04 17:06:02 +000090 // 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");
Teresa Johnsoncb15b732015-12-16 16:34:06 +000095 }
Teresa Johnson7cffaf32016-03-04 17:06:02 +000096
97 ld_plugin_input_file &file() { return *File; }
98
99 PluginInputFile(PluginInputFile &&RHS) = default;
100 PluginInputFile &operator=(PluginInputFile &&RHS) = default;
Teresa Johnsoncb15b732015-12-16 16:34:06 +0000101};
102
Rafael Espindolacaabe222015-12-10 14:19:35 +0000103struct ResolutionInfo {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000104 bool CanOmitFromDynSym = true;
105 bool DefaultVisibility = true;
Teresa Johnson8883af62018-03-14 13:26:18 +0000106 bool CanInline = true;
107 bool IsUsedInRegularObj = false;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000108};
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000109
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000110}
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000111
Rafael Espindola176e6642014-07-29 21:46:05 +0000112static ld_plugin_add_symbols add_symbols = nullptr;
113static ld_plugin_get_symbols get_symbols = nullptr;
114static ld_plugin_add_input_file add_input_file = nullptr;
115static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
116static ld_plugin_get_view get_view = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000117static bool IsExecutable = false;
Bill Wendling7bd9e942018-07-12 20:35:58 +0000118static bool SplitSections = true;
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000119static Optional<Reloc::Model> RelocationModel = None;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000120static std::string output_name = "";
121static std::list<claimed_file> Modules;
Teresa Johnson683abe72016-05-26 01:46:41 +0000122static DenseMap<int, void *> FDToLeaderHandle;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000123static StringMap<ResolutionInfo> ResInfo;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000124static std::vector<std::string> Cleanup;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000125
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000126namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000127 enum OutputType {
128 OT_NORMAL,
129 OT_DISABLE,
130 OT_BC_ONLY,
131 OT_SAVE_TEMPS
132 };
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000133 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000134 static unsigned OptLevel = 2;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000135 // Default parallelism of 0 used to indicate that user did not specify.
136 // Actual parallelism default value depends on implementation.
Teresa Johnsonec544c52016-10-19 17:35:01 +0000137 // Currently only affects ThinLTO, where the default is
138 // llvm::heavyweight_hardware_concurrency.
Teresa Johnsona9f65552016-03-04 16:36:06 +0000139 static unsigned Parallelism = 0;
Teresa Johnson896fee22016-09-23 20:35:19 +0000140 // Default regular LTO codegen parallelism (number of partitions).
141 static unsigned ParallelCodeGenParallelismLevel = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000142#ifdef NDEBUG
143 static bool DisableVerify = true;
144#else
145 static bool DisableVerify = false;
146#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000147 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000148 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000149 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000150 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000151 // When the thinlto plugin option is specified, only read the function
152 // the information from intermediate files and write a combined
153 // global index for the ThinLTO backends.
154 static bool thinlto = false;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000155 // If false, all ThinLTO backend compilations through code gen are performed
156 // using multiple threads in the gold-plugin, before handing control back to
Teresa Johnson84174c32016-05-10 13:48:23 +0000157 // gold. If true, write individual backend index files which reflect
158 // the import decisions, and exit afterwards. The assumption is
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000159 // that the build system will launch the backend processes.
160 static bool thinlto_index_only = false;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000161 // If non-empty, holds the name of a file in which to write the list of
162 // oject files gold selected for inclusion in the link after symbol
163 // resolution (i.e. they had selected symbols). This will only be non-empty
164 // in the thinlto_index_only case. It is used to identify files, which may
165 // have originally been within archive libraries specified via
166 // --start-lib/--end-lib pairs, that should be included in the final
167 // native link process (since intervening function importing and inlining
168 // may change the symbol resolution detected in the final link and which
169 // files to include out of --start-lib/--end-lib libraries as a result).
170 static std::string thinlto_linked_objects_file;
Teresa Johnson8570fe42016-05-10 15:54:09 +0000171 // If true, when generating individual index files for distributed backends,
172 // also generate a "${bitcodefile}.imports" file at the same location for each
173 // bitcode file, listing the files it imports from in plain text. This is to
174 // support distributed build file staging.
175 static bool thinlto_emit_imports_files = false;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000176 // Option to control where files for a distributed backend (the individual
177 // index files and optional imports files) are created.
178 // If specified, expects a string of the form "oldprefix:newprefix", and
179 // instead of generating these files in the same directory path as the
180 // corresponding bitcode file, will use a path formed by replacing the
181 // bitcode file's path prefix matching oldprefix with newprefix.
182 static std::string thinlto_prefix_replace;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000183 // Option to control the name of modules encoded in the individual index
184 // files for a distributed backend. This enables the use of minimized
185 // bitcode files for the thin link, assuming the name of the full bitcode
186 // file used in the backend differs just in some part of the file suffix.
187 // If specified, expects a string of the form "oldsuffix:newsuffix".
188 static std::string thinlto_object_suffix_replace;
Teresa Johnson57891a52016-08-24 15:11:47 +0000189 // Optional path to a directory for caching ThinLTO objects.
190 static std::string cache_dir;
Yi Kongbb4b4ee2017-09-18 23:24:55 +0000191 // Optional pruning policy for ThinLTO caches.
192 static std::string cache_policy;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000193 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000194 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000195 // as plugin exclusive to pass to the code generator.
Rafael Espindola125b9242014-07-29 19:17:44 +0000196 static std::vector<const char *> extra;
Dehao Chen27978002016-12-16 16:48:46 +0000197 // Sample profile file path
198 static std::string sample_profile;
Sean Fertiledf8d9982017-10-05 01:48:42 +0000199 // New pass manager
200 static bool new_pass_manager = false;
Teresa Johnson70565e42018-04-05 03:16:57 +0000201 // Debug new pass manager
202 static bool debug_pass_manager = false;
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000203 // Directory to store the .dwo files.
204 static std::string dwo_dir;
Florian Hahnd4332eb2018-04-20 10:18:36 +0000205 /// Statistics output filename.
206 static std::string stats_file;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000207
Teresa Johnsonb214af22018-04-18 13:25:23 +0000208 // Optimization remarks filename and hotness options
209 static std::string OptRemarksFilename;
210 static bool OptRemarksWithHotness = false;
211
Nick Lewycky7282dd72015-08-05 21:16:02 +0000212 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000213 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000214 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000215 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000216 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000217
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000218 if (opt.startswith("mcpu=")) {
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000219 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000220 } else if (opt.startswith("extra-library-path=")) {
221 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000222 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000223 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000224 } else if (opt.startswith("obj-path=")) {
225 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000226 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000227 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000228 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000229 TheOutputType = OT_SAVE_TEMPS;
230 } else if (opt == "disable-output") {
231 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000232 } else if (opt == "thinlto") {
233 thinlto = true;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000234 } else if (opt == "thinlto-index-only") {
235 thinlto_index_only = true;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000236 } else if (opt.startswith("thinlto-index-only=")) {
237 thinlto_index_only = true;
238 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson8570fe42016-05-10 15:54:09 +0000239 } else if (opt == "thinlto-emit-imports-files") {
240 thinlto_emit_imports_files = true;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000241 } else if (opt.startswith("thinlto-prefix-replace=")) {
242 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000243 if (thinlto_prefix_replace.find(';') == std::string::npos)
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000244 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000245 } else if (opt.startswith("thinlto-object-suffix-replace=")) {
246 thinlto_object_suffix_replace =
247 opt.substr(strlen("thinlto-object-suffix-replace="));
248 if (thinlto_object_suffix_replace.find(';') == std::string::npos)
249 message(LDPL_FATAL,
250 "thinlto-object-suffix-replace expects 'old;new' format");
Teresa Johnson57891a52016-08-24 15:11:47 +0000251 } else if (opt.startswith("cache-dir=")) {
252 cache_dir = opt.substr(strlen("cache-dir="));
Yi Kongbb4b4ee2017-09-18 23:24:55 +0000253 } else if (opt.startswith("cache-policy=")) {
254 cache_policy = opt.substr(strlen("cache-policy="));
Peter Collingbourne070843d2015-03-19 22:01:00 +0000255 } else if (opt.size() == 2 && opt[0] == 'O') {
256 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000257 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000258 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000259 } else if (opt.startswith("jobs=")) {
260 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
261 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson896fee22016-09-23 20:35:19 +0000262 } else if (opt.startswith("lto-partitions=")) {
263 if (opt.substr(strlen("lto-partitions="))
264 .getAsInteger(10, ParallelCodeGenParallelismLevel))
265 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000266 } else if (opt == "disable-verify") {
267 DisableVerify = true;
Dehao Chen27978002016-12-16 16:48:46 +0000268 } else if (opt.startswith("sample-profile=")) {
269 sample_profile= opt.substr(strlen("sample-profile="));
Sean Fertiledf8d9982017-10-05 01:48:42 +0000270 } else if (opt == "new-pass-manager") {
271 new_pass_manager = true;
Teresa Johnson70565e42018-04-05 03:16:57 +0000272 } else if (opt == "debug-pass-manager") {
273 debug_pass_manager = true;
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000274 } else if (opt.startswith("dwo_dir=")) {
275 dwo_dir = opt.substr(strlen("dwo_dir="));
Teresa Johnsonb214af22018-04-18 13:25:23 +0000276 } else if (opt.startswith("opt-remarks-filename=")) {
277 OptRemarksFilename = opt.substr(strlen("opt-remarks-filename="));
278 } else if (opt == "opt-remarks-with-hotness") {
279 OptRemarksWithHotness = true;
Florian Hahnd4332eb2018-04-20 10:18:36 +0000280 } else if (opt.startswith("stats-file=")) {
281 stats_file = opt.substr(strlen("stats-file="));
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000282 } else {
283 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000284 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
285 // add that.
286 if (extra.empty())
287 extra.push_back("LLVMgold");
288
Rafael Espindola125b9242014-07-29 19:17:44 +0000289 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000290 }
291 }
292}
293
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000294static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
295 int *claimed);
296static ld_plugin_status all_symbols_read_hook(void);
297static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000298
299extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
300ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000301 InitializeAllTargetInfos();
302 InitializeAllTargets();
303 InitializeAllTargetMCs();
304 InitializeAllAsmParsers();
305 InitializeAllAsmPrinters();
306
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000307 // We're given a pointer to the first transfer vector. We read through them
308 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
309 // contain pointers to functions that we need to call to register our own
310 // hooks. The others are addresses of functions we can use to call into gold
311 // for services.
312
313 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000314 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000315
316 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000317 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
318 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
319 // header.
320 switch (static_cast<int>(tv->tv_tag)) {
321 case LDPT_OUTPUT_NAME:
322 output_name = tv->tv_u.tv_string;
323 break;
324 case LDPT_LINKER_OUTPUT:
325 switch (tv->tv_u.tv_val) {
326 case LDPO_REL: // .o
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000327 IsExecutable = false;
Bill Wendling7bd9e942018-07-12 20:35:58 +0000328 SplitSections = false;
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000329 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000330 case LDPO_DYN: // .so
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000331 IsExecutable = false;
332 RelocationModel = Reloc::PIC_;
333 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000334 case LDPO_PIE: // position independent executable
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000335 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000336 RelocationModel = Reloc::PIC_;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000337 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000338 case LDPO_EXEC: // .exe
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000339 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000340 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000341 break;
342 default:
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000343 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
344 return LDPS_ERR;
345 }
346 break;
347 case LDPT_OPTION:
348 options::process_plugin_option(tv->tv_u.tv_string);
349 break;
350 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
351 ld_plugin_register_claim_file callback;
352 callback = tv->tv_u.tv_register_claim_file;
353
354 if (callback(claim_file_hook) != LDPS_OK)
355 return LDPS_ERR;
356
357 registeredClaimFile = true;
358 } break;
359 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
360 ld_plugin_register_all_symbols_read callback;
361 callback = tv->tv_u.tv_register_all_symbols_read;
362
363 if (callback(all_symbols_read_hook) != LDPS_OK)
364 return LDPS_ERR;
365
366 RegisteredAllSymbolsRead = true;
367 } break;
368 case LDPT_REGISTER_CLEANUP_HOOK: {
369 ld_plugin_register_cleanup callback;
370 callback = tv->tv_u.tv_register_cleanup;
371
372 if (callback(cleanup_hook) != LDPS_OK)
373 return LDPS_ERR;
374 } break;
375 case LDPT_GET_INPUT_FILE:
376 get_input_file = tv->tv_u.tv_get_input_file;
377 break;
378 case LDPT_RELEASE_INPUT_FILE:
379 release_input_file = tv->tv_u.tv_release_input_file;
380 break;
381 case LDPT_ADD_SYMBOLS:
382 add_symbols = tv->tv_u.tv_add_symbols;
383 break;
384 case LDPT_GET_SYMBOLS_V2:
385 // Do not override get_symbols_v3 with get_symbols_v2.
386 if (!get_symbols)
387 get_symbols = tv->tv_u.tv_get_symbols;
388 break;
389 case LDPT_GET_SYMBOLS_V3:
390 get_symbols = tv->tv_u.tv_get_symbols;
391 break;
392 case LDPT_ADD_INPUT_FILE:
393 add_input_file = tv->tv_u.tv_add_input_file;
394 break;
395 case LDPT_SET_EXTRA_LIBRARY_PATH:
396 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
397 break;
398 case LDPT_GET_VIEW:
399 get_view = tv->tv_u.tv_get_view;
400 break;
401 case LDPT_MESSAGE:
402 message = tv->tv_u.tv_message;
403 break;
Teresa Johnson8883af62018-03-14 13:26:18 +0000404 case LDPT_GET_WRAP_SYMBOLS:
405 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
406 // required version, this should be changed to:
407 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
408 get_wrap_symbols =
Teresa Johnson2f5c3312018-03-14 14:00:57 +0000409 (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
Teresa Johnson8883af62018-03-14 13:26:18 +0000410 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000411 default:
412 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000413 }
414 }
415
Rafael Espindolae08484d2009-02-18 08:30:15 +0000416 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000417 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000418 return LDPS_ERR;
419 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000420 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000421 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000422 return LDPS_ERR;
423 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000424
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000425 if (!RegisteredAllSymbolsRead)
426 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000427
Rafael Espindola33466a72014-08-21 20:28:55 +0000428 if (!get_input_file) {
429 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
430 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000431 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000432 if (!release_input_file) {
Marianne Mailhot-Sarrasina5a750e2016-03-30 12:20:53 +0000433 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola33466a72014-08-21 20:28:55 +0000434 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000435 }
436
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000437 return LDPS_OK;
438}
439
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000440static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000441 std::string ErrStorage;
442 {
443 raw_string_ostream OS(ErrStorage);
444 DiagnosticPrinterRawOStream DP(OS);
445 DI.print(DP);
446 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000447 ld_plugin_level Level;
448 switch (DI.getSeverity()) {
449 case DS_Error:
450 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
451 ErrStorage.c_str());
Rafael Espindola503f8832015-03-02 19:08:03 +0000452 case DS_Warning:
453 Level = LDPL_WARNING;
454 break;
455 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000456 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000457 Level = LDPL_INFO;
458 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000459 }
460 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000461}
462
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000463static void check(Error E, std::string Msg = "LLVM gold plugin") {
Mehdi Amini48f29602016-11-11 06:04:30 +0000464 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
466 return Error::success();
467 });
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000468}
469
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000470template <typename T> static T check(Expected<T> E) {
471 if (E)
472 return std::move(*E);
473 check(E.takeError());
474 return T();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000475}
476
Rafael Espindolae54d8212014-07-06 14:31:22 +0000477/// Called by gold to see whether this file is one that our plugin can handle.
478/// We'll try to open it and register all the symbols with add_symbol if
479/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000480static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
481 int *claimed) {
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000482 MemoryBufferRef BufferRef;
483 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000484 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000485 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000486 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000487 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000488 return LDPS_ERR;
489 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000490 BufferRef =
491 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000492 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000493 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000494 // Gold has found what might be IR part-way inside of a file, such as
495 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000496 if (file->offset) {
497 offset = file->offset;
498 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000499 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
500 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
501 offset);
502 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000503 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000504 return LDPS_ERR;
505 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000506 Buffer = std::move(BufferOrErr.get());
507 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000508 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000509
Rafael Espindola6c472e52014-07-29 20:46:19 +0000510 *claimed = 1;
511
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000512 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
513 if (!ObjOrErr) {
514 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
515 std::error_code EC = EI.convertToErrorCode();
516 if (EC == object::object_error::invalid_file_type ||
517 EC == object::object_error::bitcode_section_not_found)
518 *claimed = 0;
519 else
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000520 message(LDPL_FATAL,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000521 "LLVM gold plugin has failed to create LTO module: %s",
522 EI.message().c_str());
523 });
524
525 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000526 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527
528 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000529
Dehao Chen396f6242017-07-10 15:31:53 +0000530 Modules.emplace_back();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000531 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000532
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000533 cf.handle = file->handle;
Teresa Johnson683abe72016-05-26 01:46:41 +0000534 // Keep track of the first handle for each file descriptor, since there are
535 // multiple in the case of an archive. This is used later in the case of
536 // ThinLTO parallel backends to ensure that each file is only opened and
537 // released once.
538 auto LeaderHandle =
539 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
540 cf.leader_handle = LeaderHandle->second;
541 // Save the filesize since for parallel ThinLTO backends we can only
542 // invoke get_input_file once per archive (only for the leader handle).
543 cf.filesize = file->filesize;
544 // In the case of an archive library, all but the first member must have a
545 // non-zero offset, which we can append to the file name to obtain a
546 // unique name.
547 cf.name = file->name;
548 if (file->offset)
549 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000550 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000551
Rafael Espindola33466a72014-08-21 20:28:55 +0000552 for (auto &Sym : Obj->symbols()) {
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000553 cf.syms.push_back(ld_plugin_symbol());
554 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000555 sym.version = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000556 StringRef Name = Sym.getName();
557 sym.name = strdup(Name.str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000558
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000559 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola33466a72014-08-21 20:28:55 +0000560
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000561 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000562
Rafael Espindola33466a72014-08-21 20:28:55 +0000563 sym.visibility = LDPV_DEFAULT;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000564 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
565 if (Vis != GlobalValue::DefaultVisibility)
566 Res.DefaultVisibility = false;
567 switch (Vis) {
568 case GlobalValue::DefaultVisibility:
569 break;
570 case GlobalValue::HiddenVisibility:
571 sym.visibility = LDPV_HIDDEN;
572 break;
573 case GlobalValue::ProtectedVisibility:
574 sym.visibility = LDPV_PROTECTED;
575 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000576 }
577
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000578 if (Sym.isUndefined()) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000579 sym.def = LDPK_UNDEF;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000580 if (Sym.isWeak())
Rafael Espindola56548522009-04-24 16:55:21 +0000581 sym.def = LDPK_WEAKUNDEF;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000582 } else if (Sym.isCommon())
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000583 sym.def = LDPK_COMMON;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000584 else if (Sym.isWeak())
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000585 sym.def = LDPK_WEAKDEF;
586 else
Rafael Espindola33466a72014-08-21 20:28:55 +0000587 sym.def = LDPK_DEF;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000588
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000589 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000590 sym.comdat_key = nullptr;
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000591 int CI = Sym.getComdatIndex();
Rafael Espindola79121102016-10-25 12:02:03 +0000592 if (CI != -1) {
593 StringRef C = Obj->getComdatTable()[CI];
Rafael Espindola62382c92016-10-17 18:51:02 +0000594 sym.comdat_key = strdup(C.str().c_str());
Rafael Espindola79121102016-10-25 12:02:03 +0000595 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000596
597 sym.resolution = LDPR_UNKNOWN;
598 }
599
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000600 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000601 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000602 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000603 return LDPS_ERR;
604 }
605 }
606
Teresa Johnson8883af62018-03-14 13:26:18 +0000607 // Handle any --wrap options passed to gold, which are than passed
608 // along to the plugin.
609 if (get_wrap_symbols) {
610 const char **wrap_symbols;
611 uint64_t count = 0;
612 if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
613 message(LDPL_ERROR, "Unable to get wrap symbols!");
614 return LDPS_ERR;
615 }
616 for (uint64_t i = 0; i < count; i++) {
617 StringRef Name = wrap_symbols[i];
618 ResolutionInfo &Res = ResInfo[Name];
619 ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
620 ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
621 // Tell LTO not to inline symbols that will be overwritten.
622 Res.CanInline = false;
623 RealRes.CanInline = false;
624 // Tell LTO not to eliminate symbols that will be used after renaming.
625 Res.IsUsedInRegularObj = true;
626 WrapRes.IsUsedInRegularObj = true;
627 }
628 }
629
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000630 return LDPS_OK;
631}
632
Rafael Espindola538c9a82014-12-23 18:18:37 +0000633static void freeSymName(ld_plugin_symbol &Sym) {
634 free(Sym.name);
635 free(Sym.comdat_key);
636 Sym.name = nullptr;
637 Sym.comdat_key = nullptr;
638}
639
Teresa Johnsona9f65552016-03-04 16:36:06 +0000640/// Helper to get a file's symbols and a view into it via gold callbacks.
641static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramer39988a02016-03-08 14:02:46 +0000642 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000643 if (status == LDPS_NO_SYMS)
644 return nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000645
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000646 if (status != LDPS_OK)
Teresa Johnson403a7872015-10-04 14:33:43 +0000647 message(LDPL_FATAL, "Failed to get symbol information");
648
649 const void *View;
650 if (get_view(F.handle, &View) != LDPS_OK)
651 message(LDPL_FATAL, "Failed to get a view of file");
652
Teresa Johnsona9f65552016-03-04 16:36:06 +0000653 return View;
654}
655
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000656/// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
657/// \p NewSuffix strings, if it was specified.
658static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
659 std::string &NewSuffix) {
660 assert(options::thinlto_object_suffix_replace.empty() ||
661 options::thinlto_object_suffix_replace.find(";") != StringRef::npos);
662 StringRef SuffixReplace = options::thinlto_object_suffix_replace;
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000663 std::tie(OldSuffix, NewSuffix) = SuffixReplace.split(';');
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000664}
665
666/// Given the original \p Path to an output file, replace any filename
667/// suffix matching \p OldSuffix with \p NewSuffix.
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000668static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
669 StringRef NewSuffix) {
Fangrui Song9ba57402018-08-22 02:11:36 +0000670 if (Path.consume_back(OldSuffix))
671 return (Path + NewSuffix).str();
672 return Path;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000673}
674
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000675// Returns true if S is valid as a C language identifier.
676static bool isValidCIdentifier(StringRef S) {
George Rimar3040da02017-10-04 11:00:30 +0000677 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
678 std::all_of(S.begin() + 1, S.end(),
679 [](char C) { return C == '_' || isAlnum(C); });
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000680}
681
Eugene Leviant746f1522017-12-15 09:18:21 +0000682static bool isUndefined(ld_plugin_symbol &Sym) {
683 return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
684}
685
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000686static void addModule(LTO &Lto, claimed_file &F, const void *View,
687 StringRef Filename) {
688 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
689 Filename);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000690 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000691
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000692 if (!ObjOrErr)
Peter Collingbourne10039c02014-09-18 21:28:49 +0000693 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000694 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne10039c02014-09-18 21:28:49 +0000695
Rafael Espindola527e8462014-12-09 16:13:59 +0000696 unsigned SymNum = 0;
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000697 std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
698 auto InputFileSyms = Input->symbols();
699 assert(InputFileSyms.size() == F.syms.size());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000700 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne07586442016-09-14 02:55:16 +0000701 for (ld_plugin_symbol &Sym : F.syms) {
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000702 const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
Peter Collingbourne07586442016-09-14 02:55:16 +0000703 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola527e8462014-12-09 16:13:59 +0000704
Rafael Espindola33466a72014-08-21 20:28:55 +0000705 ld_plugin_symbol_resolution Resolution =
706 (ld_plugin_symbol_resolution)Sym.resolution;
707
Rafael Espindolacaabe222015-12-10 14:19:35 +0000708 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola890db272014-09-09 20:08:22 +0000709
Rafael Espindola33466a72014-08-21 20:28:55 +0000710 switch (Resolution) {
711 case LDPR_UNKNOWN:
712 llvm_unreachable("Unexpected resolution");
713
714 case LDPR_RESOLVED_IR:
715 case LDPR_RESOLVED_EXEC:
716 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000717 case LDPR_PREEMPTED_IR:
718 case LDPR_PREEMPTED_REG:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000719 case LDPR_UNDEF:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000720 break;
721
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000722 case LDPR_PREVAILING_DEF_IRONLY:
Eugene Leviant746f1522017-12-15 09:18:21 +0000723 R.Prevailing = !isUndefined(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000724 break;
Teresa Johnsonf99573b2016-08-11 12:56:40 +0000725
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000726 case LDPR_PREVAILING_DEF:
Eugene Leviant746f1522017-12-15 09:18:21 +0000727 R.Prevailing = !isUndefined(Sym);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000728 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000729 break;
730
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000731 case LDPR_PREVAILING_DEF_IRONLY_EXP:
Eugene Leviant746f1522017-12-15 09:18:21 +0000732 R.Prevailing = !isUndefined(Sym);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000733 if (!Res.CanOmitFromDynSym)
734 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000735 break;
736 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000737
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000738 // If the symbol has a C identifier section name, we need to mark
739 // it as visible to a regular object so that LTO will keep it around
740 // to ensure the linker generates special __start_<secname> and
741 // __stop_<secname> symbols which may be used elsewhere.
742 if (isValidCIdentifier(InpSym.getSectionName()))
743 R.VisibleToRegularObj = true;
744
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000745 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
746 (IsExecutable || !Res.DefaultVisibility))
747 R.FinalDefinitionInLinkageUnit = true;
748
Teresa Johnson8883af62018-03-14 13:26:18 +0000749 if (!Res.CanInline)
750 R.LinkerRedefined = true;
751
752 if (Res.IsUsedInRegularObj)
753 R.VisibleToRegularObj = true;
754
Rafael Espindola538c9a82014-12-23 18:18:37 +0000755 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000756 }
757
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000758 check(Lto.add(std::move(Input), Resols),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000759 std::string("Failed to link module ") + F.name);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000760}
761
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000762static void recordFile(const std::string &Filename, bool TempOutFile) {
Teresa Johnsona9f65552016-03-04 16:36:06 +0000763 if (add_input_file(Filename.c_str()) != LDPS_OK)
764 message(LDPL_FATAL,
765 "Unable to add .o file to the link. File left behind in: %s",
766 Filename.c_str());
767 if (TempOutFile)
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000768 Cleanup.push_back(Filename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000769}
Rafael Espindola33466a72014-08-21 20:28:55 +0000770
Mehdi Amini970800e2016-08-17 06:23:09 +0000771/// Return the desired output filename given a base input name, a flag
772/// indicating whether a temp file should be generated, and an optional task id.
773/// The new filename generated is returned in \p NewFilename.
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000774static int getOutputFileName(StringRef InFilename, bool TempOutFile,
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000775 SmallString<128> &NewFilename, int TaskID) {
776 int FD = -1;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000777 if (TempOutFile) {
778 std::error_code EC =
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000779 sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000780 if (EC)
781 message(LDPL_FATAL, "Could not create temporary file: %s",
782 EC.message().c_str());
783 } else {
784 NewFilename = InFilename;
Peter Collingbourne6201d782017-01-26 02:07:05 +0000785 if (TaskID > 0)
Teresa Johnsona9f65552016-03-04 16:36:06 +0000786 NewFilename += utostr(TaskID);
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000787 std::error_code EC =
Zachary Turner26986402018-06-07 20:37:22 +0000788 sys::fs::openFileForWrite(NewFilename, FD, sys::fs::CD_CreateAlways);
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000789 if (EC)
790 message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
791 EC.message().c_str());
Teresa Johnsona9f65552016-03-04 16:36:06 +0000792 }
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000793 return FD;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000794}
795
Peter Collingbourne4564ed12018-04-06 21:14:33 +0000796static CodeGenOpt::Level getCGOptLevel() {
797 switch (options::OptLevel) {
798 case 0:
799 return CodeGenOpt::None;
800 case 1:
801 return CodeGenOpt::Less;
802 case 2:
803 return CodeGenOpt::Default;
804 case 3:
805 return CodeGenOpt::Aggressive;
806 }
807 llvm_unreachable("Invalid optimization level");
808}
809
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000810/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
811/// \p NewPrefix strings, if it was specified.
812static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
813 std::string &NewPrefix) {
814 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000815 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000816 std::tie(OldPrefix, NewPrefix) = PrefixReplace.split(';');
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000817}
818
Vitaly Bukaa139b692018-02-22 19:06:15 +0000819/// Creates instance of LTO.
820/// OnIndexWrite is callback to let caller know when LTO writes index files.
821/// LinkedObjectsFile is an output stream to write the list of object files for
822/// the final ThinLTO linking. Can be nullptr.
823static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
824 raw_fd_ostream *LinkedObjectsFile) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000825 Config Conf;
826 ThinBackend Backend;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000827
828 Conf.CPU = options::mcpu;
829 Conf.Options = InitTargetOptionsFromCodeGenFlags();
830
831 // Disable the new X86 relax relocations since gold might not support them.
832 // FIXME: Check the gold version or add a new option to enable them.
833 Conf.Options.RelaxELFRelocations = false;
834
Bill Wendling7bd9e942018-07-12 20:35:58 +0000835 // Toggle function/data sections.
836 Conf.Options.FunctionSections = SplitSections;
837 Conf.Options.DataSections = SplitSections;
Davide Italiano756feb22017-07-25 23:32:50 +0000838
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000839 Conf.MAttrs = MAttrs;
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000840 Conf.RelocModel = RelocationModel;
Bill Wendling206afca2018-06-13 05:53:59 +0000841 Conf.CodeModel = getCodeModel();
Peter Collingbourne4564ed12018-04-06 21:14:33 +0000842 Conf.CGOptLevel = getCGOptLevel();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000843 Conf.DisableVerify = options::DisableVerify;
844 Conf.OptLevel = options::OptLevel;
Teresa Johnson896fee22016-09-23 20:35:19 +0000845 if (options::Parallelism)
846 Backend = createInProcessThinBackend(options::Parallelism);
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000847 if (options::thinlto_index_only) {
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000848 std::string OldPrefix, NewPrefix;
849 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Vitaly Bukaa139b692018-02-22 19:06:15 +0000850 Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
851 options::thinlto_emit_imports_files,
852 LinkedObjectsFile, OnIndexWrite);
Teresa Johnson84174c32016-05-10 13:48:23 +0000853 }
854
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000855 Conf.OverrideTriple = options::triple;
856 Conf.DefaultTriple = sys::getDefaultTargetTriple();
857
858 Conf.DiagHandler = diagnosticHandler;
859
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000860 switch (options::TheOutputType) {
861 case options::OT_NORMAL:
862 break;
863
864 case options::OT_DISABLE:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000865 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000866 break;
867
868 case options::OT_BC_ONLY:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000869 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000870 std::error_code EC;
871 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
872 if (EC)
873 message(LDPL_FATAL, "Failed to write the output file.");
Rafael Espindola6a86e252018-02-14 19:11:32 +0000874 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000875 return false;
876 };
877 break;
878
879 case options::OT_SAVE_TEMPS:
Mehdi Aminieccffad2016-08-18 00:12:33 +0000880 check(Conf.addSaveTemps(output_name + ".",
881 /* UseInputModulePath */ true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000882 break;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000883 }
884
Dehao Chen27978002016-12-16 16:48:46 +0000885 if (!options::sample_profile.empty())
886 Conf.SampleProfile = options::sample_profile;
887
Yunlian Jiangbd200b92018-04-13 05:03:28 +0000888 Conf.DwoDir = options::dwo_dir;
889
Teresa Johnsonb214af22018-04-18 13:25:23 +0000890 // Set up optimization remarks handling.
891 Conf.RemarksFilename = options::OptRemarksFilename;
892 Conf.RemarksWithHotness = options::OptRemarksWithHotness;
893
Sean Fertiledf8d9982017-10-05 01:48:42 +0000894 // Use new pass manager if set in driver
895 Conf.UseNewPM = options::new_pass_manager;
Teresa Johnson70565e42018-04-05 03:16:57 +0000896 // Debug new pass manager if requested
897 Conf.DebugPassManager = options::debug_pass_manager;
Sean Fertiledf8d9982017-10-05 01:48:42 +0000898
Florian Hahnd4332eb2018-04-20 10:18:36 +0000899 Conf.StatsFile = options::stats_file;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000900 return llvm::make_unique<LTO>(std::move(Conf), Backend,
Teresa Johnson896fee22016-09-23 20:35:19 +0000901 options::ParallelCodeGenParallelismLevel);
Teresa Johnson84174c32016-05-10 13:48:23 +0000902}
903
Teresa Johnson3f212b82016-09-21 19:12:05 +0000904// Write empty files that may be expected by a distributed build
905// system when invoked with thinlto_index_only. This is invoked when
906// the linker has decided not to include the given module in the
907// final link. Frequently the distributed build system will want to
908// confirm that all expected outputs are created based on all of the
909// modules provided to the linker.
Vitaly Buka769134d2018-02-16 23:38:22 +0000910// If SkipModule is true then .thinlto.bc should contain just
911// SkipModuleByDistributedBackend flag which requests distributed backend
912// to skip the compilation of the corresponding module and produce an empty
913// object file.
Vitaly Buka59baf732018-01-30 21:19:26 +0000914static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
915 const std::string &OldPrefix,
Vitaly Buka769134d2018-02-16 23:38:22 +0000916 const std::string &NewPrefix,
917 bool SkipModule) {
Teresa Johnson3f212b82016-09-21 19:12:05 +0000918 std::string NewModulePath =
919 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
920 std::error_code EC;
921 {
922 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
923 sys::fs::OpenFlags::F_None);
924 if (EC)
925 message(LDPL_FATAL, "Failed to write '%s': %s",
926 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
Vitaly Buka769134d2018-02-16 23:38:22 +0000927
928 if (SkipModule) {
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000929 ModuleSummaryIndex Index(/*HaveGVs*/ false);
Vitaly Buka769134d2018-02-16 23:38:22 +0000930 Index.setSkipModuleByDistributedBackend();
931 WriteIndexToFile(Index, OS, nullptr);
932 }
Teresa Johnson3f212b82016-09-21 19:12:05 +0000933 }
934 if (options::thinlto_emit_imports_files) {
935 raw_fd_ostream OS(NewModulePath + ".imports", EC,
936 sys::fs::OpenFlags::F_None);
937 if (EC)
938 message(LDPL_FATAL, "Failed to write '%s': %s",
939 (NewModulePath + ".imports").c_str(), EC.message().c_str());
940 }
941}
942
Vitaly Bukaa139b692018-02-22 19:06:15 +0000943// Creates and returns output stream with a list of object files for final
944// linking of distributed ThinLTO.
945static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
946 if (options::thinlto_linked_objects_file.empty())
947 return nullptr;
948 assert(options::thinlto_index_only);
949 std::error_code EC;
950 auto LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
951 options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::F_None);
952 if (EC)
953 message(LDPL_FATAL, "Failed to create '%s': %s",
954 options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
955 return LinkedObjectsFile;
956}
957
Vitaly Bukaffbf7db2018-02-22 19:06:05 +0000958/// Runs LTO and return a list of pairs <FileName, IsTemporary>.
959static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
Teresa Johnson765941a2016-08-20 01:24:07 +0000960 // Map to own RAII objects that manage the file opening and releasing
961 // interfaces with gold. This is needed only for ThinLTO mode, since
962 // unlike regular LTO, where addModule will result in the opened file
963 // being merged into a new combined module, we need to keep these files open
964 // through Lto->run().
965 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
966
Vitaly Buka59baf732018-01-30 21:19:26 +0000967 // Owns string objects and tells if index file was already created.
968 StringMap<bool> ObjectToIndexFileState;
969
Vitaly Bukaa139b692018-02-22 19:06:15 +0000970 std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
971 std::unique_ptr<LTO> Lto = createLTO(
972 [&ObjectToIndexFileState](const std::string &Identifier) {
Vitaly Buka59baf732018-01-30 21:19:26 +0000973 ObjectToIndexFileState[Identifier] = true;
Vitaly Bukaa139b692018-02-22 19:06:15 +0000974 },
975 LinkedObjects.get());
Teresa Johnson403a7872015-10-04 14:33:43 +0000976
Teresa Johnson3f212b82016-09-21 19:12:05 +0000977 std::string OldPrefix, NewPrefix;
978 if (options::thinlto_index_only)
979 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
980
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000981 std::string OldSuffix, NewSuffix;
982 getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000983
Rafael Espindolad2aac572014-07-30 01:52:40 +0000984 for (claimed_file &F : Modules) {
Teresa Johnson765941a2016-08-20 01:24:07 +0000985 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
986 HandleToInputFile.insert(std::make_pair(
987 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000988 // In case we are thin linking with a minimized bitcode file, ensure
989 // the module paths encoded in the index reflect where the backends
990 // will locate the full bitcode files for compiling/importing.
991 std::string Identifier =
992 getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
Vitaly Buka59baf732018-01-30 21:19:26 +0000993 auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000994 assert(ObjFilename.second);
Vitaly Buka59baf732018-01-30 21:19:26 +0000995 if (const void *View = getSymbolsAndView(F))
996 addModule(*Lto, F, View, ObjFilename.first->first());
Vitaly Buka769134d2018-02-16 23:38:22 +0000997 else if (options::thinlto_index_only) {
998 ObjFilename.first->second = true;
999 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
1000 /* SkipModule */ true);
1001 }
Rafael Espindola77b6d012010-06-14 21:20:52 +00001002 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001003
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001004 SmallString<128> Filename;
Mehdi Amini970800e2016-08-17 06:23:09 +00001005 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001006 if (!options::obj_path.empty())
1007 Filename = options::obj_path;
1008 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
1009 Filename = output_name + ".o";
1010 bool SaveTemps = !Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +00001011
Peter Collingbourne6201d782017-01-26 02:07:05 +00001012 size_t MaxTasks = Lto->getMaxTasks();
Vitaly Bukaffbf7db2018-02-22 19:06:05 +00001013 std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001014
Peter Collingbourne80186a52016-09-23 21:33:43 +00001015 auto AddStream =
1016 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Vitaly Bukaffbf7db2018-02-22 19:06:05 +00001017 Files[Task].second = !SaveTemps;
Vitaly Buka769134d2018-02-16 23:38:22 +00001018 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
Vitaly Bukaffbf7db2018-02-22 19:06:05 +00001019 Files[Task].first, Task);
Peter Collingbourne80186a52016-09-23 21:33:43 +00001020 return llvm::make_unique<lto::NativeObjectStream>(
1021 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001022 };
1023
Teresa Johnsona344fd32018-02-20 20:21:53 +00001024 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
Teresa Johnsonb145cca2018-02-20 19:51:30 +00001025 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourne128423f2017-03-17 00:34:07 +00001026 };
Peter Collingbourne80186a52016-09-23 21:33:43 +00001027
1028 NativeObjectCache Cache;
1029 if (!options::cache_dir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +00001030 Cache = check(localCache(options::cache_dir, AddBuffer));
Peter Collingbourne80186a52016-09-23 21:33:43 +00001031
1032 check(Lto->run(AddStream, Cache));
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001033
Vitaly Buka59baf732018-01-30 21:19:26 +00001034 // Write empty output files that may be expected by the distributed build
1035 // system.
1036 if (options::thinlto_index_only)
1037 for (auto &Identifier : ObjectToIndexFileState)
1038 if (!Identifier.getValue())
1039 writeEmptyDistributedBuildOutputs(Identifier.getKey(), OldPrefix,
Vitaly Buka769134d2018-02-16 23:38:22 +00001040 NewPrefix, /* SkipModule */ false);
Vitaly Buka59baf732018-01-30 21:19:26 +00001041
Vitaly Bukaffbf7db2018-02-22 19:06:05 +00001042 return Files;
1043}
1044
1045/// gold informs us that all symbols have been read. At this point, we use
1046/// get_symbols to see if any of our definitions have been overridden by a
1047/// native object file. Then, perform optimization and codegen.
1048static ld_plugin_status allSymbolsReadHook() {
1049 if (Modules.empty())
1050 return LDPS_OK;
1051
1052 if (unsigned NumOpts = options::extra.size())
1053 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1054
1055 std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
1056
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001057 if (options::TheOutputType == options::OT_DISABLE ||
1058 options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola6953a3a2014-11-24 21:18:14 +00001059 return LDPS_OK;
1060
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001061 if (options::thinlto_index_only) {
Teresa Johnsonaa943932018-04-19 16:55:13 +00001062 llvm_shutdown();
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001063 cleanup_hook();
1064 exit(0);
Rafael Espindolaba3398b2010-05-13 13:39:31 +00001065 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +00001066
Vitaly Bukaffbf7db2018-02-22 19:06:05 +00001067 for (const auto &F : Files)
1068 if (!F.first.empty())
1069 recordFile(F.first.str(), F.second);
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001070
Rafael Espindolaef498152010-06-23 20:20:59 +00001071 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +00001072 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1073 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +00001074
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001075 return LDPS_OK;
1076}
1077
Rafael Espindola55b32542014-08-11 19:06:54 +00001078static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001079 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola947bdb62014-11-25 20:52:49 +00001080 llvm_shutdown();
1081
Rafael Espindola6953a3a2014-11-24 21:18:14 +00001082 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001083 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano289a43e2016-03-20 20:12:33 +00001084 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001085 // Remove the output file here since ld.bfd creates the output file
1086 // early.
Davide Italiano289a43e2016-03-20 20:12:33 +00001087 std::error_code EC = sys::fs::remove(output_name);
1088 if (EC)
1089 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1090 EC.message().c_str());
1091 }
Rafael Espindola55b32542014-08-11 19:06:54 +00001092 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001093 }
Rafael Espindola55b32542014-08-11 19:06:54 +00001094
1095 return Ret;
1096}
1097
Dan Gohmanebb4ae02010-04-16 00:42:57 +00001098static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +00001099 for (std::string &Name : Cleanup) {
1100 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +00001101 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +00001102 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +00001103 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +00001104 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001105
Yi Kongbb4b4ee2017-09-18 23:24:55 +00001106 // Prune cache
Teresa Johnsonfd6fcbc2018-02-22 20:57:05 +00001107 if (!options::cache_dir.empty()) {
Yi Kongbb4b4ee2017-09-18 23:24:55 +00001108 CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
1109 pruneCache(options::cache_dir, policy);
1110 }
1111
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001112 return LDPS_OK;
1113}