blob: d2d0e77d71912787565e920a46a7ec32b04bd107 [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 Blaikiec14bfec2017-11-27 19:43:58 +000018#include "llvm/CodeGen/CommandFlags.def"
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;
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000118static Optional<Reloc::Model> RelocationModel = None;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000119static std::string output_name = "";
120static std::list<claimed_file> Modules;
Teresa Johnson683abe72016-05-26 01:46:41 +0000121static DenseMap<int, void *> FDToLeaderHandle;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000122static StringMap<ResolutionInfo> ResInfo;
Rafael Espindolabfb8b912014-06-20 01:37:35 +0000123static std::vector<std::string> Cleanup;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000124
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000125namespace options {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000126 enum OutputType {
127 OT_NORMAL,
128 OT_DISABLE,
129 OT_BC_ONLY,
130 OT_SAVE_TEMPS
131 };
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000132 static OutputType TheOutputType = OT_NORMAL;
Peter Collingbourne070843d2015-03-19 22:01:00 +0000133 static unsigned OptLevel = 2;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000134 // Default parallelism of 0 used to indicate that user did not specify.
135 // Actual parallelism default value depends on implementation.
Teresa Johnsonec544c52016-10-19 17:35:01 +0000136 // Currently only affects ThinLTO, where the default is
137 // llvm::heavyweight_hardware_concurrency.
Teresa Johnsona9f65552016-03-04 16:36:06 +0000138 static unsigned Parallelism = 0;
Teresa Johnson896fee22016-09-23 20:35:19 +0000139 // Default regular LTO codegen parallelism (number of partitions).
140 static unsigned ParallelCodeGenParallelismLevel = 1;
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000141#ifdef NDEBUG
142 static bool DisableVerify = true;
143#else
144 static bool DisableVerify = false;
145#endif
Shuxin Yang1826ae22013-08-12 21:07:31 +0000146 static std::string obj_path;
Rafael Espindolaef498152010-06-23 20:20:59 +0000147 static std::string extra_library_path;
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000148 static std::string triple;
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000149 static std::string mcpu;
Teresa Johnson403a7872015-10-04 14:33:43 +0000150 // When the thinlto plugin option is specified, only read the function
151 // the information from intermediate files and write a combined
152 // global index for the ThinLTO backends.
153 static bool thinlto = false;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000154 // If false, all ThinLTO backend compilations through code gen are performed
155 // using multiple threads in the gold-plugin, before handing control back to
Teresa Johnson84174c32016-05-10 13:48:23 +0000156 // gold. If true, write individual backend index files which reflect
157 // the import decisions, and exit afterwards. The assumption is
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000158 // that the build system will launch the backend processes.
159 static bool thinlto_index_only = false;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000160 // If non-empty, holds the name of a file in which to write the list of
161 // oject files gold selected for inclusion in the link after symbol
162 // resolution (i.e. they had selected symbols). This will only be non-empty
163 // in the thinlto_index_only case. It is used to identify files, which may
164 // have originally been within archive libraries specified via
165 // --start-lib/--end-lib pairs, that should be included in the final
166 // native link process (since intervening function importing and inlining
167 // may change the symbol resolution detected in the final link and which
168 // files to include out of --start-lib/--end-lib libraries as a result).
169 static std::string thinlto_linked_objects_file;
Teresa Johnson8570fe42016-05-10 15:54:09 +0000170 // If true, when generating individual index files for distributed backends,
171 // also generate a "${bitcodefile}.imports" file at the same location for each
172 // bitcode file, listing the files it imports from in plain text. This is to
173 // support distributed build file staging.
174 static bool thinlto_emit_imports_files = false;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000175 // Option to control where files for a distributed backend (the individual
176 // index files and optional imports files) are created.
177 // If specified, expects a string of the form "oldprefix:newprefix", and
178 // instead of generating these files in the same directory path as the
179 // corresponding bitcode file, will use a path formed by replacing the
180 // bitcode file's path prefix matching oldprefix with newprefix.
181 static std::string thinlto_prefix_replace;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000182 // Option to control the name of modules encoded in the individual index
183 // files for a distributed backend. This enables the use of minimized
184 // bitcode files for the thin link, assuming the name of the full bitcode
185 // file used in the backend differs just in some part of the file suffix.
186 // If specified, expects a string of the form "oldsuffix:newsuffix".
187 static std::string thinlto_object_suffix_replace;
Teresa Johnson57891a52016-08-24 15:11:47 +0000188 // Optional path to a directory for caching ThinLTO objects.
189 static std::string cache_dir;
Yi Kongbb4b4ee2017-09-18 23:24:55 +0000190 // Optional pruning policy for ThinLTO caches.
191 static std::string cache_policy;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000192 // Additional options to pass into the code generator.
Nick Lewycky0ac5e222010-06-03 17:10:17 +0000193 // Note: This array will contain all plugin options which are not claimed
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000194 // as plugin exclusive to pass to the code generator.
Rafael Espindola125b9242014-07-29 19:17:44 +0000195 static std::vector<const char *> extra;
Dehao Chen27978002016-12-16 16:48:46 +0000196 // Sample profile file path
197 static std::string sample_profile;
Sean Fertiledf8d9982017-10-05 01:48:42 +0000198 // New pass manager
199 static bool new_pass_manager = false;
Teresa Johnson70565e42018-04-05 03:16:57 +0000200 // Debug new pass manager
201 static bool debug_pass_manager = false;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000202
Nick Lewycky7282dd72015-08-05 21:16:02 +0000203 static void process_plugin_option(const char *opt_)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000204 {
Rafael Espindola176e6642014-07-29 21:46:05 +0000205 if (opt_ == nullptr)
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000206 return;
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000207 llvm::StringRef opt = opt_;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000208
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000209 if (opt.startswith("mcpu=")) {
Rafael Espindolaccab1dd2010-08-11 00:15:13 +0000210 mcpu = opt.substr(strlen("mcpu="));
Rafael Espindolaef498152010-06-23 20:20:59 +0000211 } else if (opt.startswith("extra-library-path=")) {
212 extra_library_path = opt.substr(strlen("extra_library_path="));
Rafael Espindola148c3282010-08-10 16:32:15 +0000213 } else if (opt.startswith("mtriple=")) {
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000214 triple = opt.substr(strlen("mtriple="));
Shuxin Yang1826ae22013-08-12 21:07:31 +0000215 } else if (opt.startswith("obj-path=")) {
216 obj_path = opt.substr(strlen("obj-path="));
Rafael Espindolac4dca3a2010-06-07 16:45:22 +0000217 } else if (opt == "emit-llvm") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000218 TheOutputType = OT_BC_ONLY;
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000219 } else if (opt == "save-temps") {
Rafael Espindola6953a3a2014-11-24 21:18:14 +0000220 TheOutputType = OT_SAVE_TEMPS;
221 } else if (opt == "disable-output") {
222 TheOutputType = OT_DISABLE;
Teresa Johnson403a7872015-10-04 14:33:43 +0000223 } else if (opt == "thinlto") {
224 thinlto = true;
Teresa Johnson7cffaf32016-03-04 17:06:02 +0000225 } else if (opt == "thinlto-index-only") {
226 thinlto_index_only = true;
Teresa Johnson1e2708c2016-07-22 18:20:22 +0000227 } else if (opt.startswith("thinlto-index-only=")) {
228 thinlto_index_only = true;
229 thinlto_linked_objects_file = opt.substr(strlen("thinlto-index-only="));
Teresa Johnson8570fe42016-05-10 15:54:09 +0000230 } else if (opt == "thinlto-emit-imports-files") {
231 thinlto_emit_imports_files = true;
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000232 } else if (opt.startswith("thinlto-prefix-replace=")) {
233 thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
Benjamin Kramere6ba5ef2016-11-30 10:01:11 +0000234 if (thinlto_prefix_replace.find(';') == std::string::npos)
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000235 message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000236 } else if (opt.startswith("thinlto-object-suffix-replace=")) {
237 thinlto_object_suffix_replace =
238 opt.substr(strlen("thinlto-object-suffix-replace="));
239 if (thinlto_object_suffix_replace.find(';') == std::string::npos)
240 message(LDPL_FATAL,
241 "thinlto-object-suffix-replace expects 'old;new' format");
Teresa Johnson57891a52016-08-24 15:11:47 +0000242 } else if (opt.startswith("cache-dir=")) {
243 cache_dir = opt.substr(strlen("cache-dir="));
Yi Kongbb4b4ee2017-09-18 23:24:55 +0000244 } else if (opt.startswith("cache-policy=")) {
245 cache_policy = opt.substr(strlen("cache-policy="));
Peter Collingbourne070843d2015-03-19 22:01:00 +0000246 } else if (opt.size() == 2 && opt[0] == 'O') {
247 if (opt[1] < '0' || opt[1] > '3')
Peter Collingbourne87202a42015-09-01 20:40:22 +0000248 message(LDPL_FATAL, "Optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000249 OptLevel = opt[1] - '0';
Peter Collingbourne87202a42015-09-01 20:40:22 +0000250 } else if (opt.startswith("jobs=")) {
251 if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
252 message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
Teresa Johnson896fee22016-09-23 20:35:19 +0000253 } else if (opt.startswith("lto-partitions=")) {
254 if (opt.substr(strlen("lto-partitions="))
255 .getAsInteger(10, ParallelCodeGenParallelismLevel))
256 message(LDPL_FATAL, "Invalid codegen partition level: %s", opt_ + 5);
Teresa Johnson8c8fe5a2015-09-16 18:06:45 +0000257 } else if (opt == "disable-verify") {
258 DisableVerify = true;
Dehao Chen27978002016-12-16 16:48:46 +0000259 } else if (opt.startswith("sample-profile=")) {
260 sample_profile= opt.substr(strlen("sample-profile="));
Sean Fertiledf8d9982017-10-05 01:48:42 +0000261 } else if (opt == "new-pass-manager") {
262 new_pass_manager = true;
Teresa Johnson70565e42018-04-05 03:16:57 +0000263 } else if (opt == "debug-pass-manager") {
264 debug_pass_manager = true;
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000265 } else {
266 // Save this option to pass to the code generator.
Rafael Espindola33466a72014-08-21 20:28:55 +0000267 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
268 // add that.
269 if (extra.empty())
270 extra.push_back("LLVMgold");
271
Rafael Espindola125b9242014-07-29 19:17:44 +0000272 extra.push_back(opt_);
Viktor Kutuzovfd7ddd92009-10-28 18:55:55 +0000273 }
274 }
275}
276
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000277static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
278 int *claimed);
279static ld_plugin_status all_symbols_read_hook(void);
280static ld_plugin_status cleanup_hook(void);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000281
282extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
283ld_plugin_status onload(ld_plugin_tv *tv) {
Peter Collingbourne1505c0a2014-07-03 23:28:03 +0000284 InitializeAllTargetInfos();
285 InitializeAllTargets();
286 InitializeAllTargetMCs();
287 InitializeAllAsmParsers();
288 InitializeAllAsmPrinters();
289
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000290 // We're given a pointer to the first transfer vector. We read through them
291 // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
292 // contain pointers to functions that we need to call to register our own
293 // hooks. The others are addresses of functions we can use to call into gold
294 // for services.
295
296 bool registeredClaimFile = false;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000297 bool RegisteredAllSymbolsRead = false;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000298
299 for (; tv->tv_tag != LDPT_NULL; ++tv) {
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000300 // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
301 // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
302 // header.
303 switch (static_cast<int>(tv->tv_tag)) {
304 case LDPT_OUTPUT_NAME:
305 output_name = tv->tv_u.tv_string;
306 break;
307 case LDPT_LINKER_OUTPUT:
308 switch (tv->tv_u.tv_val) {
309 case LDPO_REL: // .o
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000310 IsExecutable = false;
311 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000312 case LDPO_DYN: // .so
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000313 IsExecutable = false;
314 RelocationModel = Reloc::PIC_;
315 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000316 case LDPO_PIE: // position independent executable
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000317 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000318 RelocationModel = Reloc::PIC_;
Rafael Espindola8fb957e2010-06-03 21:11:20 +0000319 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000320 case LDPO_EXEC: // .exe
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000321 IsExecutable = true;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000322 RelocationModel = Reloc::Static;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000323 break;
324 default:
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000325 message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
326 return LDPS_ERR;
327 }
328 break;
329 case LDPT_OPTION:
330 options::process_plugin_option(tv->tv_u.tv_string);
331 break;
332 case LDPT_REGISTER_CLAIM_FILE_HOOK: {
333 ld_plugin_register_claim_file callback;
334 callback = tv->tv_u.tv_register_claim_file;
335
336 if (callback(claim_file_hook) != LDPS_OK)
337 return LDPS_ERR;
338
339 registeredClaimFile = true;
340 } break;
341 case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
342 ld_plugin_register_all_symbols_read callback;
343 callback = tv->tv_u.tv_register_all_symbols_read;
344
345 if (callback(all_symbols_read_hook) != LDPS_OK)
346 return LDPS_ERR;
347
348 RegisteredAllSymbolsRead = true;
349 } break;
350 case LDPT_REGISTER_CLEANUP_HOOK: {
351 ld_plugin_register_cleanup callback;
352 callback = tv->tv_u.tv_register_cleanup;
353
354 if (callback(cleanup_hook) != LDPS_OK)
355 return LDPS_ERR;
356 } break;
357 case LDPT_GET_INPUT_FILE:
358 get_input_file = tv->tv_u.tv_get_input_file;
359 break;
360 case LDPT_RELEASE_INPUT_FILE:
361 release_input_file = tv->tv_u.tv_release_input_file;
362 break;
363 case LDPT_ADD_SYMBOLS:
364 add_symbols = tv->tv_u.tv_add_symbols;
365 break;
366 case LDPT_GET_SYMBOLS_V2:
367 // Do not override get_symbols_v3 with get_symbols_v2.
368 if (!get_symbols)
369 get_symbols = tv->tv_u.tv_get_symbols;
370 break;
371 case LDPT_GET_SYMBOLS_V3:
372 get_symbols = tv->tv_u.tv_get_symbols;
373 break;
374 case LDPT_ADD_INPUT_FILE:
375 add_input_file = tv->tv_u.tv_add_input_file;
376 break;
377 case LDPT_SET_EXTRA_LIBRARY_PATH:
378 set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
379 break;
380 case LDPT_GET_VIEW:
381 get_view = tv->tv_u.tv_get_view;
382 break;
383 case LDPT_MESSAGE:
384 message = tv->tv_u.tv_message;
385 break;
Teresa Johnson8883af62018-03-14 13:26:18 +0000386 case LDPT_GET_WRAP_SYMBOLS:
387 // FIXME: When binutils 2.31 (containing gold 1.16) is the minimum
388 // required version, this should be changed to:
389 // get_wrap_symbols = tv->tv_u.tv_get_wrap_symbols;
390 get_wrap_symbols =
Teresa Johnson2f5c3312018-03-14 14:00:57 +0000391 (ld_plugin_get_wrap_symbols)tv->tv_u.tv_message;
Teresa Johnson8883af62018-03-14 13:26:18 +0000392 break;
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000393 default:
394 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000395 }
396 }
397
Rafael Espindolae08484d2009-02-18 08:30:15 +0000398 if (!registeredClaimFile) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000399 message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000400 return LDPS_ERR;
401 }
Rafael Espindolae08484d2009-02-18 08:30:15 +0000402 if (!add_symbols) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000403 message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
Rafael Espindola6add6182009-02-18 17:49:06 +0000404 return LDPS_ERR;
405 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000406
Rafael Espindolaa0d30a92014-06-19 22:20:07 +0000407 if (!RegisteredAllSymbolsRead)
408 return LDPS_OK;
Rafael Espindola6b244b12014-06-19 21:14:13 +0000409
Rafael Espindola33466a72014-08-21 20:28:55 +0000410 if (!get_input_file) {
411 message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
412 return LDPS_ERR;
Rafael Espindolac273aac2014-06-19 22:54:47 +0000413 }
Rafael Espindola33466a72014-08-21 20:28:55 +0000414 if (!release_input_file) {
Marianne Mailhot-Sarrasina5a750e2016-03-30 12:20:53 +0000415 message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
Rafael Espindola33466a72014-08-21 20:28:55 +0000416 return LDPS_ERR;
Tom Roederb5081192014-06-26 20:43:27 +0000417 }
418
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000419 return LDPS_OK;
420}
421
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000422static void diagnosticHandler(const DiagnosticInfo &DI) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000423 std::string ErrStorage;
424 {
425 raw_string_ostream OS(ErrStorage);
426 DiagnosticPrinterRawOStream DP(OS);
427 DI.print(DP);
428 }
Rafael Espindola503f8832015-03-02 19:08:03 +0000429 ld_plugin_level Level;
430 switch (DI.getSeverity()) {
431 case DS_Error:
432 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
433 ErrStorage.c_str());
Rafael Espindola503f8832015-03-02 19:08:03 +0000434 case DS_Warning:
435 Level = LDPL_WARNING;
436 break;
437 case DS_Note:
Rafael Espindolaf3f18542015-03-04 18:51:45 +0000438 case DS_Remark:
Rafael Espindola503f8832015-03-02 19:08:03 +0000439 Level = LDPL_INFO;
440 break;
Rafael Espindola503f8832015-03-02 19:08:03 +0000441 }
442 message(Level, "LLVM gold plugin: %s", ErrStorage.c_str());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000443}
444
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000445static void check(Error E, std::string Msg = "LLVM gold plugin") {
Mehdi Amini48f29602016-11-11 06:04:30 +0000446 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000447 message(LDPL_FATAL, "%s: %s", Msg.c_str(), EIB.message().c_str());
448 return Error::success();
449 });
NAKAMURA Takumib13e63c2015-11-19 10:43:44 +0000450}
451
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000452template <typename T> static T check(Expected<T> E) {
453 if (E)
454 return std::move(*E);
455 check(E.takeError());
456 return T();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000457}
458
Rafael Espindolae54d8212014-07-06 14:31:22 +0000459/// Called by gold to see whether this file is one that our plugin can handle.
460/// We'll try to open it and register all the symbols with add_symbol if
461/// possible.
Dan Gohmanebb4ae02010-04-16 00:42:57 +0000462static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
463 int *claimed) {
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000464 MemoryBufferRef BufferRef;
465 std::unique_ptr<MemoryBuffer> Buffer;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000466 if (get_view) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000467 const void *view;
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000468 if (get_view(file->handle, &view) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000469 message(LDPL_ERROR, "Failed to get a view of %s", file->name);
Rafael Espindolaece7c9c2011-04-07 21:11:00 +0000470 return LDPS_ERR;
471 }
Nick Lewycky7282dd72015-08-05 21:16:02 +0000472 BufferRef =
473 MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
Ivan Krasin5021af52011-09-12 21:47:50 +0000474 } else {
Ivan Krasin639222d2011-09-15 23:13:00 +0000475 int64_t offset = 0;
Nick Lewycky8691c472009-02-05 04:14:23 +0000476 // Gold has found what might be IR part-way inside of a file, such as
477 // an .a archive.
Ivan Krasin5021af52011-09-12 21:47:50 +0000478 if (file->offset) {
479 offset = file->offset;
480 }
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000481 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
482 MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
483 offset);
484 if (std::error_code EC = BufferOrErr.getError()) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000485 message(LDPL_ERROR, EC.message().c_str());
Ivan Krasin5021af52011-09-12 21:47:50 +0000486 return LDPS_ERR;
487 }
Rafael Espindolaeeec8e62014-08-27 20:25:55 +0000488 Buffer = std::move(BufferOrErr.get());
489 BufferRef = Buffer->getMemBufferRef();
Rafael Espindola56e41f72011-02-08 22:40:47 +0000490 }
Ivan Krasin5021af52011-09-12 21:47:50 +0000491
Rafael Espindola6c472e52014-07-29 20:46:19 +0000492 *claimed = 1;
493
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000494 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
495 if (!ObjOrErr) {
496 handleAllErrors(ObjOrErr.takeError(), [&](const ErrorInfoBase &EI) {
497 std::error_code EC = EI.convertToErrorCode();
498 if (EC == object::object_error::invalid_file_type ||
499 EC == object::object_error::bitcode_section_not_found)
500 *claimed = 0;
501 else
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000502 message(LDPL_FATAL,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000503 "LLVM gold plugin has failed to create LTO module: %s",
504 EI.message().c_str());
505 });
506
507 return *claimed ? LDPS_ERR : LDPS_OK;
Ivan Krasind5f2d8c2011-09-09 00:14:04 +0000508 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000509
510 std::unique_ptr<InputFile> Obj = std::move(*ObjOrErr);
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000511
Dehao Chen396f6242017-07-10 15:31:53 +0000512 Modules.emplace_back();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000513 claimed_file &cf = Modules.back();
Rafael Espindola4ef89f52010-08-09 21:09:46 +0000514
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000515 cf.handle = file->handle;
Teresa Johnson683abe72016-05-26 01:46:41 +0000516 // Keep track of the first handle for each file descriptor, since there are
517 // multiple in the case of an archive. This is used later in the case of
518 // ThinLTO parallel backends to ensure that each file is only opened and
519 // released once.
520 auto LeaderHandle =
521 FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
522 cf.leader_handle = LeaderHandle->second;
523 // Save the filesize since for parallel ThinLTO backends we can only
524 // invoke get_input_file once per archive (only for the leader handle).
525 cf.filesize = file->filesize;
526 // In the case of an archive library, all but the first member must have a
527 // non-zero offset, which we can append to the file name to obtain a
528 // unique name.
529 cf.name = file->name;
530 if (file->offset)
531 cf.name += ".llvm." + std::to_string(file->offset) + "." +
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532 sys::path::filename(Obj->getSourceFileName()).str();
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000533
Rafael Espindola33466a72014-08-21 20:28:55 +0000534 for (auto &Sym : Obj->symbols()) {
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000535 cf.syms.push_back(ld_plugin_symbol());
536 ld_plugin_symbol &sym = cf.syms.back();
Rafael Espindola176e6642014-07-29 21:46:05 +0000537 sym.version = nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000538 StringRef Name = Sym.getName();
539 sym.name = strdup(Name.str().c_str());
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000540
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000541 ResolutionInfo &Res = ResInfo[Name];
Rafael Espindola33466a72014-08-21 20:28:55 +0000542
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000543 Res.CanOmitFromDynSym &= Sym.canBeOmittedFromSymbolTable();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000544
Rafael Espindola33466a72014-08-21 20:28:55 +0000545 sym.visibility = LDPV_DEFAULT;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000546 GlobalValue::VisibilityTypes Vis = Sym.getVisibility();
547 if (Vis != GlobalValue::DefaultVisibility)
548 Res.DefaultVisibility = false;
549 switch (Vis) {
550 case GlobalValue::DefaultVisibility:
551 break;
552 case GlobalValue::HiddenVisibility:
553 sym.visibility = LDPV_HIDDEN;
554 break;
555 case GlobalValue::ProtectedVisibility:
556 sym.visibility = LDPV_PROTECTED;
557 break;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000558 }
559
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000560 if (Sym.isUndefined()) {
Rafael Espindola33466a72014-08-21 20:28:55 +0000561 sym.def = LDPK_UNDEF;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000562 if (Sym.isWeak())
Rafael Espindola56548522009-04-24 16:55:21 +0000563 sym.def = LDPK_WEAKUNDEF;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000564 } else if (Sym.isCommon())
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000565 sym.def = LDPK_COMMON;
Peter Collingbourne0d56b952017-03-28 22:31:35 +0000566 else if (Sym.isWeak())
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000567 sym.def = LDPK_WEAKDEF;
568 else
Rafael Espindola33466a72014-08-21 20:28:55 +0000569 sym.def = LDPK_DEF;
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000570
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000571 sym.size = 0;
Rafael Espindola33466a72014-08-21 20:28:55 +0000572 sym.comdat_key = nullptr;
Peter Collingbourne7b30f162017-03-31 04:47:07 +0000573 int CI = Sym.getComdatIndex();
Rafael Espindola79121102016-10-25 12:02:03 +0000574 if (CI != -1) {
575 StringRef C = Obj->getComdatTable()[CI];
Rafael Espindola62382c92016-10-17 18:51:02 +0000576 sym.comdat_key = strdup(C.str().c_str());
Rafael Espindola79121102016-10-25 12:02:03 +0000577 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000578
579 sym.resolution = LDPR_UNKNOWN;
580 }
581
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000582 if (!cf.syms.empty()) {
Nick Lewycky7282dd72015-08-05 21:16:02 +0000583 if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
Rafael Espindola5ad21fa2014-07-30 00:38:58 +0000584 message(LDPL_ERROR, "Unable to add symbols!");
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000585 return LDPS_ERR;
586 }
587 }
588
Teresa Johnson8883af62018-03-14 13:26:18 +0000589 // Handle any --wrap options passed to gold, which are than passed
590 // along to the plugin.
591 if (get_wrap_symbols) {
592 const char **wrap_symbols;
593 uint64_t count = 0;
594 if (get_wrap_symbols(&count, &wrap_symbols) != LDPS_OK) {
595 message(LDPL_ERROR, "Unable to get wrap symbols!");
596 return LDPS_ERR;
597 }
598 for (uint64_t i = 0; i < count; i++) {
599 StringRef Name = wrap_symbols[i];
600 ResolutionInfo &Res = ResInfo[Name];
601 ResolutionInfo &WrapRes = ResInfo["__wrap_" + Name.str()];
602 ResolutionInfo &RealRes = ResInfo["__real_" + Name.str()];
603 // Tell LTO not to inline symbols that will be overwritten.
604 Res.CanInline = false;
605 RealRes.CanInline = false;
606 // Tell LTO not to eliminate symbols that will be used after renaming.
607 Res.IsUsedInRegularObj = true;
608 WrapRes.IsUsedInRegularObj = true;
609 }
610 }
611
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000612 return LDPS_OK;
613}
614
Rafael Espindola538c9a82014-12-23 18:18:37 +0000615static void freeSymName(ld_plugin_symbol &Sym) {
616 free(Sym.name);
617 free(Sym.comdat_key);
618 Sym.name = nullptr;
619 Sym.comdat_key = nullptr;
620}
621
Teresa Johnsona9f65552016-03-04 16:36:06 +0000622/// Helper to get a file's symbols and a view into it via gold callbacks.
623static const void *getSymbolsAndView(claimed_file &F) {
Benjamin Kramer39988a02016-03-08 14:02:46 +0000624 ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000625 if (status == LDPS_NO_SYMS)
626 return nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000627
Evgeniy Stepanov330c5a62016-03-04 00:23:29 +0000628 if (status != LDPS_OK)
Teresa Johnson403a7872015-10-04 14:33:43 +0000629 message(LDPL_FATAL, "Failed to get symbol information");
630
631 const void *View;
632 if (get_view(F.handle, &View) != LDPS_OK)
633 message(LDPL_FATAL, "Failed to get a view of file");
634
Teresa Johnsona9f65552016-03-04 16:36:06 +0000635 return View;
636}
637
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000638/// Parse the thinlto-object-suffix-replace option into the \p OldSuffix and
639/// \p NewSuffix strings, if it was specified.
640static void getThinLTOOldAndNewSuffix(std::string &OldSuffix,
641 std::string &NewSuffix) {
642 assert(options::thinlto_object_suffix_replace.empty() ||
643 options::thinlto_object_suffix_replace.find(";") != StringRef::npos);
644 StringRef SuffixReplace = options::thinlto_object_suffix_replace;
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000645 std::tie(OldSuffix, NewSuffix) = SuffixReplace.split(';');
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000646}
647
648/// Given the original \p Path to an output file, replace any filename
649/// suffix matching \p OldSuffix with \p NewSuffix.
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000650static std::string getThinLTOObjectFileName(StringRef Path, StringRef OldSuffix,
651 StringRef NewSuffix) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000652 if (OldSuffix.empty() && NewSuffix.empty())
653 return Path;
654 StringRef NewPath = Path;
655 NewPath.consume_back(OldSuffix);
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000656 std::string NewNewPath = NewPath;
657 NewNewPath += NewSuffix;
658 return NewNewPath;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000659}
660
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000661// Returns true if S is valid as a C language identifier.
662static bool isValidCIdentifier(StringRef S) {
George Rimar3040da02017-10-04 11:00:30 +0000663 return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
664 std::all_of(S.begin() + 1, S.end(),
665 [](char C) { return C == '_' || isAlnum(C); });
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000666}
667
Eugene Leviant746f1522017-12-15 09:18:21 +0000668static bool isUndefined(ld_plugin_symbol &Sym) {
669 return Sym.def == LDPK_UNDEF || Sym.def == LDPK_WEAKUNDEF;
670}
671
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000672static void addModule(LTO &Lto, claimed_file &F, const void *View,
673 StringRef Filename) {
674 MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize),
675 Filename);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000676 Expected<std::unique_ptr<InputFile>> ObjOrErr = InputFile::create(BufferRef);
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000677
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000678 if (!ObjOrErr)
Peter Collingbourne10039c02014-09-18 21:28:49 +0000679 message(LDPL_FATAL, "Could not read bitcode from file : %s",
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000680 toString(ObjOrErr.takeError()).c_str());
Peter Collingbourne10039c02014-09-18 21:28:49 +0000681
Rafael Espindola527e8462014-12-09 16:13:59 +0000682 unsigned SymNum = 0;
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000683 std::unique_ptr<InputFile> Input = std::move(ObjOrErr.get());
684 auto InputFileSyms = Input->symbols();
685 assert(InputFileSyms.size() == F.syms.size());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000686 std::vector<SymbolResolution> Resols(F.syms.size());
Peter Collingbourne07586442016-09-14 02:55:16 +0000687 for (ld_plugin_symbol &Sym : F.syms) {
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000688 const InputFile::Symbol &InpSym = InputFileSyms[SymNum];
Peter Collingbourne07586442016-09-14 02:55:16 +0000689 SymbolResolution &R = Resols[SymNum++];
Rafael Espindola527e8462014-12-09 16:13:59 +0000690
Rafael Espindola33466a72014-08-21 20:28:55 +0000691 ld_plugin_symbol_resolution Resolution =
692 (ld_plugin_symbol_resolution)Sym.resolution;
693
Rafael Espindolacaabe222015-12-10 14:19:35 +0000694 ResolutionInfo &Res = ResInfo[Sym.name];
Rafael Espindola890db272014-09-09 20:08:22 +0000695
Rafael Espindola33466a72014-08-21 20:28:55 +0000696 switch (Resolution) {
697 case LDPR_UNKNOWN:
698 llvm_unreachable("Unexpected resolution");
699
700 case LDPR_RESOLVED_IR:
701 case LDPR_RESOLVED_EXEC:
702 case LDPR_RESOLVED_DYN:
Rafael Espindolacaabe222015-12-10 14:19:35 +0000703 case LDPR_PREEMPTED_IR:
704 case LDPR_PREEMPTED_REG:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000705 case LDPR_UNDEF:
Rafael Espindola5ca7fa12015-01-14 13:53:50 +0000706 break;
707
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000708 case LDPR_PREVAILING_DEF_IRONLY:
Eugene Leviant746f1522017-12-15 09:18:21 +0000709 R.Prevailing = !isUndefined(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000710 break;
Teresa Johnsonf99573b2016-08-11 12:56:40 +0000711
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000712 case LDPR_PREVAILING_DEF:
Eugene Leviant746f1522017-12-15 09:18:21 +0000713 R.Prevailing = !isUndefined(Sym);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000714 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000715 break;
716
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000717 case LDPR_PREVAILING_DEF_IRONLY_EXP:
Eugene Leviant746f1522017-12-15 09:18:21 +0000718 R.Prevailing = !isUndefined(Sym);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000719 if (!Res.CanOmitFromDynSym)
720 R.VisibleToRegularObj = true;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000721 break;
722 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000723
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000724 // If the symbol has a C identifier section name, we need to mark
725 // it as visible to a regular object so that LTO will keep it around
726 // to ensure the linker generates special __start_<secname> and
727 // __stop_<secname> symbols which may be used elsewhere.
728 if (isValidCIdentifier(InpSym.getSectionName()))
729 R.VisibleToRegularObj = true;
730
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000731 if (Resolution != LDPR_RESOLVED_DYN && Resolution != LDPR_UNDEF &&
732 (IsExecutable || !Res.DefaultVisibility))
733 R.FinalDefinitionInLinkageUnit = true;
734
Teresa Johnson8883af62018-03-14 13:26:18 +0000735 if (!Res.CanInline)
736 R.LinkerRedefined = true;
737
738 if (Res.IsUsedInRegularObj)
739 R.VisibleToRegularObj = true;
740
Rafael Espindola538c9a82014-12-23 18:18:37 +0000741 freeSymName(Sym);
Rafael Espindola33466a72014-08-21 20:28:55 +0000742 }
743
Teresa Johnsona83c3f72017-07-25 19:42:32 +0000744 check(Lto.add(std::move(Input), Resols),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000745 std::string("Failed to link module ") + F.name);
Rafael Espindola4a3b6cf2014-10-29 23:54:45 +0000746}
747
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000748static void recordFile(const std::string &Filename, bool TempOutFile) {
Teresa Johnsona9f65552016-03-04 16:36:06 +0000749 if (add_input_file(Filename.c_str()) != LDPS_OK)
750 message(LDPL_FATAL,
751 "Unable to add .o file to the link. File left behind in: %s",
752 Filename.c_str());
753 if (TempOutFile)
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000754 Cleanup.push_back(Filename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000755}
Rafael Espindola33466a72014-08-21 20:28:55 +0000756
Mehdi Amini970800e2016-08-17 06:23:09 +0000757/// Return the desired output filename given a base input name, a flag
758/// indicating whether a temp file should be generated, and an optional task id.
759/// The new filename generated is returned in \p NewFilename.
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000760static int getOutputFileName(StringRef InFilename, bool TempOutFile,
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000761 SmallString<128> &NewFilename, int TaskID) {
762 int FD = -1;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000763 if (TempOutFile) {
764 std::error_code EC =
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000765 sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
Teresa Johnsona9f65552016-03-04 16:36:06 +0000766 if (EC)
767 message(LDPL_FATAL, "Could not create temporary file: %s",
768 EC.message().c_str());
769 } else {
770 NewFilename = InFilename;
Peter Collingbourne6201d782017-01-26 02:07:05 +0000771 if (TaskID > 0)
Teresa Johnsona9f65552016-03-04 16:36:06 +0000772 NewFilename += utostr(TaskID);
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000773 std::error_code EC =
774 sys::fs::openFileForWrite(NewFilename, FD, sys::fs::F_None);
775 if (EC)
776 message(LDPL_FATAL, "Could not open file %s: %s", NewFilename.c_str(),
777 EC.message().c_str());
Teresa Johnsona9f65552016-03-04 16:36:06 +0000778 }
Benjamin Kramer74fbf452017-08-10 17:38:41 +0000779 return FD;
Teresa Johnsona9f65552016-03-04 16:36:06 +0000780}
781
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000782/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
783/// \p NewPrefix strings, if it was specified.
784static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
785 std::string &NewPrefix) {
786 StringRef PrefixReplace = options::thinlto_prefix_replace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000787 assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
Benjamin Kramerdbbe5752017-08-10 19:28:00 +0000788 std::tie(OldPrefix, NewPrefix) = PrefixReplace.split(';');
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000789}
790
Vitaly Bukaa139b692018-02-22 19:06:15 +0000791/// Creates instance of LTO.
792/// OnIndexWrite is callback to let caller know when LTO writes index files.
793/// LinkedObjectsFile is an output stream to write the list of object files for
794/// the final ThinLTO linking. Can be nullptr.
795static std::unique_ptr<LTO> createLTO(IndexWriteCallback OnIndexWrite,
796 raw_fd_ostream *LinkedObjectsFile) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000797 Config Conf;
798 ThinBackend Backend;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000799
800 Conf.CPU = options::mcpu;
801 Conf.Options = InitTargetOptionsFromCodeGenFlags();
802
803 // Disable the new X86 relax relocations since gold might not support them.
804 // FIXME: Check the gold version or add a new option to enable them.
805 Conf.Options.RelaxELFRelocations = false;
806
Davide Italiano557a0b32017-07-26 01:47:17 +0000807 // Enable function/data sections by default.
Davide Italiano756feb22017-07-25 23:32:50 +0000808 Conf.Options.FunctionSections = true;
Davide Italiano557a0b32017-07-26 01:47:17 +0000809 Conf.Options.DataSections = true;
Davide Italiano756feb22017-07-25 23:32:50 +0000810
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000811 Conf.MAttrs = MAttrs;
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000812 Conf.RelocModel = RelocationModel;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000813 Conf.DisableVerify = options::DisableVerify;
814 Conf.OptLevel = options::OptLevel;
Teresa Johnson896fee22016-09-23 20:35:19 +0000815 if (options::Parallelism)
816 Backend = createInProcessThinBackend(options::Parallelism);
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000817 if (options::thinlto_index_only) {
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000818 std::string OldPrefix, NewPrefix;
819 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
Vitaly Bukaa139b692018-02-22 19:06:15 +0000820 Backend = createWriteIndexesThinBackend(OldPrefix, NewPrefix,
821 options::thinlto_emit_imports_files,
822 LinkedObjectsFile, OnIndexWrite);
Teresa Johnson84174c32016-05-10 13:48:23 +0000823 }
824
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000825 Conf.OverrideTriple = options::triple;
826 Conf.DefaultTriple = sys::getDefaultTargetTriple();
827
828 Conf.DiagHandler = diagnosticHandler;
829
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000830 switch (options::TheOutputType) {
831 case options::OT_NORMAL:
832 break;
833
834 case options::OT_DISABLE:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000835 Conf.PreOptModuleHook = [](size_t Task, const Module &M) { return false; };
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000836 break;
837
838 case options::OT_BC_ONLY:
Mehdi Amini6ec23332016-08-22 16:41:58 +0000839 Conf.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000840 std::error_code EC;
841 raw_fd_ostream OS(output_name, EC, sys::fs::OpenFlags::F_None);
842 if (EC)
843 message(LDPL_FATAL, "Failed to write the output file.");
Rafael Espindola6a86e252018-02-14 19:11:32 +0000844 WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000845 return false;
846 };
847 break;
848
849 case options::OT_SAVE_TEMPS:
Mehdi Aminieccffad2016-08-18 00:12:33 +0000850 check(Conf.addSaveTemps(output_name + ".",
851 /* UseInputModulePath */ true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000852 break;
Teresa Johnsoncbf684e2016-08-11 13:03:56 +0000853 }
854
Dehao Chen27978002016-12-16 16:48:46 +0000855 if (!options::sample_profile.empty())
856 Conf.SampleProfile = options::sample_profile;
857
Sean Fertiledf8d9982017-10-05 01:48:42 +0000858 // Use new pass manager if set in driver
859 Conf.UseNewPM = options::new_pass_manager;
Teresa Johnson70565e42018-04-05 03:16:57 +0000860 // Debug new pass manager if requested
861 Conf.DebugPassManager = options::debug_pass_manager;
Sean Fertiledf8d9982017-10-05 01:48:42 +0000862
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000863 return llvm::make_unique<LTO>(std::move(Conf), Backend,
Teresa Johnson896fee22016-09-23 20:35:19 +0000864 options::ParallelCodeGenParallelismLevel);
Teresa Johnson84174c32016-05-10 13:48:23 +0000865}
866
Teresa Johnson3f212b82016-09-21 19:12:05 +0000867// Write empty files that may be expected by a distributed build
868// system when invoked with thinlto_index_only. This is invoked when
869// the linker has decided not to include the given module in the
870// final link. Frequently the distributed build system will want to
871// confirm that all expected outputs are created based on all of the
872// modules provided to the linker.
Vitaly Buka769134d2018-02-16 23:38:22 +0000873// If SkipModule is true then .thinlto.bc should contain just
874// SkipModuleByDistributedBackend flag which requests distributed backend
875// to skip the compilation of the corresponding module and produce an empty
876// object file.
Vitaly Buka59baf732018-01-30 21:19:26 +0000877static void writeEmptyDistributedBuildOutputs(const std::string &ModulePath,
878 const std::string &OldPrefix,
Vitaly Buka769134d2018-02-16 23:38:22 +0000879 const std::string &NewPrefix,
880 bool SkipModule) {
Teresa Johnson3f212b82016-09-21 19:12:05 +0000881 std::string NewModulePath =
882 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
883 std::error_code EC;
884 {
885 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
886 sys::fs::OpenFlags::F_None);
887 if (EC)
888 message(LDPL_FATAL, "Failed to write '%s': %s",
889 (NewModulePath + ".thinlto.bc").c_str(), EC.message().c_str());
Vitaly Buka769134d2018-02-16 23:38:22 +0000890
891 if (SkipModule) {
892 ModuleSummaryIndex Index(false);
893 Index.setSkipModuleByDistributedBackend();
894 WriteIndexToFile(Index, OS, nullptr);
895 }
Teresa Johnson3f212b82016-09-21 19:12:05 +0000896 }
897 if (options::thinlto_emit_imports_files) {
898 raw_fd_ostream OS(NewModulePath + ".imports", EC,
899 sys::fs::OpenFlags::F_None);
900 if (EC)
901 message(LDPL_FATAL, "Failed to write '%s': %s",
902 (NewModulePath + ".imports").c_str(), EC.message().c_str());
903 }
904}
905
Vitaly Bukaa139b692018-02-22 19:06:15 +0000906// Creates and returns output stream with a list of object files for final
907// linking of distributed ThinLTO.
908static std::unique_ptr<raw_fd_ostream> CreateLinkedObjectsFile() {
909 if (options::thinlto_linked_objects_file.empty())
910 return nullptr;
911 assert(options::thinlto_index_only);
912 std::error_code EC;
913 auto LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
914 options::thinlto_linked_objects_file, EC, sys::fs::OpenFlags::F_None);
915 if (EC)
916 message(LDPL_FATAL, "Failed to create '%s': %s",
917 options::thinlto_linked_objects_file.c_str(), EC.message().c_str());
918 return LinkedObjectsFile;
919}
920
Vitaly Bukaffbf7db2018-02-22 19:06:05 +0000921/// Runs LTO and return a list of pairs <FileName, IsTemporary>.
922static std::vector<std::pair<SmallString<128>, bool>> runLTO() {
Teresa Johnson765941a2016-08-20 01:24:07 +0000923 // Map to own RAII objects that manage the file opening and releasing
924 // interfaces with gold. This is needed only for ThinLTO mode, since
925 // unlike regular LTO, where addModule will result in the opened file
926 // being merged into a new combined module, we need to keep these files open
927 // through Lto->run().
928 DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
929
Vitaly Buka59baf732018-01-30 21:19:26 +0000930 // Owns string objects and tells if index file was already created.
931 StringMap<bool> ObjectToIndexFileState;
932
Vitaly Bukaa139b692018-02-22 19:06:15 +0000933 std::unique_ptr<raw_fd_ostream> LinkedObjects = CreateLinkedObjectsFile();
934 std::unique_ptr<LTO> Lto = createLTO(
935 [&ObjectToIndexFileState](const std::string &Identifier) {
Vitaly Buka59baf732018-01-30 21:19:26 +0000936 ObjectToIndexFileState[Identifier] = true;
Vitaly Bukaa139b692018-02-22 19:06:15 +0000937 },
938 LinkedObjects.get());
Teresa Johnson403a7872015-10-04 14:33:43 +0000939
Teresa Johnson3f212b82016-09-21 19:12:05 +0000940 std::string OldPrefix, NewPrefix;
941 if (options::thinlto_index_only)
942 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
943
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000944 std::string OldSuffix, NewSuffix;
945 getThinLTOOldAndNewSuffix(OldSuffix, NewSuffix);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000946
Rafael Espindolad2aac572014-07-30 01:52:40 +0000947 for (claimed_file &F : Modules) {
Teresa Johnson765941a2016-08-20 01:24:07 +0000948 if (options::thinlto && !HandleToInputFile.count(F.leader_handle))
949 HandleToInputFile.insert(std::make_pair(
950 F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000951 // In case we are thin linking with a minimized bitcode file, ensure
952 // the module paths encoded in the index reflect where the backends
953 // will locate the full bitcode files for compiling/importing.
954 std::string Identifier =
955 getThinLTOObjectFileName(F.name, OldSuffix, NewSuffix);
Vitaly Buka59baf732018-01-30 21:19:26 +0000956 auto ObjFilename = ObjectToIndexFileState.insert({Identifier, false});
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000957 assert(ObjFilename.second);
Vitaly Buka59baf732018-01-30 21:19:26 +0000958 if (const void *View = getSymbolsAndView(F))
959 addModule(*Lto, F, View, ObjFilename.first->first());
Vitaly Buka769134d2018-02-16 23:38:22 +0000960 else if (options::thinlto_index_only) {
961 ObjFilename.first->second = true;
962 writeEmptyDistributedBuildOutputs(Identifier, OldPrefix, NewPrefix,
963 /* SkipModule */ true);
964 }
Rafael Espindola77b6d012010-06-14 21:20:52 +0000965 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +0000966
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000967 SmallString<128> Filename;
Mehdi Amini970800e2016-08-17 06:23:09 +0000968 // Note that getOutputFileName will append a unique ID for each task
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000969 if (!options::obj_path.empty())
970 Filename = options::obj_path;
971 else if (options::TheOutputType == options::OT_SAVE_TEMPS)
972 Filename = output_name + ".o";
973 bool SaveTemps = !Filename.empty();
Rafael Espindola33466a72014-08-21 20:28:55 +0000974
Peter Collingbourne6201d782017-01-26 02:07:05 +0000975 size_t MaxTasks = Lto->getMaxTasks();
Vitaly Bukaffbf7db2018-02-22 19:06:05 +0000976 std::vector<std::pair<SmallString<128>, bool>> Files(MaxTasks);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000977
Peter Collingbourne80186a52016-09-23 21:33:43 +0000978 auto AddStream =
979 [&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
Vitaly Bukaffbf7db2018-02-22 19:06:05 +0000980 Files[Task].second = !SaveTemps;
Vitaly Buka769134d2018-02-16 23:38:22 +0000981 int FD = getOutputFileName(Filename, /* TempOutFile */ !SaveTemps,
Vitaly Bukaffbf7db2018-02-22 19:06:05 +0000982 Files[Task].first, Task);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000983 return llvm::make_unique<lto::NativeObjectStream>(
984 llvm::make_unique<llvm::raw_fd_ostream>(FD, true));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000985 };
986
Teresa Johnsona344fd32018-02-20 20:21:53 +0000987 auto AddBuffer = [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
Teresa Johnsonb145cca2018-02-20 19:51:30 +0000988 *AddStream(Task)->OS << MB->getBuffer();
Peter Collingbourne128423f2017-03-17 00:34:07 +0000989 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000990
991 NativeObjectCache Cache;
992 if (!options::cache_dir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000993 Cache = check(localCache(options::cache_dir, AddBuffer));
Peter Collingbourne80186a52016-09-23 21:33:43 +0000994
995 check(Lto->run(AddStream, Cache));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000996
Vitaly Buka59baf732018-01-30 21:19:26 +0000997 // Write empty output files that may be expected by the distributed build
998 // system.
999 if (options::thinlto_index_only)
1000 for (auto &Identifier : ObjectToIndexFileState)
1001 if (!Identifier.getValue())
1002 writeEmptyDistributedBuildOutputs(Identifier.getKey(), OldPrefix,
Vitaly Buka769134d2018-02-16 23:38:22 +00001003 NewPrefix, /* SkipModule */ false);
Vitaly Buka59baf732018-01-30 21:19:26 +00001004
Vitaly Bukaffbf7db2018-02-22 19:06:05 +00001005 return Files;
1006}
1007
1008/// gold informs us that all symbols have been read. At this point, we use
1009/// get_symbols to see if any of our definitions have been overridden by a
1010/// native object file. Then, perform optimization and codegen.
1011static ld_plugin_status allSymbolsReadHook() {
1012 if (Modules.empty())
1013 return LDPS_OK;
1014
1015 if (unsigned NumOpts = options::extra.size())
1016 cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1017
1018 std::vector<std::pair<SmallString<128>, bool>> Files = runLTO();
1019
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001020 if (options::TheOutputType == options::OT_DISABLE ||
1021 options::TheOutputType == options::OT_BC_ONLY)
Rafael Espindola6953a3a2014-11-24 21:18:14 +00001022 return LDPS_OK;
1023
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001024 if (options::thinlto_index_only) {
Teresa Johnson95597ae2017-02-02 17:33:53 +00001025 if (llvm::AreStatisticsEnabled())
1026 llvm::PrintStatistics();
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001027 cleanup_hook();
1028 exit(0);
Rafael Espindolaba3398b2010-05-13 13:39:31 +00001029 }
Rafael Espindola143fc3b2013-10-16 12:47:04 +00001030
Vitaly Bukaffbf7db2018-02-22 19:06:05 +00001031 for (const auto &F : Files)
1032 if (!F.first.empty())
1033 recordFile(F.first.str(), F.second);
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001034
Rafael Espindolaef498152010-06-23 20:20:59 +00001035 if (!options::extra_library_path.empty() &&
Rafael Espindola33466a72014-08-21 20:28:55 +00001036 set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1037 message(LDPL_FATAL, "Unable to set the extra library path.");
Shuxin Yang1826ae22013-08-12 21:07:31 +00001038
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001039 return LDPS_OK;
1040}
1041
Rafael Espindola55b32542014-08-11 19:06:54 +00001042static ld_plugin_status all_symbols_read_hook(void) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001043 ld_plugin_status Ret = allSymbolsReadHook();
Rafael Espindola947bdb62014-11-25 20:52:49 +00001044 llvm_shutdown();
1045
Rafael Espindola6953a3a2014-11-24 21:18:14 +00001046 if (options::TheOutputType == options::OT_BC_ONLY ||
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001047 options::TheOutputType == options::OT_DISABLE) {
Davide Italiano289a43e2016-03-20 20:12:33 +00001048 if (options::TheOutputType == options::OT_DISABLE) {
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001049 // Remove the output file here since ld.bfd creates the output file
1050 // early.
Davide Italiano289a43e2016-03-20 20:12:33 +00001051 std::error_code EC = sys::fs::remove(output_name);
1052 if (EC)
1053 message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1054 EC.message().c_str());
1055 }
Rafael Espindola55b32542014-08-11 19:06:54 +00001056 exit(0);
Michael Kupersteina07d9b92015-02-12 18:21:50 +00001057 }
Rafael Espindola55b32542014-08-11 19:06:54 +00001058
1059 return Ret;
1060}
1061
Dan Gohmanebb4ae02010-04-16 00:42:57 +00001062static ld_plugin_status cleanup_hook(void) {
Rafael Espindolad2aac572014-07-30 01:52:40 +00001063 for (std::string &Name : Cleanup) {
1064 std::error_code EC = sys::fs::remove(Name);
Rafael Espindola55ab87f2013-06-17 18:38:18 +00001065 if (EC)
Rafael Espindolad2aac572014-07-30 01:52:40 +00001066 message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
Rafael Espindola5ad21fa2014-07-30 00:38:58 +00001067 EC.message().c_str());
Rafael Espindola55ab87f2013-06-17 18:38:18 +00001068 }
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001069
Yi Kongbb4b4ee2017-09-18 23:24:55 +00001070 // Prune cache
Teresa Johnsonfd6fcbc2018-02-22 20:57:05 +00001071 if (!options::cache_dir.empty()) {
Yi Kongbb4b4ee2017-09-18 23:24:55 +00001072 CachePruningPolicy policy = check(parseCachePruningPolicy(options::cache_policy));
1073 pruneCache(options::cache_dir, policy);
1074 }
1075
Nick Lewyckyfb643e42009-02-03 07:13:24 +00001076 return LDPS_OK;
1077}